Files
setup-php/src/fetch.ts
Shivam Mathur 871ff01b2b Refactor to use ES2024+ features for Node 24
Use Set for O(1) redirect status code lookup in fetch.ts

Use at(-1) and Object.hasOwn() in tools.ts

Use for...of with entries() in utils.ts
2026-01-20 06:46:28 +05:30

43 lines
1.1 KiB
TypeScript

/**
* Redirect status codes set for O(1) lookup
*/
const REDIRECT_CODES = new Set([301, 302, 303, 307, 308]);
/**
* Function to fetch a URL using native fetch API (Node 24+)
*
* @param input_url
* @param auth_token
* @param redirect_count
*/
export async function fetch(
input_url: string,
auth_token?: string,
redirect_count = 5
): Promise<Record<string, string>> {
const headers: Record<string, string> = {
'User-Agent': `Mozilla/5.0 (${process.platform} ${process.arch}) setup-php`
};
if (auth_token) {
headers['Authorization'] = 'Bearer ' + auth_token;
}
try {
const response = await globalThis.fetch(input_url, {
headers,
redirect: redirect_count > 0 ? 'follow' : 'manual'
});
if (response.ok) {
const data = await response.text();
return {data};
} else if (REDIRECT_CODES.has(response.status) && redirect_count <= 0) {
return {error: `${response.status}: Redirect error`};
} else {
return {error: `${response.status}: ${response.statusText}`};
}
} catch (error) {
return {error: `Fetch error: ${(error as Error).message}`};
}
}