BlueGit

timfa hfy-novels

Files

hfy-novels / scripts / test-plugin.js

test-plugin.js

test-plugin.js 10.6 KiB Download Raw
1#!/usr/bin/env node
2"use strict";
3
4/**
5 * Laadt de plugin zoals LNReader dat doet: custom require-allowlist,
6 * `new Function`, en daarna popularNovels / searchNovels / parseNovel /
7 * parseChapter. De index komt van een lokale HTTP-server (testdata of
8 * public/). parseChapter gebruikt een mock van Arctic Shift, plus
9 * optioneel een live verzoek als HFY_LIVE=1.
10 */
11
12const fs = require("fs");
13const http = require("http");
14const path = require("path");
15
16const ROOT = path.resolve(__dirname, "..");
17const PLUGIN = fs.readFileSync(path.join(ROOT, "plugin", "hfy-novels.js"), "utf8");
18
19const NovelStatus = {
20 Completed: "Completed",
21 Ongoing: "Ongoing",
22 OnHiatus: "On Hiatus",
23 Unknown: "Unknown",
24};
25const FilterTypes = { Picker: "Picker", Switch: "Switch", CheckboxGroup: "CheckboxGroup" };
26
27function mimeFor(file, asImg) {
28 if (file.endsWith(".svg")) return asImg ? "image/svg+xml" : "text/plain; charset=utf-8";
29 if (file.endsWith(".json")) return "text/plain; charset=utf-8"; // BlueGit serveert raw ook als text/plain
30 if (file.endsWith(".js")) return "text/plain; charset=utf-8";
31 if (file.endsWith(".png")) return "image/png";
32 return "application/octet-stream";
33}
34
35function startServer(rootDir, chapterHandler) {
36 return new Promise((resolve, reject) => {
37 const server = http.createServer((req, res) => {
38 const url = new URL(req.url, "http://127.0.0.1");
39 if (url.pathname.startsWith("/api/posts/ids")) {
40 return chapterHandler(url, res);
41 }
42 // ?rev=master zoals BlueGit raw-URLs; voor het bestand negeren we de query.
43 let rel = decodeURIComponent(url.pathname).replace(/^\/+/, "");
44 const file = path.join(rootDir, rel);
45 if (!file.startsWith(path.resolve(rootDir))) {
46 res.writeHead(403);
47 res.end("forbidden");
48 return;
49 }
50 fs.readFile(file, (err, data) => {
51 if (err) {
52 res.writeHead(404, { "Content-Type": "text/plain" });
53 res.end("404 " + rel);
54 return;
55 }
56 const asImg = url.searchParams.get("as") === "img";
57 res.writeHead(200, { "Content-Type": mimeFor(file, asImg) });
58 res.end(data);
59 });
60 });
61 server.listen(0, "127.0.0.1", () => {
62 const { port } = server.address();
63 resolve({ server, port, url: "http://127.0.0.1:" + port });
64 });
65 server.on("error", reject);
66 });
67}
68
69function defaultChapterHandler(url, res) {
70 const ids = url.searchParams.get("ids") || "";
71 const id = ids.split(",")[0];
72 const fixture = {
73 data: [
74 {
75 id,
76 title: "The Last Terran - Part 1",
77 author: "WriterOne",
78 selftext: "It begins.\n\n[Next](https://www.reddit.com/r/HFY/comments/aaa222/x/)",
79 selftext_html: "<p>It begins.</p>",
80 permalink: "/r/HFY/comments/" + id + "/",
81 },
82 ],
83 };
84 res.writeHead(200, { "Content-Type": "application/json" });
85 res.end(JSON.stringify(fixture));
86}
87
88async function fetchApi(url, init) {
89 const res = await fetch(url, init);
90 return {
91 ok: res.ok,
92 status: res.status,
93 headers: res.headers,
94 async text() {
95 return await res.text();
96 },
97 async json() {
98 const text = await res.text();
99 return JSON.parse(text);
100 },
101 url: res.url,
102 };
103}
104
105function loadPlugin(storageMap) {
106 const allow = {
107 "@libs/fetch": { fetchApi, fetchText: async (u, i) => (await fetchApi(u, i)).text() },
108 "@libs/filterInputs": { FilterTypes },
109 "@libs/defaultCover": { defaultCover: "https://example.invalid/cover.png" },
110 "@libs/novelStatus": { NovelStatus },
111 "@libs/storage": {
112 storage: {
113 get(key) {
114 return storageMap[key];
115 },
116 set(key, value) {
117 storageMap[key] = value;
118 },
119 },
120 },
121 };
122 const pluginModule = { exports: {} };
123 const fn = new Function("exports", "require", "module", PLUGIN);
124 fn(pluginModule.exports, (name) => {
125 if (!allow[name]) {
126 throw new Error("blocked require: " + name);
127 }
128 return allow[name];
129 }, pluginModule);
130 const plugin = pluginModule.exports.default;
131 if (!plugin) {
132 throw new Error("geen default export");
133 }
134 for (const method of ["popularNovels", "searchNovels", "parseNovel", "parseChapter"]) {
135 if (typeof plugin[method] !== "function") {
136 throw new Error("plugin mist " + method);
137 }
138 }
139 return plugin;
140}
141
142function assert(cond, msg) {
143 if (!cond) {
144 throw new Error("FAIL: " + msg);
145 }
146}
147
148async function main() {
149 const fixtureRoot = path.join(ROOT, "testdata", "index-fixture");
150 const { server, url } = await startServer(fixtureRoot, defaultChapterHandler);
151 const failures = [];
152 try {
153 const storageMap = {
154 indexBaseUrl: url,
155 indexRev: "", // geen ?rev= nodig op de testhost
156 chapterSourceUrl: url,
157 };
158 const plugin = loadPlugin(storageMap);
159
160 assert(plugin.id === "hfyNovels", "id");
161 assert(plugin.name === "HFY Novels", "name");
162 assert(plugin.version === "0.1.0", "version");
163 assert(plugin.site === "https://www.reddit.com/r/HFY/", "site");
164 assert(plugin.pluginSettings && plugin.pluginSettings.indexBaseUrl, "pluginSettings");
165
166 const popular = await plugin.popularNovels(1, { showLatestNovels: false, filters: {} });
167 assert(Array.isArray(popular) && popular.length >= 1, "popularNovels geeft items");
168 assert(popular[0].name && popular[0].path, "NovelItem heeft name+path");
169 assert(popular[0].cover && popular[0].cover.indexOf("/covers/") !== -1, "cover-URL wijst naar covers/");
170 const coverIsSvg = /\.svg(\?|$)/i.test(popular[0].cover);
171 if (coverIsSvg) {
172 assert(popular[0].cover.indexOf("as=img") !== -1, "SVG-cover heeft as=img");
173 }
174 const coverRes = await fetch(popular[0].cover);
175 assert(coverRes.ok, "cover is ophaalbaar");
176 const coverBuf = Buffer.from(await coverRes.arrayBuffer());
177 if (coverIsSvg) {
178 const coverBody = coverBuf.toString("utf8");
179 assert(coverBody.indexOf("<svg") === 0, "cover is een SVG");
180 assert(coverBody.indexOf(popular[0].name) !== -1, "cover toont de titel");
181 } else {
182 assert(coverBuf[0] === 0x89 && coverBuf.toString("ascii", 1, 4) === "PNG", "cover is een PNG");
183 }
184 const coverAgain = Buffer.from(await (await fetch(popular[0].cover)).arrayBuffer());
185 assert(Buffer.compare(coverBuf, coverAgain) === 0, "dezelfde titel geeft dezelfde cover");
186 assert(popular.every((n) => !n.path.includes("ccc001")), "NSFW standaard verborgen in catalogus");
187
188 const latest = await plugin.popularNovels(1, { showLatestNovels: true, filters: {} });
189 assert(latest.length >= 1, "showLatestNovels werkt via zoekindex");
190
191 const oneshots = await plugin.popularNovels(1, {
192 filters: { kind: { value: "oneshot" }, nsfw: { value: "hide" } },
193 });
194 assert(oneshots.length === 1 && oneshots[0].name === "A Short Hello", "filter oneshot");
195
196 const nsfw = await plugin.popularNovels(1, {
197 filters: { kind: { value: "all" }, nsfw: { value: "show" } },
198 });
199 assert(nsfw.some((n) => n.path.includes("ccc001")), "NSFW zichtbaar met filter");
200
201 const search = await plugin.searchNovels("terran", 1);
202 assert(search.length === 1 && search[0].path === "series/aaa111", "searchNovels op titel");
203 const byAuthor = await plugin.searchNovels("WriterTwo", 1);
204 assert(byAuthor.length === 1, "searchNovels op auteur");
205 assert((await plugin.searchNovels("", 1)).length === 0, "lege zoekterm");
206
207 const novel = await plugin.parseNovel("series/aaa111");
208 assert(novel.path === "series/aaa111", "SourceNovel.path gelijk aan input");
209 assert(novel.author === "WriterOne", "auteur");
210 assert(novel.cover && novel.cover.indexOf("/covers/") !== -1, "parseNovel heeft een cover-URL");
211 assert(novel.chapters.length === 3, "3 hoofdstukken");
212 assert(novel.chapters[0].path === "chapter/aaa111", "hoofdstukpad");
213 assert(novel.chapters[0].chapterNumber === 1, "hoofdstuknummer");
214 assert(novel.status === NovelStatus.Ongoing || novel.status === NovelStatus.OnHiatus || novel.status === NovelStatus.Unknown, "status enum");
215
216 const html = await plugin.parseChapter("chapter/aaa111");
217 assert(/It begins/.test(html), "parseChapter bevat tekst");
218 assert(/<h1>/.test(html), "parseChapter heeft titel");
219 assert(!/<script/i.test(html), "geen script-tags");
220
221 let threw = false;
222 try {
223 await plugin.parseChapter("chapter/../etc/passwd");
224 } catch (err) {
225 threw = true;
226 }
227 assert(threw, "ongeldig hoofdstuk-id wordt geweigerd");
228
229 // Manifest-vorm controleren.
230 const manifest = JSON.parse(fs.readFileSync(path.join(ROOT, ".dist", "plugins.json"), "utf8"));
231 assert(Array.isArray(manifest) && manifest.length === 1, "plugins.json is een array");
232 const entry = manifest[0];
233 for (const key of ["id", "name", "site", "lang", "version", "url", "iconUrl"]) {
234 assert(entry[key], "manifest mist " + key);
235 }
236 assert(entry.id === plugin.id && entry.version === plugin.version, "manifest komt overeen met plugin");
237 assert(entry.lang === "English", "lang is de volle taalnaam");
238 assert(entry.hasSettings === true, "hasSettings");
239 assert(entry.url.includes("/-/raw/.dist/hfy-novels.js"), "raw URL voor de plugin-JS");
240 assert(entry.url.includes("rev=master"), "rev=master in de plugin-URL");
241
242 console.log("✔️ plugininterface: popularNovels, searchNovels, parseNovel, parseChapter");
243 console.log("✔️ plugins.json komt overeen met de plugin-export");
244
245 if (process.env.HFY_LIVE === "1") {
246 const liveStorage = {
247 indexBaseUrl: url,
248 indexRev: "",
249 chapterSourceUrl: "https://arctic-shift.photon-reddit.com",
250 };
251 const livePlugin = loadPlugin(liveStorage);
252 // Een recent, echt post-id uit de Arctic Shift-probe: willekeurig een
253 // bekend kort id heeft geen zin. We vragen een recente HFY-post op.
254 const listing = await fetch(
255 "https://arctic-shift.photon-reddit.com/api/posts/search?subreddit=HFY&limit=1&sort=desc",
256 { headers: { "User-Agent": "HFY-Novels/0.1 (plugin live test)" } },
257 );
258 if (!listing.ok) {
259 throw new Error("live listing HTTP " + listing.status);
260 }
261 const body = await listing.json();
262 const liveId = body.data[0].id;
263 const liveHtml = await livePlugin.parseChapter("chapter/" + liveId);
264 assert(liveHtml.length > 20, "live parseChapter gaf inhoud");
265 console.log("✔️ live parseChapter via Arctic Shift (" + liveId + ", " + liveHtml.length + " tekens)");
266 }
267 } catch (err) {
268 failures.push(err);
269 } finally {
270 server.close();
271 }
272
273 if (failures.length) {
274 for (const err of failures) {
275 console.error(err);
276 }
277 process.exit(1);
278 }
279}
280
281main().catch((err) => {
282 console.error(err);
283 process.exit(1);
284});