/* eslint-disable no-console */ import Inject, { RegisterScoped } from "@entity-access/entity-access/dist/di/di.js"; import jsdom, { requestInterceptor } from "jsdom"; import CacheService from "../cache/CacheService.js"; import TempFileService from "../../storage/TempFileService.js"; import TimeSpan from "@entity-access/entity-access/dist/types/TimeSpan.js"; const { JSDOM } = jsdom; const waitForExist = (w) => new Promise((resolve) => { const rt = setTimeout(() => { console.warn(`pageReady not set, timed out`); resolve(); }, 15000); const ri = setInterval(() => { if (w.pageReady) { clearInterval(ri); clearTimeout(rt); resolve(); } }, 1000); }); // const strictSSL = globalEnv.strictSSL; // class SSRLoader extends jsdom. { // fetch(url: string, options: jsdom.FetchOptions) { // if(/^(img|video|link|iframe)/i.test(options?.element?.tagName)) { // return null; // } // return super.fetch(url, options); // } // } // const resources = new SSRLoader({ // strictSSL, // userAgent: "some-bot", // }); const fetchInterceptor = requestInterceptor((request, context) => { if(/^(img|video|link|frame)/i.test(context?.element?.tagName)) { return new Response(null, { status: 200 }); } request.headers.set("user-agent", "some-bot"); }); class SSRConsole extends jsdom.VirtualConsole { constructor(private list: string[], o) { super(o); const log = (... p: any[]) => { for (const item of p) { this.list.push(item.stack ?? item.toString()); } }; this.on("error", log); this.on("info", log); this.on("warn", log); this.on("dir", log); } } const changePrototype = (a, p) => { if (Array.isArray(a)) { Object.setPrototypeOf(a, p); return a; } if (typeof a !== "object") { return a; } for (const key in a) { if (Object.hasOwn(a, key)) { const element = a[key]; changePrototype(element, p); } } return a; }; @RegisterScoped export default class SSRService { @Inject cacheService: CacheService; @Inject tempFileService: TempFileService; async generate(location: string) { const key = `/ssr-cache/${location}`; return this.cacheService.get({ key, ttl: TimeSpan.fromSeconds(15), factory: async () => { console.log(`Fetching new ${location}`); const list = []; const virtualConsole = new SSRConsole(list, {}); const fqUrl = new URL(location); const fq = (ur: any) => { if (!ur.url) { // console.log(`Fetching ${ur}`); return new URL(ur.toString(), fqUrl).toString(); } return { ... ur, url: new URL(ur.url, fqUrl).toString() }; }; const { window } = await JSDOM.fromURL(location, { runScripts: "dangerously", resources: { interceptors: [fetchInterceptor] }, virtualConsole, beforeParse(w) { w.previewMode = true; class WResponse implements Response { headers: Headers; ok: boolean; redirected: boolean; status: number; statusText: string; type: ResponseType; url: string; get body(): ReadableStream { return this.r.body; } get bodyUsed(): boolean { return this.r.bodyUsed; } constructor(private r: Response) { this.headers = r.headers; this.ok = r.ok; this.redirected = r.redirected; this.status = r.status; this.statusText = r.statusText; this.type = r.type; this.url = r.url; } bytes() { return (this.r as any).bytes(); } clone(): Response { return new WResponse(this.r.clone()); } arrayBuffer(): Promise { return this.r.arrayBuffer(); } blob(): Promise { return this.r.blob(); } formData(): Promise { return this.r.formData(); } async json(): Promise { const data = await this.r.json(); // change prototype... return changePrototype(data, w.Array.prototype); } text(): Promise { return this.r.text(); } } w.fetch = async (url, i) => new WResponse(await fetch( fq(url), i)); }, }); await waitForExist(window); window.document.body.appendChild(window.document.createTextNode("\r\n")); const comment = window.document.createComment(list.join("\r\n")); window.document.body.appendChild(comment); window.document.body.appendChild(window.document.createTextNode("\r\n")); const buffer = Buffer.from(window.document.documentElement.outerHTML, "utf-8"); window.close(); return this.tempFileService.createFrom("file.html", buffer, "text/html"); } }); } }