<commit_before>// eslint-disable-next-line import/no-nodejs-modules
import { createHmac } from 'crypto'
import { Hmac } from './cryptoUtils'

// TODO: Create a WebCrypto implementation for browser usage

class NodeCryptoSha256Hmac implements Hmac {
  async digest(key: NodeJS.TypedArray, data: NodeJS.TypedArray): Promise<Buffer> {
    const result = createHmac('sha256', key)
      .update(data)
      .digest()
    return Promise.resolve(result)
  }
}

// TODO: refactor into Promise<Hmac>
export function createHmacSha256(): Hmac {
  return new NodeCryptoSha256Hmac()
}
<commit_msg>WebCrypto implementation for hmac<commit_after>import { Hmac, isWebCryptoAvailable, NO_CRYPTO_LIB } from './cryptoUtils'

type NodeCryptoCreateHmac = typeof import('crypto').createHmac

class NodeCryptoHmacSha256 implements Hmac {
  createHmac: NodeCryptoCreateHmac

  constructor(createHmac: NodeCryptoCreateHmac) {
    this.createHmac = createHmac
  }

  async digest(key: NodeJS.TypedArray, data: NodeJS.TypedArray): Promise<Buffer> {
    const result = this.createHmac('sha256', key)
      .update(data)
      .digest()
    return Promise.resolve(result)
  }
}

class WebCryptoHmacSha256 implements Hmac {
  async digest(key: NodeJS.TypedArray, data: NodeJS.TypedArray): Promise<Buffer> {
    const cryptoKey = await crypto.subtle.importKey(
      'raw', key, { name: 'HMAC', hash: 'SHA-256' },
      true, ['sign']
    )
    const sig = await crypto.subtle.sign('HMAC', cryptoKey, data)
    return Buffer.from(sig)
  }
}

export function createHmacSha256(): Hmac {
  if (isWebCryptoAvailable()) {
    return new WebCryptoHmacSha256()
  } else {
    try {
      // eslint-disable-next-line import/no-nodejs-modules,no-restricted-modules,global-require
      const createHmac = require('crypto').createHmac
      return new NodeCryptoHmacSha256(createHmac)
    } catch (error) {
      throw new Error(NO_CRYPTO_LIB)
    }
  }
}

{'fraction_non_alphanumeric': 0.11221294363256785, 'fraction_numerical': 0.01722338204592902, 'mean_word_length': 4.031496062992126, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5189588', 'n_tokens_mistral': 655, 'n_tokens_neox': 630, 'n_words': 139}