CoolFace
Apppublic

opusdev/vector-similarity-api

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes
utils.js864 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 (165      Object.keys(val).length === 0 &&166      Object.getPrototypeOf(val) === Object.prototype167    );168  } catch (e) {169    // Fallback for any other objects that might cause RangeError with Object.keys()170    return false;171  }172};173 174/**175 * Determine if a value is a Date176 *177 * @param {*} val The value to test178 *179 * @returns {boolean} True if value is a Date, otherwise false180 */181const isDate = kindOfTest("Date");182 183/**184 * Determine if a value is a File185 *186 * @param {*} val The value to test187 *188 * @returns {boolean} True if value is a File, otherwise false189 */190const isFile = kindOfTest("File");191 192/**193 * Determine if a value is a Blob194 *195 * @param {*} val The value to test196 *197 * @returns {boolean} True if value is a Blob, otherwise false198 */199const isBlob = kindOfTest("Blob");200 201/**202 * Determine if a value is a FileList203 *204 * @param {*} val The value to test205 *206 * @returns {boolean} True if value is a File, otherwise false207 */208const isFileList = kindOfTest("FileList");209 210/**211 * Determine if a value is a Stream212 *213 * @param {*} val The value to test214 *215 * @returns {boolean} True if value is a Stream, otherwise false216 */217const isStream = (val) => isObject(val) && isFunction(val.pipe);218 219/**220 * Determine if a value is a FormData221 *222 * @param {*} thing The value to test223 *224 * @returns {boolean} True if value is an FormData, otherwise false225 */226const isFormData = (thing) => {227  let kind;228  return (229    thing &&230    ((typeof FormData === "function" && thing instanceof FormData) ||231      (isFunction(thing.append) &&232        ((kind = kindOf(thing)) === "formdata" ||233          // detect form-data instance234          (kind === "object" &&235            isFunction(thing.toString) &&236            thing.toString() === "[object FormData]"))))237  );238};239 240/**241 * Determine if a value is a URLSearchParams object242 *243 * @param {*} val The value to test244 *245 * @returns {boolean} True if value is a URLSearchParams object, otherwise false246 */247const isURLSearchParams = kindOfTest("URLSearchParams");248 249const [isReadableStream, isRequest, isResponse, isHeaders] = [250  "ReadableStream",251  "Request",252  "Response",253  "Headers",254].map(kindOfTest);255 256/**257 * Trim excess whitespace off the beginning and end of a string258 *259 * @param {String} str The String to trim260 *261 * @returns {String} The String freed of excess whitespace262 */263const trim = (str) =>264  str.trim ? str.trim() : str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");265 266/**267 * Iterate over an Array or an Object invoking a function for each item.268 *269 * If `obj` is an Array callback will be called passing270 * the value, index, and complete array for each item.271 *272 * If 'obj' is an Object callback will be called passing273 * the value, key, and complete object for each property.274 *275 * @param {Object|Array<unknown>} obj The object to iterate276 * @param {Function} fn The callback to invoke for each item277 *278 * @param {Object} [options]279 * @param {Boolean} [options.allOwnKeys = false]280 * @returns {any}281 */282function forEach(obj, fn, { allOwnKeys = false } = {}) {283  // Don't bother if no value provided284  if (obj === null || typeof obj === "undefined") {285    return;286  }287 288  let i;289  let l;290 291  // Force an array if not already something iterable292  if (typeof obj !== "object") {293    /*eslint no-param-reassign:0*/294    obj = [obj];295  }296 297  if (isArray(obj)) {298    // Iterate over array values299    for (i = 0, l = obj.length; i < l; i++) {300      fn.call(null, obj[i], i, obj);301    }302  } else {303    // Buffer check304    if (isBuffer(obj)) {305      return;306    }307 308    // Iterate over object keys309    const keys = allOwnKeys310      ? Object.getOwnPropertyNames(obj)311      : Object.keys(obj);312    const len = keys.length;313    let key;314 315    for (i = 0; i < len; i++) {316      key = keys[i];317      fn.call(null, obj[key], key, obj);318    }319  }320}321 322function findKey(obj, key) {323  if (isBuffer(obj)) {324    return null;325  }326 327  key = key.toLowerCase();328  const keys = Object.keys(obj);329  let i = keys.length;330  let _key;331  while (i-- > 0) {332    _key = keys[i];333    if (key === _key.toLowerCase()) {334      return _key;335    }336  }337  return null;338}339 340const _global = (() => {341  /*eslint no-undef:0*/342  if (typeof globalThis !== "undefined") return globalThis;343  return typeof self !== "undefined"344    ? self345    : typeof window !== "undefined"346      ? window347      : global;348})();349 350const isContextDefined = (context) =>351  !isUndefined(context) && context !== _global;352 353/**354 * Accepts varargs expecting each argument to be an object, then355 * immutably merges the properties of each object and returns result.356 *357 * When multiple objects contain the same key the later object in358 * the arguments list will take precedence.359 *360 * Example:361 *362 * ```js363 * const result = merge({foo: 123}, {foo: 456});364 * console.log(result.foo); // outputs 456365 * ```366 *367 * @param {Object} obj1 Object to merge368 *369 * @returns {Object} Result of all merge properties370 */371function merge(/* obj1, obj2, obj3, ... */) {372  const { caseless, skipUndefined } = (isContextDefined(this) && this) || {};373  const result = {};374  const assignValue = (val, key) => {375    // Skip dangerous property names to prevent prototype pollution376    if (key === "__proto__" || key === "constructor" || key === "prototype") {377      return;378    }379 380    const targetKey = (caseless && findKey(result, key)) || key;381    if (isPlainObject(result[targetKey]) && isPlainObject(val)) {382      result[targetKey] = merge(result[targetKey], val);383    } else if (isPlainObject(val)) {384      result[targetKey] = merge({}, val);385    } else if (isArray(val)) {386      result[targetKey] = val.slice();387    } else if (!skipUndefined || !isUndefined(val)) {388      result[targetKey] = val;389    }390  };391 392  for (let i = 0, l = arguments.length; i < l; i++) {393    arguments[i] && forEach(arguments[i], assignValue);394  }395  return result;396}397 398/**399 * Extends object a by mutably adding to it the properties of object b.400 *401 * @param {Object} a The object to be extended402 * @param {Object} b The object to copy properties from403 * @param {Object} thisArg The object to bind function to404 *405 * @param {Object} [options]406 * @param {Boolean} [options.allOwnKeys]407 * @returns {Object} The resulting value of object a408 */409const extend = (a, b, thisArg, { allOwnKeys } = {}) => {410  forEach(411    b,412    (val, key) => {413      if (thisArg && isFunction(val)) {414        Object.defineProperty(a, key, {415          value: bind(val, thisArg),416          writable: true,417          enumerable: true,418          configurable: true,419        });420      } else {421        Object.defineProperty(a, key, {422          value: val,423          writable: true,424          enumerable: true,425          configurable: true,426        });427      }428    },429    { allOwnKeys },430  );431  return a;432};433 434/**435 * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)436 *437 * @param {string} content with BOM438 *439 * @returns {string} content value without BOM440 */441const stripBOM = (content) => {442  if (content.charCodeAt(0) === 0xfeff) {443    content = content.slice(1);444  }445  return content;446};447 448/**449 * Inherit the prototype methods from one constructor into another450 * @param {function} constructor451 * @param {function} superConstructor452 * @param {object} [props]453 * @param {object} [descriptors]454 *455 * @returns {void}456 */457const inherits = (constructor, superConstructor, props, descriptors) => {458  constructor.prototype = Object.create(459    superConstructor.prototype,460    descriptors,461  );462  Object.defineProperty(constructor.prototype, "constructor", {463    value: constructor,464    writable: true,465    enumerable: false,466    configurable: true,467  });468  Object.defineProperty(constructor, "super", {469    value: superConstructor.prototype,470  });471  props && Object.assign(constructor.prototype, props);472};473 474/**475 * Resolve object with deep prototype chain to a flat object476 * @param {Object} sourceObj source object477 * @param {Object} [destObj]478 * @param {Function|Boolean} [filter]479 * @param {Function} [propFilter]480 *481 * @returns {Object}482 */483const toFlatObject = (sourceObj, destObj, filter, propFilter) => {484  let props;485  let i;486  let prop;487  const merged = {};488 489  destObj = destObj || {};490  // eslint-disable-next-line no-eq-null,eqeqeq491  if (sourceObj == null) return destObj;492 493  do {494    props = Object.getOwnPropertyNames(sourceObj);495    i = props.length;496    while (i-- > 0) {497      prop = props[i];498      if (499        (!propFilter || propFilter(prop, sourceObj, destObj)) &&500        !merged[prop]501      ) {502        destObj[prop] = sourceObj[prop];503        merged[prop] = true;504      }505    }506    sourceObj = filter !== false && getPrototypeOf(sourceObj);507  } while (508    sourceObj &&509    (!filter || filter(sourceObj, destObj)) &&510    sourceObj !== Object.prototype511  );512 513  return destObj;514};515 516/**517 * Determines whether a string ends with the characters of a specified string518 *519 * @param {String} str520 * @param {String} searchString521 * @param {Number} [position= 0]522 *523 * @returns {boolean}524 */525const endsWith = (str, searchString, position) => {526  str = String(str);527  if (position === undefined || position > str.length) {528    position = str.length;529  }530  position -= searchString.length;531  const lastIndex = str.indexOf(searchString, position);532  return lastIndex !== -1 && lastIndex === position;533};534 535/**536 * Returns new array from array like object or null if failed537 *538 * @param {*} [thing]539 *540 * @returns {?Array}541 */542const toArray = (thing) => {543  if (!thing) return null;544  if (isArray(thing)) return thing;545  let i = thing.length;546  if (!isNumber(i)) return null;547  const arr = new Array(i);548  while (i-- > 0) {549    arr[i] = thing[i];550  }551  return arr;552};553 554/**555 * Checking if the Uint8Array exists and if it does, it returns a function that checks if the556 * thing passed in is an instance of Uint8Array557 *558 * @param {TypedArray}559 *560 * @returns {Array}561 */562// eslint-disable-next-line func-names563const isTypedArray = ((TypedArray) => {564  // eslint-disable-next-line func-names565  return (thing) => {566    return TypedArray && thing instanceof TypedArray;567  };568})(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array));569 570/**571 * For each entry in the object, call the function with the key and value.572 *573 * @param {Object<any, any>} obj - The object to iterate over.574 * @param {Function} fn - The function to call for each entry.575 *576 * @returns {void}577 */578const forEachEntry = (obj, fn) => {579  const generator = obj && obj[iterator];580 581  const _iterator = generator.call(obj);582 583  let result;584 585  while ((result = _iterator.next()) && !result.done) {586    const pair = result.value;587    fn.call(obj, pair[0], pair[1]);588  }589};590 591/**592 * It takes a regular expression and a string, and returns an array of all the matches593 *594 * @param {string} regExp - The regular expression to match against.595 * @param {string} str - The string to search.596 *597 * @returns {Array<boolean>}598 */599const matchAll = (regExp, str) => {600  let matches;601  const arr = [];602 603  while ((matches = regExp.exec(str)) !== null) {604    arr.push(matches);605  }606 607  return arr;608};609 610/* Checking if the kindOfTest function returns true when passed an HTMLFormElement. */611const isHTMLForm = kindOfTest("HTMLFormElement");612 613const toCamelCase = (str) => {614  return str615    .toLowerCase()616    .replace(/[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) {617      return p1.toUpperCase() + p2;618    });619};620 621/* Creating a function that will check if an object has a property. */622const hasOwnProperty = (623  ({ hasOwnProperty }) =>624  (obj, prop) =>625    hasOwnProperty.call(obj, prop)626)(Object.prototype);627 628/**629 * Determine if a value is a RegExp object630 *631 * @param {*} val The value to test632 *633 * @returns {boolean} True if value is a RegExp object, otherwise false634 */635const isRegExp = kindOfTest("RegExp");636 637const reduceDescriptors = (obj, reducer) => {638  const descriptors = Object.getOwnPropertyDescriptors(obj);639  const reducedDescriptors = {};640 641  forEach(descriptors, (descriptor, name) => {642    let ret;643    if ((ret = reducer(descriptor, name, obj)) !== false) {644      reducedDescriptors[name] = ret || descriptor;645    }646  });647 648  Object.defineProperties(obj, reducedDescriptors);649};650 651/**652 * Makes all methods read-only653 * @param {Object} obj654 */655 656const freezeMethods = (obj) => {657  reduceDescriptors(obj, (descriptor, name) => {658    // skip restricted props in strict mode659    if (660      isFunction(obj) &&661      ["arguments", "caller", "callee"].indexOf(name) !== -1662    ) {663      return false;664    }665 666    const value = obj[name];667 668    if (!isFunction(value)) return;669 670    descriptor.enumerable = false;671 672    if ("writable" in descriptor) {673      descriptor.writable = false;674      return;675    }676 677    if (!descriptor.set) {678      descriptor.set = () => {679        throw Error("Can not rewrite read-only method '" + name + "'");680      };681    }682  });683};684 685const toObjectSet = (arrayOrString, delimiter) => {686  const obj = {};687 688  const define = (arr) => {689    arr.forEach((value) => {690      obj[value] = true;691    });692  };693 694  isArray(arrayOrString)695    ? define(arrayOrString)696    : define(String(arrayOrString).split(delimiter));697 698  return obj;699};700 701const noop = () => {};702 703const toFiniteNumber = (value, defaultValue) => {704  return value != null && Number.isFinite((value = +value))705    ? value706    : defaultValue;707};708 709/**710 * If the thing is a FormData object, return true, otherwise return false.711 *712 * @param {unknown} thing - The thing to check.713 *714 * @returns {boolean}715 */716function isSpecCompliantForm(thing) {717  return !!(718    thing &&719    isFunction(thing.append) &&720    thing[toStringTag] === "FormData" &&721    thing[iterator]722  );723}724 725const toJSONObject = (obj) => {726  const stack = new Array(10);727 728  const visit = (source, i) => {729    if (isObject(source)) {730      if (stack.indexOf(source) >= 0) {731        return;732      }733 734      //Buffer check735      if (isBuffer(source)) {736        return source;737      }738 739      if (!("toJSON" in source)) {740        stack[i] = source;741        const target = isArray(source) ? [] : {};742 743        forEach(source, (value, key) => {744          const reducedValue = visit(value, i + 1);745          !isUndefined(reducedValue) && (target[key] = reducedValue);746        });747 748        stack[i] = undefined;749 750        return target;751      }752    }753 754    return source;755  };756 757  return visit(obj, 0);758};759 760const isAsyncFn = kindOfTest("AsyncFunction");761 762const isThenable = (thing) =>763  thing &&764  (isObject(thing) || isFunction(thing)) &&765  isFunction(thing.then) &&766  isFunction(thing.catch);767 768// original code769// https://github.com/DigitalBrainJS/AxiosPromise/blob/16deab13710ec09779922131f3fa5954320f83ab/lib/utils.js#L11-L34770 771const _setImmediate = ((setImmediateSupported, postMessageSupported) => {772  if (setImmediateSupported) {773    return setImmediate;774  }775 776  return postMessageSupported777    ? ((token, callbacks) => {778        _global.addEventListener(779          "message",780          ({ source, data }) => {781            if (source === _global && data === token) {782              callbacks.length && callbacks.shift()();783            }784          },785          false,786        );787 788        return (cb) => {789          callbacks.push(cb);790          _global.postMessage(token, "*");791        };792      })(`axios@${Math.random()}`, [])793    : (cb) => setTimeout(cb);794})(typeof setImmediate === "function", isFunction(_global.postMessage));795 796const asap =797  typeof queueMicrotask !== "undefined"798    ? queueMicrotask.bind(_global)799    : (typeof process !== "undefined" && process.nextTick) || _setImmediate;800 801// *********************802 803const isIterable = (thing) => thing != null && isFunction(thing[iterator]);804 805export default {806  isArray,807  isArrayBuffer,808  isBuffer,809  isFormData,810  isArrayBufferView,811  isString,812  isNumber,813  isBoolean,814  isObject,815  isPlainObject,816  isEmptyObject,817  isReadableStream,818  isRequest,819  isResponse,820  isHeaders,821  isUndefined,822  isDate,823  isFile,824  isBlob,825  isRegExp,826  isFunction,827  isStream,828  isURLSearchParams,829  isTypedArray,830  isFileList,831  forEach,832  merge,833  extend,834  trim,835  stripBOM,836  inherits,837  toFlatObject,838  kindOf,839  kindOfTest,840  endsWith,841  toArray,842  forEachEntry,843  matchAll,844  isHTMLForm,845  hasOwnProperty,846  hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection847  reduceDescriptors,848  freezeMethods,849  toObjectSet,850  toCamelCase,851  noop,852  toFiniteNumber,853  findKey,854  global: _global,855  isContextDefined,856  isSpecCompliantForm,857  toJSONObject,858  isAsyncFn,859  isThenable,860  setImmediate: _setImmediate,861  asap,862  isIterable,863};864