Skip to content

Commit

Permalink
perf: use crypto.hash when available (#18317)
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red authored Oct 10, 2024
1 parent 889bfc0 commit 2a14884
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
13 changes: 11 additions & 2 deletions packages/plugin-legacy/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable n/no-extraneous-import */
import path from 'node:path'
import { createHash } from 'node:crypto'
import crypto from 'node:crypto'
import { createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
import { build, normalizePath } from 'vite'
Expand Down Expand Up @@ -970,12 +970,21 @@ function wrapIIFEBabelPlugin(): BabelPlugin {
}
}

const hash =
// eslint-disable-next-line n/no-unsupported-features/node-builtins -- crypto.hash is supported in Node 21.7.0+, 20.12.0+
crypto.hash ??
((
algorithm: string,
data: crypto.BinaryLike,
outputEncoding: crypto.BinaryToTextEncoding,
) => crypto.createHash(algorithm).update(data).digest(outputEncoding))

export const cspHashes = [
safari10NoModuleFix,
systemJSInlineCode,
detectModernBrowserCode,
dynamicFallbackInlineCode,
].map((i) => createHash('sha256').update(i).digest('base64'))
].map((i) => hash('sha256', i, 'base64'))

export type { Options }

Expand Down
13 changes: 11 additions & 2 deletions packages/vite/src/node/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { exec } from 'node:child_process'
import { createHash } from 'node:crypto'
import crypto from 'node:crypto'
import { URL, fileURLToPath } from 'node:url'
import { builtinModules, createRequire } from 'node:module'
import { promises as dns } from 'node:dns'
Expand Down Expand Up @@ -1011,8 +1011,17 @@ export const requestQueryMaybeEscapedSplitRE = /\\?\?(?!.*[/|}])/

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

const hash =
// eslint-disable-next-line n/no-unsupported-features/node-builtins -- crypto.hash is supported in Node 21.7.0+, 20.12.0+
crypto.hash ??
((
algorithm: string,
data: crypto.BinaryLike,
outputEncoding: crypto.BinaryToTextEncoding,
) => crypto.createHash(algorithm).update(data).digest(outputEncoding))

export function getHash(text: Buffer | string, length = 8): string {
const h = createHash('sha256').update(text).digest('hex').substring(0, length)
const h = hash('sha256', text, 'hex').substring(0, length)
if (length <= 64) return h
return h.padEnd(length, '_')
}
Expand Down

0 comments on commit 2a14884

Please sign in to comment.