import { expect, test, vi } from "vitest" import { Geo } from "#Source/environment/index.ts" test("getGeoInfoFromCloudflare parses key-value trace response", async () => { const mockFetch = async (): Promise<{ text: () => Promise }> => { const response = await Promise.resolve({ text: async (): Promise => { return await Promise.resolve("ip=1.2.3.4\nloc=US\nhttp=http/2\n") }, }) return response } vi.stubGlobal("fetch", vi.fn(mockFetch)) const geo = await Geo.getGeoInfoFromCloudflare() expect(geo.ip).toBe("1.2.3.4") expect(geo.loc).toBe("US") expect(geo.http).toBe("http/2") vi.unstubAllGlobals() vi.restoreAllMocks() }) test("getGeoInfoFromIpapi returns parsed JSON payload", async () => { const mockFetch = async (): Promise<{ json: () => Promise<{ ip: string; country: string }> }> => { const response = await Promise.resolve({ json: async (): Promise<{ ip: string; country: string }> => { return await Promise.resolve({ ip: "5.6.7.8", country: "US" }) }, }) return response } vi.stubGlobal("fetch", vi.fn(mockFetch)) const geo = await Geo.getGeoInfoFromIpapi() expect(geo.ip).toBe("5.6.7.8") expect(geo.country).toBe("US") vi.unstubAllGlobals() vi.restoreAllMocks() }) test("getGeoInfoFromIpify returns public IP payload", async () => { const mockFetch = async (): Promise<{ json: () => Promise<{ ip: string }> }> => { const response = await Promise.resolve({ json: async (): Promise<{ ip: string }> => { return await Promise.resolve({ ip: "9.9.9.9" }) }, }) return response } vi.stubGlobal("fetch", vi.fn(mockFetch)) const geo = await Geo.getGeoInfoFromIpify() expect(geo.ip).toBe("9.9.9.9") vi.unstubAllGlobals() vi.restoreAllMocks() }) test("getGeoInfo aggregates results from all providers", async () => { // oxlint-disable-next-line require-await explicit-function-return-type const mockFetch = async (input: URL | RequestInfo) => { let url: string if (input instanceof URL) { url = input.toString() } else if (typeof input === "string") { url = input } else { url = input.url } if (url.includes("cloudflare")) { return { text: async (): Promise => { return await Promise.resolve("ip=1.1.1.1\nloc=US\n") }, } } if (url.includes("ipapi")) { return { json: async (): Promise<{ ip: string; country: string }> => { return await Promise.resolve({ ip: "2.2.2.2", country: "US" }) }, } } return { json: async (): Promise<{ ip: string }> => { return await Promise.resolve({ ip: "3.3.3.3" }) }, } } vi.stubGlobal("fetch", vi.fn(mockFetch)) const geo = await Geo.getGeoInfo() expect(geo.cloudflare.ip).toBe("1.1.1.1") expect(geo.ipapi.ip).toBe("2.2.2.2") expect(geo.ipify.ip).toBe("3.3.3.3") vi.unstubAllGlobals() vi.restoreAllMocks() })