BlueGit

timfa hfy-novels

Files

hfy-novels / scripts / test-plugin.js

test-plugin.js

test-plugin.js 31.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, searchNovels, popularNovels en parseNovel
9 * gebruiken gemockte Reddit-JSON, vallen terug op Arctic Shift en daarna
10 * op de statische index; optioneel een live verzoek als HFY_LIVE=1.
11 */
12
13const fs = require("fs");
14const http = require("http");
15const path = require("path");
16const zlib = require("zlib");
17
18const ROOT = path.resolve(__dirname, "..");
19const PLUGIN =
20 fs.readFileSync(path.join(ROOT, "plugin", "covers.js"), "utf8") +
21 "\n" +
22 fs.readFileSync(path.join(ROOT, "plugin", "hfy-novels.js"), "utf8");
23
24const NovelStatus = {
25 Completed: "Completed",
26 Ongoing: "Ongoing",
27 OnHiatus: "On Hiatus",
28 Unknown: "Unknown",
29};
30const FilterTypes = { Picker: "Picker", Switch: "Switch", CheckboxGroup: "CheckboxGroup" };
31
32function mimeFor(file, asImg) {
33 if (file.endsWith(".svg")) return asImg ? "image/svg+xml" : "text/plain; charset=utf-8";
34 if (file.endsWith(".json")) return "text/plain; charset=utf-8"; // BlueGit serveert raw ook als text/plain
35 if (file.endsWith(".js")) return "text/plain; charset=utf-8";
36 if (file.endsWith(".png")) return "image/png";
37 return "application/octet-stream";
38}
39
40function startServer(rootDir, chapterHandler, redditHandler) {
41 return new Promise((resolve, reject) => {
42 const server = http.createServer((req, res) => {
43 const url = new URL(req.url, "http://127.0.0.1");
44 if (url.pathname.startsWith("/api/posts/ids") || url.pathname.startsWith("/api/posts/search") || url.pathname.startsWith("/api/subreddits/wikis")) {
45 return chapterHandler(url, res);
46 }
47 if (redditHandler && /\/r\/HFY\//i.test(url.pathname)) {
48 return redditHandler(url, res, req);
49 }
50 if (redditHandler && url.pathname.startsWith("/api/info")) {
51 return redditHandler(url, res, req);
52 }
53 // ?rev=master zoals BlueGit raw-URLs; voor het bestand negeren we de query.
54 let rel = decodeURIComponent(url.pathname).replace(/^\/+/, "");
55 const file = path.join(rootDir, rel);
56 if (!file.startsWith(path.resolve(rootDir))) {
57 res.writeHead(403);
58 res.end("forbidden");
59 return;
60 }
61 fs.readFile(file, (err, data) => {
62 if (err) {
63 res.writeHead(404, { "Content-Type": "text/plain" });
64 res.end("404 " + rel);
65 return;
66 }
67 const asImg = url.searchParams.get("as") === "img";
68 res.writeHead(200, { "Content-Type": mimeFor(file, asImg) });
69 res.end(data);
70 });
71 });
72 server.listen(0, "127.0.0.1", () => {
73 const { port } = server.address();
74 resolve({ server, port, url: "http://127.0.0.1:" + port });
75 });
76 server.on("error", reject);
77 });
78}
79
80function redditListingFor(id) {
81 return [
82 {
83 kind: "Listing",
84 data: {
85 children: [
86 {
87 kind: "t3",
88 data: {
89 id,
90 title: "The Last Terran - Part 1",
91 author: "WriterOne",
92 selftext: "It begins.\n\n[Next](https://www.reddit.com/r/HFY/comments/aaa222/x/)",
93 selftext_html: "<div class=\"md\"><p>It begins.</p></div>",
94 permalink: "/r/HFY/comments/" + id + "/",
95 },
96 },
97 ],
98 },
99 },
100 { kind: "Listing", data: { children: [] } },
101 ];
102}
103
104function loginHtml() {
105 return "<!DOCTYPE html><html><head><title>reddit.com: Log in</title></head><body>Log in to Reddit to continue. <a href=\"https://www.reddit.com/login\">log in</a></body></html>";
106}
107
108function blockHtml() {
109 return "<body class=theme-beta><div>Request blocked. reason=lor2</div></body>";
110}
111
112function defaultRedditHandler(mode) {
113 return function redditHandler(url, res) {
114 const m = url.pathname.match(/\/comments\/([0-9a-z]{4,10})\//i);
115 if (!m) {
116 res.writeHead(404, { "Content-Type": "text/plain" });
117 res.end("no default reddit mock for " + url.pathname);
118 return;
119 }
120 const id = m[1].toLowerCase();
121 if (mode === "ok") {
122 res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
123 res.end(JSON.stringify(redditListingFor(id)));
124 return;
125 }
126 if (mode === "403") {
127 res.writeHead(403, { "Content-Type": "text/html; charset=utf-8" });
128 res.end(blockHtml());
129 return;
130 }
131 if (mode === "login-html") {
132 res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
133 res.end(loginHtml());
134 return;
135 }
136 res.writeHead(500, { "Content-Type": "text/plain" });
137 res.end("reddit mock error");
138 };
139}
140
141function defaultChapterHandler(url, res) {
142 if (!url.pathname.startsWith("/api/posts/ids")) {
143 res.writeHead(404, { "Content-Type": "text/plain" });
144 res.end("no default arctic mock for " + url.pathname);
145 return;
146 }
147 const ids = url.searchParams.get("ids") || "";
148 const id = ids.split(",")[0];
149 const fixture = {
150 data: [
151 {
152 id,
153 title: "The Last Terran - Part 1",
154 author: "WriterOne",
155 selftext: "It begins.\n\n[Next](https://www.reddit.com/r/HFY/comments/aaa222/x/)",
156 selftext_html: "<p>It begins.</p>",
157 permalink: "/r/HFY/comments/" + id + "/",
158 },
159 ],
160 };
161 res.writeHead(200, { "Content-Type": "application/json" });
162 res.end(JSON.stringify(fixture));
163}
164
165function wrapResponse(res) {
166 return {
167 ok: res.ok,
168 status: res.status,
169 headers: res.headers,
170 async text() {
171 return await res.text();
172 },
173 async json() {
174 const text = await res.text();
175 return JSON.parse(text);
176 },
177 url: res.url,
178 };
179}
180
181function makeFetchApi(origin) {
182 return async function fetchApi(url, init) {
183 let target = String(url);
184 // Stuur Reddit-JSON naar de lokale testhost, zodat we 200/403/login kunnen simuleren.
185 if (/^https?:\/\/(www\.|old\.)?reddit\.com\//i.test(target)) {
186 const parsed = new URL(target);
187 target = origin + parsed.pathname + parsed.search;
188 }
189 const res = await fetch(target, init);
190 return wrapResponse(res);
191 };
192}
193
194function loadPlugin(storageMap, fetchApi) {
195 const allow = {
196 "@libs/fetch": { fetchApi, fetchText: async (u, i) => (await fetchApi(u, i)).text() },
197 "@libs/filterInputs": { FilterTypes },
198 "@libs/defaultCover": { defaultCover: "https://example.invalid/cover.png" },
199 "@libs/novelStatus": { NovelStatus },
200 "@libs/storage": {
201 storage: {
202 get(key) {
203 return storageMap[key];
204 },
205 set(key, value, expires) {
206 storageMap[key] = value;
207 if (expires != null) {
208 storageMap[key + "__expires"] = expires;
209 }
210 },
211 },
212 },
213 };
214 const pluginModule = { exports: {} };
215 const fn = new Function("exports", "require", "module", PLUGIN);
216 fn(pluginModule.exports, (name) => {
217 if (!allow[name]) {
218 throw new Error("blocked require: " + name);
219 }
220 return allow[name];
221 }, pluginModule);
222 const plugin = pluginModule.exports.default;
223 if (!plugin) {
224 throw new Error("geen default export");
225 }
226 for (const method of ["popularNovels", "searchNovels", "parseNovel", "parseChapter"]) {
227 if (typeof plugin[method] !== "function") {
228 throw new Error("plugin mist " + method);
229 }
230 }
231 return plugin;
232}
233
234function assert(cond, msg) {
235 if (!cond) {
236 throw new Error("FAIL: " + msg);
237 }
238}
239
240function wikiIndexPayload(markdown) {
241 return { kind: "wikipage", data: { content_md: markdown, revision_date: 1700000000 } };
242}
243
244function listingOf(posts) {
245 return {
246 kind: "Listing",
247 data: {
248 children: posts.map((p) => ({ kind: "t3", data: p })),
249 after: null,
250 },
251 };
252}
253
254function samplePost(id, title, author, extras) {
255 const extra = extras || {};
256 return Object.assign(
257 {
258 id,
259 title,
260 author,
261 created_utc: extra.created_utc || 1700000000,
262 permalink: "/r/HFY/comments/" + id + "/",
263 selftext: extra.selftext || "",
264 selftext_html: extra.selftext_html || "",
265 link_flair_text: extra.flair || "OC-Series",
266 over_18: !!extra.over_18,
267 is_self: true,
268 },
269 extra.more || {},
270 );
271}
272
273async function testLiveCatalog(origin, fixtureRoot, fetchApi, assert) {
274 const wikiIndex = fs.readFileSync(path.join(ROOT, "testdata", "wiki", "index.md"), "utf8");
275 const wikiTerran = fs.readFileSync(path.join(ROOT, "testdata", "wiki", "pages", "the_last_terran.md"), "utf8");
276 const state = { redditMode: "ok", arcticMode: "ok", wikiHits: 0, searchHits: 0, arcticSearchHits: 0, arcticWikiHits: 0, infoHits: 0 };
277
278 function redditHandler(url, res) {
279 if (state.redditMode === "403") {
280 res.writeHead(403, { "Content-Type": "text/html; charset=utf-8" });
281 res.end(blockHtml());
282 return;
283 }
284 if (state.redditMode === "error") {
285 res.writeHead(500, { "Content-Type": "text/plain" });
286 res.end("reddit mock error");
287 return;
288 }
289 if (/\/wiki\/series\/the_last_terran/i.test(url.pathname)) {
290 state.wikiHits += 1;
291 res.writeHead(200, { "Content-Type": "application/json" });
292 res.end(JSON.stringify(wikiIndexPayload(wikiTerran)));
293 return;
294 }
295 if (/\/wiki\/series/i.test(url.pathname)) {
296 state.wikiHits += 1;
297 res.writeHead(200, { "Content-Type": "application/json" });
298 res.end(JSON.stringify(wikiIndexPayload(wikiIndex)));
299 return;
300 }
301 if (/\/search\.json$/i.test(url.pathname)) {
302 state.searchHits += 1;
303 const q = (url.searchParams.get("q") || "").toLowerCase();
304 const posts = [];
305 if (q.indexOf("terran") !== -1 || q.indexOf("writerone") !== -1) {
306 posts.push(
307 samplePost("aaa111", "[OC] The Last Terran - Part 1", "WriterOne", {
308 flair: "OC-FirstOfSeries",
309 selftext: "[Next](https://www.reddit.com/r/HFY/comments/aaa222/x/)",
310 }),
311 );
312 }
313 if (q.indexOf("star") !== -1 || q.indexOf("boat") !== -1) {
314 posts.push(
315 samplePost("ddd001", "[OC] Star Boat - Part 1", "Skipper", {
316 flair: "OC-FirstOfSeries",
317 selftext: "[Next](https://www.reddit.com/r/HFY/comments/ddd002/x/)",
318 created_utc: 1700345600,
319 }),
320 );
321 posts.push(
322 samplePost("ddd002", "Star Boat - Part 2", "Skipper", {
323 flair: "OC-Series",
324 selftext: "[Prev](https://www.reddit.com/r/HFY/comments/ddd001/x/)",
325 created_utc: 1700432000,
326 }),
327 );
328 }
329 res.writeHead(200, { "Content-Type": "application/json" });
330 res.end(JSON.stringify(listingOf(posts)));
331 return;
332 }
333 if (/\/new\.json$/i.test(url.pathname)) {
334 state.searchHits += 1;
335 res.writeHead(200, { "Content-Type": "application/json" });
336 res.end(
337 JSON.stringify(
338 listingOf([
339 samplePost("ddd001", "[OC] Star Boat - Part 1", "Skipper", {
340 flair: "OC-FirstOfSeries",
341 created_utc: 1700345600,
342 }),
343 samplePost("meta999", "[META] Weekly thread", "ModAccount", { flair: "Meta", created_utc: 1700345700 }),
344 samplePost("aaa444", "The Last Terran - Part 4", "WriterOne", {
345 flair: "OC-Series",
346 created_utc: 1700259200,
347 }),
348 ]),
349 ),
350 );
351 return;
352 }
353 if (url.pathname.startsWith("/api/info") || /\/comments\/[0-9a-z]+\//i.test(url.pathname)) {
354 state.infoHits += 1;
355 const ids = [];
356 if (url.searchParams.get("id")) {
357 url.searchParams.get("id").split(",").forEach((raw) => ids.push(raw.replace(/^t3_/, "").toLowerCase()));
358 } else {
359 const m = url.pathname.match(/\/comments\/([0-9a-z]{4,10})\//i);
360 if (m) ids.push(m[1].toLowerCase());
361 }
362 const posts = ids.map((id) => {
363 if (id === "aaa222") {
364 return samplePost(id, "The Last Terran - Part 2", "WriterOne", {
365 selftext: "[Prev](https://www.reddit.com/r/HFY/comments/aaa111/x/) | [Next](https://www.reddit.com/r/HFY/comments/aaa333/x/)",
366 });
367 }
368 if (id === "aaa333") {
369 return samplePost(id, "The Last Terran Chapter 3", "WriterOne", {
370 selftext: "[Previous](/r/HFY/comments/aaa222/)",
371 });
372 }
373 return samplePost(id, "The Last Terran - Part 1", "WriterOne", {
374 flair: "OC-FirstOfSeries",
375 selftext: "[Next](https://www.reddit.com/r/HFY/comments/aaa222/x/)",
376 });
377 });
378 res.writeHead(200, { "Content-Type": "application/json" });
379 if (/\/comments\//i.test(url.pathname)) {
380 res.end(JSON.stringify(redditListingFor(ids[0] || "aaa111")));
381 } else {
382 res.end(JSON.stringify(listingOf(posts)));
383 }
384 return;
385 }
386 res.writeHead(404, { "Content-Type": "text/plain" });
387 res.end("no reddit mock for " + url.pathname);
388 }
389
390 function arcticHandler(url, res) {
391 if (url.pathname.startsWith("/api/subreddits/wikis")) {
392 state.arcticWikiHits += 1;
393 if (state.arcticMode === "fail") {
394 res.writeHead(500, { "Content-Type": "text/plain" });
395 res.end("arctic wiki fail");
396 return;
397 }
398 const paths = url.searchParams.get("paths") || "";
399 const content = /the_last_terran/.test(paths) ? wikiTerran : wikiIndex;
400 res.writeHead(200, { "Content-Type": "application/json" });
401 res.end(JSON.stringify({ data: [{ path: paths, content }] }));
402 return;
403 }
404 if (url.pathname.startsWith("/api/posts/search")) {
405 state.arcticSearchHits += 1;
406 if (state.arcticMode === "fail") {
407 res.writeHead(500, { "Content-Type": "text/plain" });
408 res.end("arctic search fail");
409 return;
410 }
411 const q = ((url.searchParams.get("query") || "") + " " + (url.searchParams.get("title") || "")).toLowerCase();
412 const posts = [];
413 if (!q.trim() || q.indexOf("star") !== -1 || q.indexOf("boat") !== -1) {
414 posts.push(
415 samplePost("ddd001", "[OC] Star Boat - Part 1", "Skipper", {
416 flair: "OC-FirstOfSeries",
417 created_utc: 1700345600,
418 }),
419 );
420 }
421 res.writeHead(200, { "Content-Type": "application/json" });
422 res.end(JSON.stringify({ data: posts }));
423 return;
424 }
425 if (url.pathname.startsWith("/api/posts/ids")) {
426 return defaultChapterHandler(url, res);
427 }
428 res.writeHead(404);
429 res.end("no arctic mock");
430 }
431
432 const started = await startServer(fixtureRoot, arcticHandler, redditHandler);
433 const liveFetch = makeFetchApi(started.url);
434 try {
435 const storageMap = {
436 indexBaseUrl: origin,
437 indexRev: "",
438 chapterSourceUrl: started.url,
439 chapterSource: "auto",
440 };
441 const plugin = loadPlugin(storageMap, liveFetch);
442
443 state.wikiHits = 0;
444 const popular = await plugin.popularNovels(1, { showLatestNovels: false, filters: {} });
445 assert(popular.some((n) => n.name === "The Last Terran"), "live wiki-index levert The Last Terran");
446 assert(popular.some((n) => n.path.indexOf("the_last_terran") !== -1 || n.path === "wiki/the_last_terran"), "wiki-pad zonder first-id");
447 const hitsAfterFirst = state.wikiHits;
448 assert(hitsAfterFirst >= 1, "wiki-index is bij Reddit opgehaald");
449 const popularAgain = await plugin.popularNovels(1, { filters: {} });
450 assert(popularAgain.some((n) => n.name === "The Last Terran"), "cache levert opnieuw de wiki-index");
451 assert(state.wikiHits === hitsAfterFirst, "tweede popularNovels gebruikt de wiki-cache");
452 const liveCover = popular.find((n) => n.name === "The Last Terran").cover;
453 assertPngDataUri(liveCover, "live wiki-cover");
454 assert(
455 popularAgain.find((n) => n.name === "The Last Terran").cover === liveCover,
456 "dezelfde live-titel geeft dezelfde cover-URI",
457 );
458
459 const latest = await plugin.popularNovels(1, { showLatestNovels: true, filters: {} });
460 assert(latest.some((n) => /Star Boat/i.test(n.name)), "Latest/Nieuw toont recente OC-reeks");
461 assert(latest.every((n) => !/Weekly thread/i.test(n.name)), "Meta-posts blijven buiten Nieuw");
462 const viaFilter = await plugin.popularNovels(1, { filters: { catalog: { value: "new" } } });
463 assert(viaFilter.some((n) => /Star Boat/i.test(n.name)), "filter Nieuw toont recente OC-posts");
464
465 const search = await plugin.searchNovels("terran", 1);
466 assert(search.some((n) => /Last Terran/i.test(n.name)), "searchNovels groepeert wiki + Part 1");
467 const star = await plugin.searchNovels("Star Boat", 1);
468 assert(star.length === 1 && /Star Boat/i.test(star[0].name), "losse Part 1+2 worden één novel");
469 assert(star[0].path === "series/ddd001", "nieuwe reeks gebruikt het eerste deel als id");
470 assertPngDataUri(star[0].cover, "live zoek-cover zonder index-PNG");
471
472 const novel = await plugin.parseNovel("wiki/the_last_terran");
473 assert(novel.name === "The Last Terran", "parseNovel gebruikt de wiki-titel");
474 assert(novel.author === "WriterOne", "parseNovel leest de auteur uit de wiki");
475 assert(novel.chapters.length === 3, "parseNovel volgt de wiki-TOC");
476 assert(novel.chapters[0].path === "chapter/aaa111", "eerste hoofdstukpad");
477 assert(novel.chapters[2].path === "chapter/aaa333", "laatste TOC-hoofdstuk");
478 assertPngDataUri(novel.cover, "parseNovel live-cover");
479
480 delete storageMap.wikiSeriesIndex;
481 state.redditMode = "403";
482 state.arcticMode = "ok";
483 state.arcticWikiHits = 0;
484 const plugin403 = loadPlugin(storageMap, liveFetch);
485 const popular403 = await plugin403.popularNovels(1, { filters: {} });
486 assert(popular403.some((n) => n.name === "The Last Terran"), "403 valt terug op Arctic Shift-wiki");
487 assert(state.arcticWikiHits >= 1, "403 roept Arctic Shift-wiki aan");
488
489 const search403 = await plugin403.searchNovels("Star Boat", 1);
490 assert(search403.some((n) => /Star Boat/i.test(n.name)), "zoeken valt bij 403 terug op Arctic Shift");
491
492 delete storageMap.wikiSeriesIndex;
493 state.redditMode = "403";
494 state.arcticMode = "fail";
495 const pluginStatic = loadPlugin(storageMap, liveFetch);
496 const popularStatic = await pluginStatic.popularNovels(1, { filters: {} });
497 assert(popularStatic.some((n) => n.path === "series/aaa111"), "na Reddit+Arctic Shift volgt de statische index");
498 const searchStatic = await pluginStatic.searchNovels("terran", 1);
499 assert(searchStatic.length === 1 && searchStatic[0].path === "series/aaa111", "zoeken valt terug op de statische index");
500
501 console.log("✔️ live catalogus: wiki, Nieuw, zoeken, parseNovel, 403→Arctic Shift→index");
502 } finally {
503 started.server.close();
504 }
505}
506
507
508
509function u32be(buf, offset) {
510 return buf.readUInt32BE(offset);
511}
512
513function assertPngDataUri(uri, label) {
514 assert(typeof uri === "string" && uri.indexOf("data:image/png;base64,") === 0, label + " is data:image/png;base64");
515 const buf = Buffer.from(uri.slice("data:image/png;base64,".length), "base64");
516 assert(buf[0] === 0x89 && buf.toString("ascii", 1, 4) === "PNG", label + " heeft PNG-signatuur");
517 assert(buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a, label + " heeft geldige PNG-header");
518 assert(u32be(buf, 8) === 13 && buf.toString("ascii", 12, 16) === "IHDR", label + " begint met IHDR");
519 assert(u32be(buf, 16) === 240 && u32be(buf, 20) === 360, label + " is 240x360");
520 assert(buf[24] === 8 && buf[25] === 3, label + " is 8-bit geïndexeerd");
521 let pos = 8;
522 const idats = [];
523 let sawIend = false;
524 while (pos + 12 <= buf.length) {
525 const len = u32be(buf, pos);
526 const typ = buf.toString("ascii", pos + 4, pos + 8);
527 const data = buf.subarray(pos + 8, pos + 8 + len);
528 if (typ === "IDAT") idats.push(data);
529 if (typ === "IEND") {
530 sawIend = true;
531 break;
532 }
533 pos += 12 + len;
534 }
535 assert(idats.length >= 1 && sawIend, label + " heeft IDAT en IEND");
536 const rows = zlib.inflateSync(Buffer.concat(idats));
537 assert(rows.length === (1 + 240) * 360, label + " IDAT inflateert tot 240x360 rijen");
538}
539
540function testGeneratedCovers(plugin) {
541 const utils = plugin.coverUtils;
542 assert(utils && typeof utils.coverDataUri === "function", "CoverUtils is beschikbaar");
543 const title = "The Last Terran";
544 assert(
545 utils.titleHash(title) === "d7f66e3b1fef9c0a266fca7c6121f6d3d30f66f6570acecc3ce39bd8875f1320",
546 "titelhash komt overeen met SHA-256",
547 );
548 assert(utils.titleHash(" The Last Terran ") === utils.titleHash(title), "whitespace wijzigt de hash niet");
549 const uri = utils.coverDataUri(title);
550 const uriAgain = utils.coverDataUri(title);
551 const uriTrim = utils.coverDataUri(" The Last Terran ");
552 assert(uri === uriAgain && uri === uriTrim, "dezelfde titel geeft dezelfde cover-bytes");
553 assert(utils.coverDataUri("A Short Hello") !== uri, "een andere titel geeft een andere cover");
554 assertPngDataUri(uri, "gegenereerde cover");
555
556 const longTitle =
557 "Wearing Power Armor to a Magic School After the Council Meeting and the Unexpected Arrival of the Third Diplomatic Envoy";
558 const layout = utils.chooseLayout(longTitle);
559 assert(layout.fontSize === 16 && layout.lines.length >= 3, "lange titel gebruikt een kleinere letter en meerdere regels");
560 assert(layout.lines.length <= 8, "lange titel blijft binnen het maximum aantal regels");
561 layout.lines.forEach((line) => {
562 assert(line.length > 0, "geen lege wrap-regel");
563 });
564 assert(
565 JSON.stringify(layout.lines) ===
566 JSON.stringify([
567 "Wearing Power Armor",
568 "to a Magic School",
569 "After the Council",
570 "Meeting and the",
571 "Unexpected Arrival",
572 "of the Third",
573 "Diplomatic Envoy",
574 ]),
575 "wrap van de lange testditel komt overeen",
576 );
577 const longUri = utils.coverDataUri(longTitle);
578 assertPngDataUri(longUri, "lange-titelcover");
579 assert(utils.coverDataUri(longTitle) === longUri, "lange titel is deterministisch");
580 console.log("✔️ gegenereerde titelcovers: hash, PNG 240x360, wrap, determinisme");
581}
582
583
584async function main() {
585 const fixtureRoot = path.join(ROOT, "testdata", "index-fixture");
586 const redditState = { mode: "ok", redditHits: 0, arcticHits: 0 };
587 const chapterHandler = (reqUrl, res) => {
588 redditState.arcticHits += 1;
589 return defaultChapterHandler(reqUrl, res);
590 };
591 const redditHandler = (reqUrl, res) => {
592 redditState.redditHits += 1;
593 return defaultRedditHandler(redditState.mode)(reqUrl, res);
594 };
595 const { server, url } = await startServer(fixtureRoot, chapterHandler, redditHandler);
596 const fetchApi = makeFetchApi(url);
597 const failures = [];
598 try {
599 const storageMap = {
600 indexBaseUrl: url,
601 indexRev: "", // geen ?rev= nodig op de testhost
602 chapterSourceUrl: url,
603 chapterSource: "auto",
604 };
605 const plugin = loadPlugin(storageMap, fetchApi);
606
607 assert(plugin.id === "hfyNovels", "id");
608 assert(plugin.name === "HFY Novels", "name");
609 assert(plugin.version === "0.3.1", "version");
610 assert(plugin.site === "https://www.reddit.com/r/HFY/", "site");
611 assert(plugin.pluginSettings && plugin.pluginSettings.indexBaseUrl, "pluginSettings");
612 assert(plugin.filters && plugin.filters.catalog, "filter Nieuw/wiki");
613 assert(plugin.pluginSettings.chapterSource && plugin.pluginSettings.chapterSource.type === "Select", "bron-instelling is Select");
614 assert(typeof plugin.resolveUrl === "function", "resolveUrl");
615 assert(plugin.resolveUrl("chapter/aaa111") === "https://www.reddit.com/r/HFY/comments/aaa111/", "resolveUrl hoofdstuk");
616 assert(plugin.resolveUrl("series/aaa111", true) === "https://www.reddit.com/r/HFY/comments/aaa111/", "resolveUrl reeks");
617 assert(plugin.resolveUrl("wiki/the_last_terran", true) === "https://www.reddit.com/r/HFY/wiki/series/the_last_terran/", "resolveUrl wiki");
618
619 testGeneratedCovers(plugin);
620
621 const popular = await plugin.popularNovels(1, { showLatestNovels: false, filters: {} });
622 assert(Array.isArray(popular) && popular.length >= 1, "popularNovels geeft items");
623 assert(popular[0].name && popular[0].path, "NovelItem heeft name+path");
624 assert(popular[0].cover && popular[0].cover.indexOf("/covers/") !== -1, "cover-URL wijst naar covers/");
625 const coverIsSvg = /\.svg(\?|$)/i.test(popular[0].cover);
626 if (coverIsSvg) {
627 assert(popular[0].cover.indexOf("as=img") !== -1, "SVG-cover heeft as=img");
628 }
629 const coverRes = await fetch(popular[0].cover);
630 assert(coverRes.ok, "cover is ophaalbaar");
631 const coverBuf = Buffer.from(await coverRes.arrayBuffer());
632 if (coverIsSvg) {
633 const coverBody = coverBuf.toString("utf8");
634 assert(coverBody.indexOf("<svg") === 0, "cover is een SVG");
635 assert(coverBody.indexOf(popular[0].name) !== -1, "cover toont de titel");
636 } else {
637 assert(coverBuf[0] === 0x89 && coverBuf.toString("ascii", 1, 4) === "PNG", "cover is een PNG");
638 }
639 const coverAgain = Buffer.from(await (await fetch(popular[0].cover)).arrayBuffer());
640 assert(Buffer.compare(coverBuf, coverAgain) === 0, "dezelfde titel geeft dezelfde cover");
641 assert(popular.every((n) => !n.path.includes("ccc001")), "NSFW standaard verborgen in catalogus");
642
643 const latest = await plugin.popularNovels(1, { showLatestNovels: true, filters: {} });
644 assert(latest.length >= 1, "showLatestNovels werkt via zoekindex");
645
646 const oneshots = await plugin.popularNovels(1, {
647 filters: { kind: { value: "oneshot" }, nsfw: { value: "hide" } },
648 });
649 assert(oneshots.length === 1 && oneshots[0].name === "A Short Hello", "filter oneshot");
650
651 const nsfw = await plugin.popularNovels(1, {
652 filters: { kind: { value: "all" }, nsfw: { value: "show" } },
653 });
654 assert(nsfw.some((n) => n.path.includes("ccc001")), "NSFW zichtbaar met filter");
655
656 const search = await plugin.searchNovels("terran", 1);
657 assert(search.length === 1 && search[0].path === "series/aaa111", "searchNovels op titel");
658 const byAuthor = await plugin.searchNovels("WriterTwo", 1);
659 assert(byAuthor.length === 1, "searchNovels op auteur");
660 assert((await plugin.searchNovels("", 1)).length === 0, "lege zoekterm");
661
662 const novel = await plugin.parseNovel("series/aaa111");
663 assert(novel.path === "series/aaa111", "SourceNovel.path gelijk aan input");
664 assert(novel.author === "WriterOne", "auteur");
665 assert(novel.cover && novel.cover.indexOf("/covers/") !== -1, "parseNovel heeft een cover-URL");
666 assert(novel.chapters.length === 3, "3 hoofdstukken");
667 assert(novel.chapters[0].path === "chapter/aaa111", "hoofdstukpad");
668 assert(novel.chapters[0].chapterNumber === 1, "hoofdstuknummer");
669 assert(novel.status === NovelStatus.Ongoing || novel.status === NovelStatus.OnHiatus || novel.status === NovelStatus.Unknown, "status enum");
670
671 redditState.mode = "ok";
672 redditState.redditHits = 0;
673 redditState.arcticHits = 0;
674 const html = await plugin.parseChapter("chapter/aaa111");
675 assert(/It begins/.test(html), "parseChapter bevat tekst");
676 assert(/<h1>/.test(html), "parseChapter heeft titel");
677 assert(!/<script/i.test(html), "geen script-tags");
678 assert(/Bron: Reddit/.test(html), "Reddit-ok toont Bron: Reddit");
679 assert(redditState.arcticHits === 0, "bij Reddit-ok geen Arctic Shift-aanroep");
680 assert(redditState.redditHits >= 1, "Reddit-JSON is aangeroepen");
681
682 redditState.mode = "403";
683 redditState.redditHits = 0;
684 redditState.arcticHits = 0;
685 const html403 = await plugin.parseChapter("chapter/aaa111");
686 assert(/It begins/.test(html403), "403 valt terug op Arctic Shift");
687 assert(/Bron: Arctic Shift \(fallback\)/.test(html403), "403 toont fallback-bron");
688 assert(redditState.arcticHits >= 1, "403 roept Arctic Shift aan");
689 assert(redditState.redditHits >= 1, "403 probeert eerst Reddit");
690
691 redditState.mode = "login-html";
692 redditState.redditHits = 0;
693 redditState.arcticHits = 0;
694 const htmlLogin = await plugin.parseChapter("chapter/aaa111");
695 assert(/It begins/.test(htmlLogin), "login-HTML valt terug op Arctic Shift");
696 assert(/Bron: Arctic Shift \(fallback\)/.test(htmlLogin), "login-HTML toont fallback-bron");
697 assert(redditState.arcticHits >= 1, "login-HTML roept Arctic Shift aan");
698
699 storageMap.chapterSource = "reddit";
700 redditState.mode = "403";
701 redditState.arcticHits = 0;
702 let redditOnlyThrew = false;
703 try {
704 await plugin.parseChapter("chapter/aaa111");
705 } catch (err) {
706 redditOnlyThrew = /Reddit/.test(String(err && err.message)) && /WebView/.test(String(err && err.message));
707 }
708 assert(redditOnlyThrew, "modus Reddit faalt zichtbaar bij 403");
709 assert(redditState.arcticHits === 0, "modus Reddit gebruikt geen fallback");
710
711 storageMap.chapterSource = "arctic";
712 redditState.mode = "ok";
713 redditState.redditHits = 0;
714 redditState.arcticHits = 0;
715 const htmlArctic = await plugin.parseChapter("chapter/aaa111");
716 assert(/Bron: Arctic Shift</.test(htmlArctic) && !/fallback/.test(htmlArctic), "modus Arctic Shift slaat Reddit over");
717 assert(redditState.redditHits === 0, "modus Arctic Shift roept Reddit niet aan");
718 assert(redditState.arcticHits >= 1, "modus Arctic Shift gebruikt Arctic Shift");
719 storageMap.chapterSource = "auto";
720
721 let threw = false;
722 try {
723 await plugin.parseChapter("chapter/../etc/passwd");
724 } catch (err) {
725 threw = true;
726 }
727 assert(threw, "ongeldig hoofdstuk-id wordt geweigerd");
728
729 // --- Live catalogus: wiki, zoeken, parseNovel, met fallbacks ---
730 await testLiveCatalog(url, fixtureRoot, fetchApi, assert);
731
732 // Manifest-vorm controleren.
733 const manifest = JSON.parse(fs.readFileSync(path.join(ROOT, ".dist", "plugins.json"), "utf8"));
734 const manifestMin = JSON.parse(fs.readFileSync(path.join(ROOT, ".dist", "plugins.min.json"), "utf8"));
735 assert(Array.isArray(manifest) && manifest.length === 1, "plugins.json is een array");
736 assert(manifestMin[0].version === manifest[0].version, "plugins.min.json heeft dezelfde versie");
737 const entry = manifest[0];
738 for (const key of ["id", "name", "site", "lang", "version", "url", "iconUrl"]) {
739 assert(entry[key], "manifest mist " + key);
740 }
741 assert(entry.id === plugin.id && entry.version === plugin.version, "manifest komt overeen met plugin");
742 assert(entry.lang === "English", "lang is de volle taalnaam");
743 assert(entry.hasSettings === true, "hasSettings");
744 assert(entry.url.includes("/-/raw/.dist/hfy-novels.js"), "raw URL voor de plugin-JS");
745 assert(entry.url.includes("rev=master"), "rev=master in de plugin-URL");
746
747 console.log("✔️ plugininterface: popularNovels, searchNovels, parseNovel, parseChapter");
748 console.log("✔️ plugins.json komt overeen met de plugin-export");
749
750 if (process.env.HFY_LIVE === "1") {
751 const liveStorage = {
752 indexBaseUrl: url,
753 indexRev: "",
754 chapterSourceUrl: "https://arctic-shift.photon-reddit.com",
755 };
756 const livePlugin = loadPlugin(liveStorage, async (reqUrl, init) => wrapResponse(await fetch(reqUrl, init)));
757 // Een recent, echt post-id uit de Arctic Shift-probe: willekeurig een
758 // bekend kort id heeft geen zin. We vragen een recente HFY-post op.
759 const listing = await fetch(
760 "https://arctic-shift.photon-reddit.com/api/posts/search?subreddit=HFY&limit=1&sort=desc",
761 { headers: { "User-Agent": "HFY-Novels/0.1 (plugin live test)" } },
762 );
763 if (!listing.ok) {
764 throw new Error("live listing HTTP " + listing.status);
765 }
766 const body = await listing.json();
767 const liveId = body.data[0].id;
768 const liveHtml = await livePlugin.parseChapter("chapter/" + liveId);
769 assert(liveHtml.length > 20, "live parseChapter gaf inhoud");
770 const liveSource = /Bron: ([^<]+)/.exec(liveHtml);
771 console.log("✔️ live parseChapter (" + liveId + ", " + liveHtml.length + " tekens, " + ((liveSource && liveSource[1]) || "bron onbekend") + ")");
772 }
773 } catch (err) {
774 failures.push(err);
775 } finally {
776 server.close();
777 }
778
779 if (failures.length) {
780 for (const err of failures) {
781 console.error(err);
782 }
783 process.exit(1);
784 }
785}
786
787main().catch((err) => {
788 console.error(err);
789 process.exit(1);
790});