Mirror: The highly customizable and versatile GraphQL client with which you add on features like normalized caching as you grow.
at main 1.5 kB view raw
1const webCrypto = ( 2 typeof window !== 'undefined' 3 ? window.crypto 4 : typeof self !== 'undefined' 5 ? self.crypto 6 : null 7) as typeof globalThis.crypto | null; 8 9let nodeCrypto: Promise<typeof import('crypto') | void> | void; 10 11const getNodeCrypto = async (): Promise<typeof import('crypto') | void> => { 12 if (!nodeCrypto) { 13 // Indirect eval'd require/import to guarantee no side-effects in module scope 14 // (optimization for minifiers) 15 try { 16 nodeCrypto = new Function('require', 'return require("crypto")')(require); 17 } catch (_error) { 18 try { 19 nodeCrypto = new Function('return import("crypto")')(); 20 } catch (_error) {} 21 } 22 } 23 return nodeCrypto; 24}; 25 26export const hash = async (query: string): Promise<string> => { 27 if (webCrypto && webCrypto.subtle) { 28 const digest = await webCrypto.subtle.digest( 29 { name: 'SHA-256' }, 30 new TextEncoder().encode(query) 31 ); 32 return new Uint8Array(digest).reduce( 33 (prev, byte) => prev + byte.toString(16).padStart(2, '0'), 34 '' 35 ); 36 } else if (await getNodeCrypto()) { 37 // Node.js support 38 return (await nodeCrypto)!.createHash('sha256').update(query).digest('hex'); 39 } 40 41 if (process.env.NODE_ENV !== 'production') { 42 console.warn( 43 '[@urql/exchange-persisted-fetch]: The Node Crypto and Web Crypto APIs are not available.\n' + 44 'This is an unexpected error. Please report it by filing a GitHub Issue.' 45 ); 46 } 47 48 return ''; 49};