first commit

This commit is contained in:
monjack
2025-06-20 18:01:48 +08:00
commit 6daa6d65c1
24611 changed files with 2512443 additions and 0 deletions

View File

@ -0,0 +1,69 @@
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = class CorsPlugin {
constructor ({ publicPath, crossorigin, integrity }) {
this.crossorigin = crossorigin
this.integrity = integrity
this.publicPath = publicPath
}
apply (compiler) {
const ID = `vue-cli-cors-plugin`
compiler.hooks.compilation.tap(ID, compilation => {
const ssri = require('ssri')
const computeHash = url => {
const filename = url.replace(this.publicPath, '')
const asset = compilation.assets[filename]
if (asset) {
const src = asset.source()
const integrity = ssri.fromData(src, {
algorithms: ['sha384']
})
return integrity.toString()
}
}
HtmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tap(ID, data => {
const tags = [...data.headTags, ...data.bodyTags]
if (this.crossorigin != null) {
tags.forEach(tag => {
if (tag.tagName === 'script' || tag.tagName === 'link') {
tag.attributes.crossorigin = this.crossorigin
}
})
}
if (this.integrity) {
tags.forEach(tag => {
if (tag.tagName === 'script') {
const hash = computeHash(tag.attributes.src)
if (hash) {
tag.attributes.integrity = hash
}
} else if (tag.tagName === 'link' && tag.attributes.rel === 'stylesheet') {
const hash = computeHash(tag.attributes.href)
if (hash) {
tag.attributes.integrity = hash
}
}
})
// when using SRI, Chrome somehow cannot reuse
// the preloaded resource, and causes the files to be downloaded twice.
// this is a Chrome bug (https://bugs.chromium.org/p/chromium/issues/detail?id=677022)
// for now we disable preload if SRI is used.
data.headTags = data.headTags.filter(tag => {
return !(
tag.tagName === 'link' &&
tag.attributes.rel === 'preload'
)
})
}
})
HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tap(ID, data => {
data.html = data.html.replace(/\scrossorigin=""/g, ' crossorigin')
})
})
}
}

View File

@ -0,0 +1,223 @@
// From https://github.com/FormidableLabs/webpack-dashboard/blob/7f99b31c5f00a7818d8129cb8a8fc6eb1b71799c/plugin/index.js
// Modified by Guillaume Chau (Akryum)
/* eslint-disable max-params, max-statements */
'use strict'
const path = require('path')
const fs = require('fs-extra')
const webpack = require('webpack')
const { IpcMessenger } = require('@vue/cli-shared-utils')
const { analyzeBundle } = require('./analyzeBundle')
const ID = 'vue-cli-dashboard-plugin'
const ONE_SECOND = 1000
const FILENAME_QUERY_REGEXP = /\?.*$/
const ipc = new IpcMessenger()
function getTimeMessage (timer) {
let time = Date.now() - timer
if (time >= ONE_SECOND) {
time /= ONE_SECOND
time = Math.round(time)
time += 's'
} else {
time += 'ms'
}
return ` (${time})`
}
class DashboardPlugin {
constructor (options) {
this.type = options.type
if (this.type === 'build' && options.moduleBuild) {
this.type = 'build-modern'
}
this.watching = false
this.autoDisconnect = !options.keepAlive
}
cleanup () {
this.sendData = null
if (this.autoDisconnect) ipc.disconnect()
}
apply (compiler) {
let sendData = this.sendData
let timer
let inProgress = false
let assetSources = new Map()
if (!sendData) {
sendData = data => ipc.send({
webpackDashboardData: {
type: this.type,
value: data
}
})
}
// Progress status
let progressTime = Date.now()
const progressPlugin = new webpack.ProgressPlugin((percent, msg) => {
// in webpack 5, progress plugin will continue sending progresses even after the done hook
// for things like caching, causing the progress indicator stuck at 0.99
// so we have to use a flag to stop sending such `compiling` progress data
if (!inProgress) {
return
}
// Debouncing
const time = Date.now()
if (time - progressTime > 300) {
progressTime = time
sendData([
{
type: 'status',
value: 'Compiling'
},
{
type: 'progress',
value: percent
},
{
type: 'operations',
value: msg + getTimeMessage(timer)
}
])
}
})
progressPlugin.apply(compiler)
compiler.hooks.watchRun.tap(ID, c => {
this.watching = true
})
compiler.hooks.run.tap(ID, c => {
this.watching = false
})
compiler.hooks.compile.tap(ID, () => {
inProgress = true
timer = Date.now()
sendData([
{
type: 'status',
value: 'Compiling'
},
{
type: 'progress',
value: 0
}
])
})
compiler.hooks.invalid.tap(ID, () => {
sendData([
{
type: 'status',
value: 'Invalidated'
},
{
type: 'progress',
value: 0
},
{
type: 'operations',
value: 'idle'
}
])
})
compiler.hooks.failed.tap(ID, () => {
sendData([
{
type: 'status',
value: 'Failed'
},
{
type: 'operations',
value: `idle${getTimeMessage(timer)}`
}
])
inProgress = false
})
compiler.hooks.afterEmit.tap(ID, compilation => {
assetSources = new Map()
for (const name in compilation.assets) {
const asset = compilation.assets[name]
const filename = name.replace(FILENAME_QUERY_REGEXP, '')
try {
assetSources.set(filename, asset.source())
} catch (e) {
const webpackFs = compiler.outputFileSystem
const fullPath = (webpackFs.join || path.join)(compiler.options.output.path, filename)
const buf = webpackFs.readFileSync(fullPath)
assetSources.set(filename, buf.toString())
}
}
})
compiler.hooks.done.tap(ID, stats => {
let statsData = stats.toJson()
// Sometimes all the information is located in `children` array
if ((!statsData.assets || !statsData.assets.length) && statsData.children && statsData.children.length) {
statsData = statsData.children[0]
}
const outputPath = compiler.options.output.path
statsData.assets.forEach(asset => {
// Removing query part from filename (yes, somebody uses it for some reason and Webpack supports it)
asset.name = asset.name.replace(FILENAME_QUERY_REGEXP, '')
asset.fullPath = path.join(outputPath, asset.name)
})
// Analyze the assets and update sizes on assets and modules
analyzeBundle(statsData, assetSources)
const hasErrors = stats.hasErrors()
sendData([
{
type: 'status',
value: hasErrors ? 'Failed' : 'Success'
},
{
type: 'progress',
value: 1
},
{
type: 'operations',
value: `idle${getTimeMessage(timer)}`
}
])
inProgress = false
const statsFile = path.resolve(process.cwd(), `./node_modules/.stats-${this.type}.json`)
fs.writeJson(statsFile, {
errors: hasErrors,
warnings: stats.hasWarnings(),
data: statsData
}).then(() => {
sendData([
{
type: 'stats'
}
])
if (!this.watching) {
this.cleanup()
}
}).catch(error => {
console.error(error)
})
})
}
}
module.exports = DashboardPlugin

View File

@ -0,0 +1,86 @@
const fs = require('fs-extra')
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
class ModernModePlugin {
constructor ({ targetDir, isModuleBuild }) {
this.targetDir = targetDir
this.isModuleBuild = isModuleBuild
}
apply (compiler) {
if (!this.isModuleBuild) {
this.applyLegacy(compiler)
} else {
this.applyModule(compiler)
}
}
applyLegacy (compiler) {
const ID = `vue-cli-legacy-bundle`
compiler.hooks.compilation.tap(ID, compilation => {
HtmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tapAsync(ID, async (data, cb) => {
// get stats, write to disk
await fs.ensureDir(this.targetDir)
const htmlName = path.basename(data.plugin.options.filename)
// Watch out for output files in sub directories
const htmlPath = path.dirname(data.plugin.options.filename)
const tempFilename = path.join(this.targetDir, htmlPath, `legacy-assets-${htmlName}.json`)
await fs.mkdirp(path.dirname(tempFilename))
let tags = data.bodyTags
if (data.plugin.options.scriptLoading === 'defer') {
tags = data.headTags
}
await fs.writeFile(tempFilename, JSON.stringify(tags))
cb()
})
})
}
applyModule (compiler) {
const ID = `vue-cli-modern-bundle`
compiler.hooks.compilation.tap(ID, compilation => {
HtmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tapAsync(ID, async (data, cb) => {
let tags = data.bodyTags
if (data.plugin.options.scriptLoading === 'defer') {
tags = data.headTags
}
// use <script type="module"> for modern assets
tags.forEach(tag => {
if (tag.tagName === 'script' && tag.attributes) {
tag.attributes.type = 'module'
}
})
// use <link rel="modulepreload"> instead of <link rel="preload">
// for modern assets
data.headTags.forEach(tag => {
if (tag.tagName === 'link' &&
tag.attributes.rel === 'preload' &&
tag.attributes.as === 'script') {
tag.attributes.rel = 'modulepreload'
}
})
// inject links for legacy assets as <script nomodule>
const htmlName = path.basename(data.plugin.options.filename)
// Watch out for output files in sub directories
const htmlPath = path.dirname(data.plugin.options.filename)
const tempFilename = path.join(this.targetDir, htmlPath, `legacy-assets-${htmlName}.json`)
const legacyAssets = JSON.parse(await fs.readFile(tempFilename, 'utf-8'))
.filter(a => a.tagName === 'script' && a.attributes)
legacyAssets.forEach(a => { a.attributes.nomodule = '' })
tags.push(...legacyAssets)
await fs.remove(tempFilename)
cb()
})
HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tap(ID, data => {
data.html = data.html.replace(/\snomodule="">/g, ' nomodule>')
})
})
}
}
module.exports = ModernModePlugin

View File

@ -0,0 +1,16 @@
const fs = require('fs-extra')
module.exports = class MovePlugin {
constructor (from, to) {
this.from = from
this.to = to
}
apply (compiler) {
compiler.hooks.done.tap('move-plugin', () => {
if (fs.existsSync(this.from)) {
fs.moveSync(this.from, this.to, { overwrite: true })
}
})
}
}

View File

@ -0,0 +1,71 @@
// https://gist.github.com/samthor/64b114e4a4f539915a95b91ffd340acc
const safariFix = `!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()},!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();`
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { semver } = require('@vue/cli-shared-utils')
const { projectModuleTargets } = require('../util/targets')
const minSafariVersion = projectModuleTargets.safari
const minIOSVersion = projectModuleTargets.ios
const supportsSafari10 =
(minSafariVersion && semver.lt(semver.coerce(minSafariVersion), '11.0.0')) ||
(minIOSVersion && semver.lt(semver.coerce(minIOSVersion), '11.0.0'))
const needsSafariFix = supportsSafari10
class SafariNomoduleFixPlugin {
constructor ({ unsafeInline, jsDirectory }) {
this.unsafeInline = unsafeInline
this.jsDirectory = jsDirectory
}
apply (compiler) {
if (!needsSafariFix) {
return
}
const { RawSource } = compiler.webpack
? compiler.webpack.sources
: require('webpack-sources')
const ID = 'SafariNomoduleFixPlugin'
compiler.hooks.compilation.tap(ID, compilation => {
HtmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tap(ID, data => {
let scriptTag
if (this.unsafeInline) {
// inject inline Safari 10 nomodule fix
scriptTag = {
tagName: 'script',
closeTag: true,
innerHTML: safariFix
}
} else {
// inject the fix as an external script
const safariFixPath = path.join(this.jsDirectory, 'safari-nomodule-fix.js')
const fullSafariFixPath = path.join(compilation.options.output.publicPath, safariFixPath)
compilation.assets[safariFixPath] = new RawSource(safariFix)
scriptTag = {
tagName: 'script',
closeTag: true,
attributes: {
src: fullSafariFixPath
}
}
}
let tags = data.bodyTags
if (data.plugin.options.scriptLoading === 'defer') {
tags = data.headTags
}
// insert just before the first actual script tag,
// and after all other tags such as `meta`
const firstScriptIndex = tags.findIndex(tag => tag.tagName === 'script')
tags.splice(firstScriptIndex, 0, scriptTag)
})
})
}
}
SafariNomoduleFixPlugin.safariFix = safariFix
module.exports = SafariNomoduleFixPlugin

View File

@ -0,0 +1,446 @@
// From https://github.com/webpack-contrib/webpack-bundle-analyzer/blob/4abac503c789bac94118e5bbfc410686fb5112c7/src/parseUtils.js
// Modified by Guillaume Chau (Akryum)
const acorn = require('acorn')
const walk = require('acorn-walk')
const mapValues = require('lodash.mapvalues')
const zlib = require('zlib')
const { warn } = require('@vue/cli-shared-utils')
exports.analyzeBundle = function analyzeBundle (bundleStats, assetSources) {
// Picking only `*.js` assets from bundle that has non-empty `chunks` array
const jsAssets = []
const otherAssets = []
// Separate JS assets
bundleStats.assets.forEach(asset => {
if (asset.name.endsWith('.js') && asset.chunks && asset.chunks.length) {
jsAssets.push(asset)
} else {
otherAssets.push(asset)
}
})
// Trying to parse bundle assets and get real module sizes
let bundlesSources = null
let parsedModules = null
bundlesSources = {}
parsedModules = {}
for (const asset of jsAssets) {
const source = assetSources.get(asset.name)
let bundleInfo
try {
bundleInfo = parseBundle(source)
} catch (err) {
const msg = (err.code === 'ENOENT') ? 'no such file' : err.message
warn(`Error parsing bundle asset "${asset.fullPath}": ${msg}`)
continue
}
bundlesSources[asset.name] = bundleInfo.src
Object.assign(parsedModules, bundleInfo.modules)
}
if (!Object.keys(bundlesSources).length) {
bundlesSources = null
parsedModules = null
warn('\nNo bundles were parsed. Analyzer will show only original module sizes from stats file.\n')
}
// Update sizes
bundleStats.modules.forEach(module => {
const parsedSrc = parsedModules && parsedModules[module.id]
module.size = {
stats: module.size
}
if (parsedSrc) {
module.size.parsed = parsedSrc.length
module.size.gzip = getGzipSize(parsedSrc)
} else {
module.size.parsed = module.size.stats
module.size.gzip = 0
}
})
jsAssets.forEach(asset => {
const src = bundlesSources && bundlesSources[asset.name]
asset.size = {
stats: asset.size
}
if (src) {
asset.size.parsed = src.length
asset.size.gzip = getGzipSize(src)
} else {
asset.size.parsed = asset.size.stats
asset.size.gzip = 0
}
}, {})
otherAssets.forEach(asset => {
const src = assetSources.get(asset.name)
asset.size = {
stats: asset.size,
parsed: asset.size
}
if (src) {
asset.size.gzip = getGzipSize(src)
} else {
asset.size.gzip = 0
}
})
}
function parseBundle (bundleContent) {
const ast = acorn.parse(bundleContent, {
sourceType: 'script',
// I believe in a bright future of ECMAScript!
// Actually, it's set to `2050` to support the latest ECMAScript version that currently exists.
// Seems like `acorn` supports such weird option value.
ecmaVersion: 2050
})
const walkState = {
locations: null,
expressionStatementDepth: 0
}
walk.recursive(
ast,
walkState,
{
ExpressionStatement (node, state, c) {
if (state.locations) return
state.expressionStatementDepth++
if (
// Webpack 5 stores modules in the the top-level IIFE
state.expressionStatementDepth === 1 &&
ast.body.includes(node) &&
isIIFE(node)
) {
const fn = getIIFECallExpression(node)
if (
// It should not contain neither arguments
fn.arguments.length === 0 &&
// ...nor parameters
fn.callee.params.length === 0
) {
// Modules are stored in the very first variable declaration as hash
const firstVariableDeclaration = fn.callee.body.body.find(n => n.type === 'VariableDeclaration')
if (firstVariableDeclaration) {
for (const declaration of firstVariableDeclaration.declarations) {
if (declaration.init) {
state.locations = getModulesLocations(declaration.init)
if (state.locations) {
break
}
}
}
}
}
}
if (!state.locations) {
c(node.expression, state)
}
state.expressionStatementDepth--
},
AssignmentExpression (node, state) {
if (state.locations) return
// Modules are stored in exports.modules:
// exports.modules = {};
const { left, right } = node
if (
left &&
left.object && left.object.name === 'exports' &&
left.property && left.property.name === 'modules' &&
isModulesHash(right)
) {
state.locations = getModulesLocations(right)
}
},
CallExpression (node, state, c) {
if (state.locations) return
const args = node.arguments
// Main chunk with webpack loader.
// Modules are stored in first argument:
// (function (...) {...})(<modules>)
if (
node.callee.type === 'FunctionExpression' &&
!node.callee.id &&
args.length === 1 &&
isSimpleModulesList(args[0])
) {
state.locations = getModulesLocations(args[0])
return
}
// Async Webpack < v4 chunk without webpack loader.
// webpackJsonp([<chunks>], <modules>, ...)
// As function name may be changed with `output.jsonpFunction` option we can't rely on it's default name.
if (
node.callee.type === 'Identifier' &&
mayBeAsyncChunkArguments(args) &&
isModulesList(args[1])
) {
state.locations = getModulesLocations(args[1])
return
}
// Async Webpack v4 chunk without webpack loader.
// (window.webpackJsonp=window.webpackJsonp||[]).push([[<chunks>], <modules>, ...]);
// As function name may be changed with `output.jsonpFunction` option we can't rely on it's default name.
if (isAsyncChunkPushExpression(node)) {
state.locations = getModulesLocations(args[0].elements[1])
return
}
// Webpack v4 WebWorkerChunkTemplatePlugin
// globalObject.chunkCallbackName([<chunks>],<modules>, ...);
// Both globalObject and chunkCallbackName can be changed through the config, so we can't check them.
if (isAsyncWebWorkerChunkExpression(node)) {
state.locations = getModulesLocations(args[1])
return
}
// Walking into arguments because some of plugins (e.g. `DedupePlugin`) or some Webpack
// features (e.g. `umd` library output) can wrap modules list into additional IIFE.
args.forEach(arg => c(arg, state))
}
}
)
let modules
if (walkState.locations) {
modules = mapValues(walkState.locations,
loc => bundleContent.slice(loc.start, loc.end)
)
} else {
modules = {}
}
return {
modules: modules,
src: bundleContent,
runtimeSrc: getBundleRuntime(bundleContent, walkState.locations)
}
}
function getGzipSize (buffer) {
return zlib.gzipSync(buffer).length
}
/**
* Returns bundle source except modules
*/
function getBundleRuntime (content, modulesLocations) {
const sortedLocations = Object.values(modulesLocations || {})
.sort((a, b) => a.start - b.start)
let result = ''
let lastIndex = 0
for (const { start, end } of sortedLocations) {
result += content.slice(lastIndex, start)
lastIndex = end
}
return result + content.slice(lastIndex, content.length)
}
function isIIFE (node) {
return (
node.type === 'ExpressionStatement' &&
(
node.expression.type === 'CallExpression' ||
(node.expression.type === 'UnaryExpression' && node.expression.argument.type === 'CallExpression')
)
)
}
function getIIFECallExpression (node) {
if (node.expression.type === 'UnaryExpression') {
return node.expression.argument
} else {
return node.expression
}
}
function isModulesList (node) {
return (
isSimpleModulesList(node) ||
// Modules are contained in expression `Array([minimum ID]).concat([<module>, <module>, ...])`
isOptimizedModulesArray(node)
)
}
function isSimpleModulesList (node) {
return (
// Modules are contained in hash. Keys are module ids.
isModulesHash(node) ||
// Modules are contained in array. Indexes are module ids.
isModulesArray(node)
)
}
function isModulesHash (node) {
return (
node.type === 'ObjectExpression' &&
node.properties
.map(p => p.value)
.every(isModuleWrapper)
)
}
function isModulesArray (node) {
return (
node.type === 'ArrayExpression' &&
node.elements.every(elem =>
// Some of array items may be skipped because there is no module with such id
!elem ||
isModuleWrapper(elem)
)
)
}
function isOptimizedModulesArray (node) {
// Checking whether modules are contained in `Array(<minimum ID>).concat(...modules)` array:
// https://github.com/webpack/webpack/blob/v1.14.0/lib/Template.js#L91
// The `<minimum ID>` + array indexes are module ids
return (
node.type === 'CallExpression' &&
node.callee.type === 'MemberExpression' &&
// Make sure the object called is `Array(<some number>)`
node.callee.object.type === 'CallExpression' &&
node.callee.object.callee.type === 'Identifier' &&
node.callee.object.callee.name === 'Array' &&
node.callee.object.arguments.length === 1 &&
isNumericId(node.callee.object.arguments[0]) &&
// Make sure the property X called for `Array(<some number>).X` is `concat`
node.callee.property.type === 'Identifier' &&
node.callee.property.name === 'concat' &&
// Make sure exactly one array is passed in to `concat`
node.arguments.length === 1 &&
isModulesArray(node.arguments[0])
)
}
function isModuleWrapper (node) {
return (
// It's an anonymous function expression that wraps module
((node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') && !node.id) ||
// If `DedupePlugin` is used it can be an ID of duplicated module...
isModuleId(node) ||
// or an array of shape [<module_id>, ...args]
(node.type === 'ArrayExpression' && node.elements.length > 1 && isModuleId(node.elements[0]))
)
}
function isModuleId (node) {
return (node.type === 'Literal' && (isNumericId(node) || typeof node.value === 'string'))
}
function isNumericId (node) {
return (node.type === 'Literal' && Number.isInteger(node.value) && node.value >= 0)
}
function isChunkIds (node) {
// Array of numeric or string ids. Chunk IDs are strings when NamedChunksPlugin is used
return (
node.type === 'ArrayExpression' &&
node.elements.every(isModuleId)
)
}
function isAsyncChunkPushExpression (node) {
const {
callee,
arguments: args
} = node
return (
callee.type === 'MemberExpression' &&
callee.property.name === 'push' &&
callee.object.type === 'AssignmentExpression' &&
args.length === 1 &&
args[0].type === 'ArrayExpression' &&
mayBeAsyncChunkArguments(args[0].elements) &&
isModulesList(args[0].elements[1])
)
}
function mayBeAsyncChunkArguments (args) {
return (
args.length >= 2 &&
isChunkIds(args[0])
)
}
function isAsyncWebWorkerChunkExpression (node) {
const { callee, type, arguments: args } = node
return (
type === 'CallExpression' &&
callee.type === 'MemberExpression' &&
args.length === 2 &&
isChunkIds(args[0]) &&
isModulesList(args[1])
)
}
function getModulesLocations (node) {
if (node.type === 'ObjectExpression') {
// Modules hash
const modulesNodes = node.properties
return modulesNodes.reduce((result, moduleNode) => {
const moduleId = moduleNode.key.name || moduleNode.key.value
result[moduleId] = getModuleLocation(moduleNode.value)
return result
}, {})
}
const isOptimizedArray = (node.type === 'CallExpression')
if (node.type === 'ArrayExpression' || isOptimizedArray) {
// Modules array or optimized array
const minId = isOptimizedArray
// Get the [minId] value from the Array() call first argument literal value
? node.callee.object.arguments[0].value
// `0` for simple array
: 0
const modulesNodes = isOptimizedArray
// The modules reside in the `concat()` function call arguments
? node.arguments[0].elements
: node.elements
return modulesNodes.reduce((result, moduleNode, i) => {
if (moduleNode) {
result[i + minId] = getModuleLocation(moduleNode)
}
return result
}, {})
}
return {}
}
function getModuleLocation (node) {
return { start: node.start, end: node.end }
}