meilisearch
Version:
The Meilisearch JS client for Node.js and the browser.
1,460 lines (1,212 loc) • 165 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.window = global.window || {}));
})(this, (function (exports) { 'use strict';
// Type definitions for meilisearch
// Project: https://github.com/meilisearch/meilisearch-js
// Definitions by: qdequele <quentin@meilisearch.com> <https://github.com/meilisearch>
// Definitions: https://github.com/meilisearch/meilisearch-js
// TypeScript Version: ^3.8.3
/*
* SEARCH PARAMETERS
*/
var MatchingStrategies = {
ALL: 'all',
LAST: 'last'
};
var ContentTypeEnum = {
JSON: 'application/json',
CSV: 'text/csv',
NDJSON: 'application/x-ndjson'
};
function _regeneratorRuntime() {
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
_regeneratorRuntime = function () {
return exports;
};
var exports = {},
Op = Object.prototype,
hasOwn = Op.hasOwnProperty,
$Symbol = "function" == typeof Symbol ? Symbol : {},
iteratorSymbol = $Symbol.iterator || "@@iterator",
asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function define(obj, key, value) {
return Object.defineProperty(obj, key, {
value: value,
enumerable: !0,
configurable: !0,
writable: !0
}), obj[key];
}
try {
define({}, "");
} catch (err) {
define = function (obj, key, value) {
return obj[key] = value;
};
}
function wrap(innerFn, outerFn, self, tryLocsList) {
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
generator = Object.create(protoGenerator.prototype),
context = new Context(tryLocsList || []);
return generator._invoke = function (innerFn, self, context) {
var state = "suspendedStart";
return function (method, arg) {
if ("executing" === state) throw new Error("Generator is already running");
if ("completed" === state) {
if ("throw" === method) throw arg;
return doneResult();
}
for (context.method = method, context.arg = arg;;) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
if ("suspendedStart" === state) throw state = "completed", context.arg;
context.dispatchException(context.arg);
} else "return" === context.method && context.abrupt("return", context.arg);
state = "executing";
var record = tryCatch(innerFn, self, context);
if ("normal" === record.type) {
if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
return {
value: record.arg,
done: context.done
};
}
"throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
}
};
}(innerFn, self, context), generator;
}
function tryCatch(fn, obj, arg) {
try {
return {
type: "normal",
arg: fn.call(obj, arg)
};
} catch (err) {
return {
type: "throw",
arg: err
};
}
}
exports.wrap = wrap;
var ContinueSentinel = {};
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
var IteratorPrototype = {};
define(IteratorPrototype, iteratorSymbol, function () {
return this;
});
var getProto = Object.getPrototypeOf,
NativeIteratorPrototype = getProto && getProto(getProto(values([])));
NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function (method) {
define(prototype, method, function (arg) {
return this._invoke(method, arg);
});
});
}
function AsyncIterator(generator, PromiseImpl) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if ("throw" !== record.type) {
var result = record.arg,
value = result.value;
return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
invoke("next", value, resolve, reject);
}, function (err) {
invoke("throw", err, resolve, reject);
}) : PromiseImpl.resolve(value).then(function (unwrapped) {
result.value = unwrapped, resolve(result);
}, function (error) {
return invoke("throw", error, resolve, reject);
});
}
reject(record.arg);
}
var previousPromise;
this._invoke = function (method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function (resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
};
}
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (undefined === method) {
if (context.delegate = null, "throw" === context.method) {
if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel;
context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
var info = record.arg;
return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
}
function pushTryEntry(locs) {
var entry = {
tryLoc: locs[0]
};
1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal", delete record.arg, entry.completion = record;
}
function Context(tryLocsList) {
this.tryEntries = [{
tryLoc: "root"
}], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
}
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) return iteratorMethod.call(iterable);
if ("function" == typeof iterable.next) return iterable;
if (!isNaN(iterable.length)) {
var i = -1,
next = function next() {
for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
return next.value = undefined, next.done = !0, next;
};
return next.next = next;
}
}
return {
next: doneResult
};
}
function doneResult() {
return {
value: undefined,
done: !0
};
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
var ctor = "function" == typeof genFun && genFun.constructor;
return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
}, exports.mark = function (genFun) {
return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
}, exports.awrap = function (arg) {
return {
__await: arg
};
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
return this;
}), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
void 0 === PromiseImpl && (PromiseImpl = Promise);
var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
return result.done ? result.value : iter.next();
});
}, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
return this;
}), define(Gp, "toString", function () {
return "[object Generator]";
}), exports.keys = function (object) {
var keys = [];
for (var key in object) keys.push(key);
return keys.reverse(), function next() {
for (; keys.length;) {
var key = keys.pop();
if (key in object) return next.value = key, next.done = !1, next;
}
return next.done = !0, next;
};
}, exports.values = values, Context.prototype = {
constructor: Context,
reset: function (skipTempReset) {
if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
},
stop: function () {
this.done = !0;
var rootRecord = this.tryEntries[0].completion;
if ("throw" === rootRecord.type) throw rootRecord.arg;
return this.rval;
},
dispatchException: function (exception) {
if (this.done) throw exception;
var context = this;
function handle(loc, caught) {
return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i],
record = entry.completion;
if ("root" === entry.tryLoc) return handle("end");
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc"),
hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
} else if (hasCatch) {
if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
} else {
if (!hasFinally) throw new Error("try statement without catch or finally");
if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
}
}
}
},
abrupt: function (type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
var record = finallyEntry ? finallyEntry.completion : {};
return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
},
complete: function (record, afterLoc) {
if ("throw" === record.type) throw record.arg;
return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
},
finish: function (finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
}
},
catch: function (tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if ("throw" === record.type) {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
throw new Error("illegal catch attempt");
},
delegateYield: function (iterable, resultName, nextLoc) {
return this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
}, "next" === this.method && (this.arg = undefined), ContinueSentinel;
}
}, exports;
}
function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _construct(Parent, args, Class) {
if (_isNativeReflectConstruct()) {
_construct = Reflect.construct.bind();
} else {
_construct = function _construct(Parent, args, Class) {
var a = [null];
a.push.apply(a, args);
var Constructor = Function.bind.apply(Parent, a);
var instance = new Constructor();
if (Class) _setPrototypeOf(instance, Class.prototype);
return instance;
};
}
return _construct.apply(null, arguments);
}
function _isNativeFunction(fn) {
return Function.toString.call(fn).indexOf("[native code]") !== -1;
}
function _wrapNativeSuper(Class) {
var _cache = typeof Map === "function" ? new Map() : undefined;
_wrapNativeSuper = function _wrapNativeSuper(Class) {
if (Class === null || !_isNativeFunction(Class)) return Class;
if (typeof Class !== "function") {
throw new TypeError("Super expression must either be null or a function");
}
if (typeof _cache !== "undefined") {
if (_cache.has(Class)) return _cache.get(Class);
_cache.set(Class, Wrapper);
}
function Wrapper() {
return _construct(Class, arguments, _getPrototypeOf(this).constructor);
}
Wrapper.prototype = Object.create(Class.prototype, {
constructor: {
value: Wrapper,
enumerable: false,
writable: true,
configurable: true
}
});
return _setPrototypeOf(Wrapper, Class);
};
return _wrapNativeSuper(Class);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
if (_i == null) return;
var _arr = [];
var _n = true;
var _d = false;
var _s, _e;
try {
for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _createForOfIteratorHelper(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
if (!it) {
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
var F = function () {};
return {
s: F,
n: function () {
if (i >= o.length) return {
done: true
};
return {
done: false,
value: o[i++]
};
},
e: function (e) {
throw e;
},
f: F
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var normalCompletion = true,
didErr = false,
err;
return {
s: function () {
it = it.call(o);
},
n: function () {
var step = it.next();
normalCompletion = step.done;
return step;
},
e: function (e) {
didErr = true;
err = e;
},
f: function () {
try {
if (!normalCompletion && it.return != null) it.return();
} finally {
if (didErr) throw err;
}
}
};
}
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
var MeiliSearchCommunicationError = /*#__PURE__*/function (_Error) {
_inherits(MeiliSearchCommunicationError, _Error);
var _super = _createSuper(MeiliSearchCommunicationError);
function MeiliSearchCommunicationError(message, body, url, stack) {
var _this;
_classCallCheck(this, MeiliSearchCommunicationError);
var _a, _b, _c;
_this = _super.call(this, message); // Make errors comparison possible. ex: error instanceof MeiliSearchCommunicationError.
Object.setPrototypeOf(_assertThisInitialized(_this), MeiliSearchCommunicationError.prototype);
_this.name = 'MeiliSearchCommunicationError';
if (body instanceof Response) {
_this.message = body.statusText;
_this.statusCode = body.status;
}
if (body instanceof Error) {
_this.errno = body.errno;
_this.code = body.code;
}
if (stack) {
_this.stack = stack;
_this.stack = (_a = _this.stack) === null || _a === void 0 ? void 0 : _a.replace(/(TypeError|FetchError)/, _this.name);
_this.stack = (_b = _this.stack) === null || _b === void 0 ? void 0 : _b.replace('Failed to fetch', "request to ".concat(url, " failed, reason: connect ECONNREFUSED"));
_this.stack = (_c = _this.stack) === null || _c === void 0 ? void 0 : _c.replace('Not Found', "Not Found: ".concat(url));
} else {
if (Error.captureStackTrace) {
Error.captureStackTrace(_assertThisInitialized(_this), MeiliSearchCommunicationError);
}
}
return _this;
}
return _createClass(MeiliSearchCommunicationError);
}( /*#__PURE__*/_wrapNativeSuper(Error));
var MeiliSearchApiError = /*#__PURE__*/function (_Error) {
_inherits(MeiliSearchApiError, _Error);
var _super = _createSuper(MeiliSearchApiError);
function MeiliSearchApiError(error, status) {
var _this;
_classCallCheck(this, MeiliSearchApiError);
_this = _super.call(this, error.message); // Make errors comparison possible. ex: error instanceof MeiliSearchApiError.
Object.setPrototypeOf(_assertThisInitialized(_this), MeiliSearchApiError.prototype);
_this.name = 'MeiliSearchApiError';
_this.code = error.code;
_this.type = error.type;
_this.link = error.link;
_this.message = error.message;
_this.httpStatus = status;
if (Error.captureStackTrace) {
Error.captureStackTrace(_assertThisInitialized(_this), MeiliSearchApiError);
}
return _this;
}
return _createClass(MeiliSearchApiError);
}( /*#__PURE__*/_wrapNativeSuper(Error));
function httpResponseErrorHandler(response) {
return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
var responseBody;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
if (response.ok) {
_context.next = 11;
break;
}
_context.prev = 1;
_context.next = 4;
return response.json();
case 4:
responseBody = _context.sent;
_context.next = 10;
break;
case 7:
_context.prev = 7;
_context.t0 = _context["catch"](1);
throw new MeiliSearchCommunicationError(response.statusText, response, response.url);
case 10:
throw new MeiliSearchApiError(responseBody, response.status);
case 11:
return _context.abrupt("return", response);
case 12:
case "end":
return _context.stop();
}
}, _callee, null, [[1, 7]]);
}));
}
function httpErrorHandler(response, stack, url) {
if (response.name !== 'MeiliSearchApiError') {
throw new MeiliSearchCommunicationError(response.message, response, url, stack);
}
throw response;
}
var MeiliSearchError = /*#__PURE__*/function (_Error) {
_inherits(MeiliSearchError, _Error);
var _super = _createSuper(MeiliSearchError);
function MeiliSearchError(message) {
var _this;
_classCallCheck(this, MeiliSearchError);
_this = _super.call(this, message); // Make errors comparison possible. ex: error instanceof MeiliSearchError.
Object.setPrototypeOf(_assertThisInitialized(_this), MeiliSearchError.prototype);
_this.name = 'MeiliSearchError';
if (Error.captureStackTrace) {
Error.captureStackTrace(_assertThisInitialized(_this), MeiliSearchError);
}
return _this;
}
return _createClass(MeiliSearchError);
}( /*#__PURE__*/_wrapNativeSuper(Error));
var MeiliSearchTimeOutError = /*#__PURE__*/function (_Error) {
_inherits(MeiliSearchTimeOutError, _Error);
var _super = _createSuper(MeiliSearchTimeOutError);
function MeiliSearchTimeOutError(message) {
var _this;
_classCallCheck(this, MeiliSearchTimeOutError);
_this = _super.call(this, message); // Make errors comparison possible. ex: error instanceof MeiliSearchTimeOutError.
Object.setPrototypeOf(_assertThisInitialized(_this), MeiliSearchTimeOutError.prototype);
_this.name = 'MeiliSearchTimeOutError';
if (Error.captureStackTrace) {
Error.captureStackTrace(_assertThisInitialized(_this), MeiliSearchTimeOutError);
}
return _this;
}
return _createClass(MeiliSearchTimeOutError);
}( /*#__PURE__*/_wrapNativeSuper(Error));
function versionErrorHintMessage(message, method) {
return "".concat(message, "\nHint: It might not be working because maybe you're not up to date with the Meilisearch version that ").concat(method, " call requires.");
}
/** Removes undefined entries from object */
function removeUndefinedFromObject(obj) {
return Object.entries(obj).reduce(function (acc, curEntry) {
var _curEntry = _slicedToArray(curEntry, 2),
key = _curEntry[0],
val = _curEntry[1];
if (val !== undefined) acc[key] = val;
return acc;
}, {});
}
function sleep(ms) {
return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return new Promise(function (resolve) {
return setTimeout(resolve, ms);
});
case 2:
return _context.abrupt("return", _context.sent);
case 3:
case "end":
return _context.stop();
}
}, _callee);
}));
}
function addProtocolIfNotPresent(host) {
if (!(host.startsWith('https://') || host.startsWith('http://'))) {
return "http://".concat(host);
}
return host;
}
function addTrailingSlash(url) {
if (!url.endsWith('/')) {
url += '/';
}
return url;
}
var PACKAGE_VERSION = '0.35.0';
function toQueryParams(parameters) {
var params = Object.keys(parameters);
var queryParams = params.reduce(function (acc, key) {
var value = parameters[key];
if (value === undefined) {
return acc;
} else if (Array.isArray(value)) {
return Object.assign(Object.assign({}, acc), _defineProperty({}, key, value.join(',')));
} else if (value instanceof Date) {
return Object.assign(Object.assign({}, acc), _defineProperty({}, key, value.toISOString()));
}
return Object.assign(Object.assign({}, acc), _defineProperty({}, key, value));
}, {});
return queryParams;
}
function constructHostURL(host) {
try {
host = addProtocolIfNotPresent(host);
host = addTrailingSlash(host);
return host;
} catch (e) {
throw new MeiliSearchError('The provided host is not valid.');
}
}
function cloneAndParseHeaders(headers) {
if (Array.isArray(headers)) {
return headers.reduce(function (acc, headerPair) {
acc[headerPair[0]] = headerPair[1];
return acc;
}, {});
} else if ('has' in headers) {
var clonedHeaders = {};
headers.forEach(function (value, key) {
return clonedHeaders[key] = value;
});
return clonedHeaders;
} else {
return Object.assign({}, headers);
}
}
function createHeaders(config) {
var _a, _b;
var agentHeader = 'X-Meilisearch-Client';
var packageAgent = "Meilisearch JavaScript (v".concat(PACKAGE_VERSION, ")");
var contentType = 'Content-Type';
var authorization = 'Authorization';
var headers = cloneAndParseHeaders((_b = (_a = config.requestConfig) === null || _a === void 0 ? void 0 : _a.headers) !== null && _b !== void 0 ? _b : {}); // do not override if user provided the header
if (config.apiKey && !headers[authorization]) {
headers[authorization] = "Bearer ".concat(config.apiKey);
}
if (!headers[contentType]) {
headers['Content-Type'] = 'application/json';
} // Creates the custom user agent with information on the package used.
if (config.clientAgents && Array.isArray(config.clientAgents)) {
var clients = config.clientAgents.concat(packageAgent);
headers[agentHeader] = clients.join(' ; ');
} else if (config.clientAgents && !Array.isArray(config.clientAgents)) {
// If the header is defined but not an array
throw new MeiliSearchError("Meilisearch: The header \"".concat(agentHeader, "\" should be an array of string(s).\n"));
} else {
headers[agentHeader] = packageAgent;
}
return headers;
}
var HttpRequests = /*#__PURE__*/function () {
function HttpRequests(config) {
_classCallCheck(this, HttpRequests);
this.headers = createHeaders(config);
this.requestConfig = config.requestConfig;
this.httpClient = config.httpClient;
try {
var host = constructHostURL(config.host);
this.url = new URL(host);
} catch (e) {
throw new MeiliSearchError('The provided host is not valid.');
}
}
_createClass(HttpRequests, [{
key: "request",
value: function request(_ref) {
var method = _ref.method,
url = _ref.url,
params = _ref.params,
body = _ref.body,
_ref$config = _ref.config,
config = _ref$config === void 0 ? {} : _ref$config;
var _a;
return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
var constructURL, queryParams, headers, fetchFn, result, response, parsedBody, stack;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
if (typeof fetch === 'undefined') {
require('cross-fetch/polyfill');
}
constructURL = new URL(url, this.url);
if (params) {
queryParams = new URLSearchParams();
Object.keys(params).filter(function (x) {
return params[x] !== null;
}).map(function (x) {
return queryParams.set(x, params[x]);
});
constructURL.search = queryParams.toString();
} // in case a custom content-type is provided
// do not stringify body
if (!((_a = config.headers) === null || _a === void 0 ? void 0 : _a['Content-Type'])) {
body = JSON.stringify(body);
}
headers = Object.assign(Object.assign({}, this.headers), config.headers);
_context.prev = 5;
fetchFn = this.httpClient ? this.httpClient : fetch;
result = fetchFn(constructURL.toString(), Object.assign(Object.assign(Object.assign({}, config), this.requestConfig), {
method: method,
body: body,
headers: headers
})); // When using a custom HTTP client, the response is returned to allow the user to parse/handle it as they see fit
if (!this.httpClient) {
_context.next = 12;
break;
}
_context.next = 11;
return result;
case 11:
return _context.abrupt("return", _context.sent);
case 12:
_context.next = 14;
return result.then(function (res) {
return httpResponseErrorHandler(res);
});
case 14:
response = _context.sent;
_context.next = 17;
return response.json().catch(function () {
return undefined;
});
case 17:
parsedBody = _context.sent;
return _context.abrupt("return", parsedBody);
case 21:
_context.prev = 21;
_context.t0 = _context["catch"](5);
stack = _context.t0.stack;
httpErrorHandler(_context.t0, stack, constructURL.toString());
case 25:
case "end":
return _context.stop();
}
}, _callee, this, [[5, 21]]);
}));
}
}, {
key: "get",
value: function get(url, params, config) {
return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
_context2.next = 2;
return this.request({
method: 'GET',
url: url,
params: params,
config: config
});
case 2:
return _context2.abrupt("return", _context2.sent);
case 3:
case "end":
return _context2.stop();
}
}, _callee2, this);
}));
}
}, {
key: "post",
value: function post(url, data, params, config) {
return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
_context3.next = 2;
return this.request({
method: 'POST',
url: url,
body: data,
params: params,
config: config
});
case 2:
return _context3.abrupt("return", _context3.sent);
case 3:
case "end":
return _context3.stop();
}
}, _callee3, this);
}));
}
}, {
key: "put",
value: function put(url, data, params, config) {
return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
_context4.next = 2;
return this.request({
method: 'PUT',
url: url,
body: data,
params: params,
config: config
});
case 2:
return _context4.abrupt("return", _context4.sent);
case 3:
case "end":
return _context4.stop();
}
}, _callee4, this);
}));
}
}, {
key: "patch",
value: function patch(url, data, params, config) {
return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee5() {
return _regeneratorRuntime().wrap(function _callee5$(_context5) {
while (1) switch (_context5.prev = _context5.next) {
case 0:
_context5.next = 2;
return this.request({
method: 'PATCH',
url: url,
body: data,
params: params,
config: config
});
case 2:
return _context5.abrupt("return", _context5.sent);
case 3:
case "end":
return _context5.stop();
}
}, _callee5, this);
}));
}
}, {
key: "delete",
value: function _delete(url, data, params, config) {
return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
return _regeneratorRuntime().wrap(function _callee6$(_context6) {
while (1) switch (_context6.prev = _context6.next) {
case 0:
_context6.next = 2;
return this.request({
method: 'DELETE',
url: url,
body: data,
params: params,
config: config
});
case 2:
return _context6.abrupt("return", _context6.sent);
case 3:
case "end":
return _context6.stop();
}
}, _callee6, this);
}));
}
}]);
return HttpRequests;
}();
var EnqueuedTask = /*#__PURE__*/_createClass(function EnqueuedTask(task) {
_classCallCheck(this, EnqueuedTask);
this.taskUid = task.taskUid;
this.indexUid = task.indexUid;
this.status = task.status;
this.type = task.type;
this.enqueuedAt = new Date(task.enqueuedAt);
});
var Task = /*#__PURE__*/_createClass(function Task(task) {
_classCallCheck(this, Task);
this.indexUid = task.indexUid;
this.status = task.status;
this.type = task.type;
this.uid = task.uid;
this.details = task.details;
this.canceledBy = task.canceledBy;
this.error = task.error;
this.duration = task.duration;
this.startedAt = new Date(task.startedAt);
this.enqueuedAt = new Date(task.enqueuedAt);
this.finishedAt = new Date(task.finishedAt);
});
var TaskClient = /*#__PURE__*/function () {
function TaskClient(config) {
_classCallCheck(this, TaskClient);
this.httpRequest = new HttpRequests(config);
}
/**
* Get one task
*
* @param uid - Unique identifier of the task
* @returns
*/
_createClass(TaskClient, [{
key: "getTask",
value: function getTask(uid) {
return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
var url, taskItem;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
url = "tasks/".concat(uid);
_context.next = 3;
return this.httpRequest.get(url);
case 3:
taskItem = _context.sent;
return _context.abrupt("return", new Task(taskItem));
case 5:
case "end":
return _context.stop();
}
}, _callee, this);
}));
}
/**
* Get tasks
*
* @param parameters - Parameters to browse the tasks
* @returns Promise containing all tasks
*/
}, {
key: "getTasks",
value: function getTasks() {
var parameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
var url, tasks;
return _regeneratorRuntime().wrap(function _callee2$(_context2) {
while (1) switch (_context2.prev = _context2.next) {
case 0:
url = "tasks";
_context2.next = 3;
return this.httpRequest.get(url, toQueryParams(parameters));
case 3:
tasks = _context2.sent;
return _context2.abrupt("return", Object.assign(Object.assign({}, tasks), {
results: tasks.results.map(function (task) {
return new Task(task);
})
}));
case 5:
case "end":
return _context2.stop();
}
}, _callee2, this);
}));
}
/**
* Wait for a task to be processed.
*
* @param taskUid - Task identifier
* @param options - Additional configuration options
* @returns Promise returning a task after it has been processed
*/
}, {
key: "waitForTask",
value: function waitForTask(taskUid) {
var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref$timeOutMs = _ref.timeOutMs,
timeOutMs = _ref$timeOutMs === void 0 ? 5000 : _ref$timeOutMs,
_ref$intervalMs = _ref.intervalMs,
intervalMs = _ref$intervalMs === void 0 ? 50 : _ref$intervalMs;
return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
var startingTime, response;
return _regeneratorRuntime().wrap(function _callee3$(_context3) {
while (1) switch (_context3.prev = _context3.next) {
case 0:
startingTime = Date.now();
case 1:
if (!(Date.now() - startingTime < timeOutMs)) {
_context3.next = 11;
break;
}
_context3.next = 4;
return this.getTask(taskUid);
case 4:
response = _context3.sent;
if (["enqueued"
/* TaskStatus.TASK_ENQUEUED */
, "processing"
/* TaskStatus.TASK_PROCESSING */
].includes(response.status)) {
_context3.next = 7;
break;
}
return _context3.abrupt("return", response);
case 7:
_context3.next = 9;
return sleep(intervalMs);
case 9:
_context3.next = 1;
break;
case 11:
throw new MeiliSearchTimeOutError("timeout of ".concat(timeOutMs, "ms has exceeded on process ").concat(taskUid, " when waiting a task to be resolved."));
case 12:
case "end":
return _context3.stop();
}
}, _callee3, this);
}));
}
/**
* Waits for multiple tasks to be processed
*
* @param taskUids - Tasks identifier list
* @param options - Wait options
* @returns Promise returning a list of tasks after they have been processed
*/
}, {
key: "waitForTasks",
value: function waitForTasks(taskUids) {
var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
_ref2$timeOutMs = _ref2.timeOutMs,
timeOutMs = _ref2$timeOutMs === void 0 ? 5000 : _ref2$timeOutMs,
_ref2$intervalMs = _ref2.intervalMs,
intervalMs = _ref2$intervalMs === void 0 ? 50 : _ref2$intervalMs;
return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
var tasks, _iterator, _step, taskUid, task;
return _regeneratorRuntime().wrap(function _callee4$(_context4) {
while (1) switch (_context4.prev = _context4.next) {
case 0:
tasks = [];
_iterator = _createForOfIteratorHelper(taskUids);
_context4.prev = 2;
_iterator.s();
case 4:
if ((_step = _iterator.n()).done) {
_context4.next = 12;
break;
}
taskUid = _step.value;
_context4.next = 8;
return this.waitForTask(taskUid, {
timeOutMs: timeOutMs,
intervalMs: intervalMs
});
case 8:
task = _context4.sent;
tasks.push(task);
case 10:
_context4.next = 4;
break;
case 12:
_context4.next = 17;
break;
case 14: