-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathdevice-cache.ts
More file actions
65 lines (54 loc) · 1.78 KB
/
device-cache.ts
File metadata and controls
65 lines (54 loc) · 1.78 KB
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
import fs from "fs";
import os from "os";
import path from "path";
import { DOMAINS } from "./domains.js";
const CACHE_DIR = path.join(os.homedir(), ".browserstack", "combined_cache");
const CACHE_FILE = path.join(CACHE_DIR, "data.json");
const TTL_MS = 24 * 60 * 60 * 1000; // 1 day
export enum BrowserStackProducts {
LIVE = "live",
APP_LIVE = "app_live",
APP_AUTOMATE = "app_automate",
}
const URLS: Record<BrowserStackProducts, string> = {
[BrowserStackProducts.LIVE]: `${DOMAINS.WWW}/list-of-browsers-and-platforms/live.json`,
[BrowserStackProducts.APP_LIVE]: `${DOMAINS.WWW}/list-of-browsers-and-platforms/app_live.json`,
[BrowserStackProducts.APP_AUTOMATE]: `${DOMAINS.WWW}/list-of-browsers-and-platforms/app_automate.json`,
};
/**
* Fetches and caches BrowserStack datasets (live + app_live + app_automate) with a shared TTL.
*/
export async function getDevicesAndBrowsers(
type: BrowserStackProducts,
): Promise<any> {
if (!fs.existsSync(CACHE_DIR)) {
fs.mkdirSync(CACHE_DIR, { recursive: true });
}
let cache: any = {};
if (fs.existsSync(CACHE_FILE)) {
const stats = fs.statSync(CACHE_FILE);
if (Date.now() - stats.mtimeMs < TTL_MS) {
try {
cache = JSON.parse(fs.readFileSync(CACHE_FILE, "utf8"));
if (cache[type]) {
return cache[type];
}
} catch (error) {
console.error("Error parsing cache file:", error);
// Continue with fetching fresh data
}
}
}
const liveRes = await fetch(URLS[type]);
if (!liveRes.ok) {
throw new Error(
`Failed to fetch configuration from BrowserStack : ${type}=${liveRes.statusText}`,
);
}
const data = await liveRes.json();
cache = {
[type]: data,
};
fs.writeFileSync(CACHE_FILE, JSON.stringify(cache), "utf8");
return cache[type];
}