// ██████╗███████╗███████╗ // ██╔════╝██╔════╝██╔════╝ // ██║ ███████╗███████╗ // ██║ ╚════██║╚════██║ // ╚██████╗███████║███████║ // ╚═════╝╚══════╝╚══════╝ // MIT License (c) 2020–present Cezar Augusto & the Extension.js authors, presence implies inheritance import * as fs from 'node:fs' import * as path from 'node:path' import {publicOwnedOutputName, toPosixPath} from '../dead-url-refs' import { CHROMIUM_EXTENSION_SCHEME, closedOnSlash, EXTENSION_BASE_ATTRIBUTE, EXTENSION_BASE_FROM_STACK, extensionBaseFromFile, GECKO_EXTENSION_SCHEME, unlessExtensionAddress } from '../extension-base-from-stack' import {toJsStringLiteral} from '../js-literal' import { hasPrivateFileName, rootAbsolutePathIsWithheld } from '../public-private-files' import type {WithheldKind} from '../withheld-file' import {rewriteCssUrls, whyNotRead} from './inline-css-imports' export const EXTENSION_ROOT_PLACEHOLDER = '__EXTENSIONJS_EXTENSION_ROOT__/' const BUNDLED_FILE_TOKEN = /__EXTENSIONJS_CSS_FILE_(\d+)__([^"\\]*)/g export function bundledFileToken(index: number): string { return `__EXTENSIONJS_CSS_FILE_${index}__` } interface InlinedCssUrlTarget { request: string absolutePath: string // A file under public/ already ships at the dist root through the public // copier, under outputName. Any other file is the bundler's to emit and // name, as it does for every other sheet, so url() carries a file token. publicOwned: boolean outputName?: string } interface RewriteInlinedCssUrlsContext { resourcePath: string manifestDir: string // The folder the public copier ships from, so names agree with its output. publicRoot: string // The same folder when the copier does ship one, for a relative ref into it. publicDir?: string // A file the build withholds keeps its address and is never bundled. projectPath?: string } function isFile(candidate: string): boolean { try { return fs.statSync(candidate).isFile() } catch { return false } } function resolveTarget( req: string, { resourcePath, manifestDir, publicRoot, publicDir }: RewriteInlinedCssUrlsContext ): | {absolutePath: string; outputName?: string; publicOwned: boolean} | undefined { // public/ keeps precedence for a root-absolute ref: it is the documented // output-root contract, and the same order the dead-reference scan uses. if (req.startsWith('/')) { // The copier leaves these names out, so they read as missing. if (rootAbsolutePathIsWithheld(req)) return undefined const rel = req.slice(1) const fromPublic = path.join(publicRoot, rel) if (isFile(fromPublic)) { return { absolutePath: fromPublic, outputName: toPosixPath(path.normalize(rel)), publicOwned: true } } const fromManifest = path.join(manifestDir, rel) if (!isFile(fromManifest)) return undefined return {absolutePath: fromManifest, publicOwned: false} } const absolutePath = path.resolve(path.dirname(resourcePath), req) if (!isFile(absolutePath)) return undefined const publicPath = publicOwnedOutputName(absolutePath, publicDir) if (publicPath) { if (hasPrivateFileName(publicPath)) return undefined return {absolutePath, outputName: publicPath, publicOwned: true} } return {absolutePath, publicOwned: false} } export function rewriteInlinedCssUrls( source: string, context: RewriteInlinedCssUrlsContext ): { css: string targets: InlinedCssUrlTarget[] withheld: Array<{request: string; kind: WithheldKind}> } { const targets: InlinedCssUrlTarget[] = [] // The addresses of files the build keeps back, each once, as written. const withheld = new Map() const seen = new Map() // Read the way CSS reads it, so a url( inside a string is left alone. The // url() of an @import names a sheet, which is never a file to bundle. const css = rewriteCssUrls( source, (request, where) => { if (where !== 'url' && where !== 'set') return undefined const suffixAt = request.search(/[?#]/) const req = suffixAt === -1 ? request : request.slice(0, suffixAt) const suffix = suffixAt === -1 ? '' : request.slice(suffixAt) if (!req || req.startsWith('//') || /^[a-z][a-z0-9+.-]*:/i.test(req)) { return undefined } if (req.startsWith('~') || req.startsWith('@')) return undefined if (req.startsWith(EXTENSION_ROOT_PLACEHOLDER)) return undefined let named = seen.get(req) if (!named) { const target = resolveTarget(req, context) if (!target) return undefined const refused = !target.publicOwned && context.projectPath ? whyNotRead(target.absolutePath, context.projectPath) : undefined if (refused) { withheld.set(request, refused.kind) return undefined } named = target.publicOwned ? `${EXTENSION_ROOT_PLACEHOLDER}${target.outputName}` : bundledFileToken( targets.filter((other) => !other.publicOwned).length ) seen.set(req, named) targets.push({request: req, ...target}) } return `${named}${suffix}` }, true ) return { css, targets, withheld: [...withheld].map(([request, kind]) => ({request, kind})) } } export const SFC_STYLE_ATTRIBUTE = 'data-extjs-sfc-style' // Where a refused element keeps the sheet that stands in for it, so the next // run of the same script replaces that sheet's rules and adds no second one. const SFC_SHEET_PROPERTY = '__extjsSfcSheet' // A single-file component's style block has no importer that reads a URL, so // its module puts the sheet in the document itself, once per style id. function styleElementLines(text: string, styleId: string): string[] { const id = JSON.stringify(styleId) const selector = JSON.stringify(`style[${SFC_STYLE_ATTRIBUTE}="${styleId}"]`) return [ `var __extjsSfcCss = ${text};`, '(function () {', ' try {', ' if (typeof document !== "object" || !document || typeof document.createElement !== "function") return;', ` var el = document.querySelector(${selector});`, ' if (!el) {', ' el = document.createElement("style");', ` el.setAttribute(${JSON.stringify(SFC_STYLE_ATTRIBUTE)}, ${id});`, ' (document.head || document.documentElement).appendChild(el);', ' }', ' if (el.textContent !== __extjsSfcCss) el.textContent = __extjsSfcCss;', // A page's style-src can refuse the element, which leaves it no sheet. // A constructed sheet is not inline style, so the page's policy lets it in. ' if (!__extjsSfcCss || el.sheet || typeof CSSStyleSheet !== "function" || !document.adoptedStyleSheets) return;', ` var sheet = el[${JSON.stringify(SFC_SHEET_PROPERTY)}];`, ' if (!sheet) {', ' sheet = new CSSStyleSheet();', ` el[${JSON.stringify(SFC_SHEET_PROPERTY)}] = sheet;`, ' document.adoptedStyleSheets = document.adoptedStyleSheets.concat([sheet]);', ' }', ' sheet.replaceSync(__extjsSfcCss);', ' } catch (error) {}', '})();', 'module.exports = __extjsSfcCss;', '' ] } // A page script can patch join and replace and read what passes through // them, so a Gecko sheet is put together by concatenation alone. function concatenatedSheet(css: string): string { const pieces: string[] = [] const literal = (text: string) => { text.split(EXTENSION_ROOT_PLACEHOLDER).forEach((part, index) => { if (index > 0) pieces.push('__extjsExtensionRoot()') if (part) pieces.push(JSON.stringify(part)) }) } let from = 0 for (const token of css.matchAll(BUNDLED_FILE_TOKEN)) { literal(css.slice(from, token.index)) pieces.push( `__extjsCssFile("", ${JSON.stringify(token[1])}, ${JSON.stringify(token[2])})` ) from = token.index + token[0].length } literal(css.slice(from)) return pieces.length > 0 ? pieces.join(' + ') : '""' } // bundledRequests[n] is the file token n stands for, as a request the bundler // resolves from the sheet's folder. export function toRuntimeStylesheetModule( css: string, bundledRequests: string[] = [], styleId?: string, gecko = false, baseAttribute: string = EXTENSION_BASE_ATTRIBUTE, baseScheme: string = gecko ? GECKO_EXTENSION_SCHEME : CHROMIUM_EXTENSION_SCHEME ): string { const root = JSON.stringify(EXTENSION_ROOT_PLACEHOLDER) const rooted = `__extjsCssText.split(${root}).join(__extjsExtensionRoot())` const text = gecko ? concatenatedSheet(css) : bundledRequests.length === 0 ? rooted : `${rooted}.replace(${String(BUNDLED_FILE_TOKEN)}, __extjsCssFile)` // A bare `browser` gets rewritten into a polyfill require that throws in // the MAIN world. Member reads on globalThis are never rewritten. return [ `var __extjsCssText = ${JSON.stringify(css)};`, 'function __extjsExtensionRoot() {', ' try {', ' var b = globalThis.browser;', ' if (typeof b === "object" && b && b.runtime && typeof b.runtime.getURL === "function") return String(b.runtime.getURL("/"));', ' } catch (error) {}', ' try {', ' var c = globalThis.chrome;', ' if (typeof c === "object" && c && c.runtime && typeof c.runtime.getURL === "function") return String(c.runtime.getURL("/"));', ' } catch (error) {}', // A MAIN-world script has no runtime API. The bridge publishes the // extension base for it on globalThis and on , as public path reads. ' try {', ...(gecko ? [ // A Gecko MAIN world file took the base as it opened, and a sheet // in a later chunk finds that copy on the require function. ` var base = ${extensionBaseFromFile(true)};`, ' if (!base && typeof __webpack_require__ === "function" && typeof __webpack_require__.extjsBase === "string") base = __webpack_require__.extjsBase;', ` if (!base && typeof document === "object" && document && document.documentElement) base = String(document.documentElement.getAttribute(${JSON.stringify(baseAttribute)}) || "");`, ` ${unlessExtensionAddress('base')}`, ` if (base) return ${closedOnSlash('base')};` ] : [ ` var base = ${EXTENSION_BASE_FROM_STACK};`, ` if (!base && typeof document === "object" && document && document.documentElement) base = String(document.documentElement.getAttribute(${JSON.stringify(baseAttribute)}) || "");`, // A shipped MAIN-world bundle clears that attribute once it has the base, // and keeps it on the require function for a sheet that loads later. ' if (!base && typeof __webpack_require__ === "function" && __webpack_require__.extjsBase) base = String(__webpack_require__.extjsBase);', ` ${unlessExtensionAddress('base', baseScheme)}`, ' if (base) return base.replace(/\\/+$/, "") + "/";' ]), ' } catch (error) {}', ' return "/";', '}', ...(bundledRequests.length === 0 ? [] : [ // The bundler answers with the file's place under its public path, // or a data: URL when it inlined the file. Only the path is kept. `var __extjsCssFiles = [${bundledRequests .map( (request) => `function(){ return new URL(${toJsStringLiteral(request)}, import.meta.url); }` ) .join(', ')}];`, 'function __extjsCssFile(match, index, suffix) {', ' try {', ' var file = __extjsCssFiles[Number(index)]();', ' if (file.protocol === "data:") return file.href;', ' return __extjsExtensionRoot() + String(file.pathname).replace(/^\\/+/, "") + suffix;', ' } catch (error) {}', ' return "about:invalid";', '}' ]), ...(styleId ? styleElementLines(text, styleId) : [ `module.exports = "data:text/css;charset=utf-8," + encodeURIComponent(${text});`, '' ]) ].join('\n') }