diff --git a/src/SEQTA.boot.test.ts b/src/SEQTA.boot.test.ts index 1960d932..7f57ec19 100644 --- a/src/SEQTA.boot.test.ts +++ b/src/SEQTA.boot.test.ts @@ -2,23 +2,27 @@ import { execFileSync } from "node:child_process"; import { runInNewContext } from "node:vm"; -// Compile the actual Vite entry in Node (esbuild cannot run in jsdom's realm). -const bootScript = execFileSync( - process.execPath, - [ - "--input-type=module", - "-e", - ` +// Compile the actual Vite entry and the 404 boot it loads in Node (esbuild +// cannot run in jsdom's realm). +const [bootScript, errorPageScript]: string[] = JSON.parse( + execFileSync( + process.execPath, + [ + "--input-type=module", + "-e", + ` import { readFileSync } from "node:fs"; import { transformSync } from "esbuild"; - process.stdout.write(transformSync(readFileSync("src/SEQTA.ts", "utf8"), { + const compile = (file) => transformSync(readFileSync(file, "utf8"), { loader: "ts", format: "cjs", supported: { "dynamic-import": false }, define: { "import.meta.env.DEV": "false", "import.meta.hot": "undefined" }, - }).code); + }).code; + process.stdout.write(JSON.stringify(["src/SEQTA.ts", "src/seqta/bootErrorPage.ts"].map(compile))); `, - ], - { encoding: "utf8" }, + ], + { encoding: "utf8" }, + ), ); test.each([{ onoff: false }, { "plugin.error-page-kitten.settings": { enabled: false } }])( @@ -27,19 +31,32 @@ test.each([{ onoff: false }, { "plugin.error-page-kitten.settings": { enabled: f document.head.innerHTML = ""; document.body.innerHTML = '
Page not found
'; const mount = jest.fn(); + const requireMock = (module: string): unknown => { + if (module === "@/seqta/bootErrorPage") { + const loaded = { exports: {} }; + runInNewContext(errorPageScript, { + document, + window, + console, + module: loaded, + exports: loaded.exports, + require: requireMock, + }); + return loaded.exports; + } + if (module === "@/lib/browser") { + return { storage: { local: { get: async () => stored } } }; + } + if (module.includes("errorPageKitten")) { + return { isSeqta404Page: () => true, mountErrorPageKitten: mount }; + } + return {}; + }; runInNewContext(bootScript, { document, window, console, - require: (module: string) => { - if (module === "@/lib/browser") { - return { storage: { local: { get: async () => stored } } }; - } - if (module.includes("errorPageKitten")) { - return { isSeqta404Page: () => true, mountErrorPageKitten: mount }; - } - return {}; - }, + require: requireMock, }); for (let i = 0; i < 10; i++) await Promise.resolve(); diff --git a/src/SEQTA.ts b/src/SEQTA.ts index 848cf5ed..f1b72e1c 100644 --- a/src/SEQTA.ts +++ b/src/SEQTA.ts @@ -1,236 +1,32 @@ -import { initializeSettingsState, settingsState } from "@/seqta/utils/listeners/SettingsState"; -import documentLoadCSS from "@/css/documentload.scss?inline"; -import icon48 from "@/resources/icons/icon-48.png?base64"; -import browser from "@/lib/browser"; +// This content script runs on every website, so it only checks whether the page +// is SEQTA and loads the rest of the extension on demand. Importing seqta/boot +// statically here made every site download and parse the whole bundle. -import { main } from "@/seqta/main"; -import { delay } from "./seqta/utils/delay"; -import { initializeHideSensitiveToggle } from "@/seqta/utils/hideSensitiveToggle"; -import { installSeqtaMenuColourPatch } from "@/seqta/utils/patchSeqtaMenuUpdateColours"; -import { installThemeImagePagePatch } from "@/seqta/utils/patchThemeImagesPageContext"; -import { initVerboseLogging, verboseInfo } from "@/utils/verboseLog"; -import { - hydrateRemoteConfigFromStorage, - installRemoteConfigStorageListener, - isEffectiveBsplusEnabled, - notifyRemoteConfigPageContext, - ensureKilledModeSettingsAccess, -} from "@/seqta/utils/remoteConfig/runtime"; -import { runStartupPopupQueue } from "@/seqta/utils/openers/StartupPopupQueue"; +import { recoverFromStaleDevModuleGraph } from "@/seqta/devModuleGraphRecovery"; -function registerFetchSeqtaAppLinkListener() { - browser.runtime.onMessage.addListener((request, _sender, sendResponse) => { - if (request?.type !== "fetchSeqtaAppLink") return false; - void (async () => { - try { - const res = await fetch(`${location.origin}/seqta/student/load/profile`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - credentials: "include", - body: JSON.stringify({}), - }); - const data = await res.json(); - const statusOk = data?.status === "200" || data?.status === 200; - const raw = data?.payload?.app_link; - const appLink = typeof raw === "string" && raw.length > 0 ? raw : null; - sendResponse({ appLink: statusOk ? appLink : null }); - } catch { - sendResponse({ appLink: null }); - } - })(); - return true; - }); -} - -let IsSEQTAPage = false; let hasSEQTAText = false; +let isSeqtaPage = false; // This check is placed outside of the document load event due to issues with EP (https://github.com/BetterSEQTA/BetterSEQTA-Plus/issues/84) if (document.childNodes[1]) { hasSEQTAText = document.childNodes[1].textContent?.includes("Copyright (c) SEQTA Software") ?? false; - if (hasSEQTAText) { - installSeqtaMenuColourPatch(); - installThemeImagePagePatch(); - } - init(); + isSeqtaPage = + hasSEQTAText && + (document.title.includes("SEQTA Learn") || document.title.includes("SEQTA Engage")); +} + +if (hasSEQTAText) { + void import("@/seqta/boot").then(({ boot }) => boot()); } // Standalone 404 documents never pass the SEQTA SPA gate above. -void bootErrorPage(); +if (!isSeqtaPage) { + void import("@/seqta/bootErrorPage").then(({ bootErrorPage }) => bootErrorPage()); +} if (import.meta.env.DEV) { window.addEventListener("unhandledrejection", (event) => { recoverFromStaleDevModuleGraph(event.reason); }); } - -async function init() { - if ( - hasSEQTAText && - (document.title.includes("SEQTA Learn") || document.title.includes("SEQTA Engage")) && - !IsSEQTAPage - ) { - IsSEQTAPage = true; - verboseInfo("[BetterSEQTA+] Verified SEQTA Page"); - - registerFetchSeqtaAppLinkListener(); - - const documentLoadStyle = document.createElement("style"); - documentLoadStyle.textContent = documentLoadCSS; - document.head.appendChild(documentLoadStyle); - - replaceIcons(); - - const observer = new MutationObserver((mutations) => { - for (const mutation of mutations) { - if ( - mutation.type === "attributes" && - mutation.target instanceof HTMLLinkElement && - mutation.target.rel.includes("icon") && - mutation.attributeName === "href" - ) { - replaceIcons(); - return; - } - } - }); - - observer.observe(document.head, { - subtree: true, - attributes: true, - attributeFilter: ["href"], - }); - - try { - await initializeSettingsState(); - initVerboseLogging(); - - if (typeof settingsState.onoff === "undefined") { - await browser.runtime.sendMessage({ type: "setDefaultStorage" }); - - await delay(5); - } - - await hydrateRemoteConfigFromStorage(); - notifyRemoteConfigPageContext(location.hostname); - installRemoteConfigStorageListener(() => { - location.reload(); - }); - - const bsplusEnabled = isEffectiveBsplusEnabled(); - - if (bsplusEnabled) { - await main(); - - const { init: Monofile } = await import("@/plugins/monofile"); - Monofile(); - - if (settingsState.onoff) { - const { initializePlugins } = await import("@/plugins/index"); - await initializePlugins(); - } - } else { - await ensureKilledModeSettingsAccess(); - void runStartupPopupQueue(); - } - - if (settingsState.devMode) { - initializeHideSensitiveToggle(); - } - - if (import.meta.env.DEV) { - sessionStorage.removeItem("bsplus-dev-export-recovery"); - } - - verboseInfo("[BetterSEQTA+] Successfully initialised BetterSEQTA+, starting to load assets."); - } catch (error) { - console.error(error); - recoverFromStaleDevModuleGraph(error); - } - } -} - -/** Hide the rebranded 404 before the kitten card mounts (removed after boot). */ -function inject404FlashHide(): void { - if (document.getElementById("bsplus-404-flash-hide")) return; - const style = document.createElement("style"); - style.id = "bsplus-404-flash-hide"; - style.textContent = "html,body{background:#333!important}.message{display:none!important}"; - (document.head ?? document.documentElement).appendChild(style); -} - -async function bootErrorPage() { - if (IsSEQTAPage) return; - - const { isSeqta404Page, mountErrorPageKitten } = - await import("@/plugins/built-in/errorPageKitten"); - - const storagePromise = browser.storage.local.get(["onoff", "plugin.error-page-kitten.settings"]); - - const watchTitle = () => { - if (isSeqta404Page()) inject404FlashHide(); - }; - watchTitle(); - if (document.readyState === "loading") { - document.addEventListener("readystatechange", watchTitle); - } - - if (document.readyState === "loading") { - await new Promise((resolve) => { - document.addEventListener("DOMContentLoaded", () => resolve(), { once: true }); - }); - } - document.removeEventListener("readystatechange", watchTitle); - - try { - if (!isSeqta404Page()) return; - - const stored = await storagePromise; - if ((stored.onoff ?? true) === false) return; - const kittenSettings = stored["plugin.error-page-kitten.settings"] as - | { enabled?: boolean } - | undefined; - if (kittenSettings?.enabled === false) return; - - mountErrorPageKitten(); - } catch (error) { - document - .querySelectorAll(".bsplus-kitten-404-hidden") - .forEach((el) => el.classList.remove("bsplus-kitten-404-hidden")); - console.error("[BetterSEQTA+] Failed to boot 404 page:", error); - } finally { - document.getElementById("bsplus-404-flash-hide")?.remove(); - } -} - -function replaceIcons() { - document.querySelectorAll('link[rel*="icon"]').forEach((link) => { - if (link.href !== icon48) { - link.href = icon48; - } - }); -} - -/** Vite/CRX HMR can leave modules with missing named exports until the graph is cleared. */ -function recoverFromStaleDevModuleGraph(error: unknown) { - if (!import.meta.env.DEV) return; - - const message = error instanceof Error ? error.message : String(error); - if (!/does not provide an export named/.test(message)) return; - - const key = "bsplus-dev-export-recovery"; - if (!sessionStorage.getItem(key)) { - sessionStorage.setItem(key, "1"); - import.meta.hot?.send("bsplus:reset-module-graph"); - setTimeout(() => { - location.reload(); - }, 80); - return; - } - - sessionStorage.removeItem(key); - console.error( - "[BetterSEQTA+] Dev module graph is still stale after recovery. Restart `npm run dev`, then reload this page.", - ); -} diff --git a/src/seqta/boot.ts b/src/seqta/boot.ts new file mode 100644 index 00000000..e378091e --- /dev/null +++ b/src/seqta/boot.ts @@ -0,0 +1,162 @@ +import { + initializeSettingsState, + settingsState, +} from "@/seqta/utils/listeners/SettingsState"; +import documentLoadCSS from "@/css/documentload.scss?inline"; +import icon48 from "@/resources/icons/icon-48.png?base64"; +import browser from "@/lib/browser"; + +import { main } from "@/seqta/main"; +import { delay } from "@/seqta/utils/delay"; +import { initializeHideSensitiveToggle } from "@/seqta/utils/hideSensitiveToggle"; +import { installSeqtaMenuColourPatch } from "@/seqta/utils/patchSeqtaMenuUpdateColours"; +import { installThemeImagePagePatch } from "@/seqta/utils/patchThemeImagesPageContext"; +import { initVerboseLogging, verboseInfo } from "@/utils/verboseLog"; +import { + hydrateRemoteConfigFromStorage, + installRemoteConfigStorageListener, + isEffectiveBsplusEnabled, + notifyRemoteConfigPageContext, + ensureKilledModeSettingsAccess, +} from "@/seqta/utils/remoteConfig/runtime"; +import { runStartupPopupQueue } from "@/seqta/utils/openers/StartupPopupQueue"; +import { recoverFromStaleDevModuleGraph } from "@/seqta/devModuleGraphRecovery"; + +function registerFetchSeqtaAppLinkListener() { + browser.runtime.onMessage.addListener((request, _sender, sendResponse) => { + if (request?.type !== "fetchSeqtaAppLink") return false; + void (async () => { + try { + const res = await fetch(`${location.origin}/seqta/student/load/profile`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + credentials: "include", + body: JSON.stringify({}), + }); + const data = await res.json(); + const statusOk = data?.status === "200" || data?.status === 200; + const raw = data?.payload?.app_link; + const appLink = typeof raw === "string" && raw.length > 0 ? raw : null; + sendResponse({ appLink: statusOk ? appLink : null }); + } catch { + sendResponse({ appLink: null }); + } + })(); + return true; + }); +} + +var IsSEQTAPage = false; + +/** Loaded on demand by SEQTA.ts for pages with the SEQTA copyright comment. */ +export function boot() { + installSeqtaMenuColourPatch(); + installThemeImagePagePatch(); + void init(); +} + +async function init() { + const hasSEQTAText = + document.childNodes[1]?.textContent?.includes( + "Copyright (c) SEQTA Software", + ) ?? false; + if ( + hasSEQTAText && + (document.title.includes("SEQTA Learn") || + document.title.includes("SEQTA Engage")) && + !IsSEQTAPage + ) { + IsSEQTAPage = true; + verboseInfo("[BetterSEQTA+] Verified SEQTA Page"); + + registerFetchSeqtaAppLinkListener(); + + const documentLoadStyle = document.createElement("style"); + documentLoadStyle.textContent = documentLoadCSS; + document.head.appendChild(documentLoadStyle); + + replaceIcons(); + + const observer = new MutationObserver((mutations) => { + for (const mutation of mutations) { + + if ( + mutation.type === "attributes" && + mutation.target instanceof HTMLLinkElement && + mutation.target.rel.includes("icon") && + mutation.attributeName === "href" + ) { + replaceIcons(); + return; + } + } + }); + + observer.observe(document.head, { + subtree: true, + attributes: true, + attributeFilter: ["href"], + }); + + + + try { + await initializeSettingsState(); + initVerboseLogging(); + + if (typeof settingsState.onoff === "undefined") { + await browser.runtime.sendMessage({ type: "setDefaultStorage" }); + + await delay(5); + } + + await hydrateRemoteConfigFromStorage(); + notifyRemoteConfigPageContext(location.hostname); + installRemoteConfigStorageListener(() => { + location.reload(); + }); + + const bsplusEnabled = isEffectiveBsplusEnabled(); + + if (bsplusEnabled) { + await main(); + + const { init: Monofile } = await import("@/plugins/monofile"); + Monofile(); + + if (settingsState.onoff) { + const { initializePlugins } = await import("@/plugins/index"); + await initializePlugins(); + } + } else { + await ensureKilledModeSettingsAccess(); + void runStartupPopupQueue(); + } + + if (settingsState.devMode) { + initializeHideSensitiveToggle(); + } + + if (import.meta.env.DEV) { + sessionStorage.removeItem("bsplus-dev-export-recovery"); + } + + verboseInfo( + "[BetterSEQTA+] Successfully initialised BetterSEQTA+, starting to load assets.", + ); + } catch (error) { + console.error(error); + recoverFromStaleDevModuleGraph(error); + } + } +} + +function replaceIcons() { + document + .querySelectorAll('link[rel*="icon"]') + .forEach((link) => { + if (link.href !== icon48) { + link.href = icon48; + } + }); +} diff --git a/src/seqta/bootErrorPage.ts b/src/seqta/bootErrorPage.ts new file mode 100644 index 00000000..f184569e --- /dev/null +++ b/src/seqta/bootErrorPage.ts @@ -0,0 +1,58 @@ +import browser from "@/lib/browser"; +import { + isSeqta404Page, + mountErrorPageKitten, +} from "@/plugins/built-in/errorPageKitten"; + +/** Hide the rebranded 404 before the kitten card mounts (removed after boot). */ +function inject404FlashHide(): void { + if (document.getElementById("bsplus-404-flash-hide")) return; + const style = document.createElement("style"); + style.id = "bsplus-404-flash-hide"; + style.textContent = + "html,body{background:#333!important}.message{display:none!important}"; + (document.head ?? document.documentElement).appendChild(style); +} + +/** Loaded on demand by SEQTA.ts for pages that aren't the SEQTA app. */ +export async function bootErrorPage() { + const storagePromise = browser.storage.local.get([ + "onoff", + "plugin.error-page-kitten.settings", + ]); + + const watchTitle = () => { + if (isSeqta404Page()) inject404FlashHide(); + }; + watchTitle(); + if (document.readyState === "loading") { + document.addEventListener("readystatechange", watchTitle); + } + + if (document.readyState === "loading") { + await new Promise((resolve) => { + document.addEventListener("DOMContentLoaded", () => resolve(), { once: true }); + }); + } + document.removeEventListener("readystatechange", watchTitle); + + try { + if (!isSeqta404Page()) return; + + const stored = await storagePromise; + if ((stored.onoff ?? true) === false) return; + const kittenSettings = stored["plugin.error-page-kitten.settings"] as + | { enabled?: boolean } + | undefined; + if (kittenSettings?.enabled === false) return; + + mountErrorPageKitten(); + } catch (error) { + document + .querySelectorAll(".bsplus-kitten-404-hidden") + .forEach((el) => el.classList.remove("bsplus-kitten-404-hidden")); + console.error("[BetterSEQTA+] Failed to boot 404 page:", error); + } finally { + document.getElementById("bsplus-404-flash-hide")?.remove(); + } +} diff --git a/src/seqta/devModuleGraphRecovery.ts b/src/seqta/devModuleGraphRecovery.ts new file mode 100644 index 00000000..18371413 --- /dev/null +++ b/src/seqta/devModuleGraphRecovery.ts @@ -0,0 +1,22 @@ +/** Vite/CRX HMR can leave modules with missing named exports until the graph is cleared. */ +export function recoverFromStaleDevModuleGraph(error: unknown) { + if (!import.meta.env.DEV) return; + + const message = error instanceof Error ? error.message : String(error); + if (!/does not provide an export named/.test(message)) return; + + const key = "bsplus-dev-export-recovery"; + if (!sessionStorage.getItem(key)) { + sessionStorage.setItem(key, "1"); + import.meta.hot?.send("bsplus:reset-module-graph"); + setTimeout(() => { + location.reload(); + }, 80); + return; + } + + sessionStorage.removeItem(key); + console.error( + "[BetterSEQTA+] Dev module graph is still stale after recovery. Restart `npm run dev`, then reload this page.", + ); +}