-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathgenerate-extractor.js
More file actions
98 lines (78 loc) · 2.52 KB
/
generate-extractor.js
File metadata and controls
98 lines (78 loc) · 2.52 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
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
import fs from "fs";
import path from "path";
import { pathToFileURL } from "url";
// Mock the chrome object for Node.js environment
if (typeof global.chrome === "undefined") {
global.chrome = {};
}
const SRC_DIR = "src";
async function generateExtractorsIndex() {
const extractorsDir = path.join(SRC_DIR, "extractors");
const indexPath = path.join(extractorsDir, "index.js");
const files = fs.readdirSync(extractorsDir).filter(
(file) =>
file.endsWith(".js") &&
file !== "index.js" &&
file !== "AbstractExtractor.js"
);
const imports = [];
const instances = [];
const AbstractExtractor = await import(pathToFileURL(path.resolve(SRC_DIR, "extractors", "AbstractExtractor.js")).href);
const Extractor = AbstractExtractor.Extractor;
for (const file of files) {
const modulePath = path.join(extractorsDir, file);
const module = await import(pathToFileURL(path.resolve(modulePath)).href).catch((err) => {
if (err.message.includes('chrome is not defined')) {
global.chrome = {};
return import(pathToFileURL(path.resolve(modulePath)).href);
}
throw err;
});
const classImports = [];
for (const [exportName, exported] of Object.entries(module)) {
if (typeof exported === "function" && exported.prototype instanceof Extractor) {
const className = exportName;
classImports.push(className);
instances.push(` new ${className}(),`);
}
}
classImports.sort();
imports.push(`import { ${classImports.join(", ")} } from "./${file.replace(/\.js$/, "")}";`);
}
imports.sort();
instances.sort();
const content = `// Auto-generated file. Do not edit manually.
import { Extractor } from "./AbstractExtractor";
${imports.join("\n")}
/** @type{Extractor[]} */
const extractors = [
${instances.join("\n")}
];
/** @param {string} url */
function getExtractor(url) {
return extractors.find((ex) => ex.isSupported(url));
}
/** @param {string} url */
function isAllowedUrl(url) {
return getExtractor(url) != undefined;
}
/** @param {string} url */
function normalizeUrl(url) {
const extractor = getExtractor(url);
if (extractor) return extractor.normalizeUrl(url);
return Extractor.prototype.normalizeUrl.call(null, url);
}
export { extractors, getExtractor, isAllowedUrl, normalizeUrl };
`;
fs.writeFileSync(indexPath, content);
console.log("Generated extractors index.js");
}
async function main() {
try {
await generateExtractorsIndex();
} catch (err) {
console.error(err);
process.exit(1);
}
}
main();