UNPKG

@graphql-hive/core

Version:
213 lines (212 loc) • 6.84 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createHash = createHash; exports.memo = memo; exports.isAsyncIterable = isAsyncIterable; exports.cache = cache; exports.cacheDocumentKey = cacheDocumentKey; exports.measureDuration = measureDuration; exports.addProperty = addProperty; exports.isHiveClient = isHiveClient; exports.logIf = logIf; exports.joinUrl = joinUrl; exports.isLegacyAccessToken = isLegacyAccessToken; exports.chooseLogger = chooseLogger; const logger_1 = require("@graphql-hive/logger"); const fetch_1 = require("@whatwg-node/fetch"); const client_js_1 = require("./client.js"); async function digest(algo, output, data) { const buffer = await fetch_1.crypto.subtle.digest(algo, new fetch_1.TextEncoder().encode(data)); if (output === 'hex') { return arrayBufferToHEX(buffer); } return arrayBufferToBase64(buffer); } function arrayBufferToHEX(buffer) { return Array.prototype.map .call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)) .join(''); } function arrayBufferToBase64(buffer) { return btoa(String.fromCharCode.apply(null, new Uint8Array(buffer))); } function createHash(algo) { let str = ''; return { update(data) { str += data; return this; }, async digest(output) { return digest(algo, output, str); }, }; } function memo(fn, cacheKeyFn) { let memoizedResult = null; let memoizedKey = null; return (arg) => { const currentKey = cacheKeyFn(arg); if (memoizedKey === currentKey) { return memoizedResult; } memoizedKey = currentKey; memoizedResult = fn(arg); return memoizedResult; }; } function isAsyncIterable(value) { return (value === null || value === void 0 ? void 0 : value[Symbol.asyncIterator]) != null; } function cache(fn, cacheKeyFn, cacheMap) { return async (arg, arg2) => { const key = await cacheKeyFn(arg, arg2); const cachedValue = await cacheMap.get(key); if (cachedValue !== null && typeof cachedValue !== 'undefined') { return { key, value: cachedValue, cacheHit: true, }; } const value = fn(arg, arg2); cacheMap.set(key, value); return { key, value, cacheHit: false, }; }; } async function cacheDocumentKey(doc, variables) { const hasher = createHash('SHA-1').update(JSON.stringify(doc)); if (variables) { hasher.update(JSON.stringify(variables, (_, value) => { if ((value && typeof value === 'object' && Object.keys(value).length) || (Array.isArray(value) && value.length)) { return value; } return ''; })); } return hasher.digest('hex'); } const HR_TO_NS = 1e9; const NS_TO_MS = 1e6; function deltaFrom(startedAt) { const endedAt = performance.now(); const ns = Math.round(((endedAt - startedAt) * HR_TO_NS) / 1000); return { ns, get ms() { return ns / NS_TO_MS; }, }; } function measureDuration() { const startAt = performance.now(); return function end() { return deltaFrom(startAt).ns; }; } function addProperty(key, value, obj) { if (value === null || typeof value === 'undefined') { return obj; } return Object.assign(Object.assign({}, obj), { [key]: value }); } function isHiveClient(clientOrOptions) { return client_js_1.hiveClientSymbol in clientOrOptions; } function logIf(condition, message, logFn) { if (condition) { logFn(message); } } function joinUrl(url, subdirectory) { const normalizedUrl = url.endsWith('/') ? url.slice(0, -1) : url; const normalizedSubdirectory = subdirectory.startsWith('/') ? subdirectory.slice(1) : subdirectory; return normalizedUrl + '/' + normalizedSubdirectory; } function isLegacyAccessToken(accessToken) { if (!accessToken.startsWith('hvo1/') && !accessToken.startsWith('hvp1/') && !accessToken.startsWith('hvu1/')) { return true; } return false; } function chooseLogger(logger, debug) { if (!logger) { return new logger_1.Logger({ writers: [{ write() { } }], }); } if (logger instanceof logger_1.Logger) { return logger; } return new logger_1.Logger({ level: 'debug', writers: [ { write(level, attrs, msg) { const errors = getErrorsFromAttrs(attrs); if (level === 'debug' && msg) { if (logger.debug) { if (errors) { for (const error of errors) { logger.debug(error); } } logger.debug(msg); return; } if (debug === true) { if (errors) { for (const error of errors) { logger.info(error); } } logger.info(msg); return; } return; } if (level === 'info' && msg) { if (errors) { for (const error of errors) { logger.info(error); } } logger.info(msg); return; } if (level === 'error' && msg) { if (errors) { for (const error of errors) { logger.error(error); } } logger.error(msg); } }, }, ], }); } function getErrorsFromAttrs(attrs) { var _a; if (!attrs || Array.isArray(attrs)) { return null; } const error = attrs === null || attrs === void 0 ? void 0 : attrs.error; if (!error) { return null; } if (error === null || error === void 0 ? void 0 : error.errors) { return error.errors.map((error) => { var _a; return `${(_a = error.name) !== null && _a !== void 0 ? _a : error.class}: ${error.message}`; }); } return [`${(_a = error.name) !== null && _a !== void 0 ? _a : error.class}: ${error.message}`]; }