From 95fde01089cd14c42208f5d77158d42623d17bd4 Mon Sep 17 00:00:00 2001 From: patak-dev Date: Mon, 15 Aug 2022 11:54:55 +0200 Subject: [PATCH 1/9] refactor: migrate from vue/compiler-dom to parse5 --- packages/vite/LICENSE.md | 87 ------ packages/vite/package.json | 2 +- packages/vite/rollup.config.ts | 9 - packages/vite/src/node/plugins/html.ts | 276 ++++++++++-------- .../src/node/server/middlewares/indexHtml.ts | 95 +++--- playground/html/index.html | 8 + pnpm-lock.yaml | 15 +- 7 files changed, 235 insertions(+), 257 deletions(-) diff --git a/packages/vite/LICENSE.md b/packages/vite/LICENSE.md index 41da37ad32dd33..f30ff9c7ccce7d 100644 --- a/packages/vite/LICENSE.md +++ b/packages/vite/LICENSE.md @@ -559,93 +559,6 @@ Repository: rollup/plugins --------------------------------------- -## @vue/compiler-core -License: MIT -By: Evan You -Repository: git+https://github.com/vuejs/core.git - -> The MIT License (MIT) -> -> Copyright (c) 2018-present, Yuxi (Evan) You -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in -> all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -> THE SOFTWARE. - ---------------------------------------- - -## @vue/compiler-dom -License: MIT -By: Evan You -Repository: git+https://github.com/vuejs/core.git - -> The MIT License (MIT) -> -> Copyright (c) 2018-present, Yuxi (Evan) You -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in -> all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -> THE SOFTWARE. - ---------------------------------------- - -## @vue/shared -License: MIT -By: Evan You -Repository: git+https://github.com/vuejs/core.git - -> The MIT License (MIT) -> -> Copyright (c) 2018-present, Yuxi (Evan) You -> -> Permission is hereby granted, free of charge, to any person obtaining a copy -> of this software and associated documentation files (the "Software"), to deal -> in the Software without restriction, including without limitation the rights -> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -> copies of the Software, and to permit persons to whom the Software is -> furnished to do so, subject to the following conditions: -> -> The above copyright notice and this permission notice shall be included in -> all copies or substantial portions of the Software. -> -> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -> THE SOFTWARE. - ---------------------------------------- - ## acorn License: MIT By: Marijn Haverbeke, Ingvar Stepanyan, Adrian Heine diff --git a/packages/vite/package.json b/packages/vite/package.json index 20e44f51170be0..9ea12edf2172d3 100644 --- a/packages/vite/package.json +++ b/packages/vite/package.json @@ -59,6 +59,7 @@ "//": "READ CONTRIBUTING.md to understand what to put under deps vs. devDeps!", "dependencies": { "esbuild": "^0.14.47", + "parse5": "^7.0.0", "postcss": "^8.4.16", "resolve": "^1.22.1", "rollup": ">=2.75.6 <2.77.0 || ~2.77.0" @@ -78,7 +79,6 @@ "@rollup/plugin-node-resolve": "13.3.0", "@rollup/plugin-typescript": "^8.3.4", "@rollup/pluginutils": "^4.2.1", - "@vue/compiler-dom": "^3.2.37", "acorn": "^8.8.0", "cac": "^6.7.12", "chokidar": "^3.5.3", diff --git a/packages/vite/rollup.config.ts b/packages/vite/rollup.config.ts index a271d4f3562906..bf5c0e9da810a2 100644 --- a/packages/vite/rollup.config.ts +++ b/packages/vite/rollup.config.ts @@ -5,7 +5,6 @@ import nodeResolve from '@rollup/plugin-node-resolve' import typescript from '@rollup/plugin-typescript' import commonjs from '@rollup/plugin-commonjs' import json from '@rollup/plugin-json' -import alias from '@rollup/plugin-alias' import license from 'rollup-plugin-license' import MagicString from 'magic-string' import colors from 'picocolors' @@ -79,14 +78,6 @@ function createNodePlugins( declarationDir: string | false ): Plugin[] { return [ - alias({ - // packages with "module" field that doesn't play well with cjs bundles - entries: { - '@vue/compiler-dom': require.resolve( - '@vue/compiler-dom/dist/compiler-dom.cjs.js' - ) - } - }), nodeResolve({ preferBuiltins: true }), typescript({ tsconfig: path.resolve(__dirname, 'src/node/tsconfig.json'), diff --git a/packages/vite/src/node/plugins/html.ts b/packages/vite/src/node/plugins/html.ts index b8cd3713edfeea..1db8b5e593fd92 100644 --- a/packages/vite/src/node/plugins/html.ts +++ b/packages/vite/src/node/plugins/html.ts @@ -7,14 +7,7 @@ import type { SourceMapInput } from 'rollup' import MagicString from 'magic-string' -import type { - AttributeNode, - CompilerError, - ElementNode, - NodeTransform, - TextNode -} from '@vue/compiler-dom' -import { NodeTypes } from '@vue/compiler-dom' +import type { DefaultTreeAdapterMap, ParserError, Token } from 'parse5' import { stripLiteral } from 'strip-literal' import type { Plugin } from '../plugin' import type { ViteDevServer } from '../server' @@ -138,83 +131,134 @@ export const isAsyncScriptMap = new WeakMap< Map >() +export function nodeIsElement( + node: DefaultTreeAdapterMap['node'] +): node is DefaultTreeAdapterMap['element'] { + return node.nodeName[0] !== '#' +} + +function traverseNodes( + node: DefaultTreeAdapterMap['node'], + visitor: (node: DefaultTreeAdapterMap['node']) => void +) { + visitor(node) + if ( + nodeIsElement(node) || + node.nodeName === '#document' || + node.nodeName === '#document-fragment' + ) { + node.childNodes.forEach((childNode) => traverseNodes(childNode, visitor)) + } +} + export async function traverseHtml( html: string, filePath: string, - visitor: NodeTransform + visitor: (node: DefaultTreeAdapterMap['node']) => void ): Promise { // lazy load compiler - const { parse, transform } = await import('@vue/compiler-dom') - // @vue/compiler-core doesn't like lowercase doctypes - html = html.replace(/ { + handleParseError(e, html, filePath) + } + }) + traverseNodes(ast, visitor) } -export function getScriptInfo(node: ElementNode): { - src: AttributeNode | undefined +export function getScriptInfo(node: DefaultTreeAdapterMap['element']): { + src: Token.Attribute | undefined + sourceCodeLocation: Token.Location | undefined isModule: boolean isAsync: boolean } { - let src: AttributeNode | undefined + let src: Token.Attribute | undefined + let sourceCodeLocation: Token.Location | undefined let isModule = false let isAsync = false - for (let i = 0; i < node.props.length; i++) { - const p = node.props[i] - if (p.type === NodeTypes.ATTRIBUTE) { - if (p.name === 'src') { - src = p - } else if (p.name === 'type' && p.value && p.value.content === 'module') { - isModule = true - } else if (p.name === 'async') { - isAsync = true - } + for (let i = 0; i < node.attrs.length; i++) { + const p = node.attrs[i] + if (p.name === 'src') { + src = p + sourceCodeLocation = node.sourceCodeLocation?.attrs!['src'] + } else if (p.name === 'type' && p.value && p.value === 'module') { + isModule = true + } else if (p.name === 'async') { + isAsync = true } } - return { src, isModule, isAsync } + return { src, sourceCodeLocation, isModule, isAsync } +} + +const attrValueWithQuotesStartRE = /=[\s\t\n\r]*"/ + +export function overwriteAttrValue( + s: MagicString, + sourceCodeLocation: Token.Location, + newValue: string +): MagicString { + const srcString = s.slice( + sourceCodeLocation!.startOffset, + sourceCodeLocation!.endOffset + ) + const valueWithQuotes = srcString.match(attrValueWithQuotesStartRE) + const valueOffset = + 1 + (valueWithQuotes ? srcString.indexOf('"') : srcString.indexOf('=')) + s.overwrite( + sourceCodeLocation.startOffset + valueOffset, + sourceCodeLocation.endOffset + (valueWithQuotes ? -1 : 0), + newValue, + { contentOnly: true } + ) + return s } /** - * Format Vue @type {CompilerError} to @type {RollupError} + * Format parse5 @type {ParserError} to @type {RollupError} */ function formatParseError( - compilerError: CompilerError, + parserError: ParserError, id: string, html: string ): RollupError { - const formattedError: RollupError = { ...(compilerError as any) } - if (compilerError.loc) { - formattedError.frame = generateCodeFrame( - html, - compilerError.loc.start.offset - ) - formattedError.loc = { - file: id, - line: compilerError.loc.start.line, - column: compilerError.loc.start.column - } + const formattedError: RollupError = { + code: parserError.code, + message: `parse5 error code ${parserError.code}` + } + formattedError.frame = generateCodeFrame(html, parserError.startOffset) + formattedError.loc = { + file: id, + line: parserError.startLine, + column: parserError.startCol } return formattedError } function handleParseError( - compilerError: CompilerError, + parserError: ParserError, html: string, filePath: string ) { + switch (parserError.code) { + case 'missing-doctype': + // ignore missing DOCTYPE + return + case 'abandoned-head-element-child': + // Accept elements without closing tag in + return + case 'duplicate-attribute': + // Accept duplicate attributes #9566 + // The first attribute is used, browsers silently ignore duplicates + return + } const parseError = { loc: filePath, frame: '', - ...formatParseError(compilerError, filePath, html) + ...formatParseError(parserError, filePath, html) } throw new Error( - `Unable to parse HTML; ${compilerError.message}\n at ${JSON.stringify( + `Unable to parse HTML; ${parseError.message}\n at ${JSON.stringify( parseError.loc )}\n${parseError.frame}` ) @@ -263,7 +307,10 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { let js = '' const s = new MagicString(html) - const assetUrls: AttributeNode[] = [] + const assetUrls: { + attr: Token.Attribute + sourceCodeLocation: Token.Location + }[] = [] const scriptUrls: ScriptAssetsUrl[] = [] const styleUrls: ScriptAssetsUrl[] = [] let inlineModuleIndex = -1 @@ -273,25 +320,25 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { let someScriptsAreDefer = false await traverseHtml(html, id, (node) => { - if (node.type !== NodeTypes.ELEMENT) { + if (!nodeIsElement(node)) { return } let shouldRemove = false // script tags - if (node.tag === 'script') { - const { src, isModule, isAsync } = getScriptInfo(node) + if (node.nodeName === 'script') { + const { src, sourceCodeLocation, isModule, isAsync } = + getScriptInfo(node) - const url = src && src.value && src.value.content + const url = src && src.value const isPublicFile = !!(url && checkPublicFile(url, config)) if (isPublicFile) { // referencing public dir url, prefix with base - s.overwrite( - src!.value!.loc.start.offset, - src!.value!.loc.end.offset, - `"${toOutputPublicFilePath(url)}"`, - { contentOnly: true } + overwriteAttrValue( + s, + sourceCodeLocation!, + toOutputPublicFilePath(url) ) } @@ -302,10 +349,10 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { // add it as an import js += `\nimport ${JSON.stringify(url)}` shouldRemove = true - } else if (node.children.length) { - const contents = node.children - .map((child: any) => child.content || '') - .join('') + } else if (node.childNodes.length) { + const scriptNode = + node.childNodes.pop() as DefaultTreeAdapterMap['textNode'] + const contents = scriptNode.value // const filePath = id.replace(normalizePath(config.root), '') addToHTMLProxyCache(config, filePath, inlineModuleIndex, { @@ -324,9 +371,10 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { ``, { contentOnly: true } ) } await traverseHtml(html, htmlPath, (node) => { - if (node.type !== NodeTypes.ELEMENT) { + if (!nodeIsElement(node)) { return } // script tags - if (node.tag === 'script') { - const { src, isModule } = getScriptInfo(node) + if (node.nodeName === 'script') { + const { src, sourceCodeLocation, isModule } = getScriptInfo(node) if (src) { - processNodeUrl(src, s, config, htmlPath, originalUrl, moduleGraph) - } else if (isModule && node.children.length) { + processNodeUrl( + src, + sourceCodeLocation!, + s, + config, + htmlPath, + originalUrl, + moduleGraph + ) + } else if (isModule && node.childNodes.length) { addInlineModule(node, 'js') } } - if (node.tag === 'style' && node.children.length) { - const children = node.children[0] as TextNode + if (node.nodeName === 'style' && node.childNodes.length) { + const children = node.childNodes[0] as DefaultTreeAdapterMap['textNode'] styleUrl.push({ - start: children.loc.start.offset, - end: children.loc.end.offset, - code: children.content + start: children.sourceCodeLocation!.startOffset, + end: children.sourceCodeLocation!.endOffset, + code: children.value }) } // elements with [href/src] attrs - const assetAttrs = assetAttrsConfig[node.tag] + const assetAttrs = assetAttrsConfig[node.nodeName] if (assetAttrs) { - for (const p of node.props) { - if ( - p.type === NodeTypes.ATTRIBUTE && - p.value && - assetAttrs.includes(p.name) - ) { - processNodeUrl(p, s, config, htmlPath, originalUrl) + for (const p of node.attrs) { + if (p.value && assetAttrs.includes(p.name)) { + processNodeUrl( + p, + node.sourceCodeLocation!.attrs![p.name], + s, + config, + htmlPath, + originalUrl + ) } } } diff --git a/playground/html/index.html b/playground/html/index.html index 783cad93172f7a..f27bd18e4107f0 100644 --- a/playground/html/index.html +++ b/playground/html/index.html @@ -8,3 +8,11 @@

Hello

+ + +
Accept duplicated attribute
+ + + + + diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6ae863cf61692e..60560930238b85 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -214,7 +214,6 @@ importers: '@rollup/plugin-node-resolve': 13.3.0 '@rollup/plugin-typescript': ^8.3.4 '@rollup/pluginutils': ^4.2.1 - '@vue/compiler-dom': ^3.2.37 acorn: ^8.8.0 cac: ^6.7.12 chokidar: ^3.5.3 @@ -241,6 +240,7 @@ importers: mrmime: ^1.0.1 okie: ^1.0.1 open: ^8.4.0 + parse5: ^7.0.0 periscopic: ^3.0.4 picocolors: ^1.0.0 postcss: ^8.4.16 @@ -263,6 +263,7 @@ importers: ws: ^8.8.1 dependencies: esbuild: 0.14.47 + parse5: 7.0.0 postcss: 8.4.16 resolve: 1.22.1 rollup: 2.77.0 @@ -280,7 +281,6 @@ importers: '@rollup/plugin-node-resolve': 13.3.0_rollup@2.77.0 '@rollup/plugin-typescript': 8.3.4_rollup@2.77.0+tslib@2.4.0 '@rollup/pluginutils': 4.2.1 - '@vue/compiler-dom': 3.2.37 acorn: 8.8.0 cac: 6.7.12 chokidar: 3.5.3 @@ -4244,6 +4244,11 @@ packages: engines: {node: '>= 0.8'} dev: true + /entities/4.3.1: + resolution: {integrity: sha512-o4q/dYJlmyjP2zfnaWDUC6A3BQFmVTX+tZPezK7k0GLSU9QYCauscf5Y+qcEPzKL+EixVouYDgLQK5H9GrLpkg==} + engines: {node: '>=0.12'} + dev: false + /env-paths/2.2.1: resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==} engines: {node: '>=6'} @@ -6870,6 +6875,12 @@ packages: engines: {node: '>= 0.10'} dev: true + /parse5/7.0.0: + resolution: {integrity: sha512-y/t8IXSPWTuRZqXc0ajH/UwDj4mnqLEbSttNbThcFhGrZuOyoyvNBO85PBp2jQa55wY9d07PBNjsK8ZP3K5U6g==} + dependencies: + entities: 4.3.1 + dev: false + /parseurl/1.3.3: resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==} engines: {node: '>= 0.8'} From fb5b3a2d41d040b01babcb0186ac902eb49dea22 Mon Sep 17 00:00:00 2001 From: patak-dev Date: Mon, 15 Aug 2022 13:36:28 +0200 Subject: [PATCH 2/9] chore: bundle parse5 --- packages/vite/LICENSE.md | 46 ++++++++++++++++++++++++++++++++++++++ packages/vite/package.json | 2 +- pnpm-lock.yaml | 6 ++--- 3 files changed, 50 insertions(+), 4 deletions(-) diff --git a/packages/vite/LICENSE.md b/packages/vite/LICENSE.md index f30ff9c7ccce7d..4f13c795f558d9 100644 --- a/packages/vite/LICENSE.md +++ b/packages/vite/LICENSE.md @@ -1191,6 +1191,25 @@ Repository: pillarjs/encodeurl --------------------------------------- +## entities +License: BSD-2-Clause +By: Felix Boehm +Repository: git://github.com/fb55/entities.git + +> Copyright (c) Felix Böhm +> All rights reserved. +> +> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: +> +> Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +> +> Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +> +> THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS, +> EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +--------------------------------------- + ## es-module-lexer License: MIT By: Guy Bedford @@ -2347,6 +2366,33 @@ Repository: sindresorhus/open --------------------------------------- +## parse5 +License: MIT +By: Ivan Nikulin, https://github.com/inikulin/parse5/graphs/contributors +Repository: git://github.com/inikulin/parse5.git + +> Copyright (c) 2013-2019 Ivan Nikulin (ifaaan@gmail.com, https://github.com/inikulin) +> +> Permission is hereby granted, free of charge, to any person obtaining a copy +> of this software and associated documentation files (the "Software"), to deal +> in the Software without restriction, including without limitation the rights +> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +> copies of the Software, and to permit persons to whom the Software is +> furnished to do so, subject to the following conditions: +> +> The above copyright notice and this permission notice shall be included in +> all copies or substantial portions of the Software. +> +> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +> THE SOFTWARE. + +--------------------------------------- + ## parseurl License: MIT By: Douglas Christopher Wilson, Jonathan Ong diff --git a/packages/vite/package.json b/packages/vite/package.json index 9ea12edf2172d3..68b5c19b9bca30 100644 --- a/packages/vite/package.json +++ b/packages/vite/package.json @@ -59,7 +59,6 @@ "//": "READ CONTRIBUTING.md to understand what to put under deps vs. devDeps!", "dependencies": { "esbuild": "^0.14.47", - "parse5": "^7.0.0", "postcss": "^8.4.16", "resolve": "^1.22.1", "rollup": ">=2.75.6 <2.77.0 || ~2.77.0" @@ -103,6 +102,7 @@ "mrmime": "^1.0.1", "okie": "^1.0.1", "open": "^8.4.0", + "parse5": "^7.0.0", "periscopic": "^3.0.4", "picocolors": "^1.0.0", "postcss-import": "^14.1.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 60560930238b85..0aa4e96dd23ee8 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -263,7 +263,6 @@ importers: ws: ^8.8.1 dependencies: esbuild: 0.14.47 - parse5: 7.0.0 postcss: 8.4.16 resolve: 1.22.1 rollup: 2.77.0 @@ -305,6 +304,7 @@ importers: mrmime: 1.0.1 okie: 1.0.1 open: 8.4.0 + parse5: 7.0.0 periscopic: 3.0.4 picocolors: 1.0.0 postcss-import: 14.1.0_postcss@8.4.16 @@ -4247,7 +4247,7 @@ packages: /entities/4.3.1: resolution: {integrity: sha512-o4q/dYJlmyjP2zfnaWDUC6A3BQFmVTX+tZPezK7k0GLSU9QYCauscf5Y+qcEPzKL+EixVouYDgLQK5H9GrLpkg==} engines: {node: '>=0.12'} - dev: false + dev: true /env-paths/2.2.1: resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==} @@ -6879,7 +6879,7 @@ packages: resolution: {integrity: sha512-y/t8IXSPWTuRZqXc0ajH/UwDj4mnqLEbSttNbThcFhGrZuOyoyvNBO85PBp2jQa55wY9d07PBNjsK8ZP3K5U6g==} dependencies: entities: 4.3.1 - dev: false + dev: true /parseurl/1.3.3: resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==} From 2cd3f108aeaab397fdfc03be06ffdfe2664c5d01 Mon Sep 17 00:00:00 2001 From: patak-dev Date: Mon, 15 Aug 2022 21:39:18 +0200 Subject: [PATCH 3/9] chore: prettier-ignore no closing tag --- playground/html/index.html | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/playground/html/index.html b/playground/html/index.html index f27bd18e4107f0..5fcb705c16b650 100644 --- a/playground/html/index.html +++ b/playground/html/index.html @@ -14,5 +14,7 @@

Hello

- + + From 81b4123778c0a105667a864c391c1374268fd12d Mon Sep 17 00:00:00 2001 From: patak-dev Date: Mon, 15 Aug 2022 21:45:12 +0200 Subject: [PATCH 4/9] refactor: valid.html --- .prettierignore | 1 + playground/html/__tests__/html.spec.ts | 7 +++++++ playground/html/index.html | 10 ---------- playground/html/valid.html | 7 +++++++ playground/html/vite.config.js | 3 ++- 5 files changed, 17 insertions(+), 11 deletions(-) create mode 100644 playground/html/valid.html diff --git a/.prettierignore b/.prettierignore index 0d5487354a8c98..b1ea458b9bb9d8 100644 --- a/.prettierignore +++ b/.prettierignore @@ -7,4 +7,5 @@ pnpm-lock.yaml pnpm-workspace.yaml playground/tsconfig-json-load-error/has-error/tsconfig.json playground/html/invalid.html +playground/html/valid.html playground/worker/classic-worker.js diff --git a/playground/html/__tests__/html.spec.ts b/playground/html/__tests__/html.spec.ts index 4c0376636abd5b..72e39ba84b890c 100644 --- a/playground/html/__tests__/html.spec.ts +++ b/playground/html/__tests__/html.spec.ts @@ -242,3 +242,10 @@ describe.runIf(isServe)('invalid', () => { expect(content).toBeTruthy() }) }) + +describe('valid html', () => { + test('duplicated attrs', async () => { + await page.goto(viteTestUrl + '/valid.html') + expect(await getColor('#duplicated-attrs')).toBe('green') + }) +}) diff --git a/playground/html/index.html b/playground/html/index.html index 5fcb705c16b650..783cad93172f7a 100644 --- a/playground/html/index.html +++ b/playground/html/index.html @@ -8,13 +8,3 @@

Hello

- - -
Accept duplicated attribute
- - - - - - diff --git a/playground/html/valid.html b/playground/html/valid.html new file mode 100644 index 00000000000000..9ff48bbeafba6b --- /dev/null +++ b/playground/html/valid.html @@ -0,0 +1,7 @@ + +
Accept duplicated attribute
+ + + + diff --git a/playground/html/vite.config.js b/playground/html/vite.config.js index 8c117aaaa663e7..32eb5a9562d279 100644 --- a/playground/html/vite.config.js +++ b/playground/html/vite.config.js @@ -26,7 +26,8 @@ module.exports = { __dirname, 'unicode-path/中文-にほんご-한글-🌕🌖🌗/index.html' ), - linkProps: resolve(__dirname, 'link-props/index.html') + linkProps: resolve(__dirname, 'link-props/index.html'), + valid: resolve(__dirname, 'valid.html') } } }, From 471d2299ef5137c8d625c43e57f50fbf2dbd3262 Mon Sep 17 00:00:00 2001 From: patak-dev Date: Sun, 21 Aug 2022 20:55:54 +0200 Subject: [PATCH 5/9] chore: support ' --- packages/vite/src/node/plugins/html.ts | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/packages/vite/src/node/plugins/html.ts b/packages/vite/src/node/plugins/html.ts index 1db8b5e593fd92..6c3db7ddfb3dad 100644 --- a/packages/vite/src/node/plugins/html.ts +++ b/packages/vite/src/node/plugins/html.ts @@ -191,7 +191,7 @@ export function getScriptInfo(node: DefaultTreeAdapterMap['element']): { return { src, sourceCodeLocation, isModule, isAsync } } -const attrValueWithQuotesStartRE = /=[\s\t\n\r]*"/ +const attrValueStartRE = /=[\s\t\n\r]*(["']|.)/ export function overwriteAttrValue( s: MagicString, @@ -202,12 +202,18 @@ export function overwriteAttrValue( sourceCodeLocation!.startOffset, sourceCodeLocation!.endOffset ) - const valueWithQuotes = srcString.match(attrValueWithQuotesStartRE) - const valueOffset = - 1 + (valueWithQuotes ? srcString.indexOf('"') : srcString.indexOf('=')) + const valueStart = srcString.match(attrValueStartRE) + if (!valueStart) { + // overwrite attr value can only be called for a well-defined value + throw new Error( + `[vite:html] internal error, failed to overwrite attribute value` + ) + } + const wrapOffset = valueStart[1] ? 1 : 0 + const valueOffset = valueStart.index! + valueStart[0].length - 1 s.overwrite( - sourceCodeLocation.startOffset + valueOffset, - sourceCodeLocation.endOffset + (valueWithQuotes ? -1 : 0), + sourceCodeLocation.startOffset + valueOffset + wrapOffset, + sourceCodeLocation.endOffset - wrapOffset, newValue, { contentOnly: true } ) From f4ccb59620c33fd4966f203fc285d9246f2d8542 Mon Sep 17 00:00:00 2001 From: patak-dev Date: Tue, 23 Aug 2022 08:11:22 +0200 Subject: [PATCH 6/9] chore: reinstate importmap test --- playground/html/__tests__/html.spec.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/playground/html/__tests__/html.spec.ts b/playground/html/__tests__/html.spec.ts index 4c0376636abd5b..388496bb49900f 100644 --- a/playground/html/__tests__/html.spec.ts +++ b/playground/html/__tests__/html.spec.ts @@ -1,5 +1,13 @@ import { beforeAll, describe, expect, test } from 'vitest' -import { editFile, getColor, isBuild, isServe, page, viteTestUrl } from '~utils' +import { + browserLogs, + editFile, + getColor, + isBuild, + isServe, + page, + viteTestUrl +} from '~utils' function testPage(isNested: boolean) { test('pre transform', async () => { @@ -242,3 +250,9 @@ describe.runIf(isServe)('invalid', () => { expect(content).toBeTruthy() }) }) + +test('importmap', () => { + expect(browserLogs).not.toContain( + 'An import map is added after module script load was triggered.' + ) +}) From 29d1e58ed7518de320f24aa47f82965b6804a68e Mon Sep 17 00:00:00 2001 From: patak Date: Tue, 23 Aug 2022 13:34:04 +0200 Subject: [PATCH 7/9] chore: update Co-authored-by: Shinigami --- packages/vite/src/node/plugins/html.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/vite/src/node/plugins/html.ts b/packages/vite/src/node/plugins/html.ts index 25ea2ecc4bf46a..dd6f3ea176fc3c 100644 --- a/packages/vite/src/node/plugins/html.ts +++ b/packages/vite/src/node/plugins/html.ts @@ -182,8 +182,7 @@ export function getScriptInfo(node: DefaultTreeAdapterMap['element']): { let sourceCodeLocation: Token.Location | undefined let isModule = false let isAsync = false - for (let i = 0; i < node.attrs.length; i++) { - const p = node.attrs[i] + for (const p of node.attrs) { if (p.name === 'src') { src = p sourceCodeLocation = node.sourceCodeLocation?.attrs!['src'] From 21e18cc09c46c0368b4eb37bbdf03128951efce2 Mon Sep 17 00:00:00 2001 From: patak Date: Tue, 23 Aug 2022 16:18:40 +0200 Subject: [PATCH 8/9] chore: update MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 翠 / green --- packages/vite/src/node/plugins/html.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/vite/src/node/plugins/html.ts b/packages/vite/src/node/plugins/html.ts index dd6f3ea176fc3c..d2fc5c25c40ad7 100644 --- a/packages/vite/src/node/plugins/html.ts +++ b/packages/vite/src/node/plugins/html.ts @@ -184,8 +184,10 @@ export function getScriptInfo(node: DefaultTreeAdapterMap['element']): { let isAsync = false for (const p of node.attrs) { if (p.name === 'src') { - src = p - sourceCodeLocation = node.sourceCodeLocation?.attrs!['src'] + if (!src) { + src = p + sourceCodeLocation = node.sourceCodeLocation?.attrs!['src'] + } } else if (p.name === 'type' && p.value && p.value === 'module') { isModule = true } else if (p.name === 'async') { From d36eb2a4506ec48867a19356555a90d373880d64 Mon Sep 17 00:00:00 2001 From: patak Date: Tue, 23 Aug 2022 16:19:55 +0200 Subject: [PATCH 9/9] chore: update MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 翠 / green --- packages/vite/src/node/plugins/html.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/vite/src/node/plugins/html.ts b/packages/vite/src/node/plugins/html.ts index d2fc5c25c40ad7..c0963f5f5f459f 100644 --- a/packages/vite/src/node/plugins/html.ts +++ b/packages/vite/src/node/plugins/html.ts @@ -205,8 +205,8 @@ export function overwriteAttrValue( newValue: string ): MagicString { const srcString = s.slice( - sourceCodeLocation!.startOffset, - sourceCodeLocation!.endOffset + sourceCodeLocation.startOffset, + sourceCodeLocation.endOffset ) const valueStart = srcString.match(attrValueStartRE) if (!valueStart) {