Understand the architecture of the generated userscript
mainThe output of to-userscript is a single, self-contained userscript that uses an internal architecture to emulate a WebExtension environment. The architecture consists of three main stages:
- Unified Polyfill: A set of templates are merged to create a runtime environment. This includes a message bus (
createEventBus,createRuntime), an abstraction layer for storage and fetching (_storageSet,_fetch), an asset management system (EXTENSION_ASSETS_MAP,_createAssetUrl), and a core polyfill (buildPolyfill()) that provides thechrome.*namespace. - Background Script Environment: All background scripts are executed immediately within the polyfill's scope upon script start.
- Orchestration Logic: The script determines its execution context based on
location.href:- Content Scripts: If the URL matches a content script pattern,
executeAllScripts()is called. This manages CSS injection and executes JavaScript in three distinct phases:document-start,document-end, anddocument-idle. - Options/Popup Pages: These are rendered within a modal using an
iframe. The iframe is populated with inlined HTML and a specializedpostmessageversion of the polyfill to allow communication.
- Content Scripts: If the URL matches a content script pattern,
// ==UserScript==
// ... Metadata Block ...
// ==/UserScript==
(function() { // IIFE for scope isolation
'use strict';
// 1. UNIFIED POLYFILL is defined here
// - messaging.template.js -> createEventBus, createRuntime
// - abstractionLayer.*.template.js -> _storageSet, _fetch, etc.
// - assetsGenerator code -> EXTENSION_ASSETS_MAP, _createAssetUrl
// - polyfill.template.js -> buildPolyfill() which creates chrome.*
// 2. BACKGROUND SCRIPT ENVIRONMENT is defined and executed
// - Runs all background scripts inside the polyfill's scope.
// - This happens immediately on script start.
// 3. ORCHESTRATION LOGIC is defined and executed
// - Checks if location.href matches a content_script pattern.
// - If it matches:
// - Calls `executeAllScripts()`.
// - This function injects CSS and runs JS in phases:
// - document-start
// - document-end
// - document-idle
// - Registers GM_registerMenuCommand for options/popup pages.
// - Options/Popup pages are rendered in a modal with an iframe.
// - The iframe's content is populated with the inlined HTML and
// a specialized 'postmessage' version of the polyfill.
})();