CoolFace
Datasetpublic

basant307/AI_Governance_Project

sourceHugging Faceapache-2.0updated 2mo agoView on Hugging Face
0likes48downloads
utils.js920 linesDownload Raw Back to lib
1'use strict';2 3import bind from './helpers/bind.js';4 5// utils is a library of generic helper functions non-specific to axios6 7const { toString } = Object.prototype;8const { getPrototypeOf } = Object;9const { iterator, toStringTag } = Symbol;10 11const kindOf = ((cache) => (thing) => {12  const str = toString.call(thing);13  return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());14})(Object.create(null));15 16const kindOfTest = (type) => {17  type = type.toLowerCase();18  return (thing) => kindOf(thing) === type;19};20 21const typeOfTest = (type) => (thing) => typeof thing === type;22 23/**24 * Determine if a value is a non-null object25 *26 * @param {Object} val The value to test27 *28 * @returns {boolean} True if value is an Array, otherwise false29 */30const { isArray } = Array;31 32/**33 * Determine if a value is undefined34 *35 * @param {*} val The value to test36 *37 * @returns {boolean} True if the value is undefined, otherwise false38 */39const isUndefined = typeOfTest('undefined');40 41/**42 * Determine if a value is a Buffer43 *44 * @param {*} val The value to test45 *46 * @returns {boolean} True if value is a Buffer, otherwise false47 */48function isBuffer(val) {49  return (50    val !== null &&51    !isUndefined(val) &&52    val.constructor !== null &&53    !isUndefined(val.constructor) &&54    isFunction(val.constructor.isBuffer) &&55    val.constructor.isBuffer(val)56  );57}58 59/**60 * Determine if a value is an ArrayBuffer61 *62 * @param {*} val The value to test63 *64 * @returns {boolean} True if value is an ArrayBuffer, otherwise false65 */66const isArrayBuffer = kindOfTest('ArrayBuffer');67 68/**69 * Determine if a value is a view on an ArrayBuffer70 *71 * @param {*} val The value to test72 *73 * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false74 */75function isArrayBufferView(val) {76  let result;77  if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {78    result = ArrayBuffer.isView(val);79  } else {80    result = val && val.buffer && isArrayBuffer(val.buffer);81  }82  return result;83}84 85/**86 * Determine if a value is a String87 *88 * @param {*} val The value to test89 *90 * @returns {boolean} True if value is a String, otherwise false91 */92const isString = typeOfTest('string');93 94/**95 * Determine if a value is a Function96 *97 * @param {*} val The value to test98 * @returns {boolean} True if value is a Function, otherwise false99 */100const isFunction = typeOfTest('function');101 102/**103 * Determine if a value is a Number104 *105 * @param {*} val The value to test106 *107 * @returns {boolean} True if value is a Number, otherwise false108 */109const isNumber = typeOfTest('number');110 111/**112 * Determine if a value is an Object113 *114 * @param {*} thing The value to test115 *116 * @returns {boolean} True if value is an Object, otherwise false117 */118const isObject = (thing) => thing !== null && typeof thing === 'object';119 120/**121 * Determine if a value is a Boolean122 *123 * @param {*} thing The value to test124 * @returns {boolean} True if value is a Boolean, otherwise false125 */126const isBoolean = (thing) => thing === true || thing === false;127 128/**129 * Determine if a value is a plain Object130 *131 * @param {*} val The value to test132 *133 * @returns {boolean} True if value is a plain Object, otherwise false134 */135const isPlainObject = (val) => {136  if (kindOf(val) !== 'object') {137    return false;138  }139 140  const prototype = getPrototypeOf(val);141  return (142    (prototype === null ||143      prototype === Object.prototype ||144      Object.getPrototypeOf(prototype) === null) &&145    !(toStringTag in val) &&146    !(iterator in val)147  );148};149 150/**151 * Determine if a value is an empty object (safely handles Buffers)152 *153 * @param {*} val The value to test154 *155 * @returns {boolean} True if value is an empty object, otherwise false156 */157const isEmptyObject = (val) => {158  // Early return for non-objects or Buffers to prevent RangeError159  if (!isObject(val) || isBuffer(val)) {160    return false;161  }162 163  try {164    return Object.keys(val).length === 0 && Object.getPrototypeOf(val) === Object.prototype;165  } catch (e) {166    // Fallback for any other objects that might cause RangeError with Object.keys()167    return false;168  }169};170 171/**172 * Determine if a value is a Date173 *174 * @param {*} val The value to test175 *176 * @returns {boolean} True if value is a Date, otherwise false177 */178const isDate = kindOfTest('Date');179 180/**181 * Determine if a value is a File182 *183 * @param {*} val The value to test184 *185 * @returns {boolean} True if value is a File, otherwise false186 */187const isFile = kindOfTest('File');188 189/**190 * Determine if a value is a React Native Blob191 * React Native "blob": an object with a `uri` attribute. Optionally, it can192 * also have a `name` and `type` attribute to specify filename and content type193 *194 * @see https://github.com/facebook/react-native/blob/26684cf3adf4094eb6c405d345a75bf8c7c0bf88/Libraries/Network/FormData.js#L68-L71195 * 196 * @param {*} value The value to test197 * 198 * @returns {boolean} True if value is a React Native Blob, otherwise false199 */200const isReactNativeBlob = (value) => {201  return !!(value && typeof value.uri !== 'undefined');202}203 204/**205 * Determine if environment is React Native206 * ReactNative `FormData` has a non-standard `getParts()` method207 * 208 * @param {*} formData The formData to test209 * 210 * @returns {boolean} True if environment is React Native, otherwise false211 */212const isReactNative = (formData) => formData && typeof formData.getParts !== 'undefined';213 214/**215 * Determine if a value is a Blob216 *217 * @param {*} val The value to test218 *219 * @returns {boolean} True if value is a Blob, otherwise false220 */221const isBlob = kindOfTest('Blob');222 223/**224 * Determine if a value is a FileList225 *226 * @param {*} val The value to test227 *228 * @returns {boolean} True if value is a File, otherwise false229 */230const isFileList = kindOfTest('FileList');231 232/**233 * Determine if a value is a Stream234 *235 * @param {*} val The value to test236 *237 * @returns {boolean} True if value is a Stream, otherwise false238 */239const isStream = (val) => isObject(val) && isFunction(val.pipe);240 241/**242 * Determine if a value is a FormData243 *244 * @param {*} thing The value to test245 *246 * @returns {boolean} True if value is an FormData, otherwise false247 */248function getGlobal() {249  if (typeof globalThis !== 'undefined') return globalThis;250  if (typeof self !== 'undefined') return self;251  if (typeof window !== 'undefined') return window;252  if (typeof global !== 'undefined') return global;253  return {};254}255 256const G = getGlobal();257const FormDataCtor = typeof G.FormData !== 'undefined' ? G.FormData : undefined;258 259const isFormData = (thing) => {260  let kind;261  return thing && (262    (FormDataCtor && thing instanceof FormDataCtor) || (263      isFunction(thing.append) && (264        (kind = kindOf(thing)) === 'formdata' ||265        // detect form-data instance266        (kind === 'object' && isFunction(thing.toString) && thing.toString() === '[object FormData]')267      )268    )269  );270};271 272/**273 * Determine if a value is a URLSearchParams object274 *275 * @param {*} val The value to test276 *277 * @returns {boolean} True if value is a URLSearchParams object, otherwise false278 */279const isURLSearchParams = kindOfTest('URLSearchParams');280 281const [isReadableStream, isRequest, isResponse, isHeaders] = [282  'ReadableStream',283  'Request',284  'Response',285  'Headers',286].map(kindOfTest);287 288/**289 * Trim excess whitespace off the beginning and end of a string290 *291 * @param {String} str The String to trim292 *293 * @returns {String} The String freed of excess whitespace294 */295const trim = (str) => {296  return str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');297};298/**299 * Iterate over an Array or an Object invoking a function for each item.300 *301 * If `obj` is an Array callback will be called passing302 * the value, index, and complete array for each item.303 *304 * If 'obj' is an Object callback will be called passing305 * the value, key, and complete object for each property.306 *307 * @param {Object|Array<unknown>} obj The object to iterate308 * @param {Function} fn The callback to invoke for each item309 *310 * @param {Object} [options]311 * @param {Boolean} [options.allOwnKeys = false]312 * @returns {any}313 */314function forEach(obj, fn, { allOwnKeys = false } = {}) {315  // Don't bother if no value provided316  if (obj === null || typeof obj === 'undefined') {317    return;318  }319 320  let i;321  let l;322 323  // Force an array if not already something iterable324  if (typeof obj !== 'object') {325    /*eslint no-param-reassign:0*/326    obj = [obj];327  }328 329  if (isArray(obj)) {330    // Iterate over array values331    for (i = 0, l = obj.length; i < l; i++) {332      fn.call(null, obj[i], i, obj);333    }334  } else {335    // Buffer check336    if (isBuffer(obj)) {337      return;338    }339 340    // Iterate over object keys341    const keys = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj);342    const len = keys.length;343    let key;344 345    for (i = 0; i < len; i++) {346      key = keys[i];347      fn.call(null, obj[key], key, obj);348    }349  }350}351 352/**353 * Finds a key in an object, case-insensitive, returning the actual key name.354 * Returns null if the object is a Buffer or if no match is found.355 *356 * @param {Object} obj - The object to search.357 * @param {string} key - The key to find (case-insensitive).358 * @returns {?string} The actual key name if found, otherwise null.359 */360function findKey(obj, key) {361  if (isBuffer(obj)) {362    return null;363  }364 365  key = key.toLowerCase();366  const keys = Object.keys(obj);367  let i = keys.length;368  let _key;369  while (i-- > 0) {370    _key = keys[i];371    if (key === _key.toLowerCase()) {372      return _key;373    }374  }375  return null;376}377 378const _global = (() => {379  /*eslint no-undef:0*/380  if (typeof globalThis !== 'undefined') return globalThis;381  return typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : global;382})();383 384const isContextDefined = (context) => !isUndefined(context) && context !== _global;385 386/**387 * Accepts varargs expecting each argument to be an object, then388 * immutably merges the properties of each object and returns result.389 *390 * When multiple objects contain the same key the later object in391 * the arguments list will take precedence.392 *393 * Example:394 *395 * ```js396 * const result = merge({foo: 123}, {foo: 456});397 * console.log(result.foo); // outputs 456398 * ```399 *400 * @param {Object} obj1 Object to merge401 *402 * @returns {Object} Result of all merge properties403 */404function merge(/* obj1, obj2, obj3, ... */) {405  const { caseless, skipUndefined } = (isContextDefined(this) && this) || {};406  const result = {};407  const assignValue = (val, key) => {408    // Skip dangerous property names to prevent prototype pollution409    if (key === '__proto__' || key === 'constructor' || key === 'prototype') {410      return;411    }412 413    const targetKey = (caseless && findKey(result, key)) || key;414    if (isPlainObject(result[targetKey]) && isPlainObject(val)) {415      result[targetKey] = merge(result[targetKey], val);416    } else if (isPlainObject(val)) {417      result[targetKey] = merge({}, val);418    } else if (isArray(val)) {419      result[targetKey] = val.slice();420    } else if (!skipUndefined || !isUndefined(val)) {421      result[targetKey] = val;422    }423  };424 425  for (let i = 0, l = arguments.length; i < l; i++) {426    arguments[i] && forEach(arguments[i], assignValue);427  }428  return result;429}430 431/**432 * Extends object a by mutably adding to it the properties of object b.433 *434 * @param {Object} a The object to be extended435 * @param {Object} b The object to copy properties from436 * @param {Object} thisArg The object to bind function to437 *438 * @param {Object} [options]439 * @param {Boolean} [options.allOwnKeys]440 * @returns {Object} The resulting value of object a441 */442const extend = (a, b, thisArg, { allOwnKeys } = {}) => {443  forEach(444    b,445    (val, key) => {446      if (thisArg && isFunction(val)) {447        Object.defineProperty(a, key, {448          value: bind(val, thisArg),449          writable: true,450          enumerable: true,451          configurable: true,452        });453      } else {454        Object.defineProperty(a, key, {455          value: val,456          writable: true,457          enumerable: true,458          configurable: true,459        });460      }461    },462    { allOwnKeys }463  );464  return a;465};466 467/**468 * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)469 *470 * @param {string} content with BOM471 *472 * @returns {string} content value without BOM473 */474const stripBOM = (content) => {475  if (content.charCodeAt(0) === 0xfeff) {476    content = content.slice(1);477  }478  return content;479};480 481/**482 * Inherit the prototype methods from one constructor into another483 * @param {function} constructor484 * @param {function} superConstructor485 * @param {object} [props]486 * @param {object} [descriptors]487 *488 * @returns {void}489 */490const inherits = (constructor, superConstructor, props, descriptors) => {491  constructor.prototype = Object.create(superConstructor.prototype, descriptors);492  Object.defineProperty(constructor.prototype, 'constructor', {493    value: constructor,494    writable: true,495    enumerable: false,496    configurable: true,497  });498  Object.defineProperty(constructor, 'super', {499    value: superConstructor.prototype,500  });501  props && Object.assign(constructor.prototype, props);502};503 504/**505 * Resolve object with deep prototype chain to a flat object506 * @param {Object} sourceObj source object507 * @param {Object} [destObj]508 * @param {Function|Boolean} [filter]509 * @param {Function} [propFilter]510 *511 * @returns {Object}512 */513const toFlatObject = (sourceObj, destObj, filter, propFilter) => {514  let props;515  let i;516  let prop;517  const merged = {};518 519  destObj = destObj || {};520  // eslint-disable-next-line no-eq-null,eqeqeq521  if (sourceObj == null) return destObj;522 523  do {524    props = Object.getOwnPropertyNames(sourceObj);525    i = props.length;526    while (i-- > 0) {527      prop = props[i];528      if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) {529        destObj[prop] = sourceObj[prop];530        merged[prop] = true;531      }532    }533    sourceObj = filter !== false && getPrototypeOf(sourceObj);534  } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);535 536  return destObj;537};538 539/**540 * Determines whether a string ends with the characters of a specified string541 *542 * @param {String} str543 * @param {String} searchString544 * @param {Number} [position= 0]545 *546 * @returns {boolean}547 */548const endsWith = (str, searchString, position) => {549  str = String(str);550  if (position === undefined || position > str.length) {551    position = str.length;552  }553  position -= searchString.length;554  const lastIndex = str.indexOf(searchString, position);555  return lastIndex !== -1 && lastIndex === position;556};557 558/**559 * Returns new array from array like object or null if failed560 *561 * @param {*} [thing]562 *563 * @returns {?Array}564 */565const toArray = (thing) => {566  if (!thing) return null;567  if (isArray(thing)) return thing;568  let i = thing.length;569  if (!isNumber(i)) return null;570  const arr = new Array(i);571  while (i-- > 0) {572    arr[i] = thing[i];573  }574  return arr;575};576 577/**578 * Checking if the Uint8Array exists and if it does, it returns a function that checks if the579 * thing passed in is an instance of Uint8Array580 *581 * @param {TypedArray}582 *583 * @returns {Array}584 */585// eslint-disable-next-line func-names586const isTypedArray = ((TypedArray) => {587  // eslint-disable-next-line func-names588  return (thing) => {589    return TypedArray && thing instanceof TypedArray;590  };591})(typeof Uint8Array !== 'undefined' && getPrototypeOf(Uint8Array));592 593/**594 * For each entry in the object, call the function with the key and value.595 *596 * @param {Object<any, any>} obj - The object to iterate over.597 * @param {Function} fn - The function to call for each entry.598 *599 * @returns {void}600 */601const forEachEntry = (obj, fn) => {602  const generator = obj && obj[iterator];603 604  const _iterator = generator.call(obj);605 606  let result;607 608  while ((result = _iterator.next()) && !result.done) {609    const pair = result.value;610    fn.call(obj, pair[0], pair[1]);611  }612};613 614/**615 * It takes a regular expression and a string, and returns an array of all the matches616 *617 * @param {string} regExp - The regular expression to match against.618 * @param {string} str - The string to search.619 *620 * @returns {Array<boolean>}621 */622const matchAll = (regExp, str) => {623  let matches;624  const arr = [];625 626  while ((matches = regExp.exec(str)) !== null) {627    arr.push(matches);628  }629 630  return arr;631};632 633/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */634const isHTMLForm = kindOfTest('HTMLFormElement');635 636const toCamelCase = (str) => {637  return str.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) {638    return p1.toUpperCase() + p2;639  });640};641 642/* Creating a function that will check if an object has a property. */643const hasOwnProperty = (644  ({ hasOwnProperty }) =>645  (obj, prop) =>646    hasOwnProperty.call(obj, prop)647)(Object.prototype);648 649/**650 * Determine if a value is a RegExp object651 *652 * @param {*} val The value to test653 *654 * @returns {boolean} True if value is a RegExp object, otherwise false655 */656const isRegExp = kindOfTest('RegExp');657 658const reduceDescriptors = (obj, reducer) => {659  const descriptors = Object.getOwnPropertyDescriptors(obj);660  const reducedDescriptors = {};661 662  forEach(descriptors, (descriptor, name) => {663    let ret;664    if ((ret = reducer(descriptor, name, obj)) !== false) {665      reducedDescriptors[name] = ret || descriptor;666    }667  });668 669  Object.defineProperties(obj, reducedDescriptors);670};671 672/**673 * Makes all methods read-only674 * @param {Object} obj675 */676 677const freezeMethods = (obj) => {678  reduceDescriptors(obj, (descriptor, name) => {679    // skip restricted props in strict mode680    if (isFunction(obj) && ['arguments', 'caller', 'callee'].indexOf(name) !== -1) {681      return false;682    }683 684    const value = obj[name];685 686    if (!isFunction(value)) return;687 688    descriptor.enumerable = false;689 690    if ('writable' in descriptor) {691      descriptor.writable = false;692      return;693    }694 695    if (!descriptor.set) {696      descriptor.set = () => {697        throw Error("Can not rewrite read-only method '" + name + "'");698      };699    }700  });701};702 703/**704 * Converts an array or a delimited string into an object set with values as keys and true as values.705 * Useful for fast membership checks.706 *707 * @param {Array|string} arrayOrString - The array or string to convert.708 * @param {string} delimiter - The delimiter to use if input is a string.709 * @returns {Object} An object with keys from the array or string, values set to true.710 */711const toObjectSet = (arrayOrString, delimiter) => {712  const obj = {};713 714  const define = (arr) => {715    arr.forEach((value) => {716      obj[value] = true;717    });718  };719 720  isArray(arrayOrString) ? define(arrayOrString) : define(String(arrayOrString).split(delimiter));721 722  return obj;723};724 725const noop = () => {};726 727const toFiniteNumber = (value, defaultValue) => {728  return value != null && Number.isFinite((value = +value)) ? value : defaultValue;729};730 731/**732 * If the thing is a FormData object, return true, otherwise return false.733 *734 * @param {unknown} thing - The thing to check.735 *736 * @returns {boolean}737 */738function isSpecCompliantForm(thing) {739  return !!(740    thing &&741    isFunction(thing.append) &&742    thing[toStringTag] === 'FormData' &&743    thing[iterator]744  );745}746 747/**748 * Recursively converts an object to a JSON-compatible object, handling circular references and Buffers.749 *750 * @param {Object} obj - The object to convert.751 * @returns {Object} The JSON-compatible object.752 */753const toJSONObject = (obj) => {754  const stack = new Array(10);755 756  const visit = (source, i) => {757    if (isObject(source)) {758      if (stack.indexOf(source) >= 0) {759        return;760      }761 762      //Buffer check763      if (isBuffer(source)) {764        return source;765      }766 767      if (!('toJSON' in source)) {768        stack[i] = source;769        const target = isArray(source) ? [] : {};770 771        forEach(source, (value, key) => {772          const reducedValue = visit(value, i + 1);773          !isUndefined(reducedValue) && (target[key] = reducedValue);774        });775 776        stack[i] = undefined;777 778        return target;779      }780    }781 782    return source;783  };784 785  return visit(obj, 0);786};787 788/**789 * Determines if a value is an async function.790 *791 * @param {*} thing - The value to test.792 * @returns {boolean} True if value is an async function, otherwise false.793 */794const isAsyncFn = kindOfTest('AsyncFunction');795 796/**797 * Determines if a value is thenable (has then and catch methods).798 *799 * @param {*} thing - The value to test.800 * @returns {boolean} True if value is thenable, otherwise false.801 */802const isThenable = (thing) =>803  thing &&804  (isObject(thing) || isFunction(thing)) &&805  isFunction(thing.then) &&806  isFunction(thing.catch);807 808// original code809// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34810 811/**812 * Provides a cross-platform setImmediate implementation.813 * Uses native setImmediate if available, otherwise falls back to postMessage or setTimeout.814 *815 * @param {boolean} setImmediateSupported - Whether setImmediate is supported.816 * @param {boolean} postMessageSupported - Whether postMessage is supported.817 * @returns {Function} A function to schedule a callback asynchronously.818 */819const _setImmediate = ((setImmediateSupported, postMessageSupported) => {820  if (setImmediateSupported) {821    return setImmediate;822  }823 824  return postMessageSupported825    ? ((token, callbacks) => {826        _global.addEventListener(827          'message',828          ({ source, data }) => {829            if (source === _global && data === token) {830              callbacks.length && callbacks.shift()();831            }832          },833          false834        );835 836        return (cb) => {837          callbacks.push(cb);838          _global.postMessage(token, '*');839        };840      })(`axios@${Math.random()}`, [])841    : (cb) => setTimeout(cb);842})(typeof setImmediate === 'function', isFunction(_global.postMessage));843 844/**845 * Schedules a microtask or asynchronous callback as soon as possible.846 * Uses queueMicrotask if available, otherwise falls back to process.nextTick or _setImmediate.847 *848 * @type {Function}849 */850const asap =851  typeof queueMicrotask !== 'undefined'852    ? queueMicrotask.bind(_global)853    : (typeof process !== 'undefined' && process.nextTick) || _setImmediate;854 855// *********************856 857const isIterable = (thing) => thing != null && isFunction(thing[iterator]);858 859export default {860  isArray,861  isArrayBuffer,862  isBuffer,863  isFormData,864  isArrayBufferView,865  isString,866  isNumber,867  isBoolean,868  isObject,869  isPlainObject,870  isEmptyObject,871  isReadableStream,872  isRequest,873  isResponse,874  isHeaders,875  isUndefined,876  isDate,877  isFile,878  isReactNativeBlob,879  isReactNative,880  isBlob,881  isRegExp,882  isFunction,883  isStream,884  isURLSearchParams,885  isTypedArray,886  isFileList,887  forEach,888  merge,889  extend,890  trim,891  stripBOM,892  inherits,893  toFlatObject,894  kindOf,895  kindOfTest,896  endsWith,897  toArray,898  forEachEntry,899  matchAll,900  isHTMLForm,901  hasOwnProperty,902  hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection903  reduceDescriptors,904  freezeMethods,905  toObjectSet,906  toCamelCase,907  noop,908  toFiniteNumber,909  findKey,910  global: _global,911  isContextDefined,912  isSpecCompliantForm,913  toJSONObject,914  isAsyncFn,915  isThenable,916  setImmediate: _setImmediate,917  asap,918  isIterable,919};920 
basant307/AI_Governance_Project · CoolFace