Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: use node hash #7975

Merged
merged 4 commits into from
May 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions packages/plugin-vue-jsx/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -152,7 +152,7 @@ function vueJsxPlugin(options = {}) {
({ name }) => ({
local: name,
exported: name,
id: hash(id + name)
id: getHash(id + name)
})
)
)
Expand All @@ -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)
})
}
}
Expand All @@ -187,15 +187,15 @@ function vueJsxPlugin(options = {}) {
hotComponents.push({
local: node.declaration.name,
exported: 'default',
id: hash(id + 'default')
id: getHash(id + 'default')
})
}
} else if (isDefineComponentCall(node.declaration)) {
hasDefault = true
hotComponents.push({
local: '__default__',
exported: 'default',
id: hash(id + 'default')
id: getHash(id + 'default')
})
}
}
Expand Down Expand Up @@ -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
3 changes: 1 addition & 2 deletions packages/plugin-vue-jsx/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 0 additions & 1 deletion packages/plugin-vue/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
8 changes: 6 additions & 2 deletions packages/plugin-vue/src/utils/descriptorCache.ts
Original file line number Diff line number Diff line change
@@ -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 '..'

Expand All @@ -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 }
Expand Down Expand Up @@ -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)
}
10 changes: 1 addition & 9 deletions packages/vite/src/node/__tests__/asset.spec.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down
8 changes: 8 additions & 0 deletions packages/vite/src/node/__tests__/utils.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, test } from 'vitest'
import {
getHash,
getPotentialTsSrcPaths,
injectQuery,
isWindows,
Expand Down Expand Up @@ -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}$/)
})
})
6 changes: 1 addition & 5 deletions packages/vite/src/node/optimizer/index.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand All @@ -12,6 +11,7 @@ import {
createDebugger,
emptyDir,
flattenId,
getHash,
lookupFile,
normalizeId,
normalizePath,
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/optimizer/registerMissing.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import colors from 'picocolors'
import _debug from 'debug'
import { getHash } from '../utils'
import type { ViteDevServer } from '..'
import {
addOptimizedDepInfo,
Expand All @@ -8,7 +9,6 @@ import {
depsFromOptimizedDepInfo,
depsLogString,
discoverProjectDependencies,
getHash,
getOptimizedDepPath,
loadCachedDepOptimizationMetadata,
newDepOptimizationProcessing,
Expand Down
11 changes: 3 additions & 8 deletions packages/vite/src/node/plugins/asset.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
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'
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

Expand Down Expand Up @@ -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'
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
6 changes: 3 additions & 3 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
cleanUrl,
combineSourcemaps,
generateCodeFrame,
getHash,
isDataUrl,
isExternalUrl,
isObject,
Expand All @@ -46,8 +47,7 @@ import {
assetUrlRE,
checkPublicFile,
fileToUrl,
getAssetFilename,
getAssetHash
getAssetFilename
} from './asset'

// const debug = createDebugger('vite:css')
Expand Down Expand Up @@ -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 ''`
Expand Down
6 changes: 3 additions & 3 deletions packages/vite/src/node/plugins/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import type { ViteDevServer } from '../server'
import {
cleanUrl,
generateCodeFrame,
getHash,
isDataUrl,
isExternalUrl,
normalizePath,
Expand All @@ -32,7 +33,6 @@ import {
assetUrlRE,
checkPublicFile,
getAssetFilename,
getAssetHash,
urlToBuiltUrl
} from './asset'
import { isCSSRequest } from './css'
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand Down
8 changes: 4 additions & 4 deletions packages/vite/src/node/plugins/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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, {
Expand Down Expand Up @@ -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`
Expand Down
5 changes: 5 additions & 0 deletions packages/vite/src/node/utils.ts
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -769,6 +770,10 @@ export function parseRequest(id: string): Record<string, string> | 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
Expand Down
7 changes: 0 additions & 7 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.