1- // thumbhash/examples/browser/index.html at main · evanw/thumbhash
1+ import type { Buffer } from 'node:buffer'
22
33import { subtle } from 'uncrypto'
44
5+ /**
6+ * @see https://stackoverflow.com/a/12101012
7+ */
8+ export function toArrayBuffer ( buffer : Buffer ) {
9+ const arrayBuffer = new ArrayBuffer ( buffer . length )
10+ const view = new Uint8Array ( arrayBuffer )
11+ for ( let i = 0 ; i < buffer . length ; ++ i ) {
12+ view [ i ] = buffer [ i ]
13+ }
14+ return arrayBuffer
15+ }
16+
517// https://github.com/evanw/thumbhash/blob/main/examples/browser/index.html
618export function binaryToBase64 ( binary : Uint8Array ) {
719 return btoa ( String . fromCharCode ( ...binary ) )
@@ -11,10 +23,10 @@ export function binaryToBase64(binary: Uint8Array) {
1123 * Hashes the given data using SHA-256 algorithm.
1224 *
1325 * Official example by MDN: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
14- * @param {Uint8Array } data - The data to be hashed
26+ * @param {BufferSource } data - The data to be hashed
1527 * @returns {Promise<string> } - The SHA-256 hash of the message
1628 */
17- async function digestUint8ArrayDataSha256 ( data : Uint8Array ) {
29+ async function digestUint8ArrayDataSha256 ( data : BufferSource ) {
1830 const hashBuffer = await subtle . digest ( 'SHA-256' , data ) // hash the message
1931 return Array . from ( new Uint8Array ( hashBuffer ) ) // convert buffer to byte array
2032}
@@ -30,11 +42,11 @@ async function digestUint8ArrayDataSha256(data: Uint8Array) {
3042 * https://github.com/rollup/rollup/blob/1b85663fde96d84fceaa2360dba246d3cb92789b/src/utils/FileEmitter.ts#L259
3143 * https://github.com/rollup/rollup/blob/1b85663fde96d84fceaa2360dba246d3cb92789b/src/utils/crypto.ts#L12
3244 *
33- * @param {Uint8Array } data - The data to be hashed
45+ * @param {BufferSource } data - The data to be hashed
3446 * @param {number } length - The length of the hash
3547 * @returns {Promise<string> } - The first 10 characters of the SHA-256 hash of the message
3648 */
37- export async function hash ( data : Uint8Array , length = 10 ) {
49+ export async function hash ( data : BufferSource , length = 10 ) {
3850 const hashResult = await digestUint8ArrayDataSha256 ( data )
3951 const hashBase64 = binaryToBase64 ( new Uint8Array ( hashResult ) ) // convert bytes to base64 encoded string
4052 if ( length > 0 )
0 commit comments