diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 3f67efc0..616572b3 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -72,12 +72,13 @@ Think of it like this: **SEQTA Learn + BetterSEQTA+ = Enhanced SEQTA Experience* ## Core Components ### 1. Entry Point (`src/SEQTA.ts`) -This is where it all begins! When you visit a SEQTA page: +This is where it all begins! It runs on every website, so it stays tiny: 1. Detects if you're on a SEQTA Learn page -2. Injects our CSS styles -3. Changes the favicon to BetterSEQTA+ icon -4. Loads settings from storage -5. Initializes the plugin system +2. If you are, loads `src/seqta/boot.ts`, which: + - Injects our CSS styles + - Changes the favicon to BetterSEQTA+ icon + - Loads settings from storage + - Initializes the plugin system ### 2. Plugin System (`src/plugins/`) The heart of BetterSEQTA+! This is what makes it extensible: diff --git a/docs/GETTING_STARTED_CONTRIBUTING.md b/docs/GETTING_STARTED_CONTRIBUTING.md index a51d39a1..3b1541fe 100644 --- a/docs/GETTING_STARTED_CONTRIBUTING.md +++ b/docs/GETTING_STARTED_CONTRIBUTING.md @@ -59,7 +59,7 @@ npm run dev ### 5. Make a Tiny Change (5 minutes) Let's prove everything works: -1. Open `src/SEQTA.ts` +1. Open `src/seqta/boot.ts` 2. Find the line that says `"[BetterSEQTA+] Successfully initialised"` 3. Change it to `"[BetterSEQTA+] Successfully initialised - Hello [YOUR_NAME]!"` 4. Save the file @@ -68,7 +68,7 @@ Let's prove everything works: ### 6. Reset Your Change (3 minutes) ```bash -git checkout -- src/SEQTA.ts +git checkout -- src/seqta/boot.ts ``` **Congratulations! 🎉 You've successfully set up BetterSEQTA+ for development!** diff --git a/src/SEQTA.boot.test.ts b/src/SEQTA.boot.test.ts index 002e122c..ff18f1e2 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([ @@ -30,19 +34,32 @@ test.each([ 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 === "webextension-polyfill") { + 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 === "webextension-polyfill") { - 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 03bdd214..5a54e8bb 100644 --- a/src/SEQTA.ts +++ b/src/SEQTA.ts @@ -1,52 +1,9 @@ -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 "webextension-polyfill"; +// 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"; - -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; 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]) { @@ -54,201 +11,19 @@ if (document.childNodes[1]) { 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(isSeqtaPage)); } // Standalone 404 documents never pass the SEQTA SPA gate above. -void 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.", +if (!isSeqtaPage) { + void import("@/seqta/bootErrorPage").then(({ bootErrorPage }) => + bootErrorPage(), ); } diff --git a/src/seqta/boot.ts b/src/seqta/boot.ts new file mode 100644 index 00000000..e25fda48 --- /dev/null +++ b/src/seqta/boot.ts @@ -0,0 +1,184 @@ +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 "webextension-polyfill"; + +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"; + +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. + * `isSeqtaPage` is true when the title also matched SEQTA Learn/Engage. + */ +export function boot(isSeqtaPage: boolean) { + installSeqtaMenuColourPatch(); + installThemeImagePagePatch(); + if (isSeqtaPage) init(); +} + +if (import.meta.env.DEV) { + window.addEventListener("unhandledrejection", (event) => { + recoverFromStaleDevModuleGraph(event.reason); + }); +} + +async function init() { + if (!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; + } + }); +} + +/** 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/bootErrorPage.ts b/src/seqta/bootErrorPage.ts new file mode 100644 index 00000000..8276a07c --- /dev/null +++ b/src/seqta/bootErrorPage.ts @@ -0,0 +1,58 @@ +import browser from "webextension-polyfill"; +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(); + } +}