import { Buffer } from '@stacks/common' ; export function isSubtleCryptoAvailable ( ) { return typeof crypto !== 'undefined' && typeof crypto . subtle !== 'undefined' ; } export function isNodeCryptoAvailable < T > ( withFeature ) ; export function isNodeCryptoAvailable < T > ( withFeature ? ) { try { const resolvedResult = require . resolve ( 'crypto' ) ; if ( ! resolvedResult ) { return false ; } const cryptoModule = require ( 'crypto' ) as typeof import ( 'crypto' ) ; if ( ! cryptoModule ) { return false ; } if ( withFeature ) { const features = withFeature ( cryptoModule ) ; return features ; } return true ; } catch ( error ) { return false ; } } export const NO_CRYPTO_LIB = 'Crypto lib not found. Either the WebCrypto "crypto.subtle" or Node.js "crypto" module must be available.' ; export type TriplesecDecryptSignature = ( arg : { data : Buffer ; key : Buffer ; } , cb : ( err : Error | null , buff : Buffer | null ) => void ) => void ; export interface WebCryptoLib { lib : SubtleCrypto ; name : 'subtleCrypto' ; } export interface NodeCryptoLib { lib : typeof import ( 'crypto' ) ; name : 'nodeCrypto' ; } export async function getCryptoLib ( ) { if ( isSubtleCryptoAvailable ( ) ) { return { lib : crypto . subtle , name : 'subtleCrypto' , } ; } else { try { const nodeCrypto = require ( 'crypto' ) as typeof import ( 'crypto' ) ; return { lib : nodeCrypto , name : 'nodeCrypto' , } ; } catch ( error ) { throw new Error ( NO_CRYPTO_LIB ) ; } } }