Skip to content

Commit 5ce7c74

Browse files
authored
refactor: use node hash (#7975)
1 parent 774bd28 commit 5ce7c74

File tree

14 files changed

+49
-50
lines changed

14 files changed

+49
-50
lines changed

Diff for: packages/plugin-vue-jsx/index.js

+13-5
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ const babel = require('@babel/core')
33
const jsx = require('@vue/babel-plugin-jsx')
44
const importMeta = require('@babel/plugin-syntax-import-meta')
55
const { createFilter, normalizePath } = require('@rollup/pluginutils')
6-
const hash = require('hash-sum')
6+
const { createHash } = require('crypto')
77
const path = require('path')
88

99
const ssrRegisterHelperId = '/__vue-jsx-ssr-register-helper'
@@ -152,7 +152,7 @@ function vueJsxPlugin(options = {}) {
152152
({ name }) => ({
153153
local: name,
154154
exported: name,
155-
id: hash(id + name)
155+
id: getHash(id + name)
156156
})
157157
)
158158
)
@@ -169,7 +169,7 @@ function vueJsxPlugin(options = {}) {
169169
hotComponents.push({
170170
local: spec.local.name,
171171
exported: spec.exported.name,
172-
id: hash(id + spec.exported.name)
172+
id: getHash(id + spec.exported.name)
173173
})
174174
}
175175
}
@@ -187,15 +187,15 @@ function vueJsxPlugin(options = {}) {
187187
hotComponents.push({
188188
local: node.declaration.name,
189189
exported: 'default',
190-
id: hash(id + 'default')
190+
id: getHash(id + 'default')
191191
})
192192
}
193193
} else if (isDefineComponentCall(node.declaration)) {
194194
hasDefault = true
195195
hotComponents.push({
196196
local: '__default__',
197197
exported: 'default',
198-
id: hash(id + 'default')
198+
id: getHash(id + 'default')
199199
})
200200
}
201201
}
@@ -276,5 +276,13 @@ function isDefineComponentCall(node) {
276276
)
277277
}
278278

279+
/**
280+
* @param {string} text
281+
* @returns {string}
282+
*/
283+
function getHash(text) {
284+
return createHash('sha256').update(text).digest('hex').substring(0, 8)
285+
}
286+
279287
module.exports = vueJsxPlugin
280288
vueJsxPlugin.default = vueJsxPlugin

Diff for: packages/plugin-vue-jsx/package.json

+1-2
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,7 @@
2626
"@babel/plugin-syntax-import-meta": "^7.10.4",
2727
"@babel/plugin-transform-typescript": "^7.16.8",
2828
"@rollup/pluginutils": "^4.2.1",
29-
"@vue/babel-plugin-jsx": "^1.1.1",
30-
"hash-sum": "^2.0.0"
29+
"@vue/babel-plugin-jsx": "^1.1.1"
3130
},
3231
"peerDependencies": {
3332
"vite": "^2.0.0",

Diff for: packages/plugin-vue/package.json

-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@
3737
"devDependencies": {
3838
"@rollup/pluginutils": "^4.2.1",
3939
"debug": "^4.3.4",
40-
"hash-sum": "^2.0.0",
4140
"rollup": "^2.72.1",
4241
"slash": "^4.0.0",
4342
"source-map": "^0.6.1",

Diff for: packages/plugin-vue/src/utils/descriptorCache.ts

+6-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import fs from 'fs'
22
import path from 'path'
3+
import { createHash } from 'crypto'
34
import slash from 'slash'
4-
import hash from 'hash-sum'
55
import type { CompilerError, SFCDescriptor } from 'vue/compiler-sfc'
66
import type { ResolvedOptions, VueQuery } from '..'
77

@@ -27,7 +27,7 @@ export function createDescriptor(
2727
// ensure the path is normalized in a way that is consistent inside
2828
// project (relative to root) and on different systems.
2929
const normalizedPath = slash(path.normalize(path.relative(root, filename)))
30-
descriptor.id = hash(normalizedPath + (isProduction ? source : ''))
30+
descriptor.id = getHash(normalizedPath + (isProduction ? source : ''))
3131

3232
cache.set(filename, descriptor)
3333
return { descriptor, errors }
@@ -88,3 +88,7 @@ export function setSrcDescriptor(
8888
}
8989
cache.set(filename, entry)
9090
}
91+
92+
function getHash(text: string): string {
93+
return createHash('sha256').update(text).digest('hex').substring(0, 8)
94+
}

Diff for: packages/vite/src/node/__tests__/asset.spec.ts

+1-9
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,5 @@
11
import { describe, expect, test } from 'vitest'
2-
import { assetFileNamesToFileName, getAssetHash } from '../plugins/asset'
3-
4-
describe('getAssetHash', () => {
5-
test('8-digit hex', () => {
6-
const hash = getAssetHash(Buffer.alloc(0))
7-
8-
expect(hash).toMatch(/^[\da-f]{8}$/)
9-
})
10-
})
2+
import { assetFileNamesToFileName } from '../plugins/asset'
113

124
describe('assetFileNamesToFileName', () => {
135
// on Windows, both forward slashes and backslashes may appear in the input

Diff for: packages/vite/src/node/__tests__/utils.spec.ts

+8
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { describe, expect, test } from 'vitest'
22
import {
3+
getHash,
34
getPotentialTsSrcPaths,
45
injectQuery,
56
isWindows,
@@ -98,3 +99,10 @@ test('ts import of file with .js and query param', () => {
9899
'test-file.js.tsx?lee=123'
99100
])
100101
})
102+
103+
describe('getHash', () => {
104+
test('8-digit hex', () => {
105+
const hash = getHash(Buffer.alloc(0))
106+
expect(hash).toMatch(/^[\da-f]{8}$/)
107+
})
108+
})

Diff for: packages/vite/src/node/optimizer/index.ts

+1-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import fs from 'fs'
22
import path from 'path'
3-
import { createHash } from 'crypto'
43
import { performance } from 'perf_hooks'
54
import _debug from 'debug'
65
import colors from 'picocolors'
@@ -12,6 +11,7 @@ import {
1211
createDebugger,
1312
emptyDir,
1413
flattenId,
14+
getHash,
1515
lookupFile,
1616
normalizeId,
1717
normalizePath,
@@ -816,10 +816,6 @@ function getOptimizedBrowserHash(
816816
return getHash(hash + JSON.stringify(deps) + timestamp)
817817
}
818818

819-
export function getHash(text: string): string {
820-
return createHash('sha256').update(text).digest('hex').substring(0, 8)
821-
}
822-
823819
export function optimizedDepInfoFromId(
824820
metadata: DepOptimizationMetadata,
825821
id: string

Diff for: packages/vite/src/node/optimizer/registerMissing.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import colors from 'picocolors'
22
import _debug from 'debug'
3+
import { getHash } from '../utils'
34
import type { ViteDevServer } from '..'
45
import {
56
addOptimizedDepInfo,
@@ -8,7 +9,6 @@ import {
89
depsFromOptimizedDepInfo,
910
depsLogString,
1011
discoverProjectDependencies,
11-
getHash,
1212
getOptimizedDepPath,
1313
loadCachedDepOptimizationMetadata,
1414
newDepOptimizationProcessing,

Diff for: packages/vite/src/node/plugins/asset.ts

+3-8
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
11
import path from 'path'
22
import { parse as parseUrl } from 'url'
33
import fs, { promises as fsp } from 'fs'
4-
import { createHash } from 'crypto'
54
import * as mrmime from 'mrmime'
65
import type { OutputOptions, PluginContext } from 'rollup'
76
import MagicString from 'magic-string'
87
import type { Plugin } from '../plugin'
98
import type { ResolvedConfig } from '../config'
109
import { cleanUrl } from '../utils'
1110
import { FS_PREFIX } from '../constants'
12-
import { normalizePath } from '../utils'
11+
import { getHash, normalizePath } from '../utils'
1312

1413
export const assetUrlRE = /__VITE_ASSET__([a-z\d]{8})__(?:\$_(.*?)__)?/g
1514

@@ -195,7 +194,7 @@ export function getAssetFilename(
195194
* const fileName = assetFileNamesToFileName(
196195
* 'assets/[name].[hash][extname]',
197196
* '/path/to/file.txt',
198-
* getAssetHash(content),
197+
* getHash(content),
199198
* content
200199
* )
201200
* // fileName: 'assets/file.982d9e3e.txt'
@@ -300,7 +299,7 @@ async function fileToBuiltUrl(
300299
// https://bundlers.tooling.report/hashing/asset-cascade/
301300
// https://github.com/rollup/rollup/issues/3415
302301
const map = assetHashToFilenameMap.get(config)!
303-
const contentHash = getAssetHash(content)
302+
const contentHash = getHash(content)
304303
const { search, hash } = parseUrl(id)
305304
const postfix = (search || '') + (hash || '')
306305
const output = config.build?.rollupOptions?.output
@@ -337,10 +336,6 @@ async function fileToBuiltUrl(
337336
return url
338337
}
339338

340-
export function getAssetHash(content: Buffer | string): string {
341-
return createHash('sha256').update(content).digest('hex').slice(0, 8)
342-
}
343-
344339
export async function urlToBuiltUrl(
345340
url: string,
346341
importer: string,

Diff for: packages/vite/src/node/plugins/css.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import {
3333
cleanUrl,
3434
combineSourcemaps,
3535
generateCodeFrame,
36+
getHash,
3637
isDataUrl,
3738
isExternalUrl,
3839
isObject,
@@ -46,8 +47,7 @@ import {
4647
assetUrlRE,
4748
checkPublicFile,
4849
fileToUrl,
49-
getAssetFilename,
50-
getAssetHash
50+
getAssetFilename
5151
} from './asset'
5252

5353
// const debug = createDebugger('vite:css')
@@ -360,7 +360,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
360360
const query = parseRequest(id)
361361
if (inlineCSS && isHTMLProxy) {
362362
addToHTMLProxyTransformResult(
363-
`${getAssetHash(cleanUrl(id))}_${Number.parseInt(query!.index)}`,
363+
`${getHash(cleanUrl(id))}_${Number.parseInt(query!.index)}`,
364364
css
365365
)
366366
return `export default ''`

Diff for: packages/vite/src/node/plugins/html.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import type { ViteDevServer } from '../server'
2121
import {
2222
cleanUrl,
2323
generateCodeFrame,
24+
getHash,
2425
isDataUrl,
2526
isExternalUrl,
2627
normalizePath,
@@ -32,7 +33,6 @@ import {
3233
assetUrlRE,
3334
checkPublicFile,
3435
getAssetFilename,
35-
getAssetHash,
3636
urlToBuiltUrl
3737
} from './asset'
3838
import { isCSSRequest } from './css'
@@ -380,7 +380,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
380380
addToHTMLProxyCache(config, filePath, inlineModuleIndex, { code })
381381
// will transform with css plugin and cache result with css-post plugin
382382
js += `\nimport "${id}?html-proxy&inline-css&index=${inlineModuleIndex}.css"`
383-
const hash = getAssetHash(cleanUrl(id))
383+
const hash = getHash(cleanUrl(id))
384384
// will transform in `applyHtmlTransforms`
385385
s.overwrite(
386386
styleNode.loc.start.offset,
@@ -399,7 +399,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
399399
code: styleNode.content
400400
})
401401
js += `\nimport "${id}?html-proxy&inline-css&index=${inlineModuleIndex}.css"`
402-
const hash = getAssetHash(cleanUrl(id))
402+
const hash = getHash(cleanUrl(id))
403403
// will transform in `applyHtmlTransforms`
404404
s.overwrite(
405405
styleNode.loc.start.offset,

Diff for: packages/vite/src/node/plugins/worker.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@ import type Rollup from 'rollup'
33
import type { EmittedFile, TransformPluginContext } from 'rollup'
44
import type { ResolvedConfig } from '../config'
55
import type { Plugin } from '../plugin'
6-
import { cleanUrl, injectQuery, parseRequest } from '../utils'
6+
import { cleanUrl, getHash, injectQuery, parseRequest } from '../utils'
77
import { ENV_PUBLIC_PATH } from '../constants'
88
import { onRollupWarning } from '../build'
9-
import { fileToUrl, getAssetHash } from './asset'
9+
import { fileToUrl } from './asset'
1010

1111
interface WorkerCache {
1212
// save worker bundle emitted files avoid overwrites the same file.
@@ -143,7 +143,7 @@ function emitSourcemapForWorkerEntry(
143143
const basename = path.parse(cleanUrl(id)).name
144144
const data = sourcemap.toString()
145145
const content = Buffer.from(data)
146-
const contentHash = getAssetHash(content)
146+
const contentHash = getHash(content)
147147
const fileName = `${basename}.${contentHash}.js.map`
148148
const filePath = path.posix.join(config.build.assetsDir, fileName)
149149
emitWorkerSourcemap(context, config, {
@@ -186,7 +186,7 @@ export async function workerFileToUrl(
186186
}
187187
const code = await bundleWorkerEntry(ctx, config, id, query)
188188
const basename = path.parse(cleanUrl(id)).name
189-
const contentHash = getAssetHash(code)
189+
const contentHash = getHash(code)
190190
const fileName = path.posix.join(
191191
config.build.assetsDir,
192192
`${basename}.${contentHash}.js`

Diff for: packages/vite/src/node/utils.ts

+5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import fs from 'fs'
22
import os from 'os'
33
import path from 'path'
4+
import { createHash } from 'crypto'
45
import { promisify } from 'util'
56
import { URL, pathToFileURL } from 'url'
67
import { builtinModules } from 'module'
@@ -769,6 +770,10 @@ export function parseRequest(id: string): Record<string, string> | null {
769770

770771
export const blankReplacer = (match: string) => ' '.repeat(match.length)
771772

773+
export function getHash(text: Buffer | string): string {
774+
return createHash('sha256').update(text).digest('hex').substring(0, 8)
775+
}
776+
772777
// Based on node-graceful-fs
773778

774779
// The ISC License

Diff for: pnpm-lock.yaml

-7
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)