From 5ce7c746c342a472e94a4a92ed92246c8a5a2027 Mon Sep 17 00:00:00 2001 From: Bjorn Lu Date: Thu, 12 May 2022 02:47:03 +0800 Subject: [PATCH] refactor: use node hash (#7975) --- packages/plugin-vue-jsx/index.js | 18 +++++++++++++----- packages/plugin-vue-jsx/package.json | 3 +-- packages/plugin-vue/package.json | 1 - .../plugin-vue/src/utils/descriptorCache.ts | 8 ++++++-- packages/vite/src/node/__tests__/asset.spec.ts | 10 +--------- packages/vite/src/node/__tests__/utils.spec.ts | 8 ++++++++ packages/vite/src/node/optimizer/index.ts | 6 +----- .../vite/src/node/optimizer/registerMissing.ts | 2 +- packages/vite/src/node/plugins/asset.ts | 11 +++-------- packages/vite/src/node/plugins/css.ts | 6 +++--- packages/vite/src/node/plugins/html.ts | 6 +++--- packages/vite/src/node/plugins/worker.ts | 8 ++++---- packages/vite/src/node/utils.ts | 5 +++++ pnpm-lock.yaml | 7 ------- 14 files changed, 49 insertions(+), 50 deletions(-) diff --git a/packages/plugin-vue-jsx/index.js b/packages/plugin-vue-jsx/index.js index 929f4fb44cd434..41fcb911c461b1 100644 --- a/packages/plugin-vue-jsx/index.js +++ b/packages/plugin-vue-jsx/index.js @@ -3,7 +3,7 @@ const babel = require('@babel/core') const jsx = require('@vue/babel-plugin-jsx') const importMeta = require('@babel/plugin-syntax-import-meta') const { createFilter, normalizePath } = require('@rollup/pluginutils') -const hash = require('hash-sum') +const { createHash } = require('crypto') const path = require('path') const ssrRegisterHelperId = '/__vue-jsx-ssr-register-helper' @@ -152,7 +152,7 @@ function vueJsxPlugin(options = {}) { ({ name }) => ({ local: name, exported: name, - id: hash(id + name) + id: getHash(id + name) }) ) ) @@ -169,7 +169,7 @@ function vueJsxPlugin(options = {}) { hotComponents.push({ local: spec.local.name, exported: spec.exported.name, - id: hash(id + spec.exported.name) + id: getHash(id + spec.exported.name) }) } } @@ -187,7 +187,7 @@ function vueJsxPlugin(options = {}) { hotComponents.push({ local: node.declaration.name, exported: 'default', - id: hash(id + 'default') + id: getHash(id + 'default') }) } } else if (isDefineComponentCall(node.declaration)) { @@ -195,7 +195,7 @@ function vueJsxPlugin(options = {}) { hotComponents.push({ local: '__default__', exported: 'default', - id: hash(id + 'default') + id: getHash(id + 'default') }) } } @@ -276,5 +276,13 @@ function isDefineComponentCall(node) { ) } +/** + * @param {string} text + * @returns {string} + */ +function getHash(text) { + return createHash('sha256').update(text).digest('hex').substring(0, 8) +} + module.exports = vueJsxPlugin vueJsxPlugin.default = vueJsxPlugin diff --git a/packages/plugin-vue-jsx/package.json b/packages/plugin-vue-jsx/package.json index 11e83bac3321b6..f62a6cd98a67ee 100644 --- a/packages/plugin-vue-jsx/package.json +++ b/packages/plugin-vue-jsx/package.json @@ -26,8 +26,7 @@ "@babel/plugin-syntax-import-meta": "^7.10.4", "@babel/plugin-transform-typescript": "^7.16.8", "@rollup/pluginutils": "^4.2.1", - "@vue/babel-plugin-jsx": "^1.1.1", - "hash-sum": "^2.0.0" + "@vue/babel-plugin-jsx": "^1.1.1" }, "peerDependencies": { "vite": "^2.0.0", diff --git a/packages/plugin-vue/package.json b/packages/plugin-vue/package.json index 5ee997fe4c05d0..22ce5ad55ab68b 100644 --- a/packages/plugin-vue/package.json +++ b/packages/plugin-vue/package.json @@ -37,7 +37,6 @@ "devDependencies": { "@rollup/pluginutils": "^4.2.1", "debug": "^4.3.4", - "hash-sum": "^2.0.0", "rollup": "^2.72.1", "slash": "^4.0.0", "source-map": "^0.6.1", diff --git a/packages/plugin-vue/src/utils/descriptorCache.ts b/packages/plugin-vue/src/utils/descriptorCache.ts index 5143a6131d5ddc..890c817a217212 100644 --- a/packages/plugin-vue/src/utils/descriptorCache.ts +++ b/packages/plugin-vue/src/utils/descriptorCache.ts @@ -1,7 +1,7 @@ import fs from 'fs' import path from 'path' +import { createHash } from 'crypto' import slash from 'slash' -import hash from 'hash-sum' import type { CompilerError, SFCDescriptor } from 'vue/compiler-sfc' import type { ResolvedOptions, VueQuery } from '..' @@ -27,7 +27,7 @@ export function createDescriptor( // ensure the path is normalized in a way that is consistent inside // project (relative to root) and on different systems. const normalizedPath = slash(path.normalize(path.relative(root, filename))) - descriptor.id = hash(normalizedPath + (isProduction ? source : '')) + descriptor.id = getHash(normalizedPath + (isProduction ? source : '')) cache.set(filename, descriptor) return { descriptor, errors } @@ -88,3 +88,7 @@ export function setSrcDescriptor( } cache.set(filename, entry) } + +function getHash(text: string): string { + return createHash('sha256').update(text).digest('hex').substring(0, 8) +} diff --git a/packages/vite/src/node/__tests__/asset.spec.ts b/packages/vite/src/node/__tests__/asset.spec.ts index a756cb12652739..8f627ce299e3ec 100644 --- a/packages/vite/src/node/__tests__/asset.spec.ts +++ b/packages/vite/src/node/__tests__/asset.spec.ts @@ -1,13 +1,5 @@ import { describe, expect, test } from 'vitest' -import { assetFileNamesToFileName, getAssetHash } from '../plugins/asset' - -describe('getAssetHash', () => { - test('8-digit hex', () => { - const hash = getAssetHash(Buffer.alloc(0)) - - expect(hash).toMatch(/^[\da-f]{8}$/) - }) -}) +import { assetFileNamesToFileName } from '../plugins/asset' describe('assetFileNamesToFileName', () => { // on Windows, both forward slashes and backslashes may appear in the input diff --git a/packages/vite/src/node/__tests__/utils.spec.ts b/packages/vite/src/node/__tests__/utils.spec.ts index 74ffa7866fa9b7..c8a824bbb3d28f 100644 --- a/packages/vite/src/node/__tests__/utils.spec.ts +++ b/packages/vite/src/node/__tests__/utils.spec.ts @@ -1,5 +1,6 @@ import { describe, expect, test } from 'vitest' import { + getHash, getPotentialTsSrcPaths, injectQuery, isWindows, @@ -98,3 +99,10 @@ test('ts import of file with .js and query param', () => { 'test-file.js.tsx?lee=123' ]) }) + +describe('getHash', () => { + test('8-digit hex', () => { + const hash = getHash(Buffer.alloc(0)) + expect(hash).toMatch(/^[\da-f]{8}$/) + }) +}) diff --git a/packages/vite/src/node/optimizer/index.ts b/packages/vite/src/node/optimizer/index.ts index 53bffb13e604d0..de09f978cd505c 100644 --- a/packages/vite/src/node/optimizer/index.ts +++ b/packages/vite/src/node/optimizer/index.ts @@ -1,6 +1,5 @@ import fs from 'fs' import path from 'path' -import { createHash } from 'crypto' import { performance } from 'perf_hooks' import _debug from 'debug' import colors from 'picocolors' @@ -12,6 +11,7 @@ import { createDebugger, emptyDir, flattenId, + getHash, lookupFile, normalizeId, normalizePath, @@ -816,10 +816,6 @@ function getOptimizedBrowserHash( return getHash(hash + JSON.stringify(deps) + timestamp) } -export function getHash(text: string): string { - return createHash('sha256').update(text).digest('hex').substring(0, 8) -} - export function optimizedDepInfoFromId( metadata: DepOptimizationMetadata, id: string diff --git a/packages/vite/src/node/optimizer/registerMissing.ts b/packages/vite/src/node/optimizer/registerMissing.ts index 1efb9e02261ae7..2788f83a52f4f4 100644 --- a/packages/vite/src/node/optimizer/registerMissing.ts +++ b/packages/vite/src/node/optimizer/registerMissing.ts @@ -1,5 +1,6 @@ import colors from 'picocolors' import _debug from 'debug' +import { getHash } from '../utils' import type { ViteDevServer } from '..' import { addOptimizedDepInfo, @@ -8,7 +9,6 @@ import { depsFromOptimizedDepInfo, depsLogString, discoverProjectDependencies, - getHash, getOptimizedDepPath, loadCachedDepOptimizationMetadata, newDepOptimizationProcessing, diff --git a/packages/vite/src/node/plugins/asset.ts b/packages/vite/src/node/plugins/asset.ts index db62325509f308..ef5255ba8ee098 100644 --- a/packages/vite/src/node/plugins/asset.ts +++ b/packages/vite/src/node/plugins/asset.ts @@ -1,7 +1,6 @@ import path from 'path' import { parse as parseUrl } from 'url' import fs, { promises as fsp } from 'fs' -import { createHash } from 'crypto' import * as mrmime from 'mrmime' import type { OutputOptions, PluginContext } from 'rollup' import MagicString from 'magic-string' @@ -9,7 +8,7 @@ import type { Plugin } from '../plugin' import type { ResolvedConfig } from '../config' import { cleanUrl } from '../utils' import { FS_PREFIX } from '../constants' -import { normalizePath } from '../utils' +import { getHash, normalizePath } from '../utils' export const assetUrlRE = /__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?/g @@ -195,7 +194,7 @@ export function getAssetFilename( * const fileName = assetFileNamesToFileName( * 'assets/[name].[hash][extname]', * '/path/to/file.txt', - * getAssetHash(content), + * getHash(content), * content * ) * // fileName: 'assets/file.982d9e3e.txt' @@ -300,7 +299,7 @@ async function fileToBuiltUrl( // https://bundlers.tooling.report/hashing/asset-cascade/ // https://github.com/rollup/rollup/issues/3415 const map = assetHashToFilenameMap.get(config)! - const contentHash = getAssetHash(content) + const contentHash = getHash(content) const { search, hash } = parseUrl(id) const postfix = (search || '') + (hash || '') const output = config.build?.rollupOptions?.output @@ -337,10 +336,6 @@ async function fileToBuiltUrl( return url } -export function getAssetHash(content: Buffer | string): string { - return createHash('sha256').update(content).digest('hex').slice(0, 8) -} - export async function urlToBuiltUrl( url: string, importer: string, diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index bee3e37d4cbe38..1f58de158fdea3 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -33,6 +33,7 @@ import { cleanUrl, combineSourcemaps, generateCodeFrame, + getHash, isDataUrl, isExternalUrl, isObject, @@ -46,8 +47,7 @@ import { assetUrlRE, checkPublicFile, fileToUrl, - getAssetFilename, - getAssetHash + getAssetFilename } from './asset' // const debug = createDebugger('vite:css') @@ -360,7 +360,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin { const query = parseRequest(id) if (inlineCSS && isHTMLProxy) { addToHTMLProxyTransformResult( - `${getAssetHash(cleanUrl(id))}_${Number.parseInt(query!.index)}`, + `${getHash(cleanUrl(id))}_${Number.parseInt(query!.index)}`, css ) return `export default ''` diff --git a/packages/vite/src/node/plugins/html.ts b/packages/vite/src/node/plugins/html.ts index ea178287f672a1..8e48a023d021cc 100644 --- a/packages/vite/src/node/plugins/html.ts +++ b/packages/vite/src/node/plugins/html.ts @@ -21,6 +21,7 @@ import type { ViteDevServer } from '../server' import { cleanUrl, generateCodeFrame, + getHash, isDataUrl, isExternalUrl, normalizePath, @@ -32,7 +33,6 @@ import { assetUrlRE, checkPublicFile, getAssetFilename, - getAssetHash, urlToBuiltUrl } from './asset' import { isCSSRequest } from './css' @@ -380,7 +380,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { addToHTMLProxyCache(config, filePath, inlineModuleIndex, { code }) // will transform with css plugin and cache result with css-post plugin js += `\nimport "${id}?html-proxy&inline-css&index=${inlineModuleIndex}.css"` - const hash = getAssetHash(cleanUrl(id)) + const hash = getHash(cleanUrl(id)) // will transform in `applyHtmlTransforms` s.overwrite( styleNode.loc.start.offset, @@ -399,7 +399,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { code: styleNode.content }) js += `\nimport "${id}?html-proxy&inline-css&index=${inlineModuleIndex}.css"` - const hash = getAssetHash(cleanUrl(id)) + const hash = getHash(cleanUrl(id)) // will transform in `applyHtmlTransforms` s.overwrite( styleNode.loc.start.offset, diff --git a/packages/vite/src/node/plugins/worker.ts b/packages/vite/src/node/plugins/worker.ts index b5b33e27bc860b..ec4e255a79f1dc 100644 --- a/packages/vite/src/node/plugins/worker.ts +++ b/packages/vite/src/node/plugins/worker.ts @@ -3,10 +3,10 @@ import type Rollup from 'rollup' import type { EmittedFile, TransformPluginContext } from 'rollup' import type { ResolvedConfig } from '../config' import type { Plugin } from '../plugin' -import { cleanUrl, injectQuery, parseRequest } from '../utils' +import { cleanUrl, getHash, injectQuery, parseRequest } from '../utils' import { ENV_PUBLIC_PATH } from '../constants' import { onRollupWarning } from '../build' -import { fileToUrl, getAssetHash } from './asset' +import { fileToUrl } from './asset' interface WorkerCache { // save worker bundle emitted files avoid overwrites the same file. @@ -143,7 +143,7 @@ function emitSourcemapForWorkerEntry( const basename = path.parse(cleanUrl(id)).name const data = sourcemap.toString() const content = Buffer.from(data) - const contentHash = getAssetHash(content) + const contentHash = getHash(content) const fileName = `${basename}.${contentHash}.js.map` const filePath = path.posix.join(config.build.assetsDir, fileName) emitWorkerSourcemap(context, config, { @@ -186,7 +186,7 @@ export async function workerFileToUrl( } const code = await bundleWorkerEntry(ctx, config, id, query) const basename = path.parse(cleanUrl(id)).name - const contentHash = getAssetHash(code) + const contentHash = getHash(code) const fileName = path.posix.join( config.build.assetsDir, `${basename}.${contentHash}.js` diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index 1e9e23c483d1ef..3748aa3b465b2c 100644 --- a/packages/vite/src/node/utils.ts +++ b/packages/vite/src/node/utils.ts @@ -1,6 +1,7 @@ import fs from 'fs' import os from 'os' import path from 'path' +import { createHash } from 'crypto' import { promisify } from 'util' import { URL, pathToFileURL } from 'url' import { builtinModules } from 'module' @@ -769,6 +770,10 @@ export function parseRequest(id: string): Record | null { export const blankReplacer = (match: string) => ' '.repeat(match.length) +export function getHash(text: Buffer | string): string { + return createHash('sha256').update(text).digest('hex').substring(0, 8) +} + // Based on node-graceful-fs // The ISC License diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f5fd44ef00fe56..57c9a304b34629 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -160,7 +160,6 @@ importers: specifiers: '@rollup/pluginutils': ^4.2.1 debug: ^4.3.4 - hash-sum: ^2.0.0 rollup: ^2.72.1 slash: ^4.0.0 source-map: ^0.6.1 @@ -168,7 +167,6 @@ importers: devDependencies: '@rollup/pluginutils': 4.2.1 debug: 4.3.4 - hash-sum: 2.0.0 rollup: 2.72.1 slash: 4.0.0 source-map: 0.6.1 @@ -181,14 +179,12 @@ importers: '@babel/plugin-transform-typescript': ^7.16.8 '@rollup/pluginutils': ^4.2.1 '@vue/babel-plugin-jsx': ^1.1.1 - hash-sum: ^2.0.0 dependencies: '@babel/core': 7.17.10 '@babel/plugin-syntax-import-meta': 7.10.4_@babel+core@7.17.10 '@babel/plugin-transform-typescript': 7.16.8_@babel+core@7.17.10 '@rollup/pluginutils': 4.2.1 '@vue/babel-plugin-jsx': 1.1.1_@babel+core@7.17.10 - hash-sum: 2.0.0 packages/vite: specifiers: @@ -4637,9 +4633,6 @@ packages: dependencies: function-bind: 1.1.1 - /hash-sum/2.0.0: - resolution: {integrity: sha512-WdZTbAByD+pHfl/g9QSsBIIwy8IT+EsPiKDs0KNX+zSHhdDLFKdZu0BQHljvO+0QI/BasbMSUa8wYNCZTvhslg==} - /helpertypes/0.0.2: resolution: {integrity: sha512-PKVtWnJ+dcvPeUJRiqtbraN/Hr2rNEnS14T/IxDBb0KgHkAL5w4YwVxMEPowA9vyoMP0DrwO0TxJ+KH3UF/6YA==} engines: {node: '>=10.0.0'}