import path from 'node:path' import { URL } from 'node:url' import escapeHtml from 'escape-html' import MagicString from 'magic-string' import type { DefaultTreeAdapterMap, ErrorCodes, ParserError, Token, } from 'parse5' import colors from 'picocolors' import type { OutputAsset, OutputBundle, OutputChunk, RollupError, SourceMapInput, } from 'rolldown' import { stripLiteral } from 'strip-literal' import { cleanUrl } from '../../shared/utils' import { getNodeAssetAttributes } from '../assetSource' import { toOutputFilePathInHtml } from '../build' import type { ResolvedConfig, ResolvedEnvironmentOptions } from '../config' import { BUNDLED_DEV_CLIENT_FILENAME } from '../constants' import { resolveEnvPrefix } from '../env' import { perEnvironmentState } from '../environment' import type { Logger } from '../logger' import type { MinimalPluginContextWithoutEnvironment, Plugin } from '../plugin' import { checkPublicFile } from '../publicDir' import type { ViteDevServer } from '../server' import { decodeURIIfPossible, encodeURIPath, generateCodeFrame, getHash, isCSSRequest, isDataUrl, isExternalUrl, normalizePath, partialEncodeURIPath, processSrcSet, removeLeadingSlash, unique, } from '../utils' import { assetUrlRE, getAssetUrlPostfix, getPublicAssetFilename, publicAssetUrlRE, urlToBuiltUrl, } from './asset' import { cssBundleNameCache } from './css' import { modulePreloadPolyfillId } from './modulePreloadPolyfill' import { getPluginHookHandler } from './index' interface ScriptAssetsUrl { start: number end: number url: string } const htmlProxyRE = /[?&]html-proxy=?(?:&inline-css)?(?:&style-attr)?&index=(\d+)\.(?:js|css)$/ const isHtmlProxyRE = /[?&]html-proxy\b/ const inlineCSSRE = /__VITE_INLINE_CSS__([a-z\d]{8}_\d+)__/g // Do not allow preceding '.', but do allow preceding '...' for spread operations const inlineImportRE = /(?]*type\s*=\s*(?:"importmap"|'importmap'|importmap)[^>]*>.*?<\/script>/is const moduleScriptRE = /[ \t]*]*type\s*=\s*(?:"module"|'module'|module)[^>]*>/i const modulePreloadLinkRE = /[ \t]*]*rel\s*=\s*(?:"modulepreload"|'modulepreload'|modulepreload)[\s\S]*?>/i const importMapAppendRE = new RegExp( [moduleScriptRE, modulePreloadLinkRE].map((r) => r.source).join('|'), 'i', ) export const isHTMLProxy = (id: string): boolean => isHtmlProxyRE.test(id) export const isHTMLRequest = (request: string): boolean => htmlLangRE.test(request) // HTML Proxy Caches are stored by config -> filePath -> index export const htmlProxyMap: WeakMap< ResolvedConfig, Map< string, { code: string map?: SourceMapInput }[] > > = new WeakMap() // HTML Proxy Transform result are stored by config // `${hash(importer)}_${query.index}` -> transformed css code // PS: key like `hash(/vite/playground/assets/index.html)_1`) export const htmlProxyResult: Map = new Map() export function htmlInlineProxyPlugin(config: ResolvedConfig): Plugin { // Should do this when `constructor` rather than when `buildStart`, // `buildStart` will be triggered multiple times then the cached result will be emptied. // https://github.com/vitejs/vite/issues/6372 htmlProxyMap.set(config, new Map()) return { name: 'vite:html-inline-proxy', resolveId: { filter: { id: isHtmlProxyRE }, handler(id) { return id }, }, load: { filter: { id: isHtmlProxyRE }, handler(id) { const proxyMatch = htmlProxyRE.exec(id) if (proxyMatch) { const index = Number(proxyMatch[1]) const file = cleanUrl(id) const url = file.replace(normalizePath(config.root), '') const result = htmlProxyMap.get(config)!.get(url)?.[index] if (result) { // set moduleSideEffects to keep the module even if `treeshake.moduleSideEffects=false` is set return { ...result, moduleSideEffects: true } } else { throw new Error(`No matching HTML proxy module found from ${id}`) } } }, }, } } export function addToHTMLProxyCache( config: ResolvedConfig, filePath: string, index: number, result: { code: string; map?: SourceMapInput }, ): void { if (!htmlProxyMap.get(config)) { htmlProxyMap.set(config, new Map()) } if (!htmlProxyMap.get(config)!.get(filePath)) { htmlProxyMap.get(config)!.set(filePath, []) } htmlProxyMap.get(config)!.get(filePath)![index] = result } export function addToHTMLProxyTransformResult( hash: string, code: string, ): void { htmlProxyResult.set(hash, code) } // Some `` elements should not be inlined in build. Excluding: // - `shortcut` : only valid for IE <9, use `icon` // - `mask-icon` : deprecated since Safari 12 (for pinned tabs) // - `apple-touch-icon-precomposed` : only valid for iOS <7 (for avoiding gloss effect) const noInlineLinkRels = new Set([ 'icon', 'apple-touch-icon', 'apple-touch-startup-image', 'manifest', 'modulepreload', 'preload', 'prefetch', ]) // If the node is a link, check if it can be inlined. If not, return `false` to // force no inline. `undefined` leaves it to the default heuristics. function getLinkShouldInline( node: DefaultTreeAdapterMap['element'], attributes: Record, ): false | undefined { const isNoInlineLink = node.nodeName === 'link' && attributes.rel && parseRelAttr(attributes.rel).some((v) => noInlineLinkRels.has(v)) return isNoInlineLink ? false : undefined } export const isAsyncScriptMap: WeakMap< ResolvedConfig, Map > = new WeakMap() export function nodeIsElement( node: DefaultTreeAdapterMap['node'], ): node is DefaultTreeAdapterMap['element'] { return node.nodeName[0] !== '#' } function traverseNodes( node: DefaultTreeAdapterMap['node'], visitor: (node: DefaultTreeAdapterMap['node']) => void, ) { if (node.nodeName === 'template') { node = (node as DefaultTreeAdapterMap['template']).content } visitor(node) if ( nodeIsElement(node) || node.nodeName === '#document' || node.nodeName === '#document-fragment' ) { node.childNodes.forEach((childNode) => traverseNodes(childNode, visitor)) } } type ParseWarnings = Partial> export async function traverseHtml( html: string, filePath: string, warn: Logger['warn'], visitor: (node: DefaultTreeAdapterMap['node']) => void, ): Promise { // lazy load compiler const { parse, ErrorCodes } = await import('parse5') const warnings: ParseWarnings = {} const ast = parse(html, { scriptingEnabled: false, // parse inside