arangojs 8.0.0 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/web.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"web.js","mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAkB,SAAID,IAEtBD,EAAe,SAAIC,GACpB,CATD,CASGK,MAAM,WACT,O,sCCVA,IAAIC,EAGAA,EADkB,oBAAXC,OACDA,YACmB,IAAXC,EAAAA,EACRA,EAAAA,EACiB,oBAATH,KACRA,KAEA,CAAC,EAGXH,EAAOD,QAAUK,C,kBCZjBJ,EAAOD,QAIP,SAAqBQ,GACnB,IAAKA,EACH,OAAO,EAET,IAAIC,EAASC,EAASC,KAAKH,GAC3B,MAAkB,sBAAXC,GACU,mBAAPD,GAAgC,oBAAXC,GACV,oBAAXH,SAENE,IAAOF,OAAOM,YACdJ,IAAOF,OAAOO,OACdL,IAAOF,OAAOQ,SACdN,IAAOF,OAAOS,OACpB,EAfA,IAAIL,EAAWM,OAAOC,UAAUP,Q,iBCFhC,IAAIQ,EAAO,SAAST,GAClB,OAAOA,EAAOU,QAAQ,aAAc,GACtC,EAKAlB,EAAOD,QAAU,SAAUoB,GACzB,IAAKA,EACH,MAAO,CAAC,EAMV,IAJA,IARqBC,EAQjBC,EAAS,CAAC,EAEVC,EAAaL,EAAKE,GAASI,MAAM,MAE5BC,EAAI,EAAGA,EAAIF,EAAWG,OAAQD,IAAK,CAC1C,IAAIE,EAAMJ,EAAWE,GACjBG,EAAQD,EAAIE,QAAQ,KACtBC,EAAMZ,EAAKS,EAAII,MAAM,EAAGH,IAAQI,cAChCC,EAAQf,EAAKS,EAAII,MAAMH,EAAQ,SAEL,IAAjBN,EAAOQ,GAChBR,EAAOQ,GAAO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yBE,GAAY,CAGjD9tB,QAAS,CAAC,GAOX,OAHAguB,EAAoBF,GAAU7tB,EAAQA,EAAOD,QAAS6tB,GAG/C5tB,EAAOD,OACf,C,OCrBA6tB,EAAoBI,EAAI,SAAShuB,GAChC,IAAIiuB,EAASjuB,GAAUA,EAAOkuB,WAC7B,WAAa,OAAOluB,EAAgB,OAAG,EACvC,WAAa,OAAOA,CAAQ,EAE7B,OADA4tB,EAAoBO,EAAEF,EAAQ,CAAEG,EAAGH,IAC5BA,CACR,ECNAL,EAAoBO,EAAI,SAASpuB,EAASsuB,GACzC,IAAI,IAAIxsB,KAAOwsB,EACXT,EAAoBU,EAAED,EAAYxsB,KAAS+rB,EAAoBU,EAAEvuB,EAAS8B,IAC5Ed,OAAOwB,eAAexC,EAAS8B,EAAK,CAAEqB,YAAY,EAAM+O,IAAKoc,EAAWxsB,IAG3E,ECPA+rB,EAAoBW,EAAI,WACvB,GAA0B,iBAAfpkB,WAAyB,OAAOA,WAC3C,IACC,OAAOzF,MAAQ,IAAI0F,SAAS,cAAb,EAGhB,CAFE,MAAOoE,GACR,GAAsB,iBAAXnO,OAAqB,OAAOA,MACxC,CACA,CAPuB,GCAxButB,EAAoBU,EAAI,SAAS9rB,EAAKyoB,GAAQ,OAAOlqB,OAAOC,UAAUsB,eAAe5B,KAAK8B,EAAKyoB,EAAO,ECCtG2C,EAAoBY,EAAI,SAASzuB,GACX,oBAAX4C,QAA0BA,OAAOM,aAC1ClC,OAAOwB,eAAexC,EAAS4C,OAAOM,YAAa,CAAEjB,MAAO,WAE7DjB,OAAOwB,eAAexC,EAAS,aAAc,CAAEiC,OAAO,GACvD,ECHA4rB,EAAoB,KACMA,EAAoB,I","sources":["webpack://arangojs/webpack/universalModuleDefinition","webpack://arangojs/./node_modules/global/window.js","webpack://arangojs/./node_modules/is-function/index.js","webpack://arangojs/./node_modules/parse-headers/parse-headers.js","webpack://arangojs/./node_modules/regenerator-runtime/runtime.js","webpack://arangojs/../src/LinkedList.ts","webpack://arangojs/../src/LinkedListItem.ts","webpack://arangojs/../src/index.ts","webpack://arangojs/./node_modules/xhr/index.js","webpack://arangojs/./node_modules/xtend/immutable.js","webpack://arangojs/./src/analyzer.ts","webpack://arangojs/./src/aql.ts","webpack://arangojs/./src/indexes.ts","webpack://arangojs/./src/collection.ts","webpack://arangojs/./src/cursor.ts","webpack://arangojs/./src/lib/btoa.web.ts","webpack://arangojs/./src/lib/normalizeUrl.ts","webpack://arangojs/./src/lib/xhr.ts","webpack://arangojs/./src/lib/request.web.ts","webpack://arangojs/./src/lib/omit.ts","webpack://arangojs/./src/connection.ts","webpack://arangojs/./src/lib/querystringify.web.ts","webpack://arangojs/./src/lib/multipart.web.ts","webpack://arangojs/./src/route.ts","webpack://arangojs/./src/transaction.ts","webpack://arangojs/./src/database.ts","webpack://arangojs/./src/documents.ts","webpack://arangojs/./src/error.ts","webpack://arangojs/./src/graph.ts","webpack://arangojs/./src/lib/codes.ts","webpack://arangojs/./src/view.ts","webpack://arangojs/./src/web.js","webpack://arangojs/webpack/bootstrap","webpack://arangojs/webpack/runtime/compat get default export","webpack://arangojs/webpack/runtime/define property getters","webpack://arangojs/webpack/runtime/global","webpack://arangojs/webpack/runtime/hasOwnProperty shorthand","webpack://arangojs/webpack/runtime/make namespace object","webpack://arangojs/webpack/startup"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"arangojs\"] = factory();\n\telse\n\t\troot[\"arangojs\"] = factory();\n})(self, function() {\nreturn ","var win;\n\nif (typeof window !== \"undefined\") {\n win = window;\n} else if (typeof global !== \"undefined\") {\n win = global;\n} else if (typeof self !== \"undefined\"){\n win = self;\n} else {\n win = {};\n}\n\nmodule.exports = win;\n","module.exports = isFunction\n\nvar toString = Object.prototype.toString\n\nfunction isFunction (fn) {\n if (!fn) {\n return false\n }\n var string = toString.call(fn)\n return string === '[object Function]' ||\n (typeof fn === 'function' && string !== '[object RegExp]') ||\n (typeof window !== 'undefined' &&\n // IE8 and below\n (fn === window.setTimeout ||\n fn === window.alert ||\n fn === window.confirm ||\n fn === window.prompt))\n};\n","var trim = function(string) {\n return string.replace(/^\\s+|\\s+$/g, '');\n}\n , isArray = function(arg) {\n return Object.prototype.toString.call(arg) === '[object Array]';\n }\n\nmodule.exports = function (headers) {\n if (!headers)\n return {}\n\n var result = {}\n\n var headersArr = trim(headers).split('\\n')\n\n for (var i = 0; i < headersArr.length; i++) {\n var row = headersArr[i]\n var index = row.indexOf(':')\n , key = trim(row.slice(0, index)).toLowerCase()\n , value = trim(row.slice(index + 1))\n\n if (typeof(result[key]) === 'undefined') {\n result[key] = value\n } else if (isArray(result[key])) {\n result[key].push(value)\n } else {\n result[key] = [ result[key], value ]\n }\n }\n\n return result\n}\n","/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar runtime = (function (exports) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; };\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n function define(obj, key, value) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n return obj[key];\n }\n try {\n // IE 8 has a broken Object.defineProperty that only works on DOM objects.\n define({}, \"\");\n } catch (err) {\n define = function(obj, key, value) {\n return obj[key] = value;\n };\n }\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n defineProperty(generator, \"_invoke\", { value: makeInvokeMethod(innerFn, self, context) });\n\n return generator;\n }\n exports.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n define(IteratorPrototype, iteratorSymbol, function () {\n return this;\n });\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = GeneratorFunctionPrototype;\n defineProperty(Gp, \"constructor\", { value: GeneratorFunctionPrototype, configurable: true });\n defineProperty(\n GeneratorFunctionPrototype,\n \"constructor\",\n { value: GeneratorFunction, configurable: true }\n );\n GeneratorFunction.displayName = define(\n GeneratorFunctionPrototype,\n toStringTagSymbol,\n \"GeneratorFunction\"\n );\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n define(prototype, method, function(arg) {\n return this._invoke(method, arg);\n });\n });\n }\n\n exports.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n exports.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n define(genFun, toStringTagSymbol, \"GeneratorFunction\");\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n // meant to be awaited.\n exports.awrap = function(arg) {\n return { __await: arg };\n };\n\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return PromiseImpl.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return PromiseImpl.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration.\n result.value = unwrapped;\n resolve(result);\n }, function(error) {\n // If a rejected Promise was yielded, throw the rejection back\n // into the async generator function so it can be handled there.\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n defineProperty(this, \"_invoke\", { value: enqueue });\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n define(AsyncIterator.prototype, asyncIteratorSymbol, function () {\n return this;\n });\n exports.AsyncIterator = AsyncIterator;\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n if (PromiseImpl === void 0) PromiseImpl = Promise;\n\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList),\n PromiseImpl\n );\n\n return exports.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n }\n\n // Call delegate.iterator[context.method](context.arg) and handle the\n // result, either by returning a { value, done } result from the\n // delegate iterator, or by modifying context.method and context.arg,\n // setting context.delegate to null, and returning the ContinueSentinel.\n function maybeInvokeDelegate(delegate, context) {\n var method = delegate.iterator[context.method];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method always terminates the yield* loop.\n context.delegate = null;\n\n if (context.method === \"throw\") {\n // Note: [\"return\"] must be used for ES3 parsing compatibility.\n if (delegate.iterator[\"return\"]) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a 'throw' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n define(Gp, toStringTagSymbol, \"Generator\");\n\n // A Generator should always return itself as the iterator object when the\n // @@iterator function is called on it. Some browsers' implementations of the\n // iterator prototype chain incorrectly implement this, causing the Generator\n // object to not be returned from this call. This ensures that doesn't happen.\n // See https://github.com/facebook/regenerator/issues/274 for more details.\n define(Gp, iteratorSymbol, function() {\n return this;\n });\n\n define(Gp, \"toString\", function() {\n return \"[object Generator]\";\n });\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n exports.keys = function(val) {\n var object = Object(val);\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n exports.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n };\n\n // Regardless of whether this script is executing as a CommonJS module\n // or not, return the runtime object so that we can declare the variable\n // regeneratorRuntime in the outer scope, which allows this module to be\n // injected easily by `bin/regenerator --include-runtime script.js`.\n return exports;\n\n}(\n // If this script is executing as a CommonJS module, use module.exports\n // as the regeneratorRuntime namespace. Otherwise create a new empty\n // object. Either way, the resulting object will be used to initialize\n // the regeneratorRuntime variable at the top of this file.\n typeof module === \"object\" ? module.exports : {}\n));\n\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n // This module should not be running in strict mode, so the above\n // assignment should always work unless something is misconfigured. Just\n // in case runtime.js accidentally runs in strict mode, in modern engines\n // we can explicitly access globalThis. In older engines we can escape\n // strict mode using a global Function call. This could conceivably fail\n // if a Content Security Policy forbids using Function, but in that case\n // the proper solution is to fix the accidental strict mode problem. If\n // you've misconfigured your bundler to force strict mode and applied a\n // CSP to forbid Function, and you're not willing to fix either of those\n // problems, please detail your unique predicament in a GitHub issue.\n if (typeof globalThis === \"object\") {\n globalThis.regeneratorRuntime = runtime;\n } else {\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n }\n}\n",null,null,null,"\"use strict\";\nvar window = require(\"global/window\")\nvar isFunction = require(\"is-function\")\nvar parseHeaders = require(\"parse-headers\")\nvar xtend = require(\"xtend\")\n\nmodule.exports = createXHR\n// Allow use of default import syntax in TypeScript\nmodule.exports.default = createXHR;\ncreateXHR.XMLHttpRequest = window.XMLHttpRequest || noop\ncreateXHR.XDomainRequest = \"withCredentials\" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest\n\nforEachArray([\"get\", \"put\", \"post\", \"patch\", \"head\", \"delete\"], function(method) {\n createXHR[method === \"delete\" ? \"del\" : method] = function(uri, options, callback) {\n options = initParams(uri, options, callback)\n options.method = method.toUpperCase()\n return _createXHR(options)\n }\n})\n\nfunction forEachArray(array, iterator) {\n for (var i = 0; i < array.length; i++) {\n iterator(array[i])\n }\n}\n\nfunction isEmpty(obj){\n for(var i in obj){\n if(obj.hasOwnProperty(i)) return false\n }\n return true\n}\n\nfunction initParams(uri, options, callback) {\n var params = uri\n\n if (isFunction(options)) {\n callback = options\n if (typeof uri === \"string\") {\n params = {uri:uri}\n }\n } else {\n params = xtend(options, {uri: uri})\n }\n\n params.callback = callback\n return params\n}\n\nfunction createXHR(uri, options, callback) {\n options = initParams(uri, options, callback)\n return _createXHR(options)\n}\n\nfunction _createXHR(options) {\n if(typeof options.callback === \"undefined\"){\n throw new Error(\"callback argument missing\")\n }\n\n var called = false\n var callback = function cbOnce(err, response, body){\n if(!called){\n called = true\n options.callback(err, response, body)\n }\n }\n\n function readystatechange() {\n if (xhr.readyState === 4) {\n setTimeout(loadFunc, 0)\n }\n }\n\n function getBody() {\n // Chrome with requestType=blob throws errors arround when even testing access to responseText\n var body = undefined\n\n if (xhr.response) {\n body = xhr.response\n } else {\n body = xhr.responseText || getXml(xhr)\n }\n\n if (isJson) {\n try {\n body = JSON.parse(body)\n } catch (e) {}\n }\n\n return body\n }\n\n function errorFunc(evt) {\n clearTimeout(timeoutTimer)\n if(!(evt instanceof Error)){\n evt = new Error(\"\" + (evt || \"Unknown XMLHttpRequest Error\") )\n }\n evt.statusCode = 0\n return callback(evt, failureResponse)\n }\n\n // will load the data & process the response in a special response object\n function loadFunc() {\n if (aborted) return\n var status\n clearTimeout(timeoutTimer)\n if(options.useXDR && xhr.status===undefined) {\n //IE8 CORS GET successful response doesn't have a status field, but body is fine\n status = 200\n } else {\n status = (xhr.status === 1223 ? 204 : xhr.status)\n }\n var response = failureResponse\n var err = null\n\n if (status !== 0){\n response = {\n body: getBody(),\n statusCode: status,\n method: method,\n headers: {},\n url: uri,\n rawRequest: xhr\n }\n if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE\n response.headers = parseHeaders(xhr.getAllResponseHeaders())\n }\n } else {\n err = new Error(\"Internal XMLHttpRequest Error\")\n }\n return callback(err, response, response.body)\n }\n\n var xhr = options.xhr || null\n\n if (!xhr) {\n if (options.cors || options.useXDR) {\n xhr = new createXHR.XDomainRequest()\n }else{\n xhr = new createXHR.XMLHttpRequest()\n }\n }\n\n var key\n var aborted\n var uri = xhr.url = options.uri || options.url\n var method = xhr.method = options.method || \"GET\"\n var body = options.body || options.data\n var headers = xhr.headers = options.headers || {}\n var sync = !!options.sync\n var isJson = false\n var timeoutTimer\n var failureResponse = {\n body: undefined,\n headers: {},\n statusCode: 0,\n method: method,\n url: uri,\n rawRequest: xhr\n }\n\n if (\"json\" in options && options.json !== false) {\n isJson = true\n headers[\"accept\"] || headers[\"Accept\"] || (headers[\"Accept\"] = \"application/json\") //Don't override existing accept header declared by user\n if (method !== \"GET\" && method !== \"HEAD\") {\n headers[\"content-type\"] || headers[\"Content-Type\"] || (headers[\"Content-Type\"] = \"application/json\") //Don't override existing accept header declared by user\n body = JSON.stringify(options.json === true ? body : options.json)\n }\n }\n\n xhr.onreadystatechange = readystatechange\n xhr.onload = loadFunc\n xhr.onerror = errorFunc\n // IE9 must have onprogress be set to a unique function.\n xhr.onprogress = function () {\n // IE must die\n }\n xhr.onabort = function(){\n aborted = true;\n }\n xhr.ontimeout = errorFunc\n xhr.open(method, uri, !sync, options.username, options.password)\n //has to be after open\n if(!sync) {\n xhr.withCredentials = !!options.withCredentials\n }\n // Cannot set timeout with sync request\n // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly\n // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent\n if (!sync && options.timeout > 0 ) {\n timeoutTimer = setTimeout(function(){\n if (aborted) return\n aborted = true//IE9 may still call readystatechange\n xhr.abort(\"timeout\")\n var e = new Error(\"XMLHttpRequest timeout\")\n e.code = \"ETIMEDOUT\"\n errorFunc(e)\n }, options.timeout )\n }\n\n if (xhr.setRequestHeader) {\n for(key in headers){\n if(headers.hasOwnProperty(key)){\n xhr.setRequestHeader(key, headers[key])\n }\n }\n } else if (options.headers && !isEmpty(options.headers)) {\n throw new Error(\"Headers cannot be set on an XDomainRequest object\")\n }\n\n if (\"responseType\" in options) {\n xhr.responseType = options.responseType\n }\n\n if (\"beforeSend\" in options &&\n typeof options.beforeSend === \"function\"\n ) {\n options.beforeSend(xhr)\n }\n\n // Microsoft Edge browser sends \"undefined\" when send is called with undefined value.\n // XMLHttpRequest spec says to pass null as body to indicate no body\n // See https://github.com/naugtur/xhr/issues/100.\n xhr.send(body || null)\n\n return xhr\n\n\n}\n\nfunction getXml(xhr) {\n // xhr.responseXML will throw Exception \"InvalidStateError\" or \"DOMException\"\n // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.\n try {\n if (xhr.responseType === \"document\") {\n return xhr.responseXML\n }\n var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === \"parsererror\"\n if (xhr.responseType === \"\" && !firefoxBugTakenEffect) {\n return xhr.responseXML\n }\n } catch (e) {}\n\n return null\n}\n\nfunction noop() {}\n","module.exports = extend\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nfunction extend() {\n var target = {}\n\n for (var i = 0; i < arguments.length; i++) {\n var source = arguments[i]\n\n for (var key in source) {\n if (hasOwnProperty.call(source, key)) {\n target[key] = source[key]\n }\n }\n }\n\n return target\n}\n","/**\n * ```ts\n * import type { Analyzer } from \"arangojs/analyzer\";\n * ```\n *\n * The \"analyzer\" module provides analyzer related types and interfaces\n * for TypeScript.\n *\n * @packageDocumentation\n */\nimport { ArangoApiResponse } from \"./connection\";\nimport { Database } from \"./database\";\nimport { isArangoError } from \"./error\";\nimport { ANALYZER_NOT_FOUND } from \"./lib/codes\";\n\n/**\n * Indicates whether the given value represents an {@link Analyzer}.\n *\n * @param analyzer - A value that might be an Analyzer.\n */\nexport function isArangoAnalyzer(analyzer: any): analyzer is Analyzer {\n return Boolean(analyzer && analyzer.isArangoAnalyzer);\n}\n\n/**\n * Name of a feature enabled for an Analyzer.\n */\nexport type AnalyzerFeature = \"frequency\" | \"norm\" | \"position\" | \"offset\";\n\n/**\n * Analyzer type and its type-specific properties.\n */\nexport type CreateAnalyzerOptions =\n | CreateIdentityAnalyzerOptions\n | CreateDelimiterAnalyzerOptions\n | CreateStemAnalyzerOptions\n | CreateNormAnalyzerOptions\n | CreateNgramAnalyzerOptions\n | CreateTextAnalyzerOptions\n | CreateSegmentationAnalyzerOptions\n | CreateAqlAnalyzerOptions\n | CreatePipelineAnalyzerOptions\n | CreateStopwordsAnalyzerOptions\n | CreateCollationAnalyzerOptions\n | CreateMinHashAnalyzerOptions\n | CreateClassificationAnalyzerOptions\n | CreateNearestNeighborsAnalyzerOptions\n | CreateGeoJsonAnalyzerOptions\n | CreateGeoPointAnalyzerOptions;\n\n/**\n * Options for creating an Identity Analyzer.\n */\nexport type CreateIdentityAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"identity\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n *\n * The `identity` Analyzer does not take additional properties.\n */\n properties?: Record<string, never>;\n};\n\n/**\n * Options for creating a Delimiter Analyzer.\n */\nexport type CreateDelimiterAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"delimiter\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n *\n * The value will be used as delimiter to split text into tokens as specified\n * in RFC 4180, without starting new records on newlines.\n */\n properties: string | { delimiter: string };\n};\n\n/**\n * Options for creating a Stem Analyzer.\n */\nexport type CreateStemAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"stem\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n *\n * The value defines the text locale.\n *\n * Format: `language[_COUNTRY][.encoding][@variant]`\n */\n properties: { locale: string };\n};\n\n/**\n * Options for creating a Norm Analyzer.\n */\nexport type CreateNormAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"norm\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * Text locale.\n *\n * Format: `language[_COUNTRY][.encoding][@variant]`\n */\n locale: string;\n /**\n * Case conversion.\n *\n * Default: `\"lower\"`\n */\n case?: \"lower\" | \"none\" | \"upper\";\n /**\n * Preserve accents in returned words.\n *\n * Default: `false`\n */\n accent?: boolean;\n };\n};\n\n/**\n * Options for creating an Ngram Analyzer.\n */\nexport type CreateNgramAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"ngram\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * Maximum n-gram length.\n */\n max: number;\n /**\n * Minimum n-gram length.\n */\n min: number;\n /**\n * Output the original value as well.\n */\n preserveOriginal: boolean;\n };\n};\n\n/**\n * Options for creating a Text Analyzer.\n */\nexport type CreateTextAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"text\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * Text locale.\n *\n * Format: `language[_COUNTRY][.encoding][@variant]`\n */\n locale: string;\n /**\n * Case conversion.\n *\n * Default: `\"lower\"`\n */\n case?: \"lower\" | \"none\" | \"upper\";\n /**\n * Words to omit from result.\n *\n * Defaults to the words loaded from the file at `stopwordsPath`.\n */\n stopwords?: string[];\n /**\n * Path with a `language` sub-directory containing files with words to omit.\n *\n * Defaults to the path specified in the server-side environment variable\n * `IRESEARCH_TEXT_STOPWORD_PATH` or the current working directory of the\n * ArangoDB process.\n */\n stopwordsPath?: string;\n /**\n * Preserve accents in returned words.\n *\n * Default: `false`\n */\n accent?: boolean;\n /**\n * Apply stemming on returned words.\n *\n * Default: `true`\n */\n stemming?: boolean;\n /**\n * If present, then edge n-grams are generated for each token (word).\n */\n edgeNgram?: { min?: number; max?: number; preserveOriginal?: boolean };\n };\n};\n\n/**\n * Options for creating a Segmentation Analyzer\n */\nexport type CreateSegmentationAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"segmentation\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * Which tokens should be returned.\n *\n * Default: `\"alpha\"`\n */\n break?: \"all\" | \"alpha\" | \"graphic\";\n /**\n * What case all returned tokens should be converted to if applicable.\n *\n * Default: `\"none\"`\n */\n case?: \"lower\" | \"upper\" | \"none\";\n };\n};\n\n/**\n * Options for creating an AQL Analyzer\n */\nexport type CreateAqlAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"aql\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * AQL query to be executed.\n */\n queryString: string;\n /**\n * If set to `true`, the position is set to `0` for all members of the query result array.\n *\n * Default: `false`\n */\n collapsePositions?: boolean;\n /**\n * If set to `false`, `null` values will be discarded from the View index.\n *\n * Default: `true`\n */\n keepNull?: boolean;\n /**\n * Number between `1` and `1000` that determines the batch size for reading\n * data from the query.\n *\n * Default: `1`\n */\n batchSize?: number;\n /**\n * Memory limit for query execution in bytes.\n *\n * Default: `1048576` (1 MiB)\n */\n memoryLimit?: number;\n /**\n * Data type of the returned tokens.\n *\n * Default: `\"string\"`\n */\n returnType?: \"string\" | \"number\" | \"bool\";\n };\n};\n\n/**\n * Options for creating a Pipeline Analyzer\n */\nexport type CreatePipelineAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"pipeline\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * Definitions for Analyzers to chain in this Pipeline Analyzer.\n */\n pipeline: Omit<CreateAnalyzerOptions, \"features\">[];\n };\n};\n\n/**\n * Options for creating a Stopwords Analyzer\n */\nexport type CreateStopwordsAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"stopwords\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * Array of strings that describe the tokens to be discarded.\n */\n stopwords: string[];\n /**\n * Whether stopword values should be interpreted as hex-encoded strings.\n *\n * Default: `false`\n */\n hex?: boolean;\n };\n};\n\n/**\n * Options for creating a Collation Analyzer\n */\nexport type CreateCollationAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"collation\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * Text locale.\n *\n * Format: `language[_COUNTRY][.encoding][@variant]`\n */\n locale: string;\n };\n};\n\n/**\n * Options for creating a MinHash Analyzer\n */\nexport type CreateMinHashAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"minhash\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * An Analyzer definition-like object with `type` and `properties` attributes.\n */\n analyzer: Omit<CreateAnalyzerOptions, \"features\">;\n /**\n * Size of the MinHash signature.\n */\n numHashes: number;\n };\n};\n\n/**\n * Options for creating a Classification Analyzer\n */\nexport type CreateClassificationAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"classification\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * On-disk path to the trained fastText supervised model.\n */\n model_location: string;\n /**\n * Number of class labels that will be produced per input.\n *\n * Default: `1`\n */\n top_k?: number;\n /**\n * Probability threshold for which a label will be assigned to an input.\n *\n * Default: `0.99`\n */\n threshold?: number;\n };\n};\n\n/**\n * Options for creating a NearestNeighbors Analyzer\n */\nexport type CreateNearestNeighborsAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"nearest_neighbors\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * On-disk path to the trained fastText supervised model.\n */\n model_location: string;\n /**\n * Number of class labels that will be produced per input.\n *\n * Default: `1`\n */\n top_k?: number;\n };\n};\n\n/**\n * Options for creating a GeoJSON Analyzer\n */\nexport type CreateGeoJsonAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"geojson\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * If set to `\"centroid\"`, only the centroid of the input geometry will be\n * computed and indexed.\n *\n * If set to `\"point\"` only GeoJSON objects of type Point will be indexed and\n * all other geometry types will be ignored.\n *\n * Default: `\"shape\"`\n */\n type?: \"shape\" | \"centroid\" | \"point\";\n /**\n * Options for fine-tuning geo queries.\n *\n * Default: `{ maxCells: 20, minLevel: 4, maxLevel: 23 }`\n */\n options?: { maxCells?: number; minLevel?: number; maxLevel?: number };\n };\n};\n\n/**\n * Options for creating a GeoPoint Analyzer\n */\nexport type CreateGeoPointAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"geopoint\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * Attribute paths of the latitude value relative to the field for which the\n * Analyzer is defined in the View.\n */\n latitude?: string[];\n /**\n * Attribute paths of the longitude value relative to the field for which the\n * Analyzer is defined in the View.\n */\n longitude?: string[];\n /**\n * Options for fine-tuning geo queries.\n *\n * Default: `{ maxCells: 20, minLevel: 4, maxLevel: 23 }`\n */\n options?: { minCells?: number; minLevel?: number; maxLevel?: number };\n };\n};\n\n/**\n * Shared attributes of all Analyzer descriptions.\n */\nexport type GenericAnalyzerDescription = {\n /**\n * A unique name for this Analyzer.\n */\n name: string;\n /**\n * Features enabled for this Analyzer.\n */\n features: AnalyzerFeature[];\n};\n\n/**\n * An object describing an Analyzer.\n */\nexport type AnalyzerDescription =\n | IdentityAnalyzerDescription\n | DelimiterAnalyzerDescription\n | StemAnalyzerDescription\n | NormAnalyzerDescription\n | NgramAnalyzerDescription\n | TextAnalyzerDescription\n | SegmentationAnalyzerDescription\n | AqlAnalyzerDescription\n | PipelineAnalyzerDescription\n | StopwordsAnalyzerDescription\n | CollationAnalyzerDescription\n | MinHashAnalyzerDescription\n | ClassificationAnalyzerDescription\n | NearestNeighborsAnalyzerDescription\n | GeoJsonAnalyzerDescription\n | GeoPointAnalyzerDescription;\n\n/**\n * An object describing an Identity Analyzer.\n */\nexport type IdentityAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"identity\";\n properties: Record<string, never>;\n};\n\n/**\n * An object describing a Delimiter Analyzer.\n */\nexport type DelimiterAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"delimiter\";\n properties: { delimiter: string };\n};\n\n/**\n * An object describing a Stem Analyzer.\n */\nexport type StemAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"stem\";\n properties: { locale: string };\n};\n\n/**\n * An object describing a Norm Analyzer.\n */\nexport type NormAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"norm\";\n properties: {\n locale: string;\n case: \"lower\" | \"none\" | \"upper\";\n accent: boolean;\n };\n};\n\n/**\n * An object describing an Ngram Analyzer.\n */\nexport type NgramAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"ngram\";\n properties: {\n max: number;\n min: number;\n preserveOriginal: boolean;\n };\n};\n\n/**\n * An object describing a Text Analyzer.\n */\nexport type TextAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"text\";\n properties: {\n locale: string;\n case: \"lower\" | \"none\" | \"upper\";\n stopwords: string[];\n stopwordsPath: string;\n accent: boolean;\n stemming: boolean;\n edgeNgram: { min: number; max: number; preserveOriginal: boolean };\n };\n};\n\n/**\n * An object describing a Segmentation Analyzer\n */\nexport type SegmentationAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"segmentation\";\n properties: {\n break: \"all\" | \"alpha\" | \"graphic\";\n case: \"lower\" | \"upper\" | \"none\";\n };\n};\n\n/**\n * An object describing an AQL Analyzer\n */\nexport type AqlAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"aql\";\n properties: {\n queryString: string;\n collapsePositions: boolean;\n keepNull: boolean;\n batchSize: number;\n memoryLimit: number;\n returnType: \"string\" | \"number\" | \"bool\";\n };\n};\n\n/**\n * An object describing a Pipeline Analyzer\n */\nexport type PipelineAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"pipeline\";\n properties: {\n pipeline: Omit<AnalyzerDescription, \"name\" | \"features\">[];\n };\n};\n\n/**\n * An object describing a Stopwords Analyzer\n */\nexport type StopwordsAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"stopwords\";\n properties: {\n stopwords: string[];\n hex: boolean;\n };\n};\n\n/**\n * An object describing a Collation Analyzer\n */\nexport type CollationAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"collation\";\n properties: {\n locale: string;\n };\n};\n\n/**\n * (Enterprise Edition only.) An object describing a MinHash Analyzer\n */\nexport type MinHashAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"minhash\";\n properties: {\n analyzer: Omit<AnalyzerDescription, \"name\" | \"features\">;\n numHashes: number;\n };\n};\n\n/**\n * (Enterprise Edition only.) An object describing a Classification Analyzer\n */\nexport type ClassificationAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"classification\";\n properties: {\n model_location: string;\n top_k: number;\n threshold: number;\n };\n};\n\n/**\n * (Enterprise Edition only.) An object describing a NearestNeighbors Analyzer\n */\nexport type NearestNeighborsAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"nearest_neighbors\";\n properties: {\n model_location: string;\n top_k: number;\n };\n};\n\n/**\n * An object describing a GeoJSON Analyzer\n */\nexport type GeoJsonAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"geojson\";\n properties: {\n type: \"shape\" | \"centroid\" | \"point\";\n description: { maxCells: number; minLevel: number; maxLevel: number };\n };\n};\n\n/**\n * An object describing a GeoPoint Analyzer\n */\nexport type GeoPointAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"geopoint\";\n properties: {\n latitude: string[];\n longitude: string[];\n description: { minCells: number; minLevel: number; maxLevel: number };\n };\n};\n\n/**\n * Represents an Analyzer in a {@link database.Database}.\n */\nexport class Analyzer {\n protected _name: string;\n protected _db: Database;\n\n /**\n * @internal\n */\n constructor(db: Database, name: string) {\n this._db = db;\n this._name = name.normalize(\"NFC\");\n }\n\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB Analyzer.\n */\n get isArangoAnalyzer(): true {\n return true;\n }\n\n /**\n * Name of this Analyzer.\n *\n * See also {@link database.Database}.\n */\n get name() {\n return this._name;\n }\n\n /**\n * Checks whether the Analyzer exists.\n *\n * @example\n * ```js\n * const db = new Database();\n * const analyzer = db.analyzer(\"some-analyzer\");\n * const result = await analyzer.exists();\n * // result indicates whether the Analyzer exists\n * ```\n */\n async exists(): Promise<boolean> {\n try {\n await this.get();\n return true;\n } catch (err: any) {\n if (isArangoError(err) && err.errorNum === ANALYZER_NOT_FOUND) {\n return false;\n }\n throw err;\n }\n }\n\n /**\n * Retrieves the Analyzer definition for the Analyzer.\n *\n * @example\n * ```js\n * const db = new Database();\n * const analyzer = db.analyzer(\"some-analyzer\");\n * const definition = await analyzer.get();\n * // definition contains the Analyzer definition\n * ```\n */\n get(): Promise<ArangoApiResponse<AnalyzerDescription>> {\n return this._db.request({\n path: `/_api/analyzer/${encodeURIComponent(this._name)}`,\n });\n }\n\n /**\n * Creates a new Analyzer with the given `options` and the instance's name.\n *\n * See also {@link database.Database#createAnalyzer}.\n *\n * @param options - Options for creating the Analyzer.\n *\n * @example\n * ```js\n * const db = new Database();\n * const analyzer = db.analyzer(\"potatoes\");\n * await analyzer.create({ type: \"identity\" });\n * // the identity Analyzer \"potatoes\" now exists\n * ```\n */\n create<Options extends CreateAnalyzerOptions>(\n options: Options\n ): Promise<\n Options extends CreateIdentityAnalyzerOptions\n ? IdentityAnalyzerDescription\n : Options extends CreateDelimiterAnalyzerOptions\n ? DelimiterAnalyzerDescription\n : Options extends CreateStemAnalyzerOptions\n ? StemAnalyzerDescription\n : Options extends CreateNormAnalyzerOptions\n ? NormAnalyzerDescription\n : Options extends CreateNgramAnalyzerOptions\n ? NgramAnalyzerDescription\n : Options extends CreateTextAnalyzerOptions\n ? TextAnalyzerDescription\n : Options extends CreateSegmentationAnalyzerOptions\n ? SegmentationAnalyzerDescription\n : Options extends CreateAqlAnalyzerOptions\n ? AqlAnalyzerDescription\n : Options extends CreatePipelineAnalyzerOptions\n ? PipelineAnalyzerDescription\n : Options extends CreateStopwordsAnalyzerOptions\n ? StopwordsAnalyzerDescription\n : Options extends CreateCollationAnalyzerOptions\n ? CollationAnalyzerDescription\n : Options extends CreateMinHashAnalyzerOptions\n ? MinHashAnalyzerDescription\n : Options extends CreateClassificationAnalyzerOptions\n ? ClassificationAnalyzerDescription\n : Options extends CreateNearestNeighborsAnalyzerOptions\n ? NearestNeighborsAnalyzerDescription\n : Options extends CreateGeoJsonAnalyzerOptions\n ? GeoJsonAnalyzerDescription\n : Options extends CreateGeoPointAnalyzerOptions\n ? GeoPointAnalyzerDescription\n : AnalyzerDescription\n > {\n return this._db.request({\n method: \"POST\",\n path: \"/_api/analyzer\",\n body: { name: this._name, ...options },\n });\n }\n\n /**\n * Deletes the Analyzer from the database.\n *\n * @param force - Whether the Analyzer should still be deleted even if it\n * is currently in use.\n *\n * @example\n * ```js\n * const db = new Database();\n * const analyzer = db.analyzer(\"some-analyzer\");\n * await analyzer.drop();\n * // the Analyzer \"some-analyzer\" no longer exists\n * ```\n */\n drop(force: boolean = false): Promise<ArangoApiResponse<{ name: string }>> {\n return this._db.request({\n method: \"DELETE\",\n path: `/_api/analyzer/${encodeURIComponent(this._name)}`,\n qs: { force },\n });\n }\n}\n","/**\n * ```js\n * import { aql } from \"arangojs/aql\";\n * ```\n *\n * The \"aql\" module provides the {@link aql} template string handler and\n * helper functions, as well as associated types and interfaces for TypeScript.\n *\n * The aql function and namespace is also re-exported by the \"index\" module.\n *\n * @packageDocumentation\n */\nimport { isArangoAnalyzer } from \"./analyzer\";\nimport { ArangoCollection, isArangoCollection } from \"./collection\";\nimport { Graph, isArangoGraph } from \"./graph\";\nimport { isArangoView, View } from \"./view\";\n\n/**\n * Generic AQL query object consisting of an AQL query string and its bind\n * parameters.\n */\nexport interface AqlQuery {\n /**\n * An AQL query string.\n */\n query: string;\n /**\n * An object mapping AQL bind parameter names to their respective values.\n *\n * Names of parameters representing collections are prefixed with an\n * at-symbol.\n */\n bindVars: Record<string, any>;\n}\n\n/**\n * Derived type representing AQL query objects generated by the AQL helper\n * functions and the AQL template string handler. These objects can be fed\n * back into these helper functions to be inlined or merged in complex queries.\n *\n * @internal\n */\nexport interface GeneratedAqlQuery extends AqlQuery {\n /**\n * @internal\n */\n _source: () => { strings: string[]; args: AqlValue[] };\n}\n\n/**\n * An object representing a trusted AQL literal that will be inlined directly\n * when used in an AQL template or passed to AQL helper functions.\n *\n * Arbitrary values can be converted to trusted AQL literals by passing them\n * to the {@link literal} helper function.\n */\nexport interface AqlLiteral {\n /**\n * @internal\n *\n * Returns a string representation of this AQL literal that can be inlined\n * in an AQL template.\n */\n toAQL: () => string;\n}\n\n/**\n * A value that can be used in an AQL template string or passed to an AQL\n * helper function.\n */\nexport type AqlValue =\n | ArangoCollection\n | View\n | Graph\n | GeneratedAqlQuery\n | AqlLiteral\n | string\n | number\n | boolean\n | null\n | undefined\n | Record<string, any>\n | any[];\n\n/**\n * Indicates whether the given value is an {@link AqlQuery}.\n *\n * @param query - A value that might be an `AqlQuery`.\n */\nexport function isAqlQuery(query: any): query is AqlQuery {\n return Boolean(query && typeof query.query === \"string\" && query.bindVars);\n}\n\n/**\n * Indicates whether the given value is a {@link GeneratedAqlQuery}.\n *\n * @param query - A value that might be a `GeneratedAqlQuery`.\n *\n * @internal\n */\nexport function isGeneratedAqlQuery(query: any): query is GeneratedAqlQuery {\n return isAqlQuery(query) && typeof (query as any)._source === \"function\";\n}\n\n/**\n * Indicates whether the given value is an {@link AqlLiteral}.\n *\n * @param literal - A value that might be an `AqlLiteral`.\n */\nexport function isAqlLiteral(literal: any): literal is AqlLiteral {\n return Boolean(literal && typeof literal.toAQL === \"function\");\n}\n\n/**\n * Template string handler (template tag) for AQL queries.\n *\n * The `aql` tag can be used to write complex AQL queries as multi-line strings\n * without having to worry about `bindVars` and the distinction between\n * collections and regular parameters.\n *\n * Tagged template strings will return an {@link AqlQuery} object with\n * `query` and `bindVars` attributes reflecting any interpolated values.\n *\n * Any {@link collection.ArangoCollection} instance used in a query string will\n * be recognized as a collection reference and generate an AQL collection bind\n * parameter instead of a regular AQL value bind parameter.\n *\n * **Note**: you should always use the `aql` template tag when writing\n * dynamic AQL queries instead of using untagged (normal) template strings.\n * Untagged template strings will inline any interpolated values and return\n * a plain string as result. The `aql` template tag will only inline references\n * to the interpolated values and produce an AQL query object containing both\n * the query and the values. This prevents most injection attacks when using\n * untrusted values in dynamic queries.\n *\n * @example\n * ```js\n * // Some user-supplied string that may be malicious\n * const untrustedValue = req.body.email;\n *\n * // Without aql tag: BAD! DO NOT DO THIS!\n * const badQuery = `\n * FOR user IN users\n * FILTER user.email == \"${untrustedValue}\"\n * RETURN user\n * `;\n * // e.g. if untrustedValue is '\" || user.admin == true || \"':\n * // Query:\n * // FOR user IN users\n * // FILTER user.email == \"\" || user.admin == true || \"\"\n * // RETURN user\n *\n * // With the aql tag: GOOD! MUCH SAFER!\n * const betterQuery = aql`\n * FOR user IN users\n * FILTER user.email == ${untrustedValue}\n * RETURN user\n * `;\n * // Query:\n * // FOR user IN users\n * // FILTER user.email == @value0\n * // RETURN user\n * // Bind parameters:\n * // value0 -> untrustedValue\n * ```\n *\n * @example\n * ```js\n * const collection = db.collection(\"some-collection\");\n * const minValue = 23;\n * const result = await db.query(aql`\n * FOR d IN ${collection}\n * FILTER d.num > ${minValue}\n * RETURN d\n * `);\n *\n * // Equivalent raw query object\n * const result2 = await db.query({\n * query: `\n * FOR d IN @@collection\n * FILTER d.num > @minValue\n * RETURN d\n * `,\n * bindVars: {\n * \"@collection\": collection.name,\n * minValue: minValue\n * }\n * });\n * ```\n *\n * @example\n * ```js\n * const collection = db.collection(\"some-collection\");\n * const color = \"green\";\n * const filter = aql`FILTER d.color == ${color}'`;\n * const result = await db.query(aql`\n * FOR d IN ${collection}\n * ${filter}\n * RETURN d\n * `);\n * ```\n */\nexport function aql(\n templateStrings: TemplateStringsArray,\n ...args: AqlValue[]\n): GeneratedAqlQuery {\n const strings = [...templateStrings];\n const bindVars: Record<string, any> = {};\n const bindValues = [];\n let query = strings[0];\n for (let i = 0; i < args.length; i++) {\n const rawValue = args[i];\n let value = rawValue;\n if (isGeneratedAqlQuery(rawValue)) {\n const src = rawValue._source();\n if (src.args.length) {\n query += src.strings[0];\n args.splice(i, 1, ...src.args);\n strings.splice(\n i,\n 2,\n strings[i] + src.strings[0],\n ...src.strings.slice(1, src.args.length),\n src.strings[src.args.length] + strings[i + 1]\n );\n } else {\n query += rawValue.query + strings[i + 1];\n args.splice(i, 1);\n strings.splice(i, 2, strings[i] + rawValue.query + strings[i + 1]);\n }\n i -= 1;\n continue;\n }\n if (rawValue === undefined) {\n query += strings[i + 1];\n continue;\n }\n if (isAqlLiteral(rawValue)) {\n query += `${rawValue.toAQL()}${strings[i + 1]}`;\n continue;\n }\n const index = bindValues.indexOf(rawValue);\n const isKnown = index !== -1;\n let name = `value${isKnown ? index : bindValues.length}`;\n if (\n isArangoCollection(rawValue) ||\n isArangoGraph(rawValue) ||\n isArangoView(rawValue) ||\n isArangoAnalyzer(rawValue)\n ) {\n name = `@${name}`;\n value = rawValue.name;\n }\n if (!isKnown) {\n bindValues.push(rawValue);\n bindVars[name] = value;\n }\n query += `@${name}${strings[i + 1]}`;\n }\n return {\n query,\n bindVars,\n _source: () => ({ strings, args }),\n };\n}\n\n/**\n * Marks an arbitrary scalar value (i.e. a string, number or boolean) as\n * safe for being inlined directly into AQL queries when used in an `aql`\n * template string, rather than being converted into a bind parameter.\n *\n * **Note**: Nesting `aql` template strings is a much safer alternative for\n * most use cases. This low-level helper function only exists to help with\n * rare edge cases where a trusted AQL query fragment must be read from a\n * string (e.g. when reading query fragments from JSON) and should only be\n * used as a last resort.\n *\n * @example\n * ```js\n * // BAD! DO NOT DO THIS!\n * const sortDirection = literal('ASC');\n *\n * // GOOD! DO THIS INSTEAD!\n * const sortDirection = aql`ASC`;\n * ```\n *\n * @example\n * ```js\n * // BAD! DO NOT DO THIS!\n * const filterColor = literal('FILTER d.color == \"green\"');\n * const result = await db.query(aql`\n * FOR d IN some-collection\n * ${filterColor}\n * RETURN d\n * `);\n *\n * // GOOD! DO THIS INSTEAD!\n * const color = \"green\";\n * const filterColor = aql`FILTER d.color === ${color}`;\n * const result = await db.query(aql`\n * FOR d IN some-collection\n * ${filterColor}\n * RETURN d\n * `);\n * ```\n *\n * @example\n * ```js\n * // WARNING: We explicitly trust the environment variable to be safe!\n * const filter = literal(process.env.FILTER_STATEMENT);\n * const users = await db.query(aql`\n * FOR user IN users\n * ${filter}\n * RETURN user\n * `);\n * ```\n */\nexport function literal(\n value: string | number | boolean | AqlLiteral | null | undefined\n): AqlLiteral {\n if (isAqlLiteral(value)) {\n return value;\n }\n return {\n toAQL() {\n if (value === undefined) {\n return \"\";\n }\n return String(value);\n },\n };\n}\n\n/**\n * Constructs {@link AqlQuery} objects from an array of arbitrary values.\n *\n * **Note**: Nesting `aql` template strings is a much safer alternative\n * for most use cases. This low-level helper function only exists to\n * complement the `aql` tag when constructing complex queries from dynamic\n * arrays of query fragments.\n *\n * @param values - Array of values to join. These values will behave exactly\n * like values interpolated in an `aql` template string.\n * @param sep - Seperator to insert between values. This value will behave\n * exactly like a value passed to {@link literal}, i.e. it will be\n * inlined as-is, rather than being converted into a bind parameter.\n *\n * @example\n * ```js\n * const users = db.collection(\"users\");\n * const filters = [];\n * if (adminsOnly) filters.push(aql`FILTER user.admin`);\n * if (activeOnly) filters.push(aql`FILTER user.active`);\n * const result = await db.query(aql`\n * FOR user IN ${users}\n * ${join(filters)}\n * RETURN user\n * `);\n * ```\n *\n * @example\n * ```js\n * const users = db.collection(\"users\");\n * const keys = [\"jreyes\", \"ghermann\"];\n *\n * // BAD! NEEDLESSLY COMPLEX!\n * const docs = keys.map(key => aql`DOCUMENT(${users}, ${key}`));\n * const result = await db.query(aql`\n * FOR user IN [\n * ${join(docs, \", \")}\n * ]\n * RETURN user\n * `);\n * // Query:\n * // FOR user IN [\n * // DOCUMENT(@@value0, @value1), DOCUMENT(@@value0, @value2)\n * // ]\n * // RETURN user\n * // Bind parameters:\n * // @value0 -> \"users\"\n * // value1 -> \"jreyes\"\n * // value2 -> \"ghermann\"\n *\n * // GOOD! MUCH SIMPLER!\n * const result = await db.query(aql`\n * FOR key IN ${keys}\n * LET user = DOCUMENT(${users}, key)\n * RETURN user\n * `);\n * // Query:\n * // FOR user IN @value0\n * // LET user = DOCUMENT(@@value1, key)\n * // RETURN user\n * // Bind parameters:\n * // value0 -> [\"jreyes\", \"ghermann\"]\n * // @value1 -> \"users\"\n * ```\n */\nexport function join(values: AqlValue[], sep: string = \" \"): GeneratedAqlQuery {\n if (!values.length) {\n return aql``;\n }\n if (values.length === 1) {\n return aql`${values[0]}`;\n }\n return aql([\"\", ...Array(values.length - 1).fill(sep), \"\"] as any, ...values);\n}\n","/**\n * ```ts\n * import type {\n * FulltextIndex,\n * GeoIndex,\n * PersistentIndex,\n * PrimaryIndex,\n * TtlIndex,\n * ZkdIndex,\n * } from \"arangojs/indexes\";\n * ```\n *\n * The \"indexes\" module provides index-related types for TypeScript.\n *\n * @packageDocumentation\n */\n\nimport { AnalyzerFeature } from \"./analyzer\";\nimport { Compression, Direction, TierConsolidationPolicy } from \"./view\";\n\n/**\n * Options for creating a persistent index.\n */\nexport type EnsurePersistentIndexOptions = {\n /**\n * Type of this index.\n */\n type: \"persistent\";\n /**\n * An array of attribute paths.\n */\n fields: string[];\n /**\n * A unique name for this index.\n */\n name?: string;\n /**\n * If set to `true`, a unique index will be created.\n *\n * Default: `false`\n */\n unique?: boolean;\n /**\n * If set to `true`, the index will omit documents that do not contain at\n * least one of the attribute paths in `fields` and these documents will be\n * ignored for uniqueness checks.\n *\n * Default: `false`\n */\n sparse?: boolean;\n /**\n * If set to `false`, inserting duplicate index values from the same\n * document will lead to a unique constraint error if this is a unique index.\n *\n * Default: `true`\n */\n deduplicate?: boolean;\n /**\n * If set to `false`, index selectivity estimates will be disabled for this\n * index.\n *\n * Default: `true`\n */\n estimates?: boolean;\n /**\n * If set to `true`, the index will be created in the background to reduce\n * the write-lock duration for the collection during index creation.\n *\n * Default: `false`\n */\n inBackground?: boolean;\n /**\n * If set to `true`, an in-memory hash cache will be put in front of the\n * persistent index.\n *\n * Default: `false`\n */\n cacheEnabled?: boolean;\n /**\n * An array of attribute paths that will be stored in the index but can not\n * be used for index lookups or sorting but can avoid full document lookups.\n */\n storedValues?: string[];\n};\n\n/**\n * Options for creating a geo index.\n */\nexport type EnsureGeoIndexOptions =\n | {\n type: \"geo\";\n /**\n * If set to `true`, `fields` must be an array containing a single attribute\n * path and the attribute value must be an array with two values, the first\n * of which will be interpreted as the longitude and the second of which will\n * be interpreted as the latitude of the document.\n *\n * Default: `false`\n */\n geoJson?: false;\n /**\n * If set to `true`, the index will use pre-3.10 rules for parsing\n * GeoJSON polygons. This option is always implicitly `true` when using\n * ArangoDB 3.9 or lower.\n */\n legacyPolygons?: boolean;\n /**\n * Attribute paths for the document's latitude and longitude values.\n */\n fields: [string, string];\n /**\n * A unique name for this index.\n */\n name?: string;\n /**\n * If set to `true`, the index will be created in the background to reduce\n * the write-lock duration for the collection during index creation.\n *\n * Default: `false`\n */\n inBackground?: boolean;\n }\n | {\n type: \"geo\";\n /**\n * If set to `true`, `fields` must be an array containing a single attribute\n * path and the attribute value must be an array with two values, the first\n * of which will be interpreted as the longitude and the second of which will\n * be interpreted as the latitude of the document.\n *\n * Default: `false`\n */\n geoJson?: boolean;\n /**\n * If set to `true`, the index will use pre-3.10 rules for parsing\n * GeoJSON polygons. This option is always implicitly `true` when using\n * ArangoDB 3.9 or lower.\n */\n legacyPolygons?: boolean;\n /**\n * An array containing the attribute path for an array containing two values,\n * the first of which will be interpreted as the latitude, the second as the\n * longitude. If `geoJson` is set to `true`, the order is reversed to match\n * the GeoJSON format.\n */\n fields: [string];\n /**\n * A unique name for this index.\n */\n name?: string;\n /**\n * If set to `true`, the index will be created in the background to reduce\n * the write-lock duration for the collection during index creation.\n *\n * Default: `false`\n */\n inBackground?: boolean;\n };\n\n/**\n * Options for creating a fulltext index.\n *\n * @deprecated Fulltext indexes have been deprecated in ArangoDB 3.10 and\n * should be replaced with ArangoSearch.\n */\nexport type EnsureFulltextIndexOptions = {\n /**\n * Type of this index.\n */\n type: \"fulltext\";\n /**\n * An array containing exactly one attribute path.\n */\n fields: [string];\n /**\n * A unique name for this index.\n */\n name?: string;\n /**\n * Minimum character length of words to index.\n */\n minLength?: number;\n /**\n * If set to `true`, the index will be created in the background to reduce\n * the write-lock duration for the collection during index creation.\n *\n * Default: `false`\n */\n inBackground?: boolean;\n};\n\n/**\n * Options for creating a TTL index.\n */\nexport type EnsureTtlIndexOptions = {\n /**\n * Type of this index.\n */\n type: \"ttl\";\n /**\n * An array containing exactly one attribute path.\n */\n fields: [string];\n /**\n * A unique name for this index.\n */\n name?: string;\n /**\n * Duration in seconds after the attribute value at which the document will\n * be considered as expired.\n */\n expireAfter: number;\n /**\n * If set to `true`, the index will be created in the background to reduce\n * the write-lock duration for the collection during index creation.\n *\n * Default: `false`\n */\n inBackground?: boolean;\n};\n\n/**\n * Options for creating a ZKD index.\n */\nexport type EnsureZkdIndexOptions = {\n /**\n * Type of this index.\n */\n type: \"zkd\";\n /**\n * An array containing attribute paths for the dimensions.\n */\n fields: string[];\n /**\n * Data type of the dimension attributes.\n */\n fieldValueTypes: \"double\";\n /**\n * A unique name for this index.\n */\n name?: string;\n /**\n * If set to `true`, a unique index will be created.\n *\n * Default: `false`\n */\n unique?: boolean;\n /**\n * If set to `true`, the index will be created in the background to reduce\n * the write-lock duration for the collection during index creation.\n *\n * Default: `false`\n */\n inBackground?: boolean;\n};\n\n/**\n * (Enterprise Edition only.) Options for a nested field in an inverted index.\n */\nexport type InvertedIndexNestedFieldOptions = {\n /**\n * An attribute path.\n */\n name: string;\n /**\n * Name of the Analyzer to apply to the values of this field.\n *\n * Defaults to the `analyzer` specified on the parent options or on the index\n * itself.\n */\n analyzer?: string;\n /**\n * List of Analyzer features to enable for this field's Analyzer.\n *\n * Defaults to the features of the Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * If set to `true` array values will be indexed using the same behavior as\n * ArangoSearch Views. This option only applies when using the index in a\n * SearchAlias View.\n *\n * Defaults to the value of `searchField` specified on the index itself.\n */\n searchField?: boolean;\n /**\n * Sub-objects to index to allow querying for co-occurring values.\n */\n nested?: (string | InvertedIndexNestedFieldOptions)[];\n};\n\n/**\n * Options for an attribute path in an inverted index.\n */\nexport type InvertedIndexFieldOptions = {\n /**\n * An attribute path.\n */\n name: string;\n /**\n * Name of the Analyzer to apply to the values of this field.\n *\n * Defaults to the `analyzer` specified on the index itself.\n */\n analyzer?: string;\n /**\n * List of Analyzer features to enable for this field's Analyzer.\n *\n * Defaults to the features of the Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * If set to `true`, all document attributes are indexed, excluding any\n * sub-attributes configured in the `fields` array. The `analyzer` and\n * `features` properties apply to the sub-attributes. This option only\n * applies when using the index in a SearchAlias View.\n *\n * Defaults to the value of `includeAllFields` specified on the index itself.\n */\n includeAllFields?: boolean;\n /**\n * If set to `true` array values will be indexed using the same behavior as\n * ArangoSearch Views. This option only applies when using the index in a\n * SearchAlias View.\n *\n * Defaults to the value of `searchField` specified on the index itself.\n */\n searchField?: boolean;\n /**\n * If set to `true`, the position of values in array values are tracked and\n * need to be specified in queries. Otherwise all values in an array are\n * treated as equivalent. This option only applies when using the index in a\n * SearchAlias View.\n *\n * Defaults to the value of `trackListPositions` specified on the index\n * itself.\n */\n trackListPositions?: boolean;\n /**\n * (Enterprise Edition only.) Sub-objects to index to allow querying for\n * co-occurring values.\n */\n nested?: (string | InvertedIndexNestedFieldOptions)[];\n};\n\n/**\n * Options for defining a stored value on an inverted index.\n */\nexport type InvertedIndexStoredValueOptions = {\n /**\n * The attribute paths to store.\n */\n fields: string[];\n /**\n * How the attribute values should be compressed.\n *\n * Default: `\"lz4\"`\n */\n compression?: Compression;\n};\n\n/**\n * Options for defining a primary sort field on an inverted index.\n */\nexport type InvertedIndexPrimarySortFieldOptions = {\n /**\n * The attribute path to sort by.\n */\n field: string;\n /**\n * The sorting direction.\n */\n direction: Direction;\n};\n\n/**\n * Options for creating an inverted index.\n */\nexport type EnsureInvertedIndexOptions = {\n /**\n * Type of this index.\n */\n type: \"inverted\";\n /**\n * An array of attribute paths or objects specifying options for the fields.\n */\n fields: (string | InvertedIndexFieldOptions)[];\n /**\n * A unique name for this index.\n */\n name?: string;\n /**\n * If set to `true` array values will by default be indexed using the same\n * behavior as ArangoSearch Views. This option only applies when using the\n * index in a SearchAlias View.\n *\n * Default: `false`\n */\n searchField?: boolean;\n /**\n * An array of attribute paths that will be stored in the index but can not\n * be used for index lookups or sorting but can avoid full document lookups.\n */\n storedValues?: InvertedIndexStoredValueOptions[];\n /**\n * Primary sort order to optimize AQL queries using a matching sort order.\n */\n primarySort?: {\n /**\n * An array of fields to sort the index by.\n */\n fields: InvertedIndexPrimarySortFieldOptions[];\n /**\n * How the primary sort data should be compressed.\n *\n * Default: `\"lz4\"`\n */\n compression?: Compression;\n };\n /**\n * Name of the default Analyzer to apply to the values of indexed fields.\n *\n * Default: `\"identity\"`\n */\n analyzer?: string;\n /**\n * List of Analyzer features to enable for the default Analyzer.\n *\n * Defaults to the Analyzer's features.\n */\n features?: AnalyzerFeature[];\n /**\n * If set to `true`, all document attributes are indexed, excluding any\n * sub-attributes configured in the `fields` array. The `analyzer` and\n * `features` properties apply to the sub-attributes. This option only\n * applies when using the index in a SearchAlias View.\n *\n * Default: `false`\n */\n includeAllFields?: boolean;\n /**\n * If set to `true`, the position of values in array values are tracked and\n * need to be specified in queries. Otherwise all values in an array are\n * treated as equivalent. This option only applies when using the index in a\n * SearchAlias View.\n *\n * Default: `false`\n */\n trackListPositions?: boolean;\n /**\n * The number of threads to use for indexing the fields.\n *\n * Default: `2`\n */\n parallelism?: number;\n /**\n * Wait at least this many commits between removing unused files in the\n * ArangoSearch data directory.\n *\n * Default: `2`\n */\n cleanupIntervalStep?: number;\n /**\n * Wait at least this many milliseconds between committing View data store\n * changes and making documents visible to queries.\n *\n * Default: `1000`\n */\n commitIntervalMsec?: number;\n /**\n * Wait at least this many milliseconds between applying\n * `consolidationPolicy` to consolidate View data store and possibly release\n * space on the filesystem.\n *\n * Default: `1000`\n */\n consolidationIntervalMsec?: number;\n /**\n * The consolidation policy to apply for selecting which segments should be\n * merged.\n *\n * Default: `{ type: \"tier\" }`\n */\n consolidationPolicy?: TierConsolidationPolicy;\n /**\n * Maximum number of writers (segments) cached in the pool.\n *\n * Default: `64`\n */\n writeBufferIdle?: number;\n /**\n * Maximum number of concurrent active writers (segments) that perform a\n * transaction.\n *\n * Default: `0` (disabled)\n */\n writeBufferActive?: number;\n /**\n * Maximum memory byte size per writer (segment) before a writer (segment)\n * flush is triggered.\n *\n * Default: `33554432` (32 MiB)\n */\n writeBufferSizeMax?: number;\n /**\n * If set to `true`, the index will be created in the background to reduce\n * the write-lock duration for the collection during index creation.\n *\n * Default: `false`\n */\n inBackground?: boolean;\n};\n\n/**\n * Shared attributes of all index types.\n */\nexport type GenericIndex = {\n /**\n * A unique name for this index.\n */\n name: string;\n /**\n * A unique identifier for this index.\n */\n id: string;\n /**\n * Whether documents not containing at least one of the attribute paths\n * are omitted by this index.\n */\n sparse: boolean;\n /**\n * Whether this index enforces uniqueness for values of its attribute paths.\n */\n unique: boolean;\n};\n\n/**\n * An object representing a persistent index.\n */\nexport type PersistentIndex = GenericIndex & {\n type: \"persistent\";\n fields: string[];\n cacheEnabled: boolean;\n deduplicate: boolean;\n estimates: boolean;\n storedValues?: string[];\n};\n\n/**\n * An object representing a primary index.\n */\nexport type PrimaryIndex = GenericIndex & {\n type: \"primary\";\n fields: string[];\n selectivityEstimate: number;\n};\n\n/**\n * An object representing a fulltext index.\n *\n * @deprecated Fulltext indexes have been deprecated in ArangoDB 3.10 and\n * should be replaced with ArangoSearch.\n */\nexport type FulltextIndex = GenericIndex & {\n type: \"fulltext\";\n fields: [string];\n minLength: number;\n};\n\n/**\n * An object representing a geo index.\n */\nexport type GeoIndex = GenericIndex & {\n type: \"geo\";\n fields: [string] | [string, string];\n geoJson: boolean;\n legacyPolygons: boolean;\n bestIndexedLevel: number;\n worstIndexedLevel: number;\n maxNumCoverCells: number;\n};\n\n/**\n * An object representing a TTL index.\n */\nexport type TtlIndex = GenericIndex & {\n type: \"ttl\";\n fields: [string];\n expireAfter: number;\n selectivityEstimate: number;\n};\n\n/**\n * An object representing a ZKD index.\n */\nexport type ZkdIndex = GenericIndex & {\n type: \"zkd\";\n fields: string[];\n fieldValueTypes: \"double\";\n};\n\n/**\n * (Enterprise Edition only.) An object representing a nested field in an\n * inverted index.\n */\nexport type InvertedIndexNestedField = {\n name: string;\n analyzer?: string;\n features?: AnalyzerFeature[];\n searchField?: boolean;\n nested?: InvertedIndexNestedField[];\n};\n\n/**\n * An object representing an inverted index.\n */\nexport type InvertedIndex = GenericIndex & {\n type: \"inverted\";\n fields: {\n name: string;\n analyzer?: string;\n features?: AnalyzerFeature[];\n includeAllFields?: boolean;\n searchField?: boolean;\n trackListPositions?: boolean;\n nested?: InvertedIndexNestedField[];\n }[];\n searchField: boolean;\n storedValues: {\n fields: string[];\n compression: Compression;\n }[];\n primarySort: {\n fields: {\n field: string;\n direction: Direction;\n }[];\n compression: Compression;\n };\n analyzer: string;\n features: AnalyzerFeature[];\n includeAllFields: boolean;\n trackListPositions: boolean;\n parallelism: number;\n cleanupIntervalStep: number;\n commitIntervalMsec: number;\n consolidationIntervalMsec: number;\n consolidationPolicy: Required<TierConsolidationPolicy>;\n writeBufferIdle: number;\n writeBufferActive: number;\n writeBufferSizeMax: number;\n};\n\n/**\n * An object representing an index.\n */\nexport type Index =\n | GeoIndex\n | FulltextIndex\n | PersistentIndex\n | PrimaryIndex\n | TtlIndex\n | ZkdIndex\n | InvertedIndex;\n\nexport type ObjectWithId = {\n [key: string]: any;\n id: string;\n};\n\nexport type ObjectWithName = {\n [key: string]: any;\n name: string;\n};\n\n/**\n * Index name, id or object with a `name` or `id` property.\n */\nexport type IndexSelector = ObjectWithId | ObjectWithName | string;\n\n/**\n * @internal\n */\nexport function _indexHandle(\n selector: IndexSelector,\n collectionName: string\n): string {\n if (typeof selector !== \"string\") {\n if (selector.id) {\n return _indexHandle(selector.id, collectionName);\n }\n throw new Error(\n \"Index handle must be a string or an object with an id attribute\"\n );\n }\n if (selector.includes(\"/\")) {\n const [head, ...tail] = selector.split(\"/\");\n const normalizedHead = head.normalize(\"NFC\");\n if (normalizedHead !== collectionName) {\n throw new Error(\n `Index ID \"${selector}\" does not match collection name \"${collectionName}\"`\n );\n }\n return [normalizedHead, ...tail].join(\"/\");\n }\n return `${collectionName}/${selector}`;\n}\n","/**\n * ```ts\n * import type {\n * DocumentCollection,\n * EdgeCollection,\n * } from \"arangojs/collection\";\n * ```\n *\n * The \"collection\" module provides collection related types and interfaces\n * for TypeScript.\n *\n * @packageDocumentation\n */\nimport { AqlLiteral, AqlQuery, isAqlLiteral, isAqlQuery } from \"./aql\";\nimport { ArangoApiResponse, Params } from \"./connection\";\nimport { ArrayCursor, BatchedArrayCursor } from \"./cursor\";\nimport { Database } from \"./database\";\nimport {\n Document,\n DocumentData,\n DocumentMetadata,\n DocumentSelector,\n Edge,\n EdgeData,\n ObjectWithKey,\n Patch,\n _documentHandle,\n} from \"./documents\";\nimport { HttpError, isArangoError } from \"./error\";\nimport {\n EnsureFulltextIndexOptions,\n EnsureGeoIndexOptions,\n EnsureInvertedIndexOptions,\n EnsurePersistentIndexOptions,\n EnsureTtlIndexOptions,\n EnsureZkdIndexOptions,\n FulltextIndex,\n GeoIndex,\n Index,\n IndexSelector,\n InvertedIndex,\n PersistentIndex,\n TtlIndex,\n ZkdIndex,\n _indexHandle,\n} from \"./indexes\";\nimport { Blob } from \"./lib/blob\";\nimport { COLLECTION_NOT_FOUND, DOCUMENT_NOT_FOUND } from \"./lib/codes\";\n\n/**\n * Indicates whether the given value represents an {@link ArangoCollection}.\n *\n * @param collection - A value that might be a collection.\n */\nexport function isArangoCollection(\n collection: any\n): collection is ArangoCollection {\n return Boolean(collection && collection.isArangoCollection);\n}\n\n/**\n * Coerces the given collection name or {@link ArangoCollection} object to\n * a string representing the collection name.\n *\n * @param collection - Collection name or {@link ArangoCollection} object.\n */\nexport function collectionToString(\n collection: string | ArangoCollection\n): string {\n if (isArangoCollection(collection)) {\n return String(collection.name);\n } else return String(collection).normalize(\"NFC\");\n}\n\n/**\n * A marker interface identifying objects that can be used in AQL template\n * strings to create references to ArangoDB collections.\n *\n * See {@link aql!aql}.\n */\nexport interface ArangoCollection {\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB collection.\n */\n readonly isArangoCollection: true;\n /**\n * Name of the collection.\n */\n readonly name: string;\n}\n\n/**\n * Integer values indicating the collection type.\n */\nexport enum CollectionType {\n DOCUMENT_COLLECTION = 2,\n EDGE_COLLECTION = 3,\n}\n\n/**\n * Integer values indicating the collection loading status.\n */\nexport enum CollectionStatus {\n NEWBORN = 1,\n UNLOADED = 2,\n LOADED = 3,\n UNLOADING = 4,\n DELETED = 5,\n LOADING = 6,\n}\n\n/**\n * Type of key generator.\n */\nexport type KeyGenerator = \"traditional\" | \"autoincrement\" | \"uuid\" | \"padded\";\n\n/**\n * Strategy for sharding a collection.\n */\nexport type ShardingStrategy =\n | \"hash\"\n | \"enterprise-hash-smart-edge\"\n | \"enterprise-hash-smart-vertex\"\n | \"community-compat\"\n | \"enterprise-compat\"\n | \"enterprise-smart-edge-compat\";\n\n/**\n * Type of document reference.\n *\n * See {@link DocumentCollection#list} and {@link EdgeCollection#list}.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryListType = \"id\" | \"key\" | \"path\";\n\n/**\n * When a validation should be applied.\n *\n * * `\"none\"`: No validation.\n * * `\"new\"`: Newly inserted documents are validated.\n * * `\"moderate\"`: New and modified documents are validated unless the modified\n * document was already invalid.\n * * `\"strict\"`: New and modified documents are always validated.\n */\nexport type ValidationLevel = \"none\" | \"new\" | \"moderate\" | \"strict\";\n\n/**\n * Write operation that can result in a computed value being computed.\n */\nexport type WriteOperation = \"insert\" | \"update\" | \"replace\";\n\n/**\n * Properties defining a computed value.\n */\nexport type ComputedValueProperties = {\n /**\n * Name of the target attribute of the computed value.\n */\n name: string;\n /**\n * AQL `RETURN` expression that computes the value.\n */\n expression: string;\n /**\n * If set to `false`, the computed value will not be applied if the\n * expression evaluates to `null`.\n */\n overwrite: boolean;\n /**\n * Which operations should result in the value being computed.\n */\n computeOn: WriteOperation[];\n /**\n * If set to `false`, the field will be unset if the expression evaluates to\n * `null`. Otherwise the field will be set to the value `null`. Has no effect\n * if `overwrite` is set to `false`.\n */\n keepNull: boolean;\n /**\n * Whether the write operation should fail if the expression produces a\n * warning.\n */\n failOnWarning: boolean;\n};\n\n/**\n * General information about a collection.\n */\nexport type CollectionMetadata = {\n /**\n * Collection name.\n */\n name: string;\n /**\n * A globally unique identifier for this collection.\n */\n globallyUniqueId: string;\n /**\n * An integer indicating the collection loading status.\n */\n status: CollectionStatus;\n /**\n * An integer indicating the collection type.\n */\n type: CollectionType;\n /**\n * @internal\n *\n * Whether the collection is a system collection.\n */\n isSystem: boolean;\n};\n\n/**\n * An object defining the collection's key generation.\n */\nexport type CollectionKeyProperties = {\n /**\n * Type of key generator to use.\n */\n type: KeyGenerator;\n /**\n * Whether documents can be created with a user-specified `_key` attribute.\n */\n allowUserKeys: boolean;\n /**\n * (Autoincrement only.) How many steps to increment the key each time.\n */\n increment?: number;\n /**\n * (Autoincrement only.) Initial offset for the key.\n */\n offset?: number;\n /**\n * Most recent key that has been generated.\n */\n lastValue: number;\n};\n\n/**\n * Properties for validating documents in a collection.\n */\nexport type SchemaProperties = {\n /**\n * Type of document validation.\n */\n type: \"json\";\n /**\n * JSON Schema description of the validation schema for documents.\n */\n rule: any;\n /**\n * When validation should be applied.\n */\n level: ValidationLevel;\n /**\n * Message to be used if validation fails.\n */\n message: string;\n};\n\n/**\n * An object defining the properties of a collection.\n */\nexport type CollectionProperties = {\n /**\n * A human-readable representation of the collection loading status.\n */\n statusString: string;\n /**\n * Whether data should be synchronized to disk before returning from\n * a document create, update, replace or removal operation.\n */\n waitForSync: boolean;\n /**\n * An object defining the collection's key generation.\n */\n keyOptions: CollectionKeyProperties;\n /**\n * Properties for validating documents in the collection.\n */\n schema: SchemaProperties | null;\n /**\n * (Cluster only.) Write concern for this collection.\n */\n writeConcern: number;\n /**\n * (Cluster only.) Number of shards of this collection.\n */\n numberOfShards?: number;\n /**\n * (Cluster only.) Keys of this collection that will be used for\n * sharding.\n */\n shardKeys?: string[];\n /**\n * (Cluster only.) Replication factor of the collection.\n */\n replicationFactor?: number | \"satellite\";\n /**\n * (Cluster only.) Sharding strategy of the collection.\n */\n shardingStrategy?: ShardingStrategy;\n /**\n * (Enterprise Edition cluster only.) If set to a collection name, sharding\n * of the new collection will follow the rules for that collection. As long\n * as the new collection exists, the indicated collection can not be dropped.\n */\n distributeShardsLike?: string;\n /**\n * (Enterprise Edition cluster only.) Attribute containing the shard key\n * value of the referred-to smart join collection.\n */\n smartJoinAttribute?: string;\n /**\n * (Enterprise Edition cluster only.) Attribute used for sharding.\n */\n smartGraphAttribute?: string;\n /**\n * Computed values applied to documents in this collection.\n */\n computedValues: ComputedValueProperties[];\n /**\n * Whether the in-memory hash cache is enabled for this collection.\n */\n cacheEnabled: boolean;\n /**\n * Whether the newer revision-based replication protocol is enabled for\n * this collection.\n */\n syncByRevision: boolean;\n /**\n * (Enterprise Edition only.) Whether the collection is used in a SmartGraph or EnterpriseGraph.\n */\n isSmart?: boolean;\n /**\n * (Enterprise Edition only.) Whether the SmartGraph this collection belongs to is disjoint.\n */\n isDisjoint?: string;\n};\n\n// Options\n\n/**\n * Options for creating a computed value.\n */\nexport type ComputedValueOptions = {\n /**\n * Name of the target attribute of the computed value.\n */\n name: string;\n /**\n * AQL `RETURN` expression that computes the value.\n *\n * Note that when passing an AQL query object, the `bindVars` will be ignored.\n */\n expression: string | AqlLiteral | AqlQuery;\n /**\n * If set to `false`, the computed value will not be applied if the\n * expression evaluates to `null`.\n *\n * Default: `true`\n */\n overwrite?: boolean;\n /**\n * Which operations should result in the value being computed.\n *\n * Default: `[\"insert\", \"update\", \"replace\"]`\n */\n computeOn?: WriteOperation[];\n /**\n * If set to `false`, the field will be unset if the expression evaluates to\n * `null`. Otherwise the field will be set to the value `null`. Has no effect\n * if `overwrite` is set to `false`.\n *\n * Default: `true`\n */\n keepNull?: boolean;\n /**\n * Whether the write operation should fail if the expression produces a\n * warning.\n *\n * Default: `false`\n */\n failOnWarning?: boolean;\n};\n\n/**\n * Options for validating collection documents.\n */\nexport type SchemaOptions = {\n /**\n * JSON Schema description of the validation schema for documents.\n */\n rule: any;\n /**\n * When validation should be applied.\n *\n * Default: `\"strict\"`\n */\n level?: ValidationLevel;\n /**\n * Message to be used if validation fails.\n */\n message?: string;\n};\n\n/**\n * Options for setting a collection's properties.\n *\n * See {@link DocumentCollection#properties} and {@link EdgeCollection#properties}.\n */\nexport type CollectionPropertiesOptions = {\n /**\n * Whether data should be synchronized to disk before returning from\n * a document create, update, replace or removal operation.\n */\n waitForSync?: boolean;\n /**\n * (Cluster only.) How many copies of each document should be kept in the\n * cluster.\n *\n * Default: `1`\n */\n replicationFactor?: number | \"satellite\";\n /**\n * (Cluster only.) Write concern for this collection.\n */\n writeConcern?: number;\n /**\n * Options for validating documents in this collection.\n */\n schema?: SchemaOptions;\n /**\n * Computed values to apply to documents in this collection.\n */\n computedValues?: ComputedValueOptions[];\n /**\n * Whether the in-memory hash cache is enabled for this collection.\n *\n * Default: `false`\n */\n cacheEnabled?: boolean;\n};\n\n/**\n * Options for retrieving a collection checksum.\n */\nexport type CollectionChecksumOptions = {\n /**\n * If set to `true`, revision IDs will be included in the calculation\n * of the checksum.\n *\n * Default: `false`\n */\n withRevisions?: boolean;\n /**\n * If set to `true`, document data will be included in the calculation\n * of the checksum.\n *\n * Default: `false`\n */\n withData?: boolean;\n};\n\n/**\n * Options for dropping collections.\n */\nexport type CollectionDropOptions = {\n /**\n * Whether the collection is a system collection. If the collection is a\n * system collection, this option must be set to `true` or ArangoDB will\n * refuse to drop the collection.\n *\n * Default: `false`\n */\n isSystem?: boolean;\n};\n\n/**\n * An object defining the collection's key generation.\n */\nexport type CollectionKeyOptions = {\n /**\n * Type of key generator to use.\n */\n type?: KeyGenerator;\n /**\n * Unless set to `false`, documents can be created with a user-specified\n * `_key` attribute.\n *\n * Default: `true`\n */\n allowUserKeys?: boolean;\n /**\n * (Autoincrement only.) How many steps to increment the key each time.\n */\n increment?: number;\n /**\n * (Autoincrement only.) Initial offset for the key.\n */\n offset?: number;\n};\n\n/**\n * Options for creating a collection.\n *\n * See {@link database.Database#createCollection}, {@link database.Database#createEdgeCollection}\n * and {@link DocumentCollection#create} or {@link EdgeCollection#create}.\n */\nexport type CreateCollectionOptions = {\n /**\n * If set to `true`, data will be synchronized to disk before returning from\n * a document create, update, replace or removal operation.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * @internal\n *\n * Whether the collection should be created as a system collection.\n *\n * Default: `false`\n */\n isSystem?: boolean;\n /**\n * An object defining the collection's key generation.\n */\n keyOptions?: CollectionKeyOptions;\n /**\n * Options for validating documents in the collection.\n */\n schema?: SchemaOptions;\n /**\n * (Cluster only.) Unless set to `false`, the server will wait for all\n * replicas to create the collection before returning.\n *\n * Default: `true`\n */\n waitForSyncReplication?: boolean;\n /**\n * (Cluster only.) Unless set to `false`, the server will check whether\n * enough replicas are available at creation time and bail out otherwise.\n *\n * Default: `true`\n */\n enforceReplicationFactor?: boolean;\n /**\n * (Cluster only.) Number of shards to distribute the collection across.\n *\n * Default: `1`\n */\n numberOfShards?: number;\n /**\n * (Cluster only.) Document attributes to use to determine the target shard\n * for each document.\n *\n * Default: `[\"_key\"]`\n */\n shardKeys?: string[];\n /**\n * (Cluster only.) How many copies of each document should be kept in the\n * cluster.\n *\n * Default: `1`\n */\n replicationFactor?: number;\n /**\n * (Cluster only.) Write concern for this collection.\n */\n writeConcern?: number;\n /**\n * (Cluster only.) Sharding strategy to use.\n */\n shardingStrategy?: ShardingStrategy;\n /**\n * (Enterprise Edition cluster only.) If set to a collection name, sharding\n * of the new collection will follow the rules for that collection. As long\n * as the new collection exists, the indicated collection can not be dropped.\n */\n distributeShardsLike?: string;\n /**\n * (Enterprise Edition cluster only.) Attribute containing the shard key\n * value of the referred-to smart join collection.\n */\n smartJoinAttribute?: string;\n /**\n * (Enterprise Edition cluster only.) Attribute used for sharding.\n */\n smartGraphAttribute?: string;\n /**\n * Computed values to apply to documents in this collection.\n */\n computedValues?: ComputedValueOptions[];\n /**\n * Whether the in-memory hash cache is enabled for this collection.\n */\n cacheEnabled?: boolean;\n};\n\n/**\n * Options for checking whether a document exists in a collection.\n */\nexport type DocumentExistsOptions = {\n /**\n * If set to a document revision, the document will only match if its `_rev`\n * matches the given revision.\n */\n ifMatch?: string;\n /**\n * If set to a document revision, the document will only match if its `_rev`\n * does not match the given revision.\n */\n ifNoneMatch?: string;\n};\n\n/**\n * Options for retrieving a document from a collection.\n */\nexport type CollectionReadOptions = {\n /**\n * If set to `true`, `null` is returned instead of an exception being thrown\n * if the document does not exist.\n */\n graceful?: boolean;\n /**\n * If set to `true`, the request will explicitly permit ArangoDB to return a\n * potentially dirty or stale result and arangojs will load balance the\n * request without distinguishing between leaders and followers.\n */\n allowDirtyRead?: boolean;\n /**\n * If set to a document revision, the request will fail with an error if the\n * document exists but its `_rev` does not match the given revision.\n */\n ifMatch?: string;\n /**\n * If set to a document revision, the request will fail with an error if the\n * document exists and its `_rev` matches the given revision. Note that an\n * `HttpError` with code 304 will be thrown instead of an `ArangoError`.\n */\n ifNoneMatch?: string;\n};\n\n/**\n * Options for retrieving multiple documents from a collection.\n */\nexport type CollectionBatchReadOptions = {\n /**\n * If set to `true`, the request will explicitly permit ArangoDB to return a\n * potentially dirty or stale result and arangojs will load balance the\n * request without distinguishing between leaders and followers.\n */\n allowDirtyRead?: boolean;\n};\n\n/**\n * Options for inserting a new document into a collection.\n */\nexport type CollectionInsertOptions = {\n /**\n * If set to `true`, data will be synchronized to disk before returning.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * If set to `true`, no data will be returned by the server. This option can\n * be used to reduce network traffic.\n *\n * Default: `false`\n */\n silent?: boolean;\n /**\n * If set to `true`, the complete new document will be returned as the `new`\n * property on the result object. Has no effect if `silent` is set to `true`.\n *\n * Default: `false`\n */\n returnNew?: boolean;\n /**\n * Defines what should happen if a document with the same `_key` or `_id`\n * already exists, instead of throwing an exception.\n *\n * Default: `\"conflict\"\n */\n overwriteMode?: \"ignore\" | \"update\" | \"replace\" | \"conflict\";\n};\n\n/**\n * Options for replacing an existing document in a collection.\n */\nexport type CollectionReplaceOptions = {\n /**\n * If set to `true`, data will be synchronized to disk before returning.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * If set to `true`, no data will be returned by the server. This option can\n * be used to reduce network traffic.\n *\n * Default: `false`\n */\n silent?: boolean;\n /**\n * If set to `true`, the complete new document will be returned as the `new`\n * property on the result object. Has no effect if `silent` is set to `true`.\n *\n * Default: `false`\n */\n returnNew?: boolean;\n /**\n * If set to `false`, the existing document will only be modified if its\n * `_rev` property matches the same property on the new data.\n *\n * Default: `true`\n */\n ignoreRevs?: boolean;\n /**\n * If set to `true`, the complete old document will be returned as the `old`\n * property on the result object. Has no effect if `silent` is set to `true`.\n *\n * Default: `false`\n */\n returnOld?: boolean;\n /**\n * If set to a document revision, the document will only be replaced if its\n * `_rev` matches the given revision.\n */\n ifMatch?: string;\n};\n\n/**\n * Options for updating a document in a collection.\n */\nexport type CollectionUpdateOptions = {\n /**\n * If set to `true`, data will be synchronized to disk before returning.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * If set to `true`, no data will be returned by the server. This option can\n * be used to reduce network traffic.\n *\n * Default: `false`\n */\n silent?: boolean;\n /**\n * If set to `true`, the complete new document will be returned as the `new`\n * property on the result object. Has no effect if `silent` is set to `true`.\n *\n * Default: `false`\n */\n returnNew?: boolean;\n /**\n * If set to `false`, the existing document will only be modified if its\n * `_rev` property matches the same property on the new data.\n *\n * Default: `true`\n */\n ignoreRevs?: boolean;\n /**\n * If set to `true`, the complete old document will be returned as the `old`\n * property on the result object. Has no effect if `silent` is set to `true`.\n *\n * Default: `false`\n */\n returnOld?: boolean;\n /**\n * If set to `false`, properties with a value of `null` will be removed from\n * the new document.\n *\n * Default: `true`\n */\n keepNull?: boolean;\n /**\n * If set to `false`, object properties that already exist in the old\n * document will be overwritten rather than merged. This does not affect\n * arrays.\n *\n * Default: `true`\n */\n mergeObjects?: boolean;\n /**\n * If set to a document revision, the document will only be updated if its\n * `_rev` matches the given revision.\n */\n ifMatch?: string;\n};\n\n/**\n * Options for removing a document from a collection.\n */\nexport type CollectionRemoveOptions = {\n /**\n * If set to `true`, changes will be synchronized to disk before returning.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * If set to `true`, the complete old document will be returned as the `old`\n * property on the result object. Has no effect if `silent` is set to `true`.\n *\n * Default: `false`\n */\n returnOld?: boolean;\n /**\n * If set to `true`, no data will be returned by the server. This option can\n * be used to reduce network traffic.\n *\n * Default: `false`\n */\n silent?: boolean;\n /**\n * If set to a document revision, the document will only be removed if its\n * `_rev` matches the given revision.\n */\n ifMatch?: string;\n};\n\n/**\n * Options for bulk importing documents into a collection.\n */\nexport type CollectionImportOptions = {\n /**\n * (Edge collections only.) Prefix to prepend to `_from` attribute values.\n */\n fromPrefix?: string;\n /**\n * (Edge collections only.) Prefix to prepend to `_to` attribute values.\n */\n toPrefix?: string;\n /**\n * If set to `true`, the collection is truncated before the data is imported.\n *\n * Default: `false`\n */\n overwrite?: boolean;\n /**\n * Whether to wait for the documents to have been synced to disk.\n */\n waitForSync?: boolean;\n /**\n * Controls behavior when a unique constraint is violated on the document key.\n *\n * * `\"error\"`: the document will not be imported.\n * * `\"update`: the document will be merged into the existing document.\n * * `\"replace\"`: the document will replace the existing document.\n * * `\"ignore\"`: the document will not be imported and the unique constraint\n * error will be ignored.\n *\n * Default: `\"error\"`\n */\n onDuplicate?: \"error\" | \"update\" | \"replace\" | \"ignore\";\n /**\n * If set to `true`, the import will abort if any error occurs.\n */\n complete?: boolean;\n /**\n * Whether the response should contain additional details about documents\n * that could not be imported.\n */\n details?: boolean;\n};\n\n/**\n * Options for retrieving a document's edges from a collection.\n */\nexport type CollectionEdgesOptions = {\n /**\n * If set to `true`, the request will explicitly permit ArangoDB to return a\n * potentially dirty or stale result and arangojs will load balance the\n * request without distinguishing between leaders and followers.\n */\n allowDirtyRead?: boolean;\n};\n\n/**\n * Options for retrieving documents by example.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryByExampleOptions = {\n /**\n * Number of documents to skip in the query.\n */\n skip?: number;\n /**\n * Maximum number of documents to return.\n */\n limit?: number;\n /**\n * Number of result values to be transferred by the server in each\n * network roundtrip (or \"batch\").\n *\n * Must be greater than zero.\n *\n * See also {@link database.QueryOptions}.\n */\n batchSize?: number;\n /**\n * Time-to-live for the cursor in seconds. The cursor results may be\n * garbage collected by ArangoDB after this much time has passed.\n *\n * See also {@link database.QueryOptions}.\n */\n ttl?: number;\n};\n\n/**\n * Options for retrieving all documents in a collection.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryAllOptions = {\n /**\n * Number of documents to skip in the query.\n */\n skip?: number;\n /**\n * Maximum number of documents to return.\n */\n limit?: number;\n /**\n * Number of result values to be transferred by the server in each\n * network roundtrip (or \"batch\").\n *\n * Must be greater than zero.\n *\n * See also {@link database.QueryOptions}.\n */\n batchSize?: number;\n /**\n * Time-to-live for the cursor in seconds. The cursor results may be\n * garbage collected by ArangoDB after this much time has passed.\n *\n * See also {@link database.QueryOptions}.\n */\n ttl?: number;\n /**\n * If set to `true`, the query will be executed as a streaming query.\n *\n * See also {@link database.QueryOptions}.\n */\n stream?: boolean;\n};\n\n/**\n * Options for updating documents by example.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryUpdateByExampleOptions = {\n /**\n * If set to `false`, properties with a value of `null` will be removed from\n * the new document.\n *\n * Default: `true`\n */\n keepNull?: boolean;\n /**\n * If set to `true`, the request will wait until all modifications have been\n * synchronized to disk before returning successfully.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * Maximum number of documents to return.\n */\n limit?: number;\n /**\n * If set to `false`, object properties that already exist in the old\n * document will be overwritten rather than merged. This does not affect\n * arrays.\n *\n * Default: `true`\n */\n mergeObjects?: boolean;\n};\n\n/**\n * Options for removing documents by example.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryRemoveByExampleOptions = {\n /**\n * If set to `true`, the request will wait until all modifications have been\n * synchronized to disk before returning successfully.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * Maximum number of documents to return.\n */\n limit?: number;\n};\n\n/**\n * Options for replacing documents by example.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryReplaceByExampleOptions =\n SimpleQueryRemoveByExampleOptions;\n\n/**\n * Options for removing documents by keys.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryRemoveByKeysOptions = {\n /**\n * If set to `true`, the complete old document will be returned as the `old`\n * property on the result object. Has no effect if `silent` is set to `true`.\n *\n * Default: `false`\n */\n returnOld?: boolean;\n /**\n * If set to `true`, no data will be returned by the server. This option can\n * be used to reduce network traffic.\n *\n * Default: `false`\n */\n silent?: boolean;\n /**\n * If set to `true`, the request will wait until all modifications have been\n * synchronized to disk before returning successfully.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n};\n\n/**\n * Options for performing a fulltext query.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryFulltextOptions = {\n /**\n * Unique identifier of the fulltext index to use to perform the query.\n */\n index?: string;\n /**\n * Maximum number of documents to return.\n */\n limit?: number;\n /**\n * Number of documents to skip in the query.\n */\n skip?: number;\n};\n\n/**\n * Options for performing a graph traversal.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type TraversalOptions = {\n /**\n * A string evaluating to the body of a JavaScript function to be executed\n * on the server to initialize the traversal result object.\n *\n * The code has access to two variables: `config`, `result`.\n * The code may modify the `result` object.\n *\n * **Note**: This code will be evaluated and executed on the\n * server inside ArangoDB's embedded JavaScript environment and can not\n * access any other variables.\n *\n * See the official ArangoDB documentation for\n * [the JavaScript `@arangodb` module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html)\n * for information about accessing the database from within ArangoDB's\n * server-side JavaScript environment.\n */\n init?: string;\n /**\n * A string evaluating to the body of a JavaScript function to be executed\n * on the server to filter nodes.\n *\n * The code has access to three variables: `config`, `vertex`, `path`.\n * The code may include a return statement for the following values:\n *\n * * `\"exclude\"`: The vertex will not be visited.\n * * `\"prune\"`: The edges of the vertex will not be followed.\n * * `\"\"` or `undefined`: The vertex will be visited and its edges followed.\n * * an array including any of the above values.\n *\n * **Note**: This code will be evaluated and executed on the\n * server inside ArangoDB's embedded JavaScript environment and can not\n * access any other variables.\n *\n * See the official ArangoDB documentation for\n * [the JavaScript `@arangodb` module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html)\n * for information about accessing the database from within ArangoDB's\n * server-side JavaScript environment.\n */\n filter?: string;\n /**\n * A string evaluating to the body of a JavaScript function to be executed\n * on the server to sort edges if `expander` is not set.\n *\n * The code has access to two variables representing edges: `l`, `r`.\n * The code must return `-1` if `l < r`, `1` if `l > r` or `0` if both\n * values are equal.\n *\n * **Note**: This code will be evaluated and executed on the\n * server inside ArangoDB's embedded JavaScript environment and can not\n * access any other variables.\n *\n * See the official ArangoDB documentation for\n * [the JavaScript `@arangodb` module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html)\n * for information about accessing the database from within ArangoDB's\n * server-side JavaScript environment.\n */\n sort?: string;\n /**\n * A string evaluating to the body of a JavaScript function to be executed\n * on the server when a node is visited.\n *\n * The code has access to five variables: `config`, `result`, `vertex`,\n * `path`, `connected`.\n * The code may modify the `result` object.\n *\n * **Note**: This code will be evaluated and executed on the\n * server inside ArangoDB's embedded JavaScript environment and can not\n * access any other variables.\n *\n * See the official ArangoDB documentation for\n * [the JavaScript `@arangodb` module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html)\n * for information about accessing the database from within ArangoDB's\n * server-side JavaScript environment.\n */\n visitor?: string;\n /**\n * A string evaluating to the body of a JavaScript function to be executed\n * on the server to use when `direction` is not set.\n *\n * The code has access to three variables: `config`, `vertex`, `path`.\n * The code must return an array of objects with `edge` and `vertex`\n * attributes representing the connections for the vertex.\n *\n * **Note**: This code will be evaluated and executed on the\n * server inside ArangoDB's embedded JavaScript environment and can not\n * access any other variables.\n *\n * See the official ArangoDB documentation for\n * [the JavaScript `@arangodb` module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html)\n * for information about accessing the database from within ArangoDB's\n * server-side JavaScript environment.\n */\n expander?: string;\n /**\n * Direction of the traversal, relative to the starting vertex if `expander`\n * is not set.\n */\n direction?: \"inbound\" | \"outbound\" | \"any\";\n /**\n * Item iteration order.\n */\n itemOrder?: \"forward\" | \"backward\";\n /**\n * Traversal strategy.\n */\n strategy?: \"depthfirst\" | \"breadthfirst\";\n /**\n * Traversal order.\n */\n order?: \"preorder\" | \"postorder\" | \"preorder-expander\";\n /**\n * Specifies uniqueness for vertices and edges.\n */\n uniqueness?: {\n /**\n * Uniqueness for vertices.\n */\n vertices?: \"none\" | \"global\" | \"path\";\n /**\n * Uniqueness for edges.\n */\n edges?: \"none\" | \"global\" | \"path\";\n };\n /**\n * If specified, only nodes in at least this depth will be visited.\n */\n minDepth?: number;\n /**\n * If specified, only nodes in at most this depth will be visited.\n */\n maxDepth?: number;\n /**\n * Maximum number of iterations before a traversal is aborted because of a\n * potential endless loop.\n */\n maxIterations?: number;\n};\n\n// Results\n\n/**\n * Result of a collection bulk import.\n */\nexport type CollectionImportResult = {\n /**\n * Whether the import failed.\n */\n error: false;\n /**\n * Number of new documents imported.\n */\n created: number;\n /**\n * Number of documents that failed with an error.\n */\n errors: number;\n /**\n * Number of empty documents.\n */\n empty: number;\n /**\n * Number of documents updated.\n */\n updated: number;\n /**\n * Number of documents that failed with an error that is ignored.\n */\n ignored: number;\n /**\n * Additional details about any errors encountered during the import.\n */\n details?: string[];\n};\n\n/**\n * Result of retrieving edges in a collection.\n */\nexport type CollectionEdgesResult<T extends Record<string, any> = any> = {\n edges: Edge<T>[];\n stats: {\n scannedIndex: number;\n filtered: number;\n };\n};\n\n/**\n * Result of removing documents by an example.\n *\n * See {@link DocumentCollection#removeByExample} and {@link EdgeCollection#removeByExample}.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryRemoveByExampleResult = {\n /**\n * Number of documents removed.\n */\n deleted: number;\n};\n\n/**\n * Result of replacing documents by an example.\n *\n * See {@link DocumentCollection#replaceByExample} and {@link EdgeCollection#replaceByExample}.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryReplaceByExampleResult = {\n /**\n * Number of documents replaced.\n */\n replaced: number;\n};\n\n/**\n * Result of updating documents by an example.\n *\n * See {@link DocumentCollection#updateByExample} and {@link EdgeCollection#updateByExample}.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryUpdateByExampleResult = {\n /**\n * Number of documents updated.\n */\n updated: number;\n};\n\n/**\n * Result of removing documents by keys.\n *\n * See {@link DocumentCollection#removeByKeys} and {@link EdgeCollection#removeByKeys}.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryRemoveByKeysResult<T extends Record<string, any> = any> =\n {\n /**\n * Number of documents removed.\n */\n removed: number;\n /**\n * Number of documents not removed.\n */\n ignored: number;\n /**\n * Documents that have been removed.\n */\n old?: DocumentMetadata[] | Document<T>[];\n };\n\n// Collections\n\n/**\n * Represents an document collection in a {@link database.Database}.\n *\n * See {@link EdgeCollection} for a variant of this interface more suited for\n * edge collections.\n *\n * When using TypeScript, collections can be cast to a specific document data\n * type to increase type safety.\n *\n * @param T - Type to use for document data. Defaults to `any`.\n *\n * @example\n * ```ts\n * interface Person {\n * name: string;\n * }\n * const db = new Database();\n * const documents = db.collection(\"persons\") as DocumentCollection<Person>;\n * ```\n */\nexport interface DocumentCollection<T extends Record<string, any> = any>\n extends ArangoCollection {\n /**\n * Checks whether the collection exists.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const result = await collection.exists();\n * // result indicates whether the collection exists\n * ```\n */\n exists(): Promise<boolean>;\n /**\n * Retrieves general information about the collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const data = await collection.get();\n * // data contains general information about the collection\n * ```\n */\n get(): Promise<ArangoApiResponse<CollectionMetadata>>;\n /**\n * Creates a collection with the given `options` and the instance's name.\n *\n * See also {@link database.Database#createCollection} and\n * {@link database.Database#createEdgeCollection}.\n *\n * **Note**: When called on an {@link EdgeCollection} instance in TypeScript,\n * the `type` option must still be set to the correct {@link CollectionType}.\n * Otherwise this will result in the collection being created with the\n * default type (i.e. as a document collection).\n *\n * @param options - Options for creating the collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"potatoes\");\n * await collection.create();\n * // the document collection \"potatoes\" now exists\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * await collection.create({ type: CollectionType.EDGE_COLLECTION });\n * // the edge collection \"friends\" now exists\n * ```\n *\n * @example\n * ```ts\n * interface Friend {\n * startDate: number;\n * endDate?: number;\n * }\n * const db = new Database();\n * const collection = db.collection(\"friends\") as EdgeCollection<Friend>;\n * // even in TypeScript you still need to indicate the collection type\n * // if you want to create an edge collection\n * await collection.create({ type: CollectionType.EDGE_COLLECTION });\n * // the edge collection \"friends\" now exists\n * ```\n */\n create(\n options?: CreateCollectionOptions & {\n type?: CollectionType;\n }\n ): Promise<ArangoApiResponse<CollectionMetadata & CollectionProperties>>;\n /**\n * Retrieves the collection's properties.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const data = await collection.properties();\n * // data contains the collection's properties\n * ```\n */\n properties(): Promise<\n ArangoApiResponse<CollectionMetadata & CollectionProperties>\n >;\n /**\n * Replaces the properties of the collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const result = await collection.setProperties({ waitForSync: true });\n * // the collection will now wait for data being written to disk\n * // whenever a document is changed\n * ```\n */\n properties(\n properties: CollectionPropertiesOptions\n ): Promise<ArangoApiResponse<CollectionMetadata & CollectionProperties>>;\n /**\n * Retrieves information about the number of documents in a collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const data = await collection.count();\n * // data contains the collection's count\n * ```\n */\n count(): Promise<\n ArangoApiResponse<\n CollectionMetadata & CollectionProperties & { count: number }\n >\n >;\n /**\n * (RocksDB only.) Instructs ArangoDB to recalculate the collection's\n * document count to fix any inconsistencies.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"inconsistent-collection\");\n * const badData = await collection.count();\n * // oh no, the collection count looks wrong -- fix it!\n * await collection.recalculateCount();\n * const goodData = await collection.count();\n * // goodData contains the collection's improved count\n * ```\n */\n recalculateCount(): Promise<boolean>;\n /**\n * Retrieves statistics for a collection.\n *\n * @param details - whether to return extended storage engine-specific details\n * to the figures, which may cause additional load and impact performance\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const data = await collection.figures();\n * // data contains the collection's figures\n * ```\n */\n figures(\n details?: boolean\n ): Promise<\n ArangoApiResponse<\n CollectionMetadata &\n CollectionProperties & { count: number; figures: Record<string, any> }\n >\n >;\n /**\n * Retrieves the collection revision ID.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const data = await collection.revision();\n * // data contains the collection's revision\n * ```\n */\n revision(): Promise<\n ArangoApiResponse<\n CollectionMetadata & CollectionProperties & { revision: string }\n >\n >;\n /**\n * Retrieves the collection checksum.\n *\n * @param options - Options for retrieving the checksum.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const data = await collection.checksum();\n * // data contains the collection's checksum\n * ```\n */\n checksum(\n options?: CollectionChecksumOptions\n ): Promise<\n ArangoApiResponse<\n CollectionMetadata & { revision: string; checksum: string }\n >\n >;\n /**\n * (RocksDB only.) Instructs ArangoDB to load as many indexes of the\n * collection into memory as permitted by the memory limit.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"indexed-collection\");\n * await collection.loadIndexes();\n * // the indexes are now loaded into memory\n * ```\n */\n loadIndexes(): Promise<boolean>;\n /**\n * Renames the collection and updates the instance's `name` to `newName`.\n *\n * Additionally removes the instance from the {@link database.Database}'s internal\n * cache.\n *\n * **Note**: Renaming collections may not be supported when ArangoDB is\n * running in a cluster configuration.\n *\n * @param newName - The new name of the collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection1 = db.collection(\"some-collection\");\n * await collection1.rename(\"other-collection\");\n * const collection2 = db.collection(\"some-collection\");\n * const collection3 = db.collection(\"other-collection\");\n * // Note all three collection instances are different objects but\n * // collection1 and collection3 represent the same ArangoDB collection!\n * ```\n */\n rename(newName: string): Promise<ArangoApiResponse<CollectionMetadata>>;\n /**\n * Deletes all documents in the collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.truncate();\n * // millions of documents cry out in terror and are suddenly silenced,\n * // the collection \"some-collection\" is now empty\n * ```\n */\n truncate(): Promise<ArangoApiResponse<CollectionMetadata>>;\n /**\n * Deletes the collection from the database.\n *\n * @param options - Options for dropping the collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.drop();\n * // The collection \"some-collection\" is now an ex-collection\n * ```\n */\n drop(\n options?: CollectionDropOptions\n ): Promise<ArangoApiResponse<Record<string, never>>>;\n\n //#region crud\n /**\n * Retrieves the `shardId` of the shard responsible for the given document.\n *\n * @param document - Document in the collection to look up the `shardId` of.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const responsibleShard = await collection.getResponsibleShard();\n * ```\n */\n getResponsibleShard(document: Partial<Document<T>>): Promise<string>;\n /**\n * Derives a document `_id` from the given selector for this collection.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const meta = await collection.save({ foo: \"bar\" }, { returnNew: true });\n * const doc = meta.new;\n * console.log(collection.documentId(meta)); // via meta._id\n * console.log(collection.documentId(doc)); // via doc._id\n * console.log(collection.documentId(meta._key)); // also works\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection1 = db.collection(\"some-collection\");\n * const collection2 = db.collection(\"other-collection\");\n * const meta = await collection1.save({ foo: \"bar\" });\n * // Mixing collections is usually a mistake\n * console.log(collection1.documentId(meta)); // ok: same collection\n * console.log(collection2.documentId(meta)); // throws: wrong collection\n * console.log(collection2.documentId(meta._id)); // also throws\n * console.log(collection2.documentId(meta._key)); // ok but wrong collection\n * ```\n */\n documentId(selector: DocumentSelector): string;\n /**\n * Checks whether a document matching the given key or id exists in this\n * collection.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const exists = await collection.documentExists(\"abc123\");\n * if (!exists) {\n * console.log(\"Document does not exist\");\n * }\n * ```\n */\n documentExists(\n selector: DocumentSelector,\n options?: DocumentExistsOptions\n ): Promise<boolean>;\n /**\n * Retrieves the document matching the given key or id.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param options - Options for retrieving the document.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * try {\n * const document = await collection.document(\"abc123\");\n * console.log(document);\n * } catch (e: any) {\n * console.error(\"Could not find document\");\n * }\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const document = await collection.document(\"abc123\", { graceful: true });\n * if (document) {\n * console.log(document);\n * } else {\n * console.error(\"Could not find document\");\n * }\n * ```\n */\n document(\n selector: DocumentSelector,\n options?: CollectionReadOptions\n ): Promise<Document<T>>;\n /**\n * Retrieves the document matching the given key or id.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param graceful - If set to `true`, `null` is returned instead of an\n * exception being thrown if the document does not exist.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * try {\n * const document = await collection.document(\"abc123\", false);\n * console.log(document);\n * } catch (e: any) {\n * console.error(\"Could not find document\");\n * }\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const document = await collection.document(\"abc123\", true);\n * if (document) {\n * console.log(document);\n * } else {\n * console.error(\"Could not find document\");\n * }\n * ```\n */\n document(selector: DocumentSelector, graceful: boolean): Promise<Document<T>>;\n /**\n * Retrieves the documents matching the given key or id values.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection, or if the document does not exist.\n *\n * @param selectors - Array of document `_key`, `_id` or objects with either\n * of those properties (e.g. a document from this collection).\n * @param options - Options for retrieving the documents.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * try {\n * const documents = await collection.documents([\"abc123\", \"xyz456\"]);\n * console.log(documents);\n * } catch (e: any) {\n * console.error(\"Could not find document\");\n * }\n * ```\n */\n documents(\n selectors: (string | ObjectWithKey)[],\n options?: CollectionBatchReadOptions\n ): Promise<Document<T>[]>;\n /**\n * Inserts a new document with the given `data` into the collection.\n *\n * @param data - The contents of the new document.\n * @param options - Options for inserting the document.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const result = await collection.save(\n * { _key: \"a\", color: \"blue\", count: 1 },\n * { returnNew: true }\n * );\n * console.log(result.new.color, result.new.count); // \"blue\" 1\n * ```\n */\n save(\n data: DocumentData<T>,\n options?: CollectionInsertOptions\n ): Promise<DocumentMetadata & { new?: Document<T> }>;\n /**\n * Inserts new documents with the given `data` into the collection.\n *\n * @param data - The contents of the new documents.\n * @param options - Options for inserting the documents.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const result = await collection.saveAll(\n * [\n * { _key: \"a\", color: \"blue\", count: 1 },\n * { _key: \"b\", color: \"red\", count: 2 },\n * ],\n * { returnNew: true }\n * );\n * console.log(result[0].new.color, result[0].new.count); // \"blue\" 1\n * console.log(result[1].new.color, result[1].new.count); // \"red\" 2\n * ```\n */\n saveAll(\n data: Array<DocumentData<T>>,\n options?: CollectionInsertOptions\n ): Promise<Array<DocumentMetadata & { new?: Document<T> }>>;\n /**\n * Replaces an existing document in the collection.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param newData - The contents of the new document.\n * @param options - Options for replacing the document.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.save({ _key: \"a\", color: \"blue\", count: 1 });\n * const result = await collection.replace(\n * \"a\",\n * { color: \"red\" },\n * { returnNew: true }\n * );\n * console.log(result.new.color, result.new.count); // \"red\" undefined\n * ```\n */\n replace(\n selector: DocumentSelector,\n newData: DocumentData<T>,\n options?: CollectionReplaceOptions\n ): Promise<DocumentMetadata & { new?: Document<T>; old?: Document<T> }>;\n /**\n * Replaces existing documents in the collection, identified by the `_key` or\n * `_id` of each document.\n *\n * @param newData - The documents to replace.\n * @param options - Options for replacing the documents.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.save({ _key: \"a\", color: \"blue\", count: 1 });\n * await collection.save({ _key: \"b\", color: \"green\", count: 3 });\n * const result = await collection.replaceAll(\n * [\n * { _key: \"a\", color: \"red\" },\n * { _key: \"b\", color: \"yellow\", count: 2 }\n * ],\n * { returnNew: true }\n * );\n * console.log(result[0].new.color, result[0].new.count); // \"red\" undefined\n * console.log(result[1].new.color, result[1].new.count); // \"yellow\" 2\n * ```\n */\n replaceAll(\n newData: Array<DocumentData<T> & ({ _key: string } | { _id: string })>,\n options?: Omit<CollectionReplaceOptions, \"ifMatch\">\n ): Promise<\n Array<DocumentMetadata & { new?: Document<T>; old?: Document<T> }>\n >;\n /**\n * Updates an existing document in the collection.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param newData - The data for updating the document.\n * @param options - Options for updating the document.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.save({ _key: \"a\", color: \"blue\", count: 1 });\n * const result = await collection.update(\n * \"a\",\n * { count: 2 },\n * { returnNew: true }\n * );\n * console.log(result.new.color, result.new.count); // \"blue\" 2\n * ```\n */\n update(\n selector: DocumentSelector,\n newData: Patch<DocumentData<T>>,\n options?: CollectionUpdateOptions\n ): Promise<DocumentMetadata & { new?: Document<T>; old?: Document<T> }>;\n /**\n * Updates existing documents in the collection, identified by the `_key` or\n * `_id` of each document.\n *\n * @param newData - The data for updating the documents.\n * @param options - Options for updating the documents.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.save({ _key: \"a\", color: \"blue\", count: 1 });\n * await collection.save({ _key: \"b\", color: \"green\", count: 3 });\n * const result = await collection.updateAll(\n * [\n * { _key: \"a\", count: 2 },\n * { _key: \"b\", count: 4 }\n * ],\n * { returnNew: true }\n * );\n * console.log(result[0].new.color, result[0].new.count); // \"blue\" 2\n * console.log(result[1].new.color, result[1].new.count); // \"green\" 4\n * ```\n */\n updateAll(\n newData: Array<\n Patch<DocumentData<T>> & ({ _key: string } | { _id: string })\n >,\n options?: Omit<CollectionUpdateOptions, \"ifMatch\">\n ): Promise<\n Array<DocumentMetadata & { new?: Document<T>; old?: Document<T> }>\n >;\n /**\n * Removes an existing document from the collection.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param options - Options for removing the document.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.remove(\"abc123\");\n * // document with key \"abc123\" deleted\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const doc = await collection.document(\"abc123\");\n * await collection.remove(doc);\n * // document with key \"abc123\" deleted\n * ```\n */\n remove(\n selector: DocumentSelector,\n options?: CollectionRemoveOptions\n ): Promise<DocumentMetadata & { old?: Document<T> }>;\n /**\n * Removes existing documents from the collection.\n *\n * Throws an exception when passed any document or `_id` from a different\n * collection.\n *\n * @param selectors - Documents `_key`, `_id` or objects with either of those\n * properties (e.g. documents from this collection).\n * @param options - Options for removing the documents.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.removeAll([\"abc123\", \"def456\"]);\n * // document with keys \"abc123\" and \"def456\" deleted\n * ```\n */\n removeAll(\n selectors: (string | ObjectWithKey)[],\n options?: Omit<CollectionRemoveOptions, \"ifMatch\">\n ): Promise<Array<DocumentMetadata & { old?: Document<T> }>>;\n /**\n * Bulk imports the given `data` into the collection.\n *\n * @param data - The data to import, as an array of document data.\n * @param options - Options for importing the data.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.import(\n * [\n * { _key: \"jcd\", password: \"bionicman\" },\n * { _key: \"jreyes\", password: \"amigo\" },\n * { _key: \"ghermann\", password: \"zeitgeist\" }\n * ]\n * );\n * ```\n */\n import(\n data: DocumentData<T>[],\n options?: CollectionImportOptions\n ): Promise<CollectionImportResult>;\n /**\n * Bulk imports the given `data` into the collection.\n *\n * @param data - The data to import, as an array containing a single array of\n * attribute names followed by one or more arrays of attribute values for\n * each document.\n * @param options - Options for importing the data.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.import(\n * [\n * [ \"_key\", \"password\" ],\n * [ \"jcd\", \"bionicman\" ],\n * [ \"jreyes\", \"amigo\" ],\n * [ \"ghermann\", \"zeitgeist\" ]\n * ]\n * );\n * ```\n */\n import(\n data: any[][],\n options?: CollectionImportOptions\n ): Promise<CollectionImportResult>;\n /**\n * Bulk imports the given `data` into the collection.\n *\n * If `type` is omitted, `data` must contain one JSON array per line with\n * the first array providing the attribute names and all other arrays\n * providing attribute values for each document.\n *\n * If `type` is set to `\"documents\"`, `data` must contain one JSON document\n * per line.\n *\n * If `type` is set to `\"list\"`, `data` must contain a JSON array of\n * documents.\n *\n * If `type` is set to `\"auto\"`, `data` can be in either of the formats\n * supported by `\"documents\"` or `\"list\"`.\n *\n * @param data - The data to import as a Buffer (Node), Blob (browser) or\n * string.\n * @param options - Options for importing the data.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.import(\n * '{\"_key\":\"jcd\",\"password\":\"bionicman\"}\\r\\n' +\n * '{\"_key\":\"jreyes\",\"password\":\"amigo\"}\\r\\n' +\n * '{\"_key\":\"ghermann\",\"password\":\"zeitgeist\"}\\r\\n',\n * { type: \"documents\" } // or \"auto\"\n * );\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.import(\n * '[{\"_key\":\"jcd\",\"password\":\"bionicman\"},' +\n * '{\"_key\":\"jreyes\",\"password\":\"amigo\"},' +\n * '{\"_key\":\"ghermann\",\"password\":\"zeitgeist\"}]',\n * { type: \"list\" } // or \"auto\"\n * );\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.import(\n * '[\"_key\",\"password\"]\\r\\n' +\n * '[\"jcd\",\"bionicman\"]\\r\\n' +\n * '[\"jreyes\",\"amigo\"]\\r\\n' +\n * '[\"ghermann\",\"zeitgeist\"]\\r\\n'\n * );\n * ```\n */\n import(\n data: Buffer | Blob | string,\n options?: CollectionImportOptions & {\n type?: \"documents\" | \"list\" | \"auto\";\n }\n ): Promise<CollectionImportResult>;\n //#endregion\n\n //#region simple queries\n\n /**\n * Retrieves a list of references for all documents in the collection.\n *\n * @param type - The type of document reference to retrieve.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const ids = await collection.list(\"id\");\n * const ids = await db.query(aql`\n * FOR doc IN ${collection}\n * RETURN doc._id\n * `);\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const keys = await collection.list(\"key\");\n * const keys = await db.query(aql`\n * FOR doc IN ${collection}\n * RETURN doc._key\n * `);\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const paths = await collection.list(\"path\");\n * const paths = await db.query(aql`\n * FOR doc IN ${collection}\n * RETURN CONCAT(\"/_db/\", CURRENT_DATABASE(), \"/_api/document/\", doc._id)\n * `);\n * ```\n */\n list(type?: SimpleQueryListType): Promise<ArrayCursor<string>>;\n\n /**\n * Retrieves all documents in the collection.\n *\n * @param options - Options for retrieving the documents.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const cursor = await collection.all();\n * const cursor = await db.query(aql`\n * FOR doc IN ${collection}\n * RETURN doc\n * `);\n * ```\n */\n all(options?: SimpleQueryAllOptions): Promise<ArrayCursor<Document<T>>>;\n\n /**\n * Retrieves a random document from the collection.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const doc = await collection.any();\n * const cursor = await db.query(aql`\n * FOR doc IN ${collection}\n * SORT RAND()\n * LIMIT 1\n * RETURN doc\n * `);\n * const doc = await cursor.next();\n * ```\n */\n any(): Promise<Document<T>>;\n\n /**\n * Retrieves all documents in the collection matching the given example.\n *\n * @param example - An object representing an example for documents.\n * @param options - Options for retrieving the documents.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const cursor = await collection.byExample({ flavor: \"strawberry\" });\n * const cursor = await db.query(aql`\n * FOR doc IN ${collection}\n * FILTER doc.flavor == \"strawberry\"\n * RETURN doc\n * `);\n * ```\n */\n byExample(\n example: Partial<DocumentData<T>>,\n options?: SimpleQueryByExampleOptions\n ): Promise<ArrayCursor<Document<T>>>;\n\n /**\n * Retrieves a single document in the collection matching the given example.\n *\n * @param example - An object representing an example for the document.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const doc = await collection.firstExample({ flavor: \"strawberry\" });\n * const cursor = await db.query(aql`\n * FOR doc IN ${collection}\n * FILTER doc.flavor == \"strawberry\"\n * LIMIT 1\n * RETURN doc\n * `);\n * const doc = await cursor.next();\n * ```\n */\n firstExample(example: Partial<DocumentData<T>>): Promise<Document<T>>;\n\n /**\n * Removes all documents in the collection matching the given example.\n *\n * @param example - An object representing an example for the document.\n * @param options - Options for removing the documents.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const { deleted } = await collection.removeByExample({\n * // flavor: \"strawberry\"\n * // });\n * const cursor = await db.query(aql`\n * RETURN LENGTH(\n * FOR doc IN ${collection}\n * FILTER doc.flavor == \"strawberry\"\n * REMOVE doc IN ${collection}\n * RETURN 1\n * )\n * `);\n * const deleted = await cursor.next();\n * ```\n */\n removeByExample(\n example: Partial<DocumentData<T>>,\n options?: SimpleQueryRemoveByExampleOptions\n ): Promise<ArangoApiResponse<SimpleQueryRemoveByExampleResult>>;\n\n /**\n * Replaces all documents in the collection matching the given example.\n *\n * @param example - An object representing an example for the documents.\n * @param newValue - Document data to replace the matching documents with.\n * @param options - Options for replacing the documents.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const newValue = { flavor: \"chocolate\" };\n * // const { replaced } = await collection.replaceByExample(\n * // { flavor: \"strawberry\" },\n * // newValue\n * // );\n * const cursor = await db.query(aql`\n * RETURN LENGTH(\n * FOR doc IN ${collection}\n * FILTER doc.flavor == \"strawberry\"\n * REPLACE doc WITH ${newValue} IN ${collection}\n * RETURN 1\n * )\n * `);\n * const replaced = await cursor.next();\n * ```\n */\n replaceByExample(\n example: Partial<DocumentData<T>>,\n newValue: DocumentData<T>,\n options?: SimpleQueryReplaceByExampleOptions\n ): Promise<ArangoApiResponse<SimpleQueryReplaceByExampleResult>>;\n\n /**\n * Updates all documents in the collection matching the given example.\n *\n * @param example - An object representing an example for the documents.\n * @param newValue - Document data to update the matching documents with.\n * @param options - Options for updating the documents.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const newData = { color: \"red\" };\n * // const { updated } = await collection.updateByExample(\n * // { flavor: \"strawberry\" },\n * // newValue\n * // );\n * const cursor = await db.query(aql`\n * RETURN LENGTH(\n * FOR doc IN ${collection}\n * FILTER doc.flavor == \"strawberry\"\n * UPDATE doc WITH ${newValue} IN ${collection}\n * RETURN 1\n * )\n * `);\n * const updated = await cursor.next();\n * ```\n */\n updateByExample(\n example: Partial<DocumentData<T>>,\n newValue: Patch<DocumentData<T>>,\n options?: SimpleQueryUpdateByExampleOptions\n ): Promise<ArangoApiResponse<SimpleQueryUpdateByExampleResult>>;\n\n /**\n * Retrieves all documents matching the given document keys.\n *\n * @param keys - An array of document keys to look up.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const keys = [\"a\", \"b\", \"c\"];\n * // const docs = await collection.byKeys(keys);\n * const cursor = await db.query(aql`\n * FOR key IN ${keys}\n * LET doc = DOCUMENT(${collection}, key)\n * RETURN doc\n * `);\n * const docs = await cursor.all();\n * ```\n */\n lookupByKeys(keys: string[]): Promise<Document<T>[]>;\n\n /**\n * Removes all documents matching the given document keys.\n *\n * @param keys - An array of document keys to remove.\n * @param options - Options for removing the documents.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const keys = [\"a\", \"b\", \"c\"];\n * // const { removed, ignored } = await collection.removeByKeys(keys);\n * const cursor = await db.query(aql`\n * FOR key IN ${keys}\n * LET doc = DOCUMENT(${collection}, key)\n * FILTER doc\n * REMOVE doc IN ${collection}\n * RETURN key\n * `);\n * const removed = await cursor.all();\n * const ignored = keys.filter((key) => !removed.includes(key));\n * ```\n */\n removeByKeys(\n keys: string[],\n options?: SimpleQueryRemoveByKeysOptions\n ): Promise<ArangoApiResponse<SimpleQueryRemoveByKeysResult<T>>>;\n\n /**\n * Performs a fulltext query in the given `attribute` on the collection.\n *\n * @param attribute - Name of the field to search.\n * @param query - Fulltext query string to search for.\n * @param options - Options for performing the fulltext query.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const cursor = await collection.fulltext(\"article\", \"needle\");\n * const cursor = await db.query(aql`\n * FOR doc IN FULLTEXT(${collection}, \"article\", \"needle\")\n * RETURN doc\n * `);\n * ```\n */\n fulltext(\n attribute: string,\n query: string,\n options?: SimpleQueryFulltextOptions\n ): Promise<ArrayCursor<Document<T>>>;\n //#endregion\n\n //#region indexes\n /**\n * Returns a list of all index descriptions for the collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const indexes = await collection.indexes();\n * ```\n */\n indexes(): Promise<Index[]>;\n /**\n * Returns an index description by name or `id` if it exists.\n *\n * @param selector - Index name, id or object with either property.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const index = await collection.index(\"some-index\");\n * ```\n */\n index(selector: IndexSelector): Promise<Index>;\n /**\n * Creates a persistent index on the collection if it does not already exist.\n *\n * @param details - Options for creating the persistent index.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // Create a unique index for looking up documents by username\n * await collection.ensureIndex({\n * type: \"persistent\",\n * fields: [\"username\"],\n * name: \"unique-usernames\",\n * unique: true\n * });\n * ```\n */\n ensureIndex(\n details: EnsurePersistentIndexOptions\n ): Promise<ArangoApiResponse<PersistentIndex & { isNewlyCreated: boolean }>>;\n /**\n * Creates a TTL index on the collection if it does not already exist.\n *\n * @param details - Options for creating the TTL index.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // Expire documents with \"createdAt\" timestamp one day after creation\n * await collection.ensureIndex({\n * type: \"ttl\",\n * fields: [\"createdAt\"],\n * expireAfter: 60 * 60 * 24 // 24 hours\n * });\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // Expire documents with \"expiresAt\" timestamp according to their value\n * await collection.ensureIndex({\n * type: \"ttl\",\n * fields: [\"expiresAt\"],\n * expireAfter: 0 // when attribute value is exceeded\n * });\n * ```\n */\n ensureIndex(\n details: EnsureTtlIndexOptions\n ): Promise<ArangoApiResponse<TtlIndex & { isNewlyCreated: boolean }>>;\n /**\n * Creates a multi-dimensional index on the collection if it does not already exist.\n *\n * @param details - Options for creating the multi-dimensional index.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-points\");\n * // Create a multi-dimensional index for the attributes x, y and z\n * await collection.ensureIndex({\n * type: \"zkd\",\n * fields: [\"x\", \"y\", \"z\"],\n * fieldValueTypes: \"double\"\n * });\n * ```\n * ```\n */\n ensureIndex(\n details: EnsureZkdIndexOptions\n ): Promise<ArangoApiResponse<ZkdIndex & { isNewlyCreated: boolean }>>;\n /**\n * Creates a fulltext index on the collection if it does not already exist.\n *\n * @param details - Options for creating the fulltext index.\n *\n * @deprecated Fulltext indexes have been deprecated in ArangoDB 3.10 and\n * should be replaced with ArangoSearch.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // Create a fulltext index for tokens longer than or equal to 3 characters\n * await collection.ensureIndex({\n * type: \"fulltext\",\n * fields: [\"description\"],\n * minLength: 3\n * });\n * ```\n */\n ensureIndex(\n details: EnsureFulltextIndexOptions\n ): Promise<ArangoApiResponse<FulltextIndex & { isNewlyCreated: boolean }>>;\n /**\n * Creates a geo index on the collection if it does not already exist.\n *\n * @param details - Options for creating the geo index.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // Create an index for GeoJSON data\n * await collection.ensureIndex({\n * type: \"geo\",\n * fields: [\"lngLat\"],\n * geoJson: true\n * });\n * ```\n */\n ensureIndex(\n details: EnsureGeoIndexOptions\n ): Promise<ArangoApiResponse<GeoIndex & { isNewlyCreated: boolean }>>;\n /**\n * Creates a inverted index on the collection if it does not already exist.\n *\n * @param details - Options for creating the inverted index.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // Create an inverted index\n * await collection.ensureIndex({\n * type: \"inverted\",\n * fields: [\"a\", { name: \"b\", analyzer: \"text_en\" }]\n * });\n * ```\n */\n ensureIndex(\n details: EnsureInvertedIndexOptions\n ): Promise<ArangoApiResponse<InvertedIndex & { isNewlyCreated: boolean }>>;\n /**\n * Deletes the index with the given name or `id` from the database.\n *\n * @param selector - Index name, id or object with either property.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.dropIndex(\"some-index\");\n * // The index \"some-index\" no longer exists\n * ```\n */\n dropIndex(\n selector: IndexSelector\n ): Promise<ArangoApiResponse<{ id: string }>>;\n /**\n * Triggers compaction for a collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.compact();\n * // Background compaction is triggered on the collection\n * ```\n */\n compact(): Promise<ArangoApiResponse<Record<string, never>>>;\n //#endregion\n}\n\n/**\n * Represents an edge collection in a {@link database.Database}.\n *\n * See {@link DocumentCollection} for a more generic variant of this interface\n * more suited for regular document collections.\n *\n * See also {@link graph.GraphEdgeCollection} for the type representing an edge\n * collection in a {@link graph.Graph}.\n *\n * When using TypeScript, collections can be cast to a specific edge document\n * data type to increase type safety.\n *\n * @param T - Type to use for edge document data. Defaults to `any`.\n *\n * @example\n * ```ts\n * interface Friend {\n * startDate: number;\n * endDate?: number;\n * }\n * const db = new Database();\n * const edges = db.collection(\"friends\") as EdgeCollection<Friend>;\n * ```\n */\nexport interface EdgeCollection<T extends Record<string, any> = any>\n extends DocumentCollection<T> {\n /**\n * Retrieves the document matching the given key or id.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection, or if the document does not exist.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param options - Options for retrieving the document.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * try {\n * const document = await collection.document(\"abc123\");\n * console.log(document);\n * } catch (e: any) {\n * console.error(\"Could not find document\");\n * }\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const document = await collection.document(\"abc123\", { graceful: true });\n * if (document) {\n * console.log(document);\n * } else {\n * console.error(\"Document does not exist\");\n * }\n * ```\n */\n document(\n selector: DocumentSelector,\n options?: CollectionReadOptions\n ): Promise<Edge<T>>;\n /**\n * Retrieves the document matching the given key or id.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection, or if the document does not exist.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param graceful - If set to `true`, `null` is returned instead of an\n * exception being thrown if the document does not exist.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * try {\n * const document = await collection.document(\"abc123\", false);\n * console.log(document);\n * } catch (e: any) {\n * console.error(\"Could not find document\");\n * }\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const document = await collection.document(\"abc123\", true);\n * if (document) {\n * console.log(document);\n * } else {\n * console.error(\"Document does not exist\");\n * }\n * ```\n */\n document(selector: DocumentSelector, graceful: boolean): Promise<Edge<T>>;\n /**\n * Retrieves the documents matching the given key or id values.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection, or if the document does not exist.\n *\n * @param selectors - Array of document `_key`, `_id` or objects with either\n * of those properties (e.g. a document from this collection).\n * @param options - Options for retrieving the documents.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * try {\n * const documents = await collection.documents([\"abc123\", \"xyz456\"]);\n * console.log(documents);\n * } catch (e: any) {\n * console.error(\"Could not find document\");\n * }\n * ```\n */\n documents(\n selectors: (string | ObjectWithKey)[],\n options?: CollectionBatchReadOptions\n ): Promise<Edge<T>[]>;\n /**\n * Inserts a new document with the given `data` into the collection.\n *\n * @param data - The contents of the new document.\n * @param options - Options for inserting the document.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * const result = await collection.save(\n * { _from: \"users/rana\", _to: \"users/mudasir\", active: false },\n * { returnNew: true }\n * );\n * ```\n */\n save(\n data: EdgeData<T>,\n options?: CollectionInsertOptions\n ): Promise<DocumentMetadata & { new?: Edge<T> }>;\n /**\n * Inserts new documents with the given `data` into the collection.\n *\n * @param data - The contents of the new documents.\n * @param options - Options for inserting the documents.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * const result = await collection.saveAll(\n * [\n * { _from: \"users/rana\", _to: \"users/mudasir\", active: false },\n * { _from: \"users/rana\", _to: \"users/salman\", active: true }\n * ],\n * { returnNew: true }\n * );\n * ```\n */\n saveAll(\n data: Array<EdgeData<T>>,\n options?: CollectionInsertOptions\n ): Promise<Array<DocumentMetadata & { new?: Edge<T> }>>;\n /**\n * Replaces an existing document in the collection.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param newData - The contents of the new document.\n * @param options - Options for replacing the document.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * await collection.save(\n * {\n * _key: \"musadir\",\n * _from: \"users/rana\",\n * _to: \"users/mudasir\",\n * active: true,\n * best: true\n * }\n * );\n * const result = await collection.replace(\n * \"musadir\",\n * { active: false },\n * { returnNew: true }\n * );\n * console.log(result.new.active, result.new.best); // false undefined\n * ```\n */\n replace(\n selector: DocumentSelector,\n newData: DocumentData<T>,\n options?: CollectionReplaceOptions\n ): Promise<DocumentMetadata & { new?: Edge<T>; old?: Edge<T> }>;\n /**\n * Replaces existing documents in the collection, identified by the `_key` or\n * `_id` of each document.\n *\n * @param newData - The documents to replace.\n * @param options - Options for replacing the documents.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * await collection.save(\n * {\n * _key: \"musadir\",\n * _from: \"users/rana\",\n * _to: \"users/mudasir\",\n * active: true,\n * best: true\n * }\n * );\n * await collection.save(\n * {\n * _key: \"salman\",\n * _from: \"users/rana\",\n * _to: \"users/salman\",\n * active: false,\n * best: false\n * }\n * );\n * const result = await collection.replaceAll(\n * [\n * { _key: \"musadir\", active: false },\n * { _key: \"salman\", active: true, best: true }\n * ],\n * { returnNew: true }\n * );\n * console.log(result[0].new.active, result[0].new.best); // false undefined\n * console.log(result[1].new.active, result[1].new.best); // true true\n * ```\n */\n replaceAll(\n newData: Array<DocumentData<T> & ({ _key: string } | { _id: string })>,\n options?: CollectionReplaceOptions\n ): Promise<Array<DocumentMetadata & { new?: Edge<T>; old?: Edge<T> }>>;\n /**\n * Updates an existing document in the collection.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param newData - The data for updating the document.\n * @param options - Options for updating the document.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * await collection.save(\n * {\n * _key: \"musadir\",\n * _from: \"users/rana\",\n * _to: \"users/mudasir\",\n * active: true,\n * best: true\n * }\n * );\n * const result = await collection.update(\n * \"musadir\",\n * { active: false },\n * { returnNew: true }\n * );\n * console.log(result.new.active, result.new.best); // false true\n * ```\n */\n update(\n selector: DocumentSelector,\n newData: Patch<DocumentData<T>>,\n options?: CollectionUpdateOptions\n ): Promise<DocumentMetadata & { new?: Edge<T>; old?: Edge<T> }>;\n /**\n * Updates existing documents in the collection, identified by the `_key` or\n * `_id` of each document.\n *\n * @param newData - The data for updating the documents.\n * @param options - Options for updating the documents.\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * await collection.save(\n * {\n * _key: \"musadir\",\n * _from: \"users/rana\",\n * _to: \"users/mudasir\",\n * active: true,\n * best: true\n * }\n * );\n * await collection.save(\n * {\n * _key: \"salman\",\n * _from: \"users/rana\",\n * _to: \"users/salman\",\n * active: false,\n * best: false\n * }\n * );\n * const result = await collection.updateAll(\n * [\n * { _key: \"musadir\", active: false },\n * { _key: \"salman\", active: true, best: true }\n * ],\n * { returnNew: true }\n * );\n * console.log(result[0].new.active, result[0].new.best); // false true\n * console.log(result[1].new.active, result[1].new.best); // true true\n * ```\n */\n updateAll(\n newData: Array<\n Patch<DocumentData<T>> & ({ _key: string } | { _id: string })\n >,\n options?: CollectionUpdateOptions\n ): Promise<Array<DocumentMetadata & { new?: Edge<T>; old?: Edge<T> }>>;\n /**\n * Removes an existing document from the collection.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param options - Options for removing the document.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * const doc = await collection.document(\"musadir\");\n * await collection.remove(doc);\n * // document with key \"musadir\" deleted\n * ```\n */\n remove(\n selector: DocumentSelector,\n options?: CollectionRemoveOptions\n ): Promise<DocumentMetadata & { old?: Edge<T> }>;\n /**\n * Removes existing documents from the collection.\n *\n * Throws an exception when passed any document or `_id` from a different\n * collection.\n *\n * @param selectors - Documents `_key`, `_id` or objects with either of those\n * properties (e.g. documents from this collection).\n * @param options - Options for removing the documents.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * await collection.removeAll([\"musadir\", \"salman\"]);\n * // document with keys \"musadir\" and \"salman\" deleted\n * ```\n */\n removeAll(\n selectors: DocumentSelector[],\n options?: CollectionRemoveOptions\n ): Promise<Array<DocumentMetadata & { old?: Edge<T> }>>;\n /**\n * Bulk imports the given `data` into the collection.\n *\n * @param data - The data to import, as an array of edge data.\n * @param options - Options for importing the data.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.import(\n * [\n * { _key: \"x\", _from: \"vertices/a\", _to: \"vertices/b\", weight: 1 },\n * { _key: \"y\", _from: \"vertices/a\", _to: \"vertices/c\", weight: 2 }\n * ]\n * );\n * ```\n */\n import(\n data: EdgeData<T>[],\n options?: CollectionImportOptions\n ): Promise<CollectionImportResult>;\n /**\n * Bulk imports the given `data` into the collection.\n *\n * @param data - The data to import, as an array containing a single array of\n * attribute names followed by one or more arrays of attribute values for\n * each edge document.\n * @param options - Options for importing the data.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.import(\n * [\n * [ \"_key\", \"_from\", \"_to\", \"weight\" ],\n * [ \"x\", \"vertices/a\", \"vertices/b\", 1 ],\n * [ \"y\", \"vertices/a\", \"vertices/c\", 2 ]\n * ]\n * );\n * ```\n */\n import(\n data: any[][],\n options?: CollectionImportOptions\n ): Promise<CollectionImportResult>;\n /**\n * Bulk imports the given `data` into the collection.\n *\n * If `type` is omitted, `data` must contain one JSON array per line with\n * the first array providing the attribute names and all other arrays\n * providing attribute values for each edge document.\n *\n * If `type` is set to `\"documents\"`, `data` must contain one JSON document\n * per line.\n *\n * If `type` is set to `\"list\"`, `data` must contain a JSON array of\n * edge documents.\n *\n * If `type` is set to `\"auto\"`, `data` can be in either of the formats\n * supported by `\"documents\"` or `\"list\"`.\n *\n * @param data - The data to import as a Buffer (Node), Blob (browser) or\n * string.\n * @param options - Options for importing the data.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.import(\n * '{\"_key\":\"x\",\"_from\":\"vertices/a\",\"_to\":\"vertices/b\",\"weight\":1}\\r\\n' +\n * '{\"_key\":\"y\",\"_from\":\"vertices/a\",\"_to\":\"vertices/c\",\"weight\":2}\\r\\n',\n * { type: \"documents\" } // or \"auto\"\n * );\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.import(\n * '[{\"_key\":\"x\",\"_from\":\"vertices/a\",\"_to\":\"vertices/b\",\"weight\":1},' +\n * '{\"_key\":\"y\",\"_from\":\"vertices/a\",\"_to\":\"vertices/c\",\"weight\":2}]',\n * { type: \"list\" } // or \"auto\"\n * );\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.import(\n * '[\"_key\",\"_from\",\"_to\",\"weight\"]\\r\\n' +\n * '[\"x\",\"vertices/a\",\"vertices/b\",1]\\r\\n' +\n * '[\"y\",\"vertices/a\",\"vertices/c\",2]\\r\\n'\n * );\n * ```\n */\n import(\n data: Buffer | Blob | string,\n options?: CollectionImportOptions & {\n type?: \"documents\" | \"list\" | \"auto\";\n }\n ): Promise<CollectionImportResult>;\n //#endregion\n\n //#region simple queries\n\n /**\n * Retrieves all documents in the collection.\n *\n * @param options - Options for retrieving the documents.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const cursor = await collection.all();\n * const cursor = await db.query(aql`\n * FOR doc IN ${collection}\n * RETURN doc\n * `);\n * ```\n */\n all(options?: SimpleQueryAllOptions): Promise<ArrayCursor<Edge<T>>>;\n\n /**\n * Retrieves a random document from the collection.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const doc = await collection.any();\n * const cursor = await db.query(aql`\n * FOR doc IN ${collection}\n * SORT RAND()\n * LIMIT 1\n * RETURN doc\n * `);\n * const doc = await cursor.next();\n * ```\n */\n any(): Promise<Edge<T>>;\n\n /**\n * Retrieves all documents in the collection matching the given example.\n *\n * @param example - An object representing an example for documents.\n * @param options - Options for retrieving the documents.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const cursor = await collection.byExample({ flavor: \"strawberry\" });\n * const cursor = await db.query(aql`\n * FOR doc IN ${collection}\n * FILTER doc.flavor == \"strawberry\"\n * RETURN doc\n * `);\n * ```\n */\n byExample(\n example: Partial<DocumentData<T>>,\n options?: SimpleQueryByExampleOptions\n ): Promise<ArrayCursor<Edge<T>>>;\n\n /**\n * Retrieves a single document in the collection matching the given example.\n *\n * @param example - An object representing an example for the document.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const doc = await collection.firstExample({ flavor: \"strawberry\" });\n * const cursor = await db.query(aql`\n * FOR doc IN ${collection}\n * FILTER doc.flavor == \"strawberry\"\n * LIMIT 1\n * RETURN doc\n * `);\n * const doc = await cursor.next();\n * ```\n */\n firstExample(example: Partial<DocumentData<T>>): Promise<Edge<T>>;\n\n /**\n * Retrieves all documents matching the given document keys.\n *\n * @param keys - An array of document keys to look up.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const keys = [\"a\", \"b\", \"c\"];\n * // const docs = await collection.byKeys(keys);\n * const cursor = await db.query(aql`\n * FOR key IN ${keys}\n * LET doc = DOCUMENT(${collection}, key)\n * RETURN doc\n * `);\n * const docs = await cursor.all();\n * ```\n */\n lookupByKeys(keys: string[]): Promise<Edge<T>[]>;\n\n /**\n * Performs a fulltext query in the given `attribute` on the collection.\n *\n * @param attribute - Name of the field to search.\n * @param query - Fulltext query string to search for.\n * @param options - Options for performing the fulltext query.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const cursor = await collection.fulltext(\"article\", \"needle\");\n * const cursor = await db.query(aql`\n * FOR doc IN FULLTEXT(${collection}, \"article\", \"needle\")\n * RETURN doc\n * `);\n * ```\n */\n fulltext(\n attribute: string,\n query: string,\n options?: SimpleQueryFulltextOptions\n ): Promise<ArrayCursor<Edge<T>>>;\n //#endregion\n\n //#region edges\n /**\n * Retrieves a list of all edges of the document matching the given\n * `selector`.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param options - Options for retrieving the edges.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"edges\");\n * await collection.import([\n * [\"_key\", \"_from\", \"_to\"],\n * [\"x\", \"vertices/a\", \"vertices/b\"],\n * [\"y\", \"vertices/a\", \"vertices/c\"],\n * [\"z\", \"vertices/d\", \"vertices/a\"],\n * ]);\n * const edges = await collection.edges(\"vertices/a\");\n * console.log(edges.map((edge) => edge._key)); // [\"x\", \"y\", \"z\"]\n * ```\n */\n edges(\n selector: DocumentSelector,\n options: CollectionEdgesOptions\n ): Promise<ArangoApiResponse<CollectionEdgesResult<T>>>;\n /**\n * Retrieves a list of all incoming edges of the document matching the given\n * `selector`.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param options - Options for retrieving the edges.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"edges\");\n * await collection.import([\n * [\"_key\", \"_from\", \"_to\"],\n * [\"x\", \"vertices/a\", \"vertices/b\"],\n * [\"y\", \"vertices/a\", \"vertices/c\"],\n * [\"z\", \"vertices/d\", \"vertices/a\"],\n * ]);\n * const edges = await collection.inEdges(\"vertices/a\");\n * console.log(edges.map((edge) => edge._key)); // [\"z\"]\n * ```\n */\n inEdges(\n selector: DocumentSelector,\n options: CollectionEdgesOptions\n ): Promise<ArangoApiResponse<CollectionEdgesResult<T>>>;\n /**\n * Retrieves a list of all outgoing edges of the document matching the given\n * `selector`.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param options - Options for retrieving the edges.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"edges\");\n * await collection.import([\n * [\"_key\", \"_from\", \"_to\"],\n * [\"x\", \"vertices/a\", \"vertices/b\"],\n * [\"y\", \"vertices/a\", \"vertices/c\"],\n * [\"z\", \"vertices/d\", \"vertices/a\"],\n * ]);\n * const edges = await collection.outEdges(\"vertices/a\");\n * console.log(edges.map((edge) => edge._key)); // [\"x\", \"y\"]\n * ```\n */\n outEdges(\n selector: DocumentSelector,\n options: CollectionEdgesOptions\n ): Promise<ArangoApiResponse<CollectionEdgesResult<T>>>;\n\n /**\n * Performs a traversal starting from the given `startVertex` and following\n * edges contained in this edge collection.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * See also {@link graph.Graph#traversal}.\n *\n * @param startVertex - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param options - Options for performing the traversal.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"edges\");\n * await collection.import([\n * [\"_key\", \"_from\", \"_to\"],\n * [\"x\", \"vertices/a\", \"vertices/b\"],\n * [\"y\", \"vertices/b\", \"vertices/c\"],\n * [\"z\", \"vertices/c\", \"vertices/d\"],\n * ]);\n * const startVertex = \"vertices/a\";\n * const cursor = await db.query(aql`\n * FOR vertex IN OUTBOUND ${startVertex}\n * RETURN vertex._key\n * `);\n * const result = await cursor.all();\n * console.log(result); // [\"a\", \"b\", \"c\", \"d\"]\n * ```\n */\n traversal(\n startVertex: DocumentSelector,\n options?: TraversalOptions\n ): Promise<any>;\n //#endregion\n}\n\n/**\n * @internal\n */\nexport class Collection<T extends Record<string, any> = any>\n implements EdgeCollection<T>, DocumentCollection<T>\n{\n //#region attributes\n protected _name: string;\n protected _db: Database;\n //#endregion\n\n /**\n * @internal\n */\n constructor(db: Database, name: string) {\n this._name = name.normalize(\"NFC\");\n this._db = db;\n }\n\n //#region metadata\n get isArangoCollection(): true {\n return true;\n }\n\n get name() {\n return this._name;\n }\n\n get() {\n return this._db.request({\n path: `/_api/collection/${encodeURIComponent(this._name)}`,\n });\n }\n\n async exists() {\n try {\n await this.get();\n return true;\n } catch (err: any) {\n if (isArangoError(err) && err.errorNum === COLLECTION_NOT_FOUND) {\n return false;\n }\n throw err;\n }\n }\n\n create(\n options: CreateCollectionOptions & {\n type?: CollectionType;\n } = {}\n ) {\n const {\n waitForSyncReplication = undefined,\n enforceReplicationFactor = undefined,\n ...opts\n } = options;\n if (opts.computedValues) {\n opts.computedValues = opts.computedValues.map((computedValue) => {\n if (isAqlLiteral(computedValue.expression)) {\n return {\n ...computedValue,\n expression: computedValue.expression.toAQL(),\n };\n }\n if (isAqlQuery(computedValue.expression)) {\n return {\n ...computedValue,\n expression: computedValue.expression.query,\n };\n }\n return computedValue;\n });\n }\n const qs: Params = {};\n if (typeof waitForSyncReplication === \"boolean\") {\n qs.waitForSyncReplication = waitForSyncReplication ? 1 : 0;\n }\n if (typeof enforceReplicationFactor === \"boolean\") {\n qs.enforceReplicationFactor = enforceReplicationFactor ? 1 : 0;\n }\n return this._db.request({\n method: \"POST\",\n path: \"/_api/collection\",\n qs,\n body: {\n ...opts,\n name: this._name,\n },\n });\n }\n\n properties(\n properties?: CollectionPropertiesOptions\n ): Promise<ArangoApiResponse<CollectionMetadata & CollectionProperties>> {\n if (!properties) {\n return this._db.request({\n path: `/_api/collection/${encodeURIComponent(this._name)}/properties`,\n });\n }\n return this._db.request({\n method: \"PUT\",\n path: `/_api/collection/${encodeURIComponent(this._name)}/properties`,\n body: properties,\n });\n }\n\n count(): Promise<\n ArangoApiResponse<\n CollectionMetadata & CollectionProperties & { count: number }\n >\n > {\n return this._db.request({\n path: `/_api/collection/${encodeURIComponent(this._name)}/count`,\n });\n }\n\n async recalculateCount(): Promise<boolean> {\n return this._db.request(\n {\n method: \"PUT\",\n path: `/_api/collection/${encodeURIComponent(\n this._name\n )}/recalculateCount`,\n },\n (res) => res.body.result\n );\n }\n\n figures(\n details = false\n ): Promise<\n CollectionMetadata &\n ArangoApiResponse<\n CollectionProperties & { count: number; figures: Record<string, any> }\n >\n > {\n return this._db.request({\n path: `/_api/collection/${encodeURIComponent(this._name)}/figures`,\n qs: { details },\n });\n }\n\n revision(): Promise<\n ArangoApiResponse<\n CollectionMetadata & CollectionProperties & { revision: string }\n >\n > {\n return this._db.request({\n path: `/_api/collection/${encodeURIComponent(this._name)}/revision`,\n });\n }\n\n checksum(\n options?: CollectionChecksumOptions\n ): Promise<\n ArangoApiResponse<\n CollectionMetadata & { revision: string; checksum: string }\n >\n > {\n return this._db.request({\n path: `/_api/collection/${encodeURIComponent(this._name)}/checksum`,\n qs: options,\n });\n }\n\n async loadIndexes(): Promise<boolean> {\n return this._db.request(\n {\n method: \"PUT\",\n path: `/_api/collection/${encodeURIComponent(\n this._name\n )}/loadIndexesIntoMemory`,\n },\n (res) => res.body.result\n );\n }\n\n async rename(newName: string) {\n const result = await this._db.renameCollection(this._name, newName);\n this._name = newName.normalize(\"NFC\");\n return result;\n }\n\n truncate(): Promise<ArangoApiResponse<CollectionMetadata>> {\n return this._db.request({\n method: \"PUT\",\n path: `/_api/collection/${this._name}/truncate`,\n });\n }\n\n drop(options?: CollectionDropOptions) {\n return this._db.request({\n method: \"DELETE\",\n path: `/_api/collection/${encodeURIComponent(this._name)}`,\n qs: options,\n });\n }\n //#endregion\n\n //#region crud\n getResponsibleShard(document: Partial<Document<T>>): Promise<string> {\n return this._db.request(\n {\n method: \"PUT\",\n path: `/_api/collection/${encodeURIComponent(\n this._name\n )}/responsibleShard`,\n body: document,\n },\n (res) => res.body.shardId\n );\n }\n\n documentId(selector: DocumentSelector): string {\n return _documentHandle(selector, this._name);\n }\n\n async documentExists(\n selector: DocumentSelector,\n options: DocumentExistsOptions = {}\n ): Promise<boolean> {\n const { ifMatch = undefined, ifNoneMatch = undefined } = options;\n const headers = {} as Record<string, string>;\n if (ifMatch) headers[\"if-match\"] = ifMatch;\n if (ifNoneMatch) headers[\"if-none-match\"] = ifNoneMatch;\n try {\n return await this._db.request(\n {\n method: \"HEAD\",\n path: `/_api/document/${encodeURI(\n _documentHandle(selector, this._name)\n )}`,\n headers,\n },\n (res) => {\n if (ifNoneMatch && res.statusCode === 304) {\n throw new HttpError(res);\n }\n return true;\n }\n );\n } catch (err: any) {\n if (err.code === 404) {\n return false;\n }\n throw err;\n }\n }\n\n documents(\n selectors: (string | ObjectWithKey)[],\n options: CollectionBatchReadOptions = {}\n ) {\n const { allowDirtyRead = undefined } = options;\n return this._db.request({\n method: \"PUT\",\n path: `/_api/document/${encodeURIComponent(this._name)}`,\n qs: { onlyget: true },\n allowDirtyRead,\n body: selectors,\n });\n }\n\n async document(\n selector: DocumentSelector,\n options: boolean | CollectionReadOptions = {}\n ) {\n if (typeof options === \"boolean\") {\n options = { graceful: options };\n }\n const {\n allowDirtyRead = undefined,\n graceful = false,\n ifMatch = undefined,\n ifNoneMatch = undefined,\n } = options;\n const headers = {} as Record<string, string>;\n if (ifMatch) headers[\"if-match\"] = ifMatch;\n if (ifNoneMatch) headers[\"if-none-match\"] = ifNoneMatch;\n const result = this._db.request(\n {\n path: `/_api/document/${encodeURI(\n _documentHandle(selector, this._name)\n )}`,\n headers,\n allowDirtyRead,\n },\n (res) => {\n if (ifNoneMatch && res.statusCode === 304) {\n throw new HttpError(res);\n }\n return res.body;\n }\n );\n if (!graceful) return result;\n try {\n return await result;\n } catch (err: any) {\n if (isArangoError(err) && err.errorNum === DOCUMENT_NOT_FOUND) {\n return null;\n }\n throw err;\n }\n }\n\n save(data: DocumentData<T>, options?: CollectionInsertOptions) {\n return this._db.request(\n {\n method: \"POST\",\n path: `/_api/document/${encodeURIComponent(this._name)}`,\n body: data,\n qs: options,\n },\n (res) => (options?.silent ? undefined : res.body)\n );\n }\n\n saveAll(data: Array<DocumentData<T>>, options?: CollectionInsertOptions) {\n return this._db.request(\n {\n method: \"POST\",\n path: `/_api/document/${encodeURIComponent(this._name)}`,\n body: data,\n qs: options,\n },\n (res) => (options?.silent ? undefined : res.body)\n );\n }\n\n replace(\n selector: DocumentSelector,\n newData: DocumentData<T>,\n options: CollectionReplaceOptions = {}\n ) {\n const { ifMatch = undefined, ...opts } = options;\n const headers = {} as Record<string, string>;\n if (ifMatch) headers[\"if-match\"] = ifMatch;\n return this._db.request(\n {\n method: \"PUT\",\n path: `/_api/document/${encodeURI(\n _documentHandle(selector, this._name)\n )}`,\n headers,\n body: newData,\n qs: opts,\n },\n (res) => (options?.silent ? undefined : res.body)\n );\n }\n\n replaceAll(\n newData: Array<DocumentData<T> & ({ _key: string } | { _id: string })>,\n options?: CollectionReplaceOptions\n ) {\n return this._db.request(\n {\n method: \"PUT\",\n path: `/_api/document/${encodeURIComponent(this._name)}`,\n body: newData,\n qs: options,\n },\n (res) => (options?.silent ? undefined : res.body)\n );\n }\n\n update(\n selector: DocumentSelector,\n newData: Patch<DocumentData<T>>,\n options: CollectionUpdateOptions = {}\n ) {\n const { ifMatch = undefined, ...opts } = options;\n const headers = {} as Record<string, string>;\n if (ifMatch) headers[\"if-match\"] = ifMatch;\n return this._db.request(\n {\n method: \"PATCH\",\n path: `/_api/document/${encodeURI(\n _documentHandle(selector, this._name)\n )}`,\n headers,\n body: newData,\n qs: opts,\n },\n (res) => (options?.silent ? undefined : res.body)\n );\n }\n\n updateAll(\n newData: Array<\n Patch<DocumentData<T>> & ({ _key: string } | { _id: string })\n >,\n options?: CollectionUpdateOptions\n ) {\n return this._db.request(\n {\n method: \"PATCH\",\n path: `/_api/document/${encodeURIComponent(this._name)}`,\n body: newData,\n qs: options,\n },\n (res) => (options?.silent ? undefined : res.body)\n );\n }\n\n remove(selector: DocumentSelector, options: CollectionRemoveOptions = {}) {\n const { ifMatch = undefined, ...opts } = options;\n const headers = {} as Record<string, string>;\n if (ifMatch) headers[\"if-match\"] = ifMatch;\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/document/${encodeURI(\n _documentHandle(selector, this._name)\n )}`,\n headers,\n qs: opts,\n },\n (res) => (options?.silent ? undefined : res.body)\n );\n }\n\n removeAll(\n selectors: (string | ObjectWithKey)[],\n options?: CollectionRemoveOptions\n ) {\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/document/${encodeURIComponent(this._name)}`,\n body: selectors,\n qs: options,\n },\n (res) => (options?.silent ? undefined : res.body)\n );\n }\n\n import(\n data: Buffer | Blob | string | any[],\n options: CollectionImportOptions & {\n type?: \"documents\" | \"list\" | \"auto\";\n } = {}\n ): Promise<CollectionImportResult> {\n const qs = { ...options, collection: this._name };\n if (Array.isArray(data)) {\n qs.type = Array.isArray(data[0]) ? undefined : \"documents\";\n const lines = data as any[];\n data = lines.map((line) => JSON.stringify(line)).join(\"\\r\\n\") + \"\\r\\n\";\n }\n return this._db.request({\n method: \"POST\",\n path: \"/_api/import\",\n body: data,\n isBinary: true,\n qs,\n });\n }\n //#endregion\n\n //#region edges\n protected _edges(\n selector: DocumentSelector,\n options: CollectionEdgesOptions,\n direction?: \"in\" | \"out\"\n ) {\n const { allowDirtyRead = undefined } = options;\n return this._db.request({\n path: `/_api/edges/${encodeURIComponent(this._name)}`,\n allowDirtyRead,\n qs: {\n direction,\n vertex: _documentHandle(selector, this._name, false),\n },\n });\n }\n\n edges(vertex: DocumentSelector, options: CollectionEdgesOptions) {\n return this._edges(vertex, options);\n }\n\n inEdges(vertex: DocumentSelector, options: CollectionEdgesOptions) {\n return this._edges(vertex, options, \"in\");\n }\n\n outEdges(vertex: DocumentSelector, options: CollectionEdgesOptions) {\n return this._edges(vertex, options, \"out\");\n }\n\n traversal(startVertex: DocumentSelector, options?: TraversalOptions) {\n return this._db.request(\n {\n method: \"POST\",\n path: \"/_api/traversal\",\n body: {\n ...options,\n startVertex,\n edgeCollection: this._name,\n },\n },\n (res) => res.body.result\n );\n }\n //#endregion\n\n //#region simple queries\n list(type: SimpleQueryListType = \"id\") {\n return this._db.request(\n {\n method: \"PUT\",\n path: \"/_api/simple/all-keys\",\n body: { type, collection: this._name },\n },\n (res) =>\n new BatchedArrayCursor(this._db, res.body, res.arangojsHostUrl).items\n );\n }\n\n all(options?: SimpleQueryAllOptions) {\n return this._db.request(\n {\n method: \"PUT\",\n path: \"/_api/simple/all\",\n body: {\n ...options,\n collection: this._name,\n },\n },\n (res) =>\n new BatchedArrayCursor(this._db, res.body, res.arangojsHostUrl).items\n );\n }\n\n any() {\n return this._db.request(\n {\n method: \"PUT\",\n path: \"/_api/simple/any\",\n body: { collection: this._name },\n },\n (res) => res.body.document\n );\n }\n\n byExample(\n example: Partial<DocumentData<T>>,\n options?: SimpleQueryByExampleOptions\n ) {\n return this._db.request(\n {\n method: \"PUT\",\n path: \"/_api/simple/by-example\",\n body: {\n ...options,\n example,\n collection: this._name,\n },\n },\n (res) =>\n new BatchedArrayCursor(this._db, res.body, res.arangojsHostUrl).items\n );\n }\n\n firstExample(example: Partial<DocumentData<T>>) {\n return this._db.request(\n {\n method: \"PUT\",\n path: \"/_api/simple/first-example\",\n body: {\n example,\n collection: this._name,\n },\n },\n (res) => res.body.document\n );\n }\n\n removeByExample(\n example: Partial<DocumentData<T>>,\n options?: SimpleQueryRemoveByExampleOptions\n ) {\n return this._db.request({\n method: \"PUT\",\n path: \"/_api/simple/remove-by-example\",\n body: {\n ...options,\n example,\n collection: this._name,\n },\n });\n }\n\n replaceByExample(\n example: Partial<DocumentData<T>>,\n newValue: DocumentData<T>,\n options?: SimpleQueryReplaceByExampleOptions\n ) {\n return this._db.request({\n method: \"PUT\",\n path: \"/_api/simple/replace-by-example\",\n body: {\n ...options,\n example,\n newValue,\n collection: this._name,\n },\n });\n }\n\n updateByExample(\n example: Partial<DocumentData<T>>,\n newValue: Patch<DocumentData<T>>,\n options?: SimpleQueryUpdateByExampleOptions\n ) {\n return this._db.request({\n method: \"PUT\",\n path: \"/_api/simple/update-by-example\",\n body: {\n ...options,\n example,\n newValue,\n collection: this._name,\n },\n });\n }\n\n lookupByKeys(keys: string[]) {\n return this._db.request(\n {\n method: \"PUT\",\n path: \"/_api/simple/lookup-by-keys\",\n body: {\n keys,\n collection: this._name,\n },\n },\n (res) => res.body.documents\n );\n }\n\n removeByKeys(keys: string[], options?: SimpleQueryRemoveByKeysOptions) {\n return this._db.request({\n method: \"PUT\",\n path: \"/_api/simple/remove-by-keys\",\n body: {\n options: options,\n keys,\n collection: this._name,\n },\n });\n }\n //#endregion\n\n //#region indexes\n indexes() {\n return this._db.request(\n {\n path: \"/_api/index\",\n qs: { collection: this._name },\n },\n (res) => res.body.indexes\n );\n }\n\n index(selector: IndexSelector) {\n return this._db.request({\n path: `/_api/index/${encodeURI(_indexHandle(selector, this._name))}`,\n });\n }\n\n ensureIndex(\n options:\n | EnsurePersistentIndexOptions\n | EnsureGeoIndexOptions\n | EnsureFulltextIndexOptions\n | EnsureTtlIndexOptions\n | EnsureZkdIndexOptions\n | EnsureInvertedIndexOptions\n ) {\n return this._db.request({\n method: \"POST\",\n path: \"/_api/index\",\n body: options,\n qs: { collection: this._name },\n });\n }\n\n dropIndex(selector: IndexSelector) {\n return this._db.request({\n method: \"DELETE\",\n path: `/_api/index/${encodeURI(_indexHandle(selector, this._name))}`,\n });\n }\n\n fulltext(\n attribute: string,\n query: string,\n { index, ...options }: SimpleQueryFulltextOptions = {}\n ) {\n return this._db.request(\n {\n method: \"PUT\",\n path: \"/_api/simple/fulltext\",\n body: {\n ...options,\n index: index ? _indexHandle(index, this._name) : undefined,\n attribute,\n query,\n collection: this._name,\n },\n },\n (res) =>\n new BatchedArrayCursor(this._db, res.body, res.arangojsHostUrl).items\n );\n }\n\n compact() {\n return this._db.request(\n {\n method: \"PUT\",\n path: `/_api/collection/${this._name}/compact`,\n },\n (res) => res.body\n );\n }\n //#endregion\n}\n","/**\n * ```ts\n * import type { ArrayCursor, BatchedArrayCursor } from \"arangojs/cursor\";\n * ```\n *\n * The \"cursor\" module provides cursor-related interfaces for TypeScript.\n *\n * @packageDocumentation\n */\nimport { LinkedList } from \"x3-linkedlist\";\nimport { Database } from \"./database\";\n\n/**\n * Additional information about the cursor.\n */\nexport interface CursorExtras {\n /**\n * Warnings encountered while executing the query.\n */\n warnings: {\n code: number;\n message: string;\n }[];\n /**\n * Query execution plan for the executed query.\n */\n plan?: Record<string, any>;\n /**\n * Additional profiling information for the executed query.\n */\n profile?: Record<string, number>;\n /**\n * Additional statistics about the query execution.\n */\n stats?: CursorStats;\n}\n\n/**\n * Additional statics about the query execution of the cursor.\n */\nexport interface CursorStats {\n /**\n * Total number of index entries read from in-memory caches for indexes of\n * type edge or persistent.\n */\n cacheHits: number;\n /**\n * Total number of cache read attempts for index entries that could not be\n * served from in-memory caches for indexes of type edge or persistent.\n */\n cacheMisses: number;\n /**\n * Total number of cursor objects created during query execution.\n */\n cursorsCreated: number;\n /**\n * Total number of times an existing cursor object was repurposed.\n */\n cursorsRearmed: number;\n /**\n * Total number of data-modification operations successfully executed.\n */\n writesExecuted: number;\n /**\n * Total number of data-modification operations that were unsuccessful, but have been ignored because of query option ignoreErrors.\n */\n writesIgnored: number;\n /**\n * Total number of documents iterated over when scanning a collection without an index.\n */\n scannedFull: number;\n /**\n * Total number of documents iterated over when scanning a collection using an index.\n */\n scannedIndex: number;\n /**\n * Total number of documents that were removed after executing a filter condition in a FilterNode.\n */\n filtered: number;\n /**\n * Maximum memory usage of the query while it was running.\n */\n peakMemoryUsage: number;\n /**\n * Execution time of the query in seconds.\n */\n executionTime: number;\n /**\n * Total number of documents that matched the search condition if the query’s final top-level LIMIT statement were not present.\n */\n fullCount?: number;\n /**\n * Total number of cluster-internal HTTP requests performed.\n */\n httpRequests: number;\n /**\n * Runtime statistics per query execution node if `profile` was set to `2` or greater.\n */\n nodes?: {\n /**\n * Execution node ID to correlate this node with nodes in the `extra.plan`.\n */\n id: number;\n /**\n * Number of calls in this node.\n */\n calls: number;\n /**\n * Number of temporary result items returned by this node.\n */\n items: number;\n filter: number;\n /**\n * Execution time of this node in seconds.\n */\n runtime: number;\n }[];\n}\n\ninterface BatchView<T = any> {\n isEmpty: boolean;\n more(): Promise<void>;\n shift(): T | undefined;\n}\n\n/**\n * The `BatchedArrayCursor` provides a batch-wise API to an {@link ArrayCursor}.\n *\n * When using TypeScript, cursors can be cast to a specific item type in order\n * to increase type safety.\n *\n * @param T - Type to use for each item. Defaults to `any`.\n *\n * @example\n * ```ts\n * const db = new Database();\n * const query = aql`FOR x IN 1..5 RETURN x`;\n * const cursor = await db.query(query) as ArrayCursor<number>;\n * const batches = cursor.batches;\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const query = aql`FOR x IN 1..10000 RETURN x`;\n * const cursor = await db.query(query, { batchSize: 10 });\n * for await (const batch of cursor.batches) {\n * // Process all values in a batch in parallel\n * await Promise.all(batch.map(\n * value => asyncProcessValue(value)\n * ));\n * }\n * ```\n */\nexport class BatchedArrayCursor<T = any> {\n protected _db: Database;\n protected _batches: LinkedList<LinkedList<any>>;\n protected _count?: number;\n protected _extra: CursorExtras;\n protected _hasMore: boolean;\n protected _id: string | undefined;\n protected _hostUrl?: string;\n protected _allowDirtyRead?: boolean;\n protected _itemsCursor: ArrayCursor<T>;\n\n /**\n * @internal\n */\n constructor(\n db: Database,\n body: {\n extra: any;\n result: T[];\n hasMore: boolean;\n id: string;\n count: number;\n },\n hostUrl?: string,\n allowDirtyRead?: boolean\n ) {\n const batches = new LinkedList(\n body.result.length ? [new LinkedList(body.result)] : []\n );\n this._db = db;\n this._batches = batches;\n this._id = body.id;\n this._hasMore = Boolean(body.id && body.hasMore);\n this._hostUrl = hostUrl;\n this._count = body.count;\n this._extra = body.extra;\n this._allowDirtyRead = allowDirtyRead;\n this._itemsCursor = new ArrayCursor(this, {\n get isEmpty() {\n return !batches.length;\n },\n more: () => this._more(),\n shift: () => {\n let batch = batches.first?.value;\n while (batch && !batch.length) {\n batches.shift();\n batch = batches.first?.value;\n }\n if (!batch) return undefined;\n const value = batch.shift();\n if (!batch.length) batches.shift();\n return value;\n },\n });\n }\n\n protected async _more(): Promise<void> {\n if (!this.hasMore) return;\n const body = await this._db.request({\n method: \"PUT\",\n path: `/_api/cursor/${encodeURIComponent(this._id!)}`,\n hostUrl: this._hostUrl,\n allowDirtyRead: this._allowDirtyRead,\n });\n this._batches.push(new LinkedList(body.result));\n this._hasMore = body.hasMore;\n }\n\n /**\n * An {@link ArrayCursor} providing item-wise access to the cursor result set.\n *\n * See also {@link ArrayCursor#batches}.\n */\n get items() {\n return this._itemsCursor;\n }\n\n /**\n * Additional information about the cursor.\n */\n get extra(): Readonly<CursorExtras> {\n return this._extra;\n }\n\n /**\n * Total number of documents in the query result. Only available if the\n * `count` option was used.\n */\n get count(): number | undefined {\n return this._count;\n }\n\n /**\n * Whether the cursor has any remaining batches that haven't yet been\n * fetched. If set to `false`, all batches have been fetched and no\n * additional requests to the server will be made when consuming any\n * remaining batches from this cursor.\n */\n get hasMore(): boolean {\n return this._hasMore;\n }\n\n /**\n * Whether the cursor has more batches. If set to `false`, the cursor has\n * already been depleted and contains no more batches.\n */\n get hasNext(): boolean {\n return this.hasMore || Boolean(this._batches.length);\n }\n\n /**\n * Enables use with `for await` to deplete the cursor by asynchronously\n * yielding every batch in the cursor's remaining result set.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`\n * FOR user IN users\n * FILTER user.isActive\n * RETURN user\n * `);\n * for await (const users of cursor.batches) {\n * for (const user of users) {\n * console.log(user.email, user.isAdmin);\n * }\n * }\n * ```\n */\n async *[Symbol.asyncIterator](): AsyncGenerator<T[], undefined, undefined> {\n while (this.hasNext) {\n yield this.next() as Promise<T[]>;\n }\n return undefined;\n }\n\n /**\n * Loads all remaining batches from the server.\n *\n * **Warning**: This may impact memory use when working with very large\n * query result sets.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 1 }\n * );\n * console.log(cursor.hasMore); // true\n * await cursor.batches.loadAll();\n * console.log(cursor.hasMore); // false\n * console.log(cursor.hasNext); // true\n * for await (const item of cursor) {\n * console.log(item);\n * // No server roundtrips necessary any more\n * }\n * ```\n */\n async loadAll(): Promise<void> {\n while (this._hasMore) {\n await this._more();\n }\n }\n\n /**\n * Depletes the cursor, then returns an array containing all batches in the\n * cursor's remaining result list.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * const result = await cursor.batches.all(); // [[1, 2], [3, 4], [5]]\n * console.log(cursor.hasNext); // false\n * ```\n */\n async all(): Promise<T[][]> {\n return this.map((batch) => batch);\n }\n\n /**\n * Advances the cursor and returns all remaining values in the cursor's\n * current batch. If the current batch has already been exhausted, fetches\n * the next batch from the server and returns it, or `undefined` if the\n * cursor has been depleted.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR i IN 1..10 RETURN i`,\n * { batchSize: 5 }\n * );\n * const firstBatch = await cursor.batches.next(); // [1, 2, 3, 4, 5]\n * await cursor.next(); // 6\n * const lastBatch = await cursor.batches.next(); // [7, 8, 9, 10]\n * console.log(cursor.hasNext); // false\n * ```\n */\n async next(): Promise<T[] | undefined> {\n while (!this._batches.length && this.hasNext) {\n await this._more();\n }\n if (!this._batches.length) {\n return undefined;\n }\n const batch = this._batches.shift();\n if (!batch) return undefined;\n const values = [...batch.values()];\n batch.clear(true);\n return values;\n }\n\n /**\n * Advances the cursor by applying the `callback` function to each item in\n * the cursor's remaining result list until the cursor is depleted or\n * `callback` returns the exact value `false`. Returns a promise that\n * evalues to `true` unless the function returned `false`.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * [`Array.prototype.forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach).\n *\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * const result = await cursor.batches.forEach((currentBatch) => {\n * for (const value of currentBatch) {\n * console.log(value);\n * }\n * });\n * console.log(result) // true\n * console.log(cursor.hasNext); // false\n * ```\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * const result = await cursor.batches.forEach((currentBatch) => {\n * for (const value of currentBatch) {\n * console.log(value);\n * }\n * return false; // stop after the first batch\n * });\n * console.log(result); // false\n * console.log(cursor.hasNext); // true\n * ```\n */\n async forEach(\n callback: (currentBatch: T[], index: number, self: this) => false | void\n ): Promise<boolean> {\n let index = 0;\n while (this.hasNext) {\n const currentBatch = await this.next();\n const result = callback(currentBatch!, index, this);\n index++;\n if (result === false) return result;\n if (this.hasNext) await this._more();\n }\n return true;\n }\n\n /**\n * Depletes the cursor by applying the `callback` function to each batch in\n * the cursor's remaining result list. Returns an array containing the\n * return values of `callback` for each batch.\n *\n * **Note**: This creates an array of all return values, which may impact\n * memory use when working with very large query result sets. Consider using\n * {@link BatchedArrayCursor#forEach}, {@link BatchedArrayCursor#reduce} or\n * {@link BatchedArrayCursor#flatMap} instead.\n *\n * See also:\n * [`Array.prototype.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map).\n *\n * @param R - Return type of the `callback` function.\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * const squares = await cursor.batches.map((currentBatch) => {\n * return currentBatch.map((value) => value ** 2);\n * });\n * console.log(squares); // [[1, 4], [9, 16], [25]]\n * console.log(cursor.hasNext); // false\n * ```\n */\n async map<R>(\n callback: (currentBatch: T[], index: number, self: this) => R\n ): Promise<R[]> {\n let index = 0;\n const result: any[] = [];\n while (this.hasNext) {\n const currentBatch = await this.next();\n result.push(callback(currentBatch!, index, this));\n index++;\n }\n return result;\n }\n\n /**\n * Depletes the cursor by applying the `callback` function to each batch in\n * the cursor's remaining result list. Returns an array containing the\n * return values of `callback` for each batch, flattened to a depth of 1.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * [`Array.prototype.flatMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap).\n *\n * @param R - Return type of the `callback` function.\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * const squares = await cursor.batches.flatMap((currentBatch) => {\n * return currentBatch.map((value) => value ** 2);\n * });\n * console.log(squares); // [1, 1, 2, 4, 3, 9, 4, 16, 5, 25]\n * console.log(cursor.hasNext); // false\n * ```\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 1 }\n * );\n * const odds = await cursor.batches.flatMap((currentBatch) => {\n * if (currentBatch[0] % 2 === 0) {\n * return []; // empty array flattens into nothing\n * }\n * return currentBatch;\n * });\n * console.logs(odds); // [1, 3, 5]\n * ```\n */\n async flatMap<R>(\n callback: (currentBatch: T[], index: number, self: this) => R | R[]\n ): Promise<R[]> {\n let index = 0;\n const result: any[] = [];\n while (this.hasNext) {\n const currentBatch = await this.next();\n const value = callback(currentBatch!, index, this);\n if (Array.isArray(value)) {\n result.push(...value);\n } else {\n result.push(value);\n }\n index++;\n }\n return result;\n }\n\n /**\n * Depletes the cursor by applying the `reducer` function to each batch in\n * the cursor's remaining result list. Returns the return value of `reducer`\n * for the last batch.\n *\n * **Note**: Most complex uses of the `reduce` method can be replaced with\n * simpler code using {@link BatchedArrayCursor#forEach} or the `for await`\n * syntax.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * [`Array.prototype.reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce).\n *\n * @param R - Return type of the `reducer` function.\n * @param reducer - Function to execute on each element.\n * @param initialValue - Initial value of the `accumulator` value passed to\n * the `reducer` function.\n *\n * @example\n * ```js\n * function largestValue(baseline, values) {\n * return Math.max(baseline, ...values);\n * }\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 3 }\n * );\n * const result = await cursor.batches.reduce(largestValue, 0);\n * console.log(result); // 5\n * console.log(cursor.hasNext); // false\n * const emptyResult = await cursor.batches.reduce(largestValue, 0);\n * console.log(emptyResult); // 0\n * ```\n *\n * @example\n * ```js\n * // BAD! NEEDLESSLY COMPLEX!\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 1 }\n * );\n * const result = await cursor.reduce((accumulator, currentBatch) => {\n * if (currentBatch[0] % 2 === 0) {\n * accumulator.even.push(...currentBatch);\n * } else {\n * accumulator.odd.push(...currentBatch);\n * }\n * return accumulator;\n * }, { odd: [], even: [] });\n * console.log(result); // { odd: [1, 3, 5], even: [2, 4] }\n *\n * // GOOD! MUCH SIMPLER!\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const odd = [];\n * const even = [];\n * for await (const currentBatch of cursor) {\n * if (currentBatch[0] % 2 === 0) {\n * even.push(...currentBatch);\n * } else {\n * odd.push(...currentBatch);\n * }\n * }\n * console.log({ odd, even }); // { odd: [1, 3, 5], even: [2, 4] }\n * ```\n */\n async reduce<R>(\n reducer: (\n accumulator: R,\n currentBatch: T[],\n index: number,\n self: this\n ) => R,\n initialValue: R\n ): Promise<R>;\n\n /**\n * Depletes the cursor by applying the `reducer` function to each batch in\n * the cursor's remaining result list. Returns the return value of `reducer`\n * for the last batch.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * [`Array.prototype.reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce).\n *\n * @param R - Return type of the `reducer` function.\n * @param reducer - Function to execute on each element.\n *\n * @example\n * ```js\n * function largestValue(values1, values2) {\n * return [Math.max(...values1, ...values2)];\n * }\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 3 }\n * );\n * const result = await cursor.batches.reduce(largestValue);\n * console.log(result); // [5]\n * console.log(cursor.hasNext); // false\n * ```\n *\n */\n async reduce<R>(\n reducer: (\n accumulator: T[] | R,\n currentBatch: T[],\n index: number,\n self: this\n ) => R\n ): Promise<R | undefined>;\n async reduce<R>(\n reducer: (\n accumulator: R,\n currentBatch: T[],\n index: number,\n self: this\n ) => R,\n initialValue?: R\n ): Promise<R | undefined> {\n let index = 0;\n if (!this.hasNext) return initialValue;\n if (initialValue === undefined) {\n initialValue = (await this.next()) as any;\n index += 1;\n }\n let value = initialValue as R;\n while (this.hasNext) {\n const currentBatch = await this.next();\n value = reducer(value, currentBatch!, index, this);\n index++;\n }\n return value;\n }\n\n /**\n * Drains the cursor and frees up associated database resources.\n *\n * This method has no effect if all batches have already been consumed.\n *\n * @example\n * ```js\n * const cursor1 = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * console.log(cursor1.hasMore); // false\n * await cursor1.kill(); // no effect\n *\n * const cursor2 = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * console.log(cursor2.hasMore); // true\n * await cursor2.kill(); // cursor is depleted\n * ```\n */\n async kill(): Promise<void> {\n if (this._batches.length) {\n for (const batch of this._batches.values()) {\n batch.clear();\n }\n this._batches.clear();\n }\n if (!this.hasNext) return undefined;\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/cursor/${encodeURIComponent(this._id!)}`,\n },\n () => {\n this._hasMore = false;\n return undefined;\n }\n );\n }\n}\n\n/**\n * The `ArrayCursor` type represents a cursor returned from a\n * {@link database.Database#query}.\n *\n * When using TypeScript, cursors can be cast to a specific item type in order\n * to increase type safety.\n *\n * See also {@link BatchedArrayCursor}.\n *\n * @param T - Type to use for each item. Defaults to `any`.\n *\n * @example\n * ```ts\n * const db = new Database();\n * const query = aql`FOR x IN 1..5 RETURN x`;\n * const result = await db.query(query) as ArrayCursor<number>;\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const query = aql`FOR x IN 1..10 RETURN x`;\n * const cursor = await db.query(query);\n * for await (const value of cursor) {\n * // Process each value asynchronously\n * await processValue(value);\n * }\n * ```\n */\nexport class ArrayCursor<T = any> {\n protected _batches: BatchedArrayCursor<T>;\n protected _view: BatchView<T>;\n\n /**\n * @internal\n */\n constructor(batchedCursor: BatchedArrayCursor, view: BatchView<T>) {\n this._batches = batchedCursor;\n this._view = view;\n }\n\n /**\n * A {@link BatchedArrayCursor} providing batch-wise access to the cursor\n * result set.\n *\n * See also {@link BatchedArrayCursor#items}.\n */\n get batches() {\n return this._batches;\n }\n\n /**\n * Additional information about the cursor.\n */\n get extra(): CursorExtras {\n return this.batches.extra;\n }\n\n /**\n * Total number of documents in the query result. Only available if the\n * `count` option was used.\n */\n get count(): number | undefined {\n return this.batches.count;\n }\n\n /**\n * Whether the cursor has more values. If set to `false`, the cursor has\n * already been depleted and contains no more items.\n */\n get hasNext(): boolean {\n return this.batches.hasNext;\n }\n\n /**\n * Enables use with `for await` to deplete the cursor by asynchronously\n * yielding every value in the cursor's remaining result set.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`\n * FOR user IN users\n * FILTER user.isActive\n * RETURN user\n * `);\n * for await (const user of cursor) {\n * console.log(user.email, user.isAdmin);\n * }\n * ```\n */\n async *[Symbol.asyncIterator](): AsyncGenerator<T, undefined, undefined> {\n while (this.hasNext) {\n yield this.next() as Promise<T>;\n }\n return undefined;\n }\n\n /**\n * Depletes the cursor, then returns an array containing all values in the\n * cursor's remaining result list.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.all(); // [1, 2, 3, 4, 5]\n * console.log(cursor.hasNext); // false\n * ```\n */\n async all(): Promise<T[]> {\n return this.batches.flatMap((v) => v);\n }\n\n /**\n * Advances the cursor and returns the next value in the cursor's remaining\n * result list, or `undefined` if the cursor has been depleted.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..3 RETURN x`);\n * const one = await cursor.next(); // 1\n * const two = await cursor.next(); // 2\n * const three = await cursor.next(); // 3\n * const empty = await cursor.next(); // undefined\n * ```\n */\n async next(): Promise<T | undefined> {\n while (this._view.isEmpty && this.batches.hasMore) {\n await this._view.more();\n }\n if (this._view.isEmpty) {\n return undefined;\n }\n return this._view.shift();\n }\n\n /**\n * Advances the cursor by applying the `callback` function to each item in\n * the cursor's remaining result list until the cursor is depleted or\n * `callback` returns the exact value `false`. Returns a promise that\n * evalues to `true` unless the function returned `false`.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * [`Array.prototype.forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach).\n *\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.forEach((currentValue) => {\n * console.log(currentValue);\n * });\n * console.log(result) // true\n * console.log(cursor.hasNext); // false\n * ```\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.forEach((currentValue) => {\n * console.log(currentValue);\n * return false; // stop after the first item\n * });\n * console.log(result); // false\n * console.log(cursor.hasNext); // true\n * ```\n */\n async forEach(\n callback: (currentValue: T, index: number, self: this) => false | void\n ): Promise<boolean> {\n let index = 0;\n while (this.hasNext) {\n const value = await this.next();\n const result = callback(value!, index, this);\n index++;\n if (result === false) return result;\n }\n return true;\n }\n\n /**\n * Depletes the cursor by applying the `callback` function to each item in\n * the cursor's remaining result list. Returns an array containing the\n * return values of `callback` for each item.\n *\n * **Note**: This creates an array of all return values, which may impact\n * memory use when working with very large query result sets. Consider using\n * {@link ArrayCursor#forEach}, {@link ArrayCursor#reduce} or\n * {@link ArrayCursor#flatMap} instead.\n *\n * See also:\n * [`Array.prototype.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map).\n *\n * @param R - Return type of the `callback` function.\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const squares = await cursor.map((currentValue) => {\n * return currentValue ** 2;\n * });\n * console.log(squares); // [1, 4, 9, 16, 25]\n * console.log(cursor.hasNext); // false\n * ```\n */\n async map<R>(\n callback: (currentValue: T, index: number, self: this) => R\n ): Promise<R[]> {\n let index = 0;\n const result: any[] = [];\n while (this.hasNext) {\n const value = await this.next();\n result.push(callback(value!, index, this));\n index++;\n }\n return result;\n }\n\n /**\n * Depletes the cursor by applying the `callback` function to each item in\n * the cursor's remaining result list. Returns an array containing the\n * return values of `callback` for each item, flattened to a depth of 1.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * [`Array.prototype.flatMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap).\n *\n * @param R - Return type of the `callback` function.\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const squares = await cursor.flatMap((currentValue) => {\n * return [currentValue, currentValue ** 2];\n * });\n * console.log(squares); // [1, 1, 2, 4, 3, 9, 4, 16, 5, 25]\n * console.log(cursor.hasNext); // false\n * ```\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const odds = await cursor.flatMap((currentValue) => {\n * if (currentValue % 2 === 0) {\n * return []; // empty array flattens into nothing\n * }\n * return currentValue; // or [currentValue]\n * });\n * console.logs(odds); // [1, 3, 5]\n * ```\n */\n async flatMap<R>(\n callback: (currentValue: T, index: number, self: this) => R | R[]\n ): Promise<R[]> {\n let index = 0;\n const result: any[] = [];\n while (this.hasNext) {\n const value = await this.next();\n const item = callback(value!, index, this);\n if (Array.isArray(item)) {\n result.push(...item);\n } else {\n result.push(item);\n }\n index++;\n }\n return result;\n }\n\n /**\n * Depletes the cursor by applying the `reducer` function to each item in\n * the cursor's remaining result list. Returns the return value of `reducer`\n * for the last item.\n *\n * **Note**: Most complex uses of the `reduce` method can be replaced with\n * simpler code using {@link ArrayCursor#forEach} or the `for await` syntax.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * [`Array.prototype.reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce).\n *\n * @param R - Return type of the `reducer` function.\n * @param reducer - Function to execute on each element.\n * @param initialValue - Initial value of the `accumulator` value passed to\n * the `reducer` function.\n *\n * @example\n * ```js\n * function largestOfTwo(one, two) {\n * return Math.max(one, two);\n * }\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.reduce(largestOfTwo, 0);\n * console.log(result); // 5\n * console.log(cursor.hasNext); // false\n * const emptyResult = await cursor.reduce(largestOfTwo, 0);\n * console.log(emptyResult); // 0\n * ```\n *\n * @example\n * ```js\n * // BAD! NEEDLESSLY COMPLEX!\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.reduce((accumulator, currentValue) => {\n * if (currentValue % 2 === 0) {\n * accumulator.even.push(...currentValue);\n * } else {\n * accumulator.odd.push(...currentValue);\n * }\n * return accumulator;\n * }, { odd: [], even: [] });\n * console.log(result); // { odd: [1, 3, 5], even: [2, 4] }\n *\n * // GOOD! MUCH SIMPLER!\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const odd = [];\n * const even = [];\n * for await (const currentValue of cursor) {\n * if (currentValue % 2 === 0) {\n * even.push(currentValue);\n * } else {\n * odd.push(currentValue);\n * }\n * }\n * console.log({ odd, even }); // { odd: [1, 3, 5], even: [2, 4] }\n * ```\n */\n async reduce<R>(\n reducer: (accumulator: R, currentValue: T, index: number, self: this) => R,\n initialValue: R\n ): Promise<R>;\n /**\n * Depletes the cursor by applying the `reducer` function to each item in\n * the cursor's remaining result list. Returns the return value of `reducer`\n * for the last item.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * [`Array.prototype.reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce).\n *\n * @param R - Return type of the `reducer` function.\n * @param reducer - Function to execute on each element.\n *\n * @example\n * ```js\n * function largestOfTwo(one, two) {\n * return Math.max(one, two);\n * }\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.reduce(largestOfTwo);\n * console.log(result); // 5\n * console.log(cursor.hasNext); // false\n * const emptyResult = await cursor.reduce(largestOfTwo);\n * console.log(emptyResult); // undefined\n * ```\n */\n async reduce<R>(\n reducer: (\n accumulator: T | R,\n currentValue: T,\n index: number,\n self: this\n ) => R\n ): Promise<R | undefined>;\n async reduce<R>(\n reducer: (accumulator: R, currentValue: T, index: number, self: this) => R,\n initialValue?: R\n ): Promise<R | undefined> {\n let index = 0;\n if (!this.hasNext) return initialValue;\n if (initialValue === undefined) {\n const value = (await this.next()) as any;\n initialValue = value as R;\n index += 1;\n }\n let value = initialValue;\n while (this.hasNext) {\n const item = await this.next();\n value = reducer(value, item!, index, this);\n index++;\n }\n return value;\n }\n\n /**\n * Kills the cursor and frees up associated database resources.\n *\n * This method has no effect if all batches have already been fetched.\n *\n * @example\n * ```js\n * const cursor1 = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * console.log(cursor1.hasMore); // false\n * await cursor1.kill(); // no effect\n *\n * const cursor2 = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * console.log(cursor2.hasMore); // true\n * await cursor2.kill(); // cursor is depleted\n * ```\n */\n async kill(): Promise<void> {\n return this.batches.kill();\n }\n}\n","/**\n * Wrapper around browser `btoa` function to allow substituting a\n * Node.js-specific implementation.\n *\n * @packageDocumentation\n * @internal\n */\n\n/**\n * @internal\n */\nexport function base64Encode(str: string): string {\n return btoa(str);\n}\n","/**\n * Utility function for normalizing URLs.\n *\n * @packageDocumentation\n * @internal\n */\n\n/**\n * @internal\n */\nexport function normalizeUrl(url: string): string {\n const raw = url.match(/^(tcp|ssl|tls)((?::|\\+).+)/);\n if (raw) url = (raw[1] === \"tcp\" ? \"http\" : \"https\") + raw[2];\n const unix = url.match(/^(?:(http|https)\\+)?unix:\\/\\/(\\/.+)/);\n if (unix) url = `${unix[1] || \"http\"}://unix:${unix[2]}`;\n return url;\n}\n","/**\n * Wrapper around the `xhr` module for HTTP(S) requests in the browser.\n *\n * @packageDocumentation\n * @internal\n */\n\nimport { ClientRequest } from \"http\";\nimport { Errback } from \"./errback\";\n\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nexport default require(\"xhr\") as (\n options: any,\n cb: Errback<any>\n) => ClientRequest;\n","/// <reference lib=\"dom\" />\n\n/**\n * Node.js implementation of the HTTP(S) request function.\n *\n * @packageDocumentation\n * @internal\n */\n\nimport { RequestInterceptors, XhrOptions } from \"../connection\";\nimport { base64Encode } from \"./btoa\";\nimport { Errback } from \"./errback\";\nimport { omit } from \"./omit\";\nimport {\n ArangojsError,\n ArangojsResponse,\n RequestOptions,\n} from \"./request.node\";\nimport xhr from \"./xhr\";\n\nexport const isBrowser = true;\n\n/**\n * @internal\n */\nfunction errorToJSON(this: Error) {\n return {\n error: true,\n message: this.message,\n };\n}\n\n/**\n * Create a function for performing requests against a given host.\n *\n * @param baseUrl - Base URL of the host, i.e. protocol, port and domain name.\n * @param agentOptions - Options to use for performing requests.\n *\n * @param baseUrl\n * @param agentOptions\n *\n * @internal\n */\nexport function createRequest(\n baseUrl: string,\n agentOptions: XhrOptions & RequestInterceptors\n) {\n const base = new URL(baseUrl);\n const auth = base64Encode(`${base.username || \"root\"}:${base.password}`);\n base.username = \"\";\n base.password = \"\";\n const options = omit(agentOptions, [\"maxSockets\"]);\n return function request(\n {\n method,\n url: reqUrl,\n headers,\n body,\n timeout,\n expectBinary,\n }: RequestOptions,\n cb: Errback<ArangojsResponse>\n ) {\n const url = new URL(reqUrl.pathname, base);\n if (base.search || reqUrl.search) {\n url.search = reqUrl.search\n ? `${base.search}&${reqUrl.search.slice(1)}`\n : base.search;\n }\n if (!headers[\"authorization\"]) {\n headers[\"authorization\"] = `Basic ${auth}`;\n }\n\n let callback: Errback<ArangojsResponse> = (err, res) => {\n callback = () => undefined;\n cb(err, res);\n };\n const req = xhr(\n {\n useXDR: true,\n withCredentials: true,\n ...options,\n responseType: expectBinary ? \"blob\" : \"text\",\n url: String(url),\n body,\n method,\n headers,\n timeout,\n },\n (err: Error | null, res?: any) => {\n if (!err) {\n const response = res as ArangojsResponse;\n response.request = req;\n if (!response.body) response.body = \"\";\n if (options.after) {\n options.after(null, response);\n }\n callback(null, response as ArangojsResponse);\n } else {\n const error = err as ArangojsError;\n error.request = req;\n error.toJSON = errorToJSON;\n if (options.after) {\n options.after(error);\n }\n callback(error);\n }\n }\n );\n if (options.before) {\n options.before(req);\n }\n };\n}\n","/**\n * Utility function for omitting properties by key.\n *\n * @packageDocumentation\n * @internal\n */\n\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function omit<T extends {}>(obj: T, keys: (keyof T)[]): T {\n const result = {} as T;\n for (const key of Object.keys(obj)) {\n if (keys.includes(key as keyof T)) continue;\n result[key as keyof T] = obj[key as keyof T];\n }\n return result;\n}\n","/**\n * ```ts\n * import type { Config } from \"arangojs/connection\";\n * ```\n *\n * The \"connection\" module provides connection and configuration related types\n * for TypeScript.\n *\n * @packageDocumentation\n */\nimport { ClientRequest } from \"http\";\nimport { AgentOptions as NodeAgentOptions } from \"https\";\nimport { LinkedList } from \"x3-linkedlist\";\nimport { Database } from \"./database\";\nimport {\n ArangoError,\n HttpError,\n isArangoError,\n isArangoErrorResponse,\n isSystemError,\n} from \"./error\";\nimport { base64Encode } from \"./lib/btoa\";\nimport {\n ERROR_ARANGO_CONFLICT,\n ERROR_ARANGO_MAINTENANCE_MODE,\n} from \"./lib/codes\";\nimport { Errback } from \"./lib/errback\";\nimport { normalizeUrl } from \"./lib/normalizeUrl\";\nimport { querystringify } from \"./lib/querystringify\";\nimport {\n ArangojsError,\n ArangojsResponse,\n createRequest,\n isBrowser,\n RequestFunction,\n} from \"./lib/request\";\n\nconst MIME_JSON = /\\/(json|javascript)(\\W|$)/;\nconst LEADER_ENDPOINT_HEADER = \"x-arango-endpoint\";\n\n/**\n * Determines the behavior when multiple URLs are used:\n *\n * - `\"NONE\"`: No load balancing. All requests will be handled by the first\n * URL in the list until a network error is encountered. On network error,\n * arangojs will advance to using the next URL in the list.\n *\n * - `\"ONE_RANDOM\"`: Randomly picks one URL from the list initially, then\n * behaves like `\"NONE\"`.\n *\n * - `\"ROUND_ROBIN\"`: Every sequential request uses the next URL in the list.\n */\nexport type LoadBalancingStrategy = \"NONE\" | \"ROUND_ROBIN\" | \"ONE_RANDOM\";\n\n/**\n * An arbitrary object with string values representing HTTP headers and their\n * values.\n *\n * Header names should always be lowercase.\n */\nexport type Headers = Record<string, string>;\n\n/**\n * An arbitrary object with scalar values representing query string parameters\n * and their values.\n */\nexport type Params = Record<string, any>;\n\n/**\n * Generic properties shared by all ArangoDB HTTP API responses.\n */\nexport type ArangoResponseMetadata = {\n /**\n * Indicates that the request was successful.\n */\n error: false;\n /**\n * Response status code, typically `200`.\n */\n code: number;\n};\n\n/**\n * Extends the given base type `T` with the generic HTTP API response properties.\n */\nexport type ArangoApiResponse<T> = T & ArangoResponseMetadata;\n\n/**\n * Credentials for HTTP Basic authentication.\n */\nexport type BasicAuthCredentials = {\n /**\n * Username to use for authentication, e.g. `\"root\"`.\n */\n username: string;\n /**\n * Password to use for authentication. Defaults to an empty string.\n */\n password?: string;\n};\n\n/**\n * Credentials for HTTP Bearer token authentication.\n */\nexport type BearerAuthCredentials = {\n /**\n * Bearer token to use for authentication.\n */\n token: string;\n};\n\nfunction isBearerAuth(auth: any): auth is BearerAuthCredentials {\n return auth.hasOwnProperty(\"token\");\n}\n\n/**\n * @internal\n */\nfunction generateStackTrace() {\n let err = new Error();\n if (!err.stack) {\n try {\n throw err;\n } catch (e: any) {\n err = e;\n }\n }\n return err;\n}\n\n/**\n * @internal\n */\ntype UrlInfo = {\n absolutePath?: boolean;\n basePath?: string;\n path?: string;\n qs?: string | Params;\n};\n\n/**\n * Options of the `xhr` module that can be set using `agentOptions` when using\n * arangojs in the browser. Additionally `maxSockets` can be used to control\n * the maximum number of parallel requests.\n *\n * See also: [`xhr` on npm](https://www.npmjs.com/package/xhr).\n */\nexport type XhrOptions = {\n /**\n * Maximum number of parallel requests arangojs will perform. If any\n * additional requests are attempted, they will be enqueued until one of the\n * active requests has completed.\n */\n maxSockets?: number;\n /**\n * Number of milliseconds to wait for a response.\n *\n * Default: `0` (disabled)\n */\n timeout?: number;\n /**\n * Callback that will be invoked immediately before the `send` method of the\n * request is called.\n *\n * See also {@link RequestInterceptors}.\n */\n beforeSend?: (xhrObject: any) => void;\n /**\n * `XMLHttpRequest` object to use instead of the native implementation.\n */\n xhr?: any;\n /**\n * (Internet Explorer 10 and lower only.) Whether `XDomainRequest` should be\n * used instead of `XMLHttpRequest`. Only required for performing\n * cross-domain requests in older versions of Internet Explorer.\n */\n useXdr?: boolean;\n /**\n * Specifies whether browser credentials (e.g. cookies) should be sent if\n * performing a cross-domain request.\n *\n * See [`XMLHttpRequest.withCredentials`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials).\n */\n withCredentials?: boolean;\n};\n\n/**\n * Additional options for intercepting the request/response. These methods\n * are primarily intended for tracking network related metrics.\n */\nexport type RequestInterceptors = {\n /**\n * Callback that will be invoked with the finished request object before it\n * is finalized. In the browser the request may already have been sent.\n *\n * @param req - Request object or XHR instance used for this request.\n */\n before?: (req: ClientRequest) => void;\n /**\n * Callback that will be invoked when the server response has been received\n * and processed or when the request has been failed without a response.\n *\n * The originating request will be available as the `request` property\n * on either the error or response object.\n *\n * @param err - Error encountered when handling this request or `null`.\n * @param res - Response object for this request, if no error occurred.\n */\n after?: (err: ArangojsError | null, res?: ArangojsResponse) => void;\n};\n\n/**\n * Options for performing a request with arangojs.\n */\nexport type RequestOptions = {\n /**\n * @internal\n *\n * Identifier of a specific ArangoDB host to use when more than one is known.\n */\n hostUrl?: string;\n /**\n * HTTP method to use in order to perform the request.\n *\n * Default: `\"GET\"`\n */\n method?: string;\n /**\n * Request body data.\n */\n body?: any;\n /**\n * If set to `true`, the response body will not be interpreted as JSON and\n * instead passed as-is.\n */\n expectBinary?: boolean;\n /**\n * If set to `true`, the request body will not be converted to JSON and\n * instead passed as-is.\n */\n isBinary?: boolean;\n /**\n * Whether ArangoDB is allowed to perform a dirty read to respond to this\n * request. If set to `true`, the response may reflect a dirty state from\n * a non-authoritative server.\n */\n allowDirtyRead?: boolean;\n /**\n * If set to a positive number, the request will automatically be retried at\n * most this many times if it results in a write-write conflict.\n *\n * Default: `config.retryOnConflict`\n */\n retryOnConflict?: number;\n /**\n * HTTP headers to pass along with this request in addition to the default\n * headers generated by arangojs.\n */\n headers?: Headers;\n /**\n * Time in milliseconds after which arangojs will abort the request if the\n * socket has not already timed out.\n *\n * See also `agentOptions.timeout` in {@link Config}.\n */\n timeout?: number;\n /**\n * Optional prefix path to prepend to the `path`.\n */\n basePath?: string;\n /**\n * URL path, relative to the `basePath` and server domain.\n */\n path?: string;\n /**\n * URL parameters to pass as part of the query string.\n */\n qs?: string | Params;\n};\n\n/**\n * @internal\n */\ntype Task = {\n hostUrl?: string;\n stack?: () => string;\n allowDirtyRead: boolean;\n retryOnConflict: number;\n resolve: (result: any) => void;\n reject: (error: Error) => void;\n transform?: (res: ArangojsResponse) => any;\n retries: number;\n options: {\n method: string;\n expectBinary: boolean;\n timeout?: number;\n url: { pathname: string; search?: string };\n headers: Headers;\n body: any;\n };\n};\n\n/**\n * Options for creating the Node.js `http.Agent` or `https.Agent`.\n *\n * In browser environments this option can be used to pass additional options\n * to the underlying calls of the\n * [xhr module](https://www.npmjs.com/package/xhr).\n *\n * See also [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options)\n * and [`https.Agent`](https://nodejs.org/api/https.html#https_new_agent_options)\n * (when using TLS).\n */\nexport type AgentOptions = NodeAgentOptions | XhrOptions;\n\n/**\n * Options for configuring arangojs.\n */\nexport type Config = {\n /**\n * Name of the database to use.\n *\n * Default: `\"_system\"`\n */\n databaseName?: string;\n /**\n * Base URL of the ArangoDB server or list of server URLs.\n *\n * When working with a cluster or a single server with leader/follower\n * failover, the method {@link database.Database#acquireHostList} can be used to\n * automatically pick up additional coordinators/followers at any point.\n *\n * When running ArangoDB on a unix socket, e.g. `/tmp/arangodb.sock`, the\n * following URL formats are supported for unix sockets:\n *\n * - `unix:///tmp/arangodb.sock` (no SSL)\n * - `http+unix:///tmp/arangodb.sock` (or `https+unix://` for SSL)\n * - `http://unix:/tmp/arangodb.sock` (or `https://unix:` for SSL)\n *\n * Additionally `ssl` and `tls` are treated as synonymous with `https` and\n * `tcp` is treated as synonymous with `http`, so the following URLs are\n * considered identical:\n *\n * - `tcp://127.0.0.1:8529` and `http://127.0.0.1:8529`\n * - `ssl://127.0.0.1:8529` and `https://127.0.0.1:8529`\n * - `tcp+unix:///tmp/arangodb.sock` and `http+unix:///tmp/arangodb.sock`\n * - `ssl+unix:///tmp/arangodb.sock` and `https+unix:///tmp/arangodb.sock`\n * - `tcp://unix:/tmp/arangodb.sock` and `http://unix:/tmp/arangodb.sock`\n * - `ssl://unix:/tmp/arangodb.sock` and `https://unix:/tmp/arangodb.sock`\n *\n * See also `auth` for passing authentication credentials.\n *\n * Default: `\"http://127.0.0.1:8529\"`\n */\n url?: string | string[];\n /**\n * Credentials to use for authentication.\n *\n * See also {@link database.Database#useBasicAuth} and\n * {@link database.Database#useBearerAuth}.\n *\n * Default: `{ username: \"root\", password: \"\" }`\n */\n auth?: BasicAuthCredentials | BearerAuthCredentials;\n /**\n * Numeric representation of the ArangoDB version the driver should expect.\n * The format is defined as `XYYZZ` where `X` is the major version, `Y` is\n * the zero-filled two-digit minor version and `Z` is the zero-filled two-digit\n * bugfix version, e.g. `30102` for 3.1.2, `20811` for 2.8.11.\n *\n * Depending on this value certain methods may become unavailable or change\n * their behavior to remain compatible with different versions of ArangoDB.\n *\n * Default: `30900`\n */\n arangoVersion?: number;\n /**\n * Determines the behavior when multiple URLs are provided:\n *\n * - `\"NONE\"`: No load balancing. All requests will be handled by the first\n * URL in the list until a network error is encountered. On network error,\n * arangojs will advance to using the next URL in the list.\n *\n * - `\"ONE_RANDOM\"`: Randomly picks one URL from the list initially, then\n * behaves like `\"NONE\"`.\n *\n * - `\"ROUND_ROBIN\"`: Every sequential request uses the next URL in the list.\n *\n * Default: `\"NONE\"`\n */\n loadBalancingStrategy?: LoadBalancingStrategy;\n /**\n * Determines the behavior when a request fails because the underlying\n * connection to the server could not be opened\n * (i.e. [`ECONNREFUSED` in Node.js](https://nodejs.org/api/errors.html#errors_common_system_errors)):\n *\n * - `false`: the request fails immediately.\n *\n * - `0`: the request is retried until a server can be reached but only a\n * total number of times matching the number of known servers (including\n * the initial failed request).\n *\n * - any other number: the request is retried until a server can be reached\n * or the request has been retried a total of `maxRetries` number of times\n * (not including the initial failed request).\n *\n * When working with a single server without leader/follower failover, the\n * retries (if any) will be made to the same server.\n *\n * This setting currently has no effect when using arangojs in a browser.\n *\n * **Note**: Requests bound to a specific server (e.g. fetching query results)\n * will never be retried automatically and ignore this setting.\n *\n * **Note**: To set the number of retries when a write-write conflict is\n * encountered, see `retryOnConflict` instead.\n *\n * Default: `0`\n */\n maxRetries?: false | number;\n /**\n * If set to a positive number, requests will automatically be retried at\n * most this many times if they result in a write-write conflict.\n *\n * Default: `0`\n */\n retryOnConflict?: number;\n /**\n * An http `Agent` instance to use for connections.\n *\n * By default a new `Agent` instance will be created using the `agentOptions`.\n *\n * This option has no effect when using the browser version of arangojs.\n *\n * See also [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options)\n * and [`https.Agent`](https://nodejs.org/api/https.html#https_new_agent_options)\n * (when using TLS).\n */\n agent?: any;\n /**\n * Options used to create that underlying HTTP/HTTPS `Agent` (or the `xhr`\n * module when using arangojs in the browser). This will be ignored if\n * `agent` is also provided.\n *\n * The option `maxSockets` is also used to limit how many requests\n * arangojs will perform concurrently. The maximum number of requests is\n * equal to `maxSockets`.\n *\n * **Note:** arangojs will limit the number of concurrent requests based on\n * this value even if an `agent` is provided.\n *\n * **Note:** when using `ROUND_ROBIN` load balancing and passing an array of\n * URLs in the `url` option, the default value of `maxSockets` will be set\n * to `3 * url.length` instead of `3`.\n *\n * Default (Node.js): `{ maxSockets: 3, keepAlive: true, keepAliveMsecs: 1000 }`\n *\n * Default (browser): `{ maxSockets: 3, useXDR: true, withCredentials: true }`\n */\n agentOptions?: AgentOptions & RequestInterceptors;\n /**\n * An object with additional headers to send with every request.\n *\n * If an `\"authorization\"` header is provided, it will be overridden when\n * using {@link database.Database#useBasicAuth}, {@link database.Database#useBearerAuth} or\n * the `auth` configuration option.\n */\n headers?: Headers;\n /**\n * If set to `true`, arangojs will generate stack traces every time a request\n * is initiated and augment the stack traces of any errors it generates.\n *\n * **Warning**: This will cause arangojs to generate stack traces in advance\n * even if the request does not result in an error. Generating stack traces\n * may negatively impact performance.\n */\n precaptureStackTraces?: boolean;\n /**\n * Limits the number of values of server-reported response queue times that\n * will be stored and accessible using {@link database.Database#queueTime}. If set to\n * a finite value, older values will be discarded to make room for new values\n * when that limit is reached.\n *\n * Default: `10`\n */\n responseQueueTimeSamples?: number;\n};\n\n/**\n * Indicates whether the given value represents a {@link Connection}.\n *\n * @param connection - A value that might be a connection.\n *\n * @internal\n */\nexport function isArangoConnection(connection: any): connection is Connection {\n return Boolean(connection && connection.isArangoConnection);\n}\n\n/**\n * Represents a connection pool shared by one or more databases.\n *\n * @internal\n */\nexport class Connection {\n protected _activeTasks: number = 0;\n protected _agent?: any;\n protected _agentOptions: { [key: string]: any };\n protected _arangoVersion: number = 30900;\n protected _headers: Headers;\n protected _loadBalancingStrategy: LoadBalancingStrategy;\n protected _maxRetries: number | false;\n protected _retryOnConflict: number;\n protected _maxTasks: number;\n protected _queue = new LinkedList<Task>();\n protected _databases = new Map<string, Database>();\n protected _hosts: RequestFunction[] = [];\n protected _hostUrls: string[] = [];\n protected _activeHostUrl: string;\n protected _activeDirtyHostUrl: string;\n protected _transactionId: string | null = null;\n protected _precaptureStackTraces: boolean;\n protected _queueTimes = new LinkedList<[number, number]>();\n protected _responseQueueTimeSamples: number;\n\n /**\n * @internal\n *\n * Creates a new `Connection` instance.\n *\n * @param config - An object with configuration options.\n *\n */\n constructor(config: Omit<Config, \"databaseName\"> = {}) {\n const URLS = config.url\n ? Array.isArray(config.url)\n ? config.url\n : [config.url]\n : [\"http://127.0.0.1:8529\"];\n const MAX_SOCKETS =\n 3 * (config.loadBalancingStrategy === \"ROUND_ROBIN\" ? URLS.length : 1);\n\n if (config.arangoVersion !== undefined) {\n this._arangoVersion = config.arangoVersion;\n }\n this._agent = config.agent;\n this._agentOptions = isBrowser\n ? { maxSockets: MAX_SOCKETS, ...config.agentOptions }\n : {\n maxSockets: MAX_SOCKETS,\n keepAlive: true,\n keepAliveMsecs: 1000,\n scheduling: \"lifo\",\n ...config.agentOptions,\n };\n this._maxTasks = this._agentOptions.maxSockets;\n this._headers = { ...config.headers };\n this._loadBalancingStrategy = config.loadBalancingStrategy ?? \"NONE\";\n this._precaptureStackTraces = Boolean(config.precaptureStackTraces);\n this._responseQueueTimeSamples = config.responseQueueTimeSamples ?? 10;\n this._retryOnConflict = config.retryOnConflict ?? 0;\n if (this._responseQueueTimeSamples < 0) {\n this._responseQueueTimeSamples = Infinity;\n }\n if (config.maxRetries === false) {\n this._maxRetries = false;\n } else {\n this._maxRetries = Number(config.maxRetries ?? 0);\n }\n\n this.addToHostList(URLS);\n\n if (config.auth) {\n if (isBearerAuth(config.auth)) {\n this.setBearerAuth(config.auth);\n } else {\n this.setBasicAuth(config.auth);\n }\n }\n\n if (this._loadBalancingStrategy === \"ONE_RANDOM\") {\n this._activeHostUrl =\n this._hostUrls[Math.floor(Math.random() * this._hostUrls.length)];\n this._activeDirtyHostUrl =\n this._hostUrls[Math.floor(Math.random() * this._hostUrls.length)];\n } else {\n this._activeHostUrl = this._hostUrls[0];\n this._activeDirtyHostUrl = this._hostUrls[0];\n }\n }\n\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB connection.\n */\n get isArangoConnection(): true {\n return true;\n }\n\n get queueTime() {\n return {\n getLatest: () => this._queueTimes.last?.value[1],\n getValues: () => Array.from(this._queueTimes.values()),\n getAvg: () => {\n let avg = 0;\n for (const [, [, value]] of this._queueTimes) {\n avg += value / this._queueTimes.length;\n }\n return avg;\n },\n };\n }\n\n protected _runQueue() {\n if (!this._queue.length || this._activeTasks >= this._maxTasks) return;\n const task = this._queue.shift()!;\n let hostUrl = this._activeHostUrl;\n if (task.hostUrl !== undefined) {\n hostUrl = task.hostUrl;\n } else if (task.allowDirtyRead) {\n hostUrl = this._activeDirtyHostUrl;\n this._activeDirtyHostUrl =\n this._hostUrls[\n (this._hostUrls.indexOf(this._activeDirtyHostUrl) + 1) %\n this._hostUrls.length\n ];\n task.options.headers[\"x-arango-allow-dirty-read\"] = \"true\";\n } else if (this._loadBalancingStrategy === \"ROUND_ROBIN\") {\n this._activeHostUrl =\n this._hostUrls[\n (this._hostUrls.indexOf(this._activeHostUrl) + 1) %\n this._hostUrls.length\n ];\n }\n this._activeTasks += 1;\n const callback: Errback<ArangojsResponse> = (err, res) => {\n this._activeTasks -= 1;\n if (!err && res) {\n if (res.statusCode === 503 && res.headers[LEADER_ENDPOINT_HEADER]) {\n const url = res.headers[LEADER_ENDPOINT_HEADER]!;\n const [cleanUrl] = this.addToHostList(url);\n task.hostUrl = cleanUrl;\n if (this._activeHostUrl === hostUrl) {\n this._activeHostUrl = cleanUrl;\n }\n this._queue.push(task);\n } else {\n res.arangojsHostUrl = hostUrl;\n const contentType = res.headers[\"content-type\"];\n const queueTime = res.headers[\"x-arango-queue-time-seconds\"];\n if (queueTime) {\n this._queueTimes.push([Date.now(), Number(queueTime)]);\n while (this._responseQueueTimeSamples < this._queueTimes.length) {\n this._queueTimes.shift();\n }\n }\n let parsedBody: any = undefined;\n if (res.body.length && contentType && contentType.match(MIME_JSON)) {\n try {\n parsedBody = res.body;\n parsedBody = JSON.parse(parsedBody);\n } catch (e: any) {\n if (!task.options.expectBinary) {\n if (typeof parsedBody !== \"string\") {\n parsedBody = res.body.toString(\"utf-8\");\n }\n e.res = res;\n if (task.stack) {\n e.stack += task.stack();\n }\n callback(e);\n return;\n }\n }\n } else if (res.body && !task.options.expectBinary) {\n parsedBody = res.body.toString(\"utf-8\");\n } else {\n parsedBody = res.body;\n }\n if (isArangoErrorResponse(parsedBody)) {\n res.body = parsedBody;\n err = new ArangoError(res);\n } else if (res.statusCode && res.statusCode >= 400) {\n res.body = parsedBody;\n err = new HttpError(res);\n } else {\n if (!task.options.expectBinary) res.body = parsedBody;\n task.resolve(task.transform ? task.transform(res) : (res as any));\n }\n }\n }\n if (err) {\n if (\n !task.allowDirtyRead &&\n this._hosts.length > 1 &&\n this._activeHostUrl === hostUrl &&\n this._loadBalancingStrategy !== \"ROUND_ROBIN\"\n ) {\n this._activeHostUrl =\n this._hostUrls[\n (this._hostUrls.indexOf(this._activeHostUrl) + 1) %\n this._hostUrls.length\n ];\n }\n if (\n isArangoError(err) &&\n err.errorNum === ERROR_ARANGO_CONFLICT &&\n task.retryOnConflict > 0\n ) {\n task.retryOnConflict -= 1;\n this._queue.push(task);\n } else if (\n ((isSystemError(err) &&\n err.syscall === \"connect\" &&\n err.code === \"ECONNREFUSED\") ||\n (isArangoError(err) &&\n err.errorNum === ERROR_ARANGO_MAINTENANCE_MODE)) &&\n task.hostUrl === undefined &&\n this._maxRetries !== false &&\n task.retries < (this._maxRetries || this._hosts.length - 1)\n ) {\n task.retries += 1;\n this._queue.push(task);\n } else {\n if (task.stack) {\n err.stack += task.stack();\n }\n task.reject(err);\n }\n }\n this._runQueue();\n };\n try {\n this._hosts[this._hostUrls.indexOf(hostUrl)](task.options, callback);\n } catch (e: any) {\n callback(e);\n }\n }\n\n protected _buildUrl({ basePath, path, qs }: UrlInfo) {\n const pathname = `${basePath || \"\"}${path || \"\"}`;\n let search;\n if (qs) {\n if (typeof qs === \"string\") search = `?${qs}`;\n else search = `?${querystringify(qs)}`;\n }\n return search ? { pathname, search } : { pathname };\n }\n\n setBearerAuth(auth: BearerAuthCredentials) {\n this.setHeader(\"authorization\", `Bearer ${auth.token}`);\n }\n\n setBasicAuth(auth: BasicAuthCredentials) {\n this.setHeader(\n \"authorization\",\n `Basic ${base64Encode(`${auth.username}:${auth.password}`)}`\n );\n }\n\n setResponseQueueTimeSamples(responseQueueTimeSamples: number) {\n if (responseQueueTimeSamples < 0) {\n responseQueueTimeSamples = Infinity;\n }\n this._responseQueueTimeSamples = responseQueueTimeSamples;\n while (this._responseQueueTimeSamples < this._queueTimes.length) {\n this._queueTimes.shift();\n }\n }\n\n /**\n * @internal\n *\n * Fetches a {@link database.Database} instance for the given database name from the\n * internal cache, if available.\n *\n * @param databaseName - Name of the database.\n */\n database(databaseName: string): Database | undefined;\n /**\n * @internal\n *\n * Adds a {@link database.Database} instance for the given database name to the\n * internal cache.\n *\n * @param databaseName - Name of the database.\n * @param database - Database instance to add to the cache.\n */\n database(databaseName: string, database: Database): Database;\n /**\n * @internal\n *\n * Clears any {@link database.Database} instance stored for the given database name\n * from the internal cache, if present.\n *\n * @param databaseName - Name of the database.\n * @param database - Must be `null`.\n */\n database(databaseName: string, database: null): undefined;\n database(\n databaseName: string,\n database?: Database | null\n ): Database | undefined {\n if (database === null) {\n this._databases.delete(databaseName);\n return undefined;\n }\n if (!database) {\n return this._databases.get(databaseName);\n }\n this._databases.set(databaseName, database);\n return database;\n }\n\n /**\n * @internal\n *\n * Replaces the host list with the given URLs.\n *\n * See {@link Connection#acquireHostList}.\n *\n * @param urls - URLs to use as host list.\n */\n setHostList(urls: string[]): void {\n const cleanUrls = urls.map((url) => normalizeUrl(url));\n this._hosts.splice(\n 0,\n this._hosts.length,\n ...cleanUrls.map((url) => {\n const i = this._hostUrls.indexOf(url);\n if (i !== -1) return this._hosts[i];\n return createRequest(url, this._agentOptions, this._agent);\n })\n );\n this._hostUrls.splice(0, this._hostUrls.length, ...cleanUrls);\n }\n\n /**\n * @internal\n *\n * Adds the given URL or URLs to the host list.\n *\n * See {@link Connection#acquireHostList}.\n *\n * @param urls - URL or URLs to add.\n */\n addToHostList(urls: string | string[]): string[] {\n const cleanUrls = (Array.isArray(urls) ? urls : [urls]).map((url) =>\n normalizeUrl(url)\n );\n const newUrls = cleanUrls.filter(\n (url) => this._hostUrls.indexOf(url) === -1\n );\n this._hostUrls.push(...newUrls);\n this._hosts.push(\n ...newUrls.map((url: string) =>\n createRequest(url, this._agentOptions, this._agent)\n )\n );\n return cleanUrls;\n }\n\n /**\n * @internal\n *\n * Sets the connection's active `transactionId`.\n *\n * While set, all requests will use this ID, ensuring the requests are executed\n * within the transaction if possible. Setting the ID manually may cause\n * unexpected behavior.\n *\n * See also {@link Connection#clearTransactionId}.\n *\n * @param transactionId - ID of the active transaction.\n */\n setTransactionId(transactionId: string) {\n this._transactionId = transactionId;\n }\n\n /**\n * @internal\n *\n * Clears the connection's active `transactionId`.\n */\n clearTransactionId() {\n this._transactionId = null;\n }\n\n /**\n * @internal\n *\n * Sets the header `headerName` with the given `value` or clears the header if\n * `value` is `null`.\n *\n * @param headerName - Name of the header to set.\n * @param value - Value of the header.\n */\n setHeader(headerName: string, value: string | null) {\n if (value === null) {\n delete this._headers[headerName];\n } else {\n this._headers[headerName] = value;\n }\n }\n\n /**\n * @internal\n *\n * Closes all open connections.\n *\n * See {@link database.Database#close}.\n */\n close() {\n for (const host of this._hosts) {\n if (host.close) host.close();\n }\n }\n\n /**\n * @internal\n *\n * Waits for propagation.\n *\n * See {@link database.Database#waitForPropagation}.\n *\n * @param request - Request to perform against each coordinator.\n * @param timeout - Maximum number of milliseconds to wait for propagation.\n */\n async waitForPropagation(request: RequestOptions, timeout = Infinity) {\n const numHosts = this._hosts.length;\n const propagated = [] as string[];\n const started = Date.now();\n let index = 0;\n while (true) {\n if (propagated.length === numHosts) {\n return;\n }\n while (propagated.includes(this._hostUrls[index])) {\n index = (index + 1) % numHosts;\n }\n const hostUrl = this._hostUrls[index];\n try {\n await this.request({ ...request, hostUrl });\n } catch (e: any) {\n if (started + timeout < Date.now()) {\n throw e;\n }\n await new Promise((resolve) => setTimeout(resolve, 1000));\n continue;\n }\n if (!propagated.includes(hostUrl)) {\n propagated.push(hostUrl);\n }\n }\n }\n\n /**\n * @internal\n *\n * Performs a request using the arangojs connection pool.\n */\n request<T = ArangojsResponse>(\n {\n hostUrl,\n method = \"GET\",\n body,\n expectBinary = false,\n isBinary = false,\n allowDirtyRead = false,\n retryOnConflict = this._retryOnConflict,\n timeout = 0,\n headers,\n ...urlInfo\n }: RequestOptions,\n transform?: (res: ArangojsResponse) => T\n ): Promise<T> {\n return new Promise((resolve, reject) => {\n let contentType = \"text/plain\";\n if (isBinary) {\n contentType = \"application/octet-stream\";\n } else if (body) {\n if (typeof body === \"object\") {\n body = JSON.stringify(body);\n contentType = \"application/json\";\n } else {\n body = String(body);\n }\n }\n\n const extraHeaders: Headers = {\n ...this._headers,\n \"content-type\": contentType,\n \"x-arango-version\": String(this._arangoVersion),\n };\n\n if (this._transactionId) {\n extraHeaders[\"x-arango-trx-id\"] = this._transactionId;\n }\n\n const task: Task = {\n retries: 0,\n hostUrl,\n allowDirtyRead,\n retryOnConflict,\n options: {\n url: this._buildUrl(urlInfo),\n headers: { ...extraHeaders, ...headers },\n timeout,\n method,\n expectBinary,\n body,\n },\n reject,\n resolve,\n transform,\n };\n\n if (this._precaptureStackTraces) {\n if (typeof Error.captureStackTrace === \"function\") {\n const capture = {} as { readonly stack: string };\n Error.captureStackTrace(capture);\n task.stack = () =>\n `\\n${capture.stack.split(\"\\n\").slice(3).join(\"\\n\")}`;\n } else {\n const capture = generateStackTrace() as { readonly stack: string };\n if (Object.prototype.hasOwnProperty.call(capture, \"stack\")) {\n task.stack = () =>\n `\\n${capture.stack.split(\"\\n\").slice(4).join(\"\\n\")}`;\n }\n }\n }\n\n this._queue.push(task);\n this._runQueue();\n });\n }\n}\n","export function querystringify(\n obj: Record<\n string,\n | string\n | number\n | boolean\n | null\n | undefined\n | readonly (string | number | boolean | null | undefined)[]\n >\n) {\n let result = \"\";\n for (let [key, value] of Object.entries(obj)) {\n if (value === undefined) continue;\n key = encodeURIComponent(key);\n if (!Array.isArray(value)) {\n if (value === null) value = \"\";\n else value = encodeURIComponent(String(value));\n result += `&${key}=${value}`;\n } else {\n for (let item of value) {\n if (item == null) item = \"\";\n else item = encodeURIComponent(String(item));\n result += `&${key}=${item}`;\n }\n }\n }\n return result.slice(1);\n}\n","/**\n * Utility function for constructing a multipart form in the browser.\n *\n * @packageDocumentation\n * @internal\n */\n\nimport { Errback } from \"./errback\";\nimport { Fields, MultipartRequest } from \"./multipart\";\n\ndeclare const FormData: any;\ndeclare const Blob: any;\n\n/**\n * @internal\n */\nexport function toForm(fields: Fields, callback: Errback<MultipartRequest>) {\n let form;\n try {\n form = new FormData();\n for (const key of Object.keys(fields)) {\n let value = fields[key];\n if (value === undefined) continue;\n if (\n !(value instanceof Blob) &&\n (typeof value === \"object\" || typeof value === \"function\")\n ) {\n value = JSON.stringify(value);\n }\n form.append(key, value);\n }\n } catch (e: any) {\n callback(e);\n return;\n }\n callback(null, { body: form });\n}\n","/**\n * ```ts\n * import type { Route } from \"arangojs/route\";\n * ```\n *\n * The \"route\" module provides route related types and interfaces for TypeScript.\n *\n * @packageDocumentation\n */\nimport { Headers, Params, RequestOptions } from \"./connection\";\nimport { Database } from \"./database\";\nimport { ArangojsResponse } from \"./lib/request\";\n\n/**\n * Represents an arbitrary route relative to an ArangoDB database.\n */\nexport class Route {\n protected _db: Database;\n protected _path: string;\n protected _headers: Headers;\n\n /**\n * @internal\n */\n constructor(db: Database, path: string = \"\", headers: Headers = {}) {\n if (!path) path = \"\";\n else if (path.charAt(0) !== \"/\") path = `/${path}`;\n this._db = db;\n this._path = path;\n this._headers = headers;\n }\n\n /**\n * Creates a new route relative to this route that inherits any of its default\n * HTTP headers.\n *\n * @param path - Path relative to this route.\n * @param headers - Additional headers that will be sent with each request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const users = foxx.route(\"/users\");\n * ```\n */\n route(path: string, headers?: Headers) {\n if (!path) path = \"\";\n else if (path.charAt(0) !== \"/\") path = `/${path}`;\n return new Route(this._db, this._path + path, {\n ...this._headers,\n ...headers,\n });\n }\n\n /**\n * Performs an arbitrary HTTP request relative to this route and returns the\n * server response.\n *\n * @param options - Options for performing the request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const res = await foxx.request({\n * method: \"POST\",\n * path: \"/users\",\n * body: {\n * username: \"admin\",\n * password: \"hunter2\"\n * }\n * });\n * ```\n */\n request(options?: RequestOptions) {\n const opts = { ...options };\n if (!opts.path || opts.path === \"/\") opts.path = \"\";\n else if (!this._path || opts.path.charAt(0) === \"/\") opts.path = opts.path;\n else opts.path = `/${opts.path}`;\n opts.basePath = this._path;\n opts.headers = { ...this._headers, ...opts.headers };\n opts.method = opts.method ? opts.method.toUpperCase() : \"GET\";\n return this._db.request(opts, false);\n }\n\n /**\n * Performs a DELETE request against the given path relative to this route\n * and returns the server response.\n *\n * @param path - Path relative to this route.\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const res = await foxx.delete(\"/users/admin\");\n * ```\n */\n delete(\n path: string,\n qs?: string | Params,\n headers?: Headers\n ): Promise<ArangojsResponse>;\n /**\n * Performs a DELETE request against the given path relative to this route\n * and returns the server response.\n *\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const user = foxx.roue(\"/users/admin\");\n * const res = await user.delete();\n * ```\n */\n delete(qs?: Params, headers?: Headers): Promise<ArangojsResponse>;\n delete(...args: any[]): Promise<ArangojsResponse> {\n const path = typeof args[0] === \"string\" ? args.shift() : undefined;\n const [qs, headers] = args;\n return this.request({ method: \"DELETE\", path, qs, headers });\n }\n\n /**\n * Performs a GET request against the given path relative to this route\n * and returns the server response.\n *\n * @param path - Path relative to this route.\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const res = await foxx.get(\"/users\", { offset: 10, limit: 5 });\n * ```\n */\n get(\n path: string,\n qs?: string | Params,\n headers?: Headers\n ): Promise<ArangojsResponse>;\n /**\n * Performs a GET request against the given path relative to this route\n * and returns the server response.\n *\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const users = foxx.route(\"/users\");\n * const res = await users.get({ offset: 10, limit: 5 });\n * ```\n */\n get(qs?: Params, headers?: Headers): Promise<ArangojsResponse>;\n get(...args: any[]): Promise<ArangojsResponse> {\n const path = typeof args[0] === \"string\" ? args.shift() : undefined;\n const [qs, headers] = args;\n return this.request({ method: \"GET\", path, qs, headers });\n }\n\n /**\n * Performs a HEAD request against the given path relative to this route\n * and returns the server response.\n *\n * @param path - Path relative to this route.\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const res = await foxx.head(\"/users\", { offset: 10, limit: 5 });\n * ```\n */\n head(\n path: string,\n qs?: string | Params,\n headers?: Headers\n ): Promise<ArangojsResponse>;\n /**\n * Performs a HEAD request against the given path relative to this route\n * and returns the server response.\n *\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const users = foxx.route(\"/users\");\n * const res = await users.head({ offset: 10, limit: 5 });\n * ```\n */\n head(qs?: Params, headers?: Headers): Promise<ArangojsResponse>;\n head(...args: any[]): Promise<ArangojsResponse> {\n const path = typeof args[0] === \"string\" ? args.shift() : undefined;\n const [qs, headers] = args;\n return this.request({ method: \"HEAD\", path, qs, headers });\n }\n\n /**\n * Performs a PATCH request against the given path relative to this route\n * and returns the server response.\n *\n * @param path - Path relative to this route.\n * @param body - Body of the request object.\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const res = await foxx.patch(\"/users/admin\", { password: \"admin\" });\n * ```\n */\n patch(\n path: string,\n body?: any,\n qs?: string | Params,\n headers?: Headers\n ): Promise<ArangojsResponse>;\n /**\n * Performs a PATCH request against the given path relative to this route\n * and returns the server response.\n *\n * **Note**: `body` must not be a `string`.\n *\n * @param body - Body of the request object. Must not be a string.\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const user = foxx.route(\"/users/admin\")\n * const res = await user.patch({ password: \"admin\" });\n * ```\n */\n patch(\n body?: any,\n qs?: string | Params,\n headers?: Headers\n ): Promise<ArangojsResponse>;\n patch(...args: any[]): Promise<ArangojsResponse> {\n const path = typeof args[0] === \"string\" ? args.shift() : undefined;\n const [body, qs, headers] = args;\n return this.request({ method: \"PATCH\", path, body, qs, headers });\n }\n\n /**\n * Performs a POST request against the given path relative to this route\n * and returns the server response.\n *\n * @param path - Path relative to this route.\n * @param body - Body of the request object.\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const res = await foxx.post(\"/users\", {\n * username: \"admin\",\n * password: \"hunter2\"\n * });\n * ```\n */\n post(\n path: string,\n body?: any,\n qs?: string | Params,\n headers?: Headers\n ): Promise<ArangojsResponse>;\n /**\n * Performs a POST request against the given path relative to this route\n * and returns the server response.\n *\n * **Note**: `body` must not be a `string`.\n *\n * @param body - Body of the request object. Must not be a string.\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const users = foxx.route(\"/users\");\n * const res = await users.post({\n * username: \"admin\",\n * password: \"hunter2\"\n * });\n * ```\n */\n post(\n body?: any,\n qs?: string | Params,\n headers?: Headers\n ): Promise<ArangojsResponse>;\n post(...args: any[]): Promise<ArangojsResponse> {\n const path = typeof args[0] === \"string\" ? args.shift() : undefined;\n const [body, qs, headers] = args;\n return this.request({ method: \"POST\", path, body, qs, headers });\n }\n\n /**\n * Performs a PUT request against the given path relative to this route\n * and returns the server response.\n *\n * @param path - Path relative to this route.\n * @param body - Body of the request object.\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const res = await foxx.put(\"/users/admin/password\", { password: \"admin\" });\n * ```\n */\n put(\n path: string,\n body?: any,\n qs?: string | Params,\n headers?: Headers\n ): Promise<ArangojsResponse>;\n /**\n * Performs a PUT request against the given path relative to this route\n * and returns the server response.\n *\n * **Note**: `body` must not be a `string`.\n *\n * @param body - Body of the request object. Must not be a string.\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const password = foxx.route(\"/users/admin/password\");\n * const res = await password.put({ password: \"admin\" });\n * ```\n */\n put(\n body?: any,\n qs?: string | Params,\n headers?: Headers\n ): Promise<ArangojsResponse>;\n put(...args: any[]): Promise<ArangojsResponse> {\n const path = typeof args[0] === \"string\" ? args.shift() : undefined;\n const [body, qs, headers] = args;\n return this.request({ method: \"PUT\", path, body, qs, headers });\n }\n}\n","/**\n * ```ts\n * import type { Transaction } from \"arangojs/transaction\";\n * ```\n *\n * The \"transaction\" module provides transaction related types and interfaces\n * for TypeScript.\n *\n * @packageDocumentation\n */\nimport { Connection } from \"./connection\";\nimport { Database } from \"./database\";\nimport { isArangoError } from \"./error\";\nimport { TRANSACTION_NOT_FOUND } from \"./lib/codes\";\n\n/**\n * Indicates whether the given value represents a {@link Transaction}.\n *\n * @param transaction - A value that might be a transaction.\n */\nexport function isArangoTransaction(\n transaction: any\n): transaction is Transaction {\n return Boolean(transaction && transaction.isArangoTransaction);\n}\n\n/**\n * Options for how the transaction should be committed.\n */\nexport type TransactionCommitOptions = {\n /**\n * If set to `true`, the request will explicitly permit ArangoDB to return a\n * potentially dirty or stale result and arangojs will load balance the\n * request without distinguishing between leaders and followers.\n */\n allowDirtyRead?: boolean;\n};\n\n/**\n * Options for how the transaction should be aborted.\n */\nexport type TransactionAbortOptions = {\n /**\n * If set to `true`, the request will explicitly permit ArangoDB to return a\n * potentially dirty or stale result and arangojs will load balance the\n * request without distinguishing between leaders and followers.\n */\n allowDirtyRead?: boolean;\n};\n\n/**\n * Status of a given transaction.\n *\n * See also {@link database.TransactionDetails}.\n */\nexport type TransactionStatus = {\n /**\n * Unique identifier of the transaction.\n */\n id: string;\n /**\n * Status of the transaction.\n */\n status: \"running\" | \"committed\" | \"aborted\";\n};\n\n/**\n * Represents a streaming transaction in a {@link database.Database}.\n */\nexport class Transaction {\n protected _db: Database;\n protected _id: string;\n\n /**\n * @internal\n */\n constructor(db: Database, id: string) {\n this._db = db;\n this._id = id;\n }\n\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB transaction.\n */\n get isArangoTransaction(): true {\n return true;\n }\n\n /**\n * Unique identifier of this transaction.\n *\n * See {@link database.Database#transaction}.\n */\n get id() {\n return this._id;\n }\n\n /**\n * Checks whether the transaction exists.\n *\n * @example\n * ```js\n * const db = new Database();\n * const trx = db.transaction(\"some-transaction\");\n * const result = await trx.exists();\n * // result indicates whether the transaction exists\n * ```\n */\n async exists(): Promise<boolean> {\n try {\n await this.get();\n return true;\n } catch (err: any) {\n if (isArangoError(err) && err.errorNum === TRANSACTION_NOT_FOUND) {\n return false;\n }\n throw err;\n }\n }\n\n /**\n * Retrieves general information about the transaction.\n *\n * @example\n * ```js\n * const db = new Database();\n * const col = db.collection(\"some-collection\");\n * const trx = db.beginTransaction(col);\n * await trx.step(() => col.save({ hello: \"world\" }));\n * const info = await trx.get();\n * // the transaction exists\n * ```\n */\n get(): Promise<TransactionStatus> {\n return this._db.request(\n {\n path: `/_api/transaction/${encodeURIComponent(this.id)}`,\n },\n (res) => res.body.result\n );\n }\n\n /**\n * Attempts to commit the transaction to the databases.\n *\n * @param options - Options for comitting the transaction.\n *\n * @example\n * ```js\n * const db = new Database();\n * const col = db.collection(\"some-collection\");\n * const trx = db.beginTransaction(col);\n * await trx.step(() => col.save({ hello: \"world\" }));\n * const result = await trx.commit();\n * // result indicates the updated transaction status\n * ```\n */\n commit(options: TransactionCommitOptions = {}): Promise<TransactionStatus> {\n const { allowDirtyRead = undefined } = options;\n return this._db.request(\n {\n method: \"PUT\",\n path: `/_api/transaction/${encodeURIComponent(this.id)}`,\n allowDirtyRead,\n },\n (res) => res.body.result\n );\n }\n\n /**\n * Attempts to abort the transaction to the databases.\n *\n * @param options - Options for aborting the transaction.\n *\n * @example\n * ```js\n * const db = new Database();\n * const col = db.collection(\"some-collection\");\n * const trx = db.beginTransaction(col);\n * await trx.step(() => col.save({ hello: \"world\" }));\n * const result = await trx.abort();\n * // result indicates the updated transaction status\n * ```\n */\n abort(options: TransactionAbortOptions = {}): Promise<TransactionStatus> {\n const { allowDirtyRead = undefined } = options;\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/transaction/${encodeURIComponent(this.id)}`,\n allowDirtyRead,\n },\n (res) => res.body.result\n );\n }\n\n /**\n * Executes the given function locally as a single step of the transaction.\n *\n * @param T - Type of the callback's returned promise.\n * @param callback - Callback function returning a promise.\n *\n * **Warning**: The callback function should wrap a single call of an async\n * arangojs method (e.g. a method on a `Collection` object of a collection\n * that is involved in the transaction or the `db.query` method).\n * If the callback function is async, only the first promise-returning (or\n * async) method call will be executed as part of the transaction. See the\n * examples below for how to avoid common mistakes when using this method.\n *\n * **Note**: Avoid defining the callback as an async function if possible\n * as arangojs will throw an error if the callback did not return a promise.\n * Async functions will return an empty promise by default, making it harder\n * to notice if you forgot to return something from the callback.\n *\n * **Note**: Although almost anything can be wrapped in a callback and passed\n * to this method, that does not guarantee ArangoDB can actually do it in a\n * transaction. Refer to the ArangoDB documentation if you are unsure whether\n * a given operation can be executed as part of a transaction. Generally any\n * modification or retrieval of data is eligible but modifications of\n * collections or databases are not.\n *\n * @example\n * ```js\n * const db = new Database();\n * const vertices = db.collection(\"vertices\");\n * const edges = db.collection(\"edges\");\n * const trx = await db.beginTransaction({ write: [vertices, edges] });\n *\n * // The following code will be part of the transaction\n * const left = await trx.step(() => vertices.save({ label: \"left\" }));\n * const right = await trx.step(() => vertices.save({ label: \"right\" }));\n *\n * // Results from preceding actions can be used normally\n * await trx.step(() => edges.save({\n * _from: left._id,\n * _to: right._id,\n * data: \"potato\"\n * }));\n *\n * // Transaction must be committed for changes to take effected\n * // Always call either trx.commit or trx.abort to end a transaction\n * await trx.commit();\n * ```\n *\n * @example\n * ```js\n * // BAD! If the callback is an async function it must only use await once!\n * await trx.step(async () => {\n * await collection.save(data);\n * await collection.save(moreData); // WRONG\n * });\n *\n * // BAD! Callback function must use only one arangojs call!\n * await trx.step(() => {\n * return collection.save(data)\n * .then(() => collection.save(moreData)); // WRONG\n * });\n *\n * // BETTER: Wrap every arangojs method call that should be part of the\n * // transaction in a separate `trx.step` call\n * await trx.step(() => collection.save(data));\n * await trx.step(() => collection.save(moreData));\n * ```\n *\n * @example\n * ```js\n * // BAD! If the callback is an async function it must not await before\n * // calling an arangojs method!\n * await trx.step(async () => {\n * await doSomethingElse();\n * return collection.save(data); // WRONG\n * });\n *\n * // BAD! Any arangojs inside the callback must not happen inside a promise\n * // method!\n * await trx.step(() => {\n * return doSomethingElse()\n * .then(() => collection.save(data)); // WRONG\n * });\n *\n * // BETTER: Perform any async logic needed outside the `trx.step` call\n * await doSomethingElse();\n * await trx.step(() => collection.save(data));\n *\n * // OKAY: You can perform async logic in the callback after the arangojs\n * // method call as long as it does not involve additional arangojs method\n * // calls, but this makes it easy to make mistakes later\n * await trx.step(async () => {\n * await collection.save(data);\n * await doSomethingDifferent(); // no arangojs method calls allowed\n * });\n * ```\n *\n * @example\n * ```js\n * // BAD! The callback should not use any functions that themselves use any\n * // arangojs methods!\n * async function saveSomeData() {\n * await collection.save(data);\n * await collection.save(moreData);\n * }\n * await trx.step(() => saveSomeData()); // WRONG\n *\n * // BETTER: Pass the transaction to functions that need to call arangojs\n * // methods inside a transaction\n * async function saveSomeData(trx) {\n * await trx.step(() => collection.save(data));\n * await trx.step(() => collection.save(moreData));\n * }\n * await saveSomeData(); // no `trx.step` call needed\n * ```\n *\n * @example\n * ```js\n * // BAD! You must wait for the promise to resolve (or await on the\n * // `trx.step` call) before calling `trx.step` again!\n * trx.step(() => collection.save(data)); // WRONG\n * await trx.step(() => collection.save(moreData));\n *\n * // BAD! The trx.step callback can not make multiple calls to async arangojs\n * // methods, not even using Promise.all!\n * await trx.step(() => Promise.all([ // WRONG\n * collection.save(data),\n * collection.save(moreData),\n * ]));\n *\n * // BAD! Multiple `trx.step` calls can not run in parallel!\n * await Promise.all([ // WRONG\n * trx.step(() => collection.save(data)),\n * trx.step(() => collection.save(moreData)),\n * ]));\n *\n * // BETTER: Always call `trx.step` sequentially, one after the other\n * await trx.step(() => collection.save(data));\n * await trx.step(() => collection.save(moreData));\n *\n * // OKAY: The then callback can be used if async/await is not available\n * trx.step(() => collection.save(data))\n * .then(() => trx.step(() => collection.save(moreData)));\n * ```\n *\n * @example\n * ```js\n * // BAD! The callback will return an empty promise that resolves before\n * // the inner arangojs method call has even talked to ArangoDB!\n * await trx.step(async () => {\n * collection.save(data); // WRONG\n * });\n *\n * // BETTER: Use an arrow function so you don't forget to return\n * await trx.step(() => collection.save(data));\n *\n * // OKAY: Remember to always return when using a function body\n * await trx.step(() => {\n * return collection.save(data); // easy to forget!\n * });\n *\n * // OKAY: You do not have to use arrow functions but it helps\n * await trx.step(function () {\n * return collection.save(data);\n * });\n * ```\n *\n * @example\n * ```js\n * // BAD! You can not pass promises instead of a callback!\n * await trx.step(collection.save(data)); // WRONG\n *\n * // BETTER: Wrap the code in a function and pass the function instead\n * await trx.step(() => collection.save(data));\n * ```\n *\n * @example\n * ```js\n * // WORSE: Calls to non-async arangojs methods don't need to be performed\n * // as part of a transaction\n * const collection = await trx.step(() => db.collection(\"my-documents\"));\n *\n * // BETTER: If an arangojs method is not async and doesn't return promises,\n * // call it without `trx.step`\n * const collection = db.collection(\"my-documents\");\n * ```\n */\n step<T>(callback: () => Promise<T>): Promise<T> {\n const conn = (this._db as any)._connection as Connection;\n conn.setTransactionId(this.id);\n try {\n const promise = callback();\n if (!promise) {\n throw new Error(\n \"Transaction callback was not an async function or did not return a promise!\"\n );\n }\n return Promise.resolve(promise);\n } finally {\n conn.clearTransactionId();\n }\n }\n}\n","/**\n * ```js\n * import { Database } from \"arangojs/database\";\n * ```\n *\n * The \"database\" module provides the {@link Database} class and associated\n * types and interfaces for TypeScript.\n *\n * The Database class is also re-exported by the \"index\" module.\n *\n * @packageDocumentation\n */\nimport { Readable } from \"stream\";\nimport {\n Analyzer,\n AnalyzerDescription,\n CreateAnalyzerOptions,\n} from \"./analyzer\";\nimport { AqlLiteral, AqlQuery, isAqlLiteral, isAqlQuery } from \"./aql\";\nimport {\n ArangoCollection,\n Collection,\n CollectionMetadata,\n collectionToString,\n CollectionType,\n CreateCollectionOptions,\n DocumentCollection,\n EdgeCollection,\n isArangoCollection,\n} from \"./collection\";\nimport {\n ArangoApiResponse,\n Config,\n Connection,\n Headers,\n RequestOptions,\n} from \"./connection\";\nimport { ArrayCursor, BatchedArrayCursor } from \"./cursor\";\nimport { isArangoError } from \"./error\";\nimport { FoxxManifest } from \"./foxx-manifest\";\nimport {\n CreateGraphOptions,\n EdgeDefinitionOptions,\n Graph,\n GraphInfo,\n} from \"./graph\";\nimport { Blob } from \"./lib/blob\";\nimport { DATABASE_NOT_FOUND } from \"./lib/codes\";\nimport { toForm } from \"./lib/multipart\";\nimport { ArangojsResponse } from \"./lib/request\";\nimport { Route } from \"./route\";\nimport { Transaction } from \"./transaction\";\nimport { CreateViewOptions, View, ViewDescription } from \"./view\";\n\n/**\n * Indicates whether the given value represents a {@link Database}.\n *\n * @param database - A value that might be a database.\n */\nexport function isArangoDatabase(database: any): database is Database {\n return Boolean(database && database.isArangoDatabase);\n}\n\n/**\n * @internal\n */\nfunction coerceTransactionCollections(\n collections:\n | (TransactionCollections & { allowImplicit?: boolean })\n | (string | ArangoCollection)[]\n | string\n | ArangoCollection\n): CoercedTransactionCollections {\n if (typeof collections === \"string\") {\n return { write: [collections] };\n }\n if (Array.isArray(collections)) {\n return { write: collections.map(collectionToString) };\n }\n if (isArangoCollection(collections)) {\n return { write: collectionToString(collections) };\n }\n const cols: CoercedTransactionCollections = {};\n if (collections) {\n if (collections.allowImplicit !== undefined) {\n cols.allowImplicit = collections.allowImplicit;\n }\n if (collections.read) {\n cols.read = Array.isArray(collections.read)\n ? collections.read.map(collectionToString)\n : collectionToString(collections.read);\n }\n if (collections.write) {\n cols.write = Array.isArray(collections.write)\n ? collections.write.map(collectionToString)\n : collectionToString(collections.write);\n }\n if (collections.exclusive) {\n cols.exclusive = Array.isArray(collections.exclusive)\n ? collections.exclusive.map(collectionToString)\n : collectionToString(collections.exclusive);\n }\n }\n return cols;\n}\n\n/**\n * @internal\n */\ntype CoercedTransactionCollections = {\n allowImplicit?: boolean;\n exclusive?: string | string[];\n write?: string | string[];\n read?: string | string[];\n};\n\n/**\n * Collections involved in a transaction.\n */\nexport type TransactionCollections = {\n /**\n * An array of collections or a single collection that will be read from or\n * written to during the transaction with no other writes being able to run\n * in parallel.\n */\n exclusive?: (string | ArangoCollection)[] | string | ArangoCollection;\n /**\n * An array of collections or a single collection that will be read from or\n * written to during the transaction.\n */\n write?: (string | ArangoCollection)[] | string | ArangoCollection;\n /**\n * An array of collections or a single collection that will be read from\n * during the transaction.\n */\n read?: (string | ArangoCollection)[] | string | ArangoCollection;\n};\n\n/**\n * Options for how the transaction should be performed.\n */\nexport type TransactionOptions = {\n /**\n * Whether the transaction may read from collections not specified for this\n * transaction. If set to `false`, accessing any collections not specified\n * will result in the transaction being aborted to avoid potential deadlocks.\n *\n * Default: `true`.\n */\n allowImplicit?: boolean;\n /**\n * If set to `true`, the request will explicitly permit ArangoDB to return a\n * potentially dirty or stale result and arangojs will load balance the\n * request without distinguishing between leaders and followers.\n */\n allowDirtyRead?: boolean;\n /**\n * Determines whether to force the transaction to write all data to disk\n * before returning.\n */\n waitForSync?: boolean;\n /**\n * Determines how long the database will wait while attempting to gain locks\n * on collections used by the transaction before timing out.\n */\n lockTimeout?: number;\n /**\n * (RocksDB only.) Determines the transaction size limit in bytes.\n */\n maxTransactionSize?: number;\n};\n\n/**\n * Options for executing a query.\n *\n * See {@link Database#query}.\n */\nexport type QueryOptions = {\n /**\n * If set to `true`, the query will be executed with support for dirty reads\n * enabled, permitting ArangoDB to return a potentially dirty or stale result\n * and arangojs will load balance the request without distinguishing between\n * leaders and followers.\n *\n * Note that dirty reads are only supported for read-only queries, not data\n * modification queries (e.g. using `INSERT`, `UPDATE`, `REPLACE` or\n * `REMOVE`) and only when using ArangoDB 3.4 or later.\n *\n * Default: `false`\n */\n allowDirtyRead?: boolean;\n /**\n * Maximum time in milliseconds arangojs will wait for a server response.\n * Exceeding this value will result in the request being cancelled.\n *\n * **Note**: Setting a timeout for the client does not guarantee the query\n * will be killed by ArangoDB if it is already being executed. See the\n * `maxRuntime` option for limiting the execution time within ArangoDB.\n */\n timeout?: number;\n /**\n * If set to a positive number, the query will automatically be retried at\n * most this many times if it results in a write-write conflict.\n *\n * Default: `0`\n */\n retryOnConflict?: number;\n /**\n * Unless set to `false`, the number of result values in the result set will\n * be returned in the `count` attribute. This may be disabled by default in\n * a future version of ArangoDB if calculating this value has a performance\n * impact for some queries.\n *\n * Default: `true`.\n */\n count?: boolean;\n /**\n * Number of result values to be transferred by the server in each\n * network roundtrip (or \"batch\").\n *\n * Must be greater than zero.\n */\n batchSize?: number;\n /**\n * If set to `false`, the AQL query results cache lookup will be skipped for\n * this query.\n *\n * Default: `true`\n */\n cache?: boolean;\n /**\n * Maximum memory size in bytes that the query is allowed to use.\n * Exceeding this value will result in the query failing with an error.\n *\n * If set to `0`, the memory limit is disabled.\n *\n * Default: `0`\n */\n memoryLimit?: number;\n /**\n * Maximum allowed execution time before the query will be killed in seconds.\n *\n * If set to `0`, the query will be allowed to run indefinitely.\n *\n * Default: `0`\n */\n maxRuntime?: number;\n /**\n * Time-to-live for the cursor in seconds. The cursor results may be\n * garbage collected by ArangoDB after this much time has passed.\n *\n * Default: `30`\n */\n ttl?: number;\n /**\n * If set to `true`, the query will throw an exception and abort if it would\n otherwise produce a warning.\n */\n failOnWarning?: boolean;\n /**\n * If set to `1` or `true`, additional query profiling information will be\n * returned in the `extra.profile` attribute if the query is not served from\n * the result cache.\n *\n * If set to `2`, the query will return execution stats per query plan node\n * in the `extra.stats.nodes` attribute. Additionally the query plan is\n * returned in `extra.plan`.\n */\n profile?: boolean | number;\n /**\n * If set to `true`, the query will be executed as a streaming query.\n */\n stream?: boolean;\n /**\n * Limits the maximum number of warnings a query will return.\n */\n maxWarningsCount?: number;\n /**\n * If set to `true` and the query has a `LIMIT` clause, the total number of\n * values matched before the last top-level `LIMIT` in the query was applied\n * will be returned in the `extra.stats.fullCount` attribute.\n */\n fullCount?: boolean;\n /**\n * If set to `false`, the query data will not be stored in the RocksDB block\n * cache. This can be used to avoid thrashing he block cache when reading a\n * lot of data.\n */\n fillBlockCache?: boolean;\n /**\n * An object with a `rules` property specifying a list of optimizer rules to\n * be included or excluded by the optimizer for this query. Prefix a rule\n * name with `+` to include it, or `-` to exclude it. The name `all` acts as\n * an alias matching all optimizer rules.\n */\n optimizer?: { rules: string[] };\n /**\n * Limits the maximum number of plans that will be created by the AQL query\n * optimizer.\n */\n maxPlans?: number;\n /**\n * Controls after how many execution nodes in a query a stack split should be\n * performed.\n *\n * Default: `250` (`200` on macOS)\n */\n maxNodesPerCallstack?: number;\n /**\n * (RocksDB only.) Maximum size of transactions in bytes.\n */\n maxTransactionSize?: number;\n /**\n * (RocksDB only.) Maximum number of operations after which an intermediate\n * commit is automatically performed.\n */\n intermediateCommitCount?: number;\n /**\n * (RocksDB only.) Maximum total size of operations in bytes after which an\n * intermediate commit is automatically performed.\n */\n intermediateCommitSize?: number;\n /**\n * (Enterprise Edition cluster only.) If set to `true`, collections\n * inaccessible to current user will result in an access error instead\n * of being treated as empty.\n */\n skipInaccessibleCollections?: boolean;\n /**\n * (Enterprise Edition cluster only.) Limits the maximum time in seconds a\n * DBServer will wait to bring satellite collections involved in the query\n * into sync. Exceeding this value will result in the query being stopped.\n *\n * Default: `60`\n */\n satelliteSyncWait?: number;\n};\n\n/**\n * Options for explaining a query.\n *\n * See {@link Database#explain}.\n */\nexport type ExplainOptions = {\n /**\n * An object with a `rules` property specifying a list of optimizer rules to\n * be included or excluded by the optimizer for this query. Prefix a rule\n * name with `+` to include it, or `-` to exclude it. The name `all` acts as\n * an alias matching all optimizer rules.\n */\n optimizer?: { rules: string[] };\n /**\n * Maximum number of plans that the optimizer is allowed to generate.\n * Setting this to a low value limits the amount of work the optimizer does.\n */\n maxNumberOfPlans?: number;\n /**\n * If set to true, all possible execution plans will be returned as the\n * `plans` property. Otherwise only the optimal execution plan will be\n * returned as the `plan` property.\n *\n * Default: `false`\n */\n allPlans?: boolean;\n};\n\n/**\n * Details for a transaction.\n *\n * See also {@link transaction.TransactionStatus}.\n */\nexport type TransactionDetails = {\n /**\n * Unique identifier of the transaction.\n */\n id: string;\n /**\n * Status (or \"state\") of the transaction.\n */\n state: \"running\" | \"committed\" | \"aborted\";\n};\n\n/**\n * Plan explaining query execution.\n */\nexport type ExplainPlan = {\n /**\n * Execution nodes in this plan.\n */\n nodes: {\n [key: string]: any;\n type: string;\n id: number;\n dependencies: number[];\n estimatedCost: number;\n estimatedNrItems: number;\n }[];\n /**\n * Rules applied by the optimizer.\n */\n rules: string[];\n /**\n * Information about collections involved in the query.\n */\n collections: {\n name: string;\n type: \"read\" | \"write\";\n }[];\n /**\n * Variables used in the query.\n */\n variables: {\n id: number;\n name: string;\n }[];\n /**\n * Total estimated cost of the plan.\n */\n estimatedCost: number;\n /**\n * Estimated number of items returned by the query.\n */\n estimatedNrItems: number;\n /**\n * Whether the query is a data modification query.\n */\n isModificationQuery: boolean;\n};\n\n/**\n * Result of explaining a query with a single plan.\n */\nexport type SingleExplainResult = {\n /**\n * Query plan.\n */\n plan: ExplainPlan;\n /**\n * Whether it would be possible to cache the query.\n */\n cacheable: boolean;\n /**\n * Warnings encountered while planning the query execution.\n */\n warnings: { code: number; message: string }[];\n /**\n * Statistical information about the query plan generation.\n */\n stats: {\n /**\n * Total number of rules executed for this query.\n */\n rulesExecuted: number;\n /**\n * Number of rules skipped for this query.\n */\n rulesSkipped: number;\n /**\n * Total number of plans created.\n */\n plansCreated: number;\n };\n};\n\n/**\n * Result of explaining a query with multiple plans.\n */\nexport type MultiExplainResult = {\n /**\n * Query plans.\n */\n plans: ExplainPlan[];\n /**\n * Whether it would be possible to cache the query.\n */\n cacheable: boolean;\n /**\n * Warnings encountered while planning the query execution.\n */\n warnings: { code: number; message: string }[];\n /**\n * Statistical information about the query plan generation.\n */\n stats: {\n /**\n * Total number of rules executed for this query.\n */\n rulesExecuted: number;\n /**\n * Number of rules skipped for this query.\n */\n rulesSkipped: number;\n /**\n * Total number of plans created.\n */\n plansCreated: number;\n };\n};\n\n/**\n * Node in an AQL abstract syntax tree (AST).\n */\nexport type AstNode = {\n [key: string]: any;\n type: string;\n subNodes: AstNode[];\n};\n\n/**\n * Result of parsing a query.\n */\nexport type ParseResult = {\n /**\n * Whether the query was parsed.\n */\n parsed: boolean;\n /**\n * Names of all collections involved in the query.\n */\n collections: string[];\n /**\n * Names of all bind parameters used in the query.\n */\n bindVars: string[];\n /**\n * Abstract syntax tree (AST) of the query.\n */\n ast: AstNode[];\n};\n\n/**\n * Optimizer rule for AQL queries.\n */\nexport type QueryOptimizerRule = {\n name: string;\n flags: {\n hidden: boolean;\n clusterOnly: boolean;\n canBeDisabled: boolean;\n canCreateAdditionalPlans: boolean;\n disabledByDefault: boolean;\n enterpriseOnly: boolean;\n };\n};\n\n/**\n * Information about query tracking.\n */\nexport type QueryTracking = {\n /**\n * Whether query tracking is enabled.\n */\n enabled: boolean;\n /**\n * Maximum query string length in bytes that is kept in the list.\n */\n maxQueryStringLength: number;\n /**\n * Maximum number of slow queries that is kept in the list.\n */\n maxSlowQueries: number;\n /**\n * Threshold execution time in seconds for when a query is\n * considered slow.\n */\n slowQueryThreshold: number;\n /**\n * Whether bind parameters are being tracked along with queries.\n */\n trackBindVars: boolean;\n /**\n * Whether slow queries are being tracked.\n */\n trackSlowQueries: boolean;\n};\n\n/**\n * Options for query tracking.\n *\n * See {@link Database#queryTracking}.\n */\nexport type QueryTrackingOptions = {\n /**\n * If set to `false`, neither queries nor slow queries will be tracked.\n */\n enabled?: boolean;\n /**\n * Maximum query string length in bytes that will be kept in the list.\n */\n maxQueryStringLength?: number;\n /**\n * Maximum number of slow queries to be kept in the list.\n */\n maxSlowQueries?: number;\n /**\n * Threshold execution time in seconds for when a query will be\n * considered slow.\n */\n slowQueryThreshold?: number;\n /**\n * If set to `true`, bind parameters will be tracked along with queries.\n */\n trackBindVars?: boolean;\n /**\n * If set to `true` and `enabled` is also set to `true`, slow queries will be\n * tracked if their execution time exceeds `slowQueryThreshold`.\n */\n trackSlowQueries?: boolean;\n};\n\n/**\n * Object describing a query.\n */\nexport type QueryInfo = {\n /**\n * Unique identifier for this query.\n */\n id: string;\n /**\n * Query string (potentially truncated).\n */\n query: string;\n /**\n * Bind parameters used in the query.\n */\n bindVars: Record<string, any>;\n /**\n * Query's running time in seconds.\n */\n runTime: number;\n /**\n * Date and time the query was started.\n */\n started: string;\n /**\n * Query's current execution state.\n */\n state: \"executing\" | \"finished\" | \"killed\";\n /**\n * Whether the query uses a streaming cursor.\n */\n stream: boolean;\n};\n\n/**\n * Database user to create with a database.\n */\nexport type CreateDatabaseUser = {\n /**\n * Username of the user to create.\n */\n username: string;\n /**\n * Password of the user to create.\n *\n * Default: `\"\"`\n */\n passwd?: string;\n /**\n * Whether the user is active.\n *\n * Default: `true`\n */\n active?: boolean;\n /**\n * Additional data to store with the user object.\n */\n extra?: Record<string, any>;\n};\n\n/**\n * Options for creating a database.\n *\n * See {@link Database#createDatabase}.\n */\nexport type CreateDatabaseOptions = {\n /**\n * Database users to create with the database.\n */\n users?: CreateDatabaseUser[];\n /**\n * (Cluster only.) The sharding method to use for new collections in the\n * database.\n */\n sharding?: \"\" | \"flexible\" | \"single\";\n /**\n * (Cluster only.) Default replication factor for new collections in this\n * database.\n *\n * Setting this to `1` disables replication. Setting this to `\"satellite\"`\n * will replicate to every DBServer.\n */\n replicationFactor?: \"satellite\" | number;\n /**\n * (Cluster only.) Default write concern for new collections created in this\n * database.\n */\n writeConcern?: number;\n};\n\n/**\n * Object describing a database.\n *\n * See {@link Database#get}.\n */\nexport type DatabaseInfo = {\n /**\n * Name of the database.\n */\n name: string;\n /**\n * Unique identifier of the database.\n */\n id: string;\n /**\n * File system path of the database.\n */\n path: string;\n /**\n * Whether the database is the system database.\n */\n isSystem: boolean;\n /**\n * (Cluster only.) The sharding method to use for new collections in the\n * database.\n */\n sharding?: \"\" | \"flexible\" | \"single\";\n /**\n * (Cluster only.) Default replication factor for new collections in this\n * database.\n */\n replicationFactor?: \"satellite\" | number;\n /**\n * (Cluster only.) Default write concern for new collections created in this\n * database.\n */\n writeConcern?: number;\n};\n\n/**\n * Result of retrieving database version information.\n */\nexport type VersionInfo = {\n /**\n * Value identifying the server type, i.e. `\"arango\"`.\n */\n server: string;\n /**\n * ArangoDB license type or \"edition\".\n */\n license: \"community\" | \"enterprise\";\n /**\n * ArangoDB server version.\n */\n version: string;\n /**\n * Additional information about the ArangoDB server.\n */\n details?: { [key: string]: string };\n};\n\n/**\n * Definition of an AQL User Function.\n */\nexport type AqlUserFunction = {\n /**\n * Name of the AQL User Function.\n */\n name: string;\n /**\n * Implementation of the AQL User Function.\n */\n code: string;\n /**\n * Whether the function is deterministic.\n *\n * See {@link Database#createFunction}.\n */\n isDeterministic: boolean;\n};\n\n/**\n * Options for installing the service.\n *\n * See {@link Database#installService}.\n */\nexport type InstallServiceOptions = {\n /**\n * An object mapping configuration option names to values.\n *\n * See also {@link Database#getServiceConfiguration}.\n */\n configuration?: Record<string, any>;\n /**\n * An object mapping dependency aliases to mount points.\n *\n * See also {@link Database#getServiceDependencies}.\n */\n dependencies?: Record<string, string>;\n /**\n * Whether the service should be installed in development mode.\n *\n * See also {@link Database#setServiceDevelopmentMode}.\n *\n * Default: `false`\n */\n development?: boolean;\n /**\n * Whether the service should be installed in legacy compatibility mode\n *\n * This overrides the `engines` option in the service manifest (if any).\n *\n * Default: `false`\n */\n legacy?: boolean;\n /**\n * Whether the \"setup\" script should be executed.\n *\n * Default: `true`\n */\n setup?: boolean;\n};\n\n/**\n * Options for replacing a service.\n *\n * See {@link Database#replaceService}.\n */\nexport type ReplaceServiceOptions = {\n /**\n * An object mapping configuration option names to values.\n *\n * See also {@link Database#getServiceConfiguration}.\n */\n configuration?: Record<string, any>;\n /**\n * An object mapping dependency aliases to mount points.\n *\n * See also {@link Database#getServiceDependencies}.\n */\n dependencies?: Record<string, string>;\n /**\n * Whether the service should be installed in development mode.\n *\n * See also {@link Database#setServiceDevelopmentMode}.\n *\n * Default: `false`\n */\n development?: boolean;\n /**\n * Whether the service should be installed in legacy compatibility mode\n *\n * This overrides the `engines` option in the service manifest (if any).\n *\n * Default: `false`\n */\n legacy?: boolean;\n /**\n * Whether the \"setup\" script should be executed.\n *\n * Default: `true`\n */\n setup?: boolean;\n /**\n * Whether the existing service's \"teardown\" script should be executed\n * prior to removing that service.\n *\n * Default: `true`\n */\n teardown?: boolean;\n /**\n * If set to `true`, replacing a service that does not already exist will\n * fall back to installing the new service.\n *\n * Default: `false`\n */\n force?: boolean;\n};\n\n/**\n * Options for upgrading a service.\n *\n * See {@link Database#upgradeService}.\n */\nexport type UpgradeServiceOptions = {\n /**\n * An object mapping configuration option names to values.\n *\n * See also {@link Database#getServiceConfiguration}.\n */\n configuration?: Record<string, any>;\n /**\n * An object mapping dependency aliases to mount points.\n *\n * See also {@link Database#getServiceDependencies}.\n */\n dependencies?: Record<string, string>;\n /**\n * Whether the service should be installed in development mode.\n *\n * See also {@link Database#setServiceDevelopmentMode}.\n *\n * Default: `false`\n */\n development?: boolean;\n /**\n * Whether the service should be installed in legacy compatibility mode\n *\n * This overrides the `engines` option in the service manifest (if any).\n *\n * Default: `false`\n */\n legacy?: boolean;\n /**\n * Whether the \"setup\" script should be executed.\n *\n * Default: `true`\n */\n setup?: boolean;\n /**\n * Whether the existing service's \"teardown\" script should be executed\n * prior to upgrading that service.\n *\n * Default: `false`\n */\n teardown?: boolean;\n /**\n * Unless set to `true`, upgrading a service that does not already exist will\n * fall back to installing the new service.\n *\n * Default: `false`\n */\n force?: boolean;\n};\n\n/**\n * Options for uninstalling a service.\n *\n * See {@link Database#uninstallService}.\n */\nexport type UninstallServiceOptions = {\n /**\n * Whether the service's \"teardown\" script should be executed\n * prior to removing that service.\n *\n * Default: `true`\n */\n teardown?: boolean;\n /**\n * If set to `true`, uninstalling a service that does not already exist\n * will be considered successful.\n *\n * Default: `false`\n */\n force?: boolean;\n};\n\n/**\n * Object briefly describing a Foxx service.\n */\nexport type ServiceSummary = {\n /**\n * Service mount point, relative to the database.\n */\n mount: string;\n /**\n * Name defined in the service manifest.\n */\n name?: string;\n /**\n * Version defined in the service manifest.\n */\n version?: string;\n /**\n * Service dependencies the service expects to be able to match as a mapping\n * from dependency names to versions the service is compatible with.\n */\n provides: Record<string, string>;\n /**\n * Whether development mode is enabled for this service.\n */\n development: boolean;\n /**\n * Whether the service is running in legacy compatibility mode.\n */\n legacy: boolean;\n};\n\n/**\n * Object describing a Foxx service in detail.\n */\nexport type ServiceInfo = {\n /**\n * Service mount point, relative to the database.\n */\n mount: string;\n /**\n * File system path of the service.\n */\n path: string;\n /**\n * Name defined in the service manifest.\n */\n name?: string;\n /**\n * Version defined in the service manifest.\n */\n version?: string;\n /**\n * Whether development mode is enabled for this service.\n */\n development: boolean;\n /**\n * Whether the service is running in legacy compatibility mode.\n */\n legacy: boolean;\n /**\n * Content of the service manifest of this service.\n */\n manifest: FoxxManifest;\n /**\n * Internal checksum of the service's initial source bundle.\n */\n checksum: string;\n /**\n * Options for this service.\n */\n options: {\n /**\n * Configuration values set for this service.\n */\n configuration: Record<string, any>;\n /**\n * Service dependency configuration of this service.\n */\n dependencies: Record<string, string>;\n };\n};\n\n/**\n * Object describing a configuration option of a Foxx service.\n */\nexport type ServiceConfiguration = {\n /**\n * Data type of the configuration value.\n *\n * **Note**: `\"int\"` and `\"bool\"` are historical synonyms for `\"integer\"` and\n * `\"boolean\"`. The `\"password\"` type is synonymous with `\"string\"` but can\n * be used to distinguish values which should not be displayed in plain text\n * by software when managing the service.\n */\n type:\n | \"integer\"\n | \"boolean\"\n | \"string\"\n | \"number\"\n | \"json\"\n | \"password\"\n | \"int\"\n | \"bool\";\n /**\n * Current value of the configuration option as stored internally.\n */\n currentRaw: any;\n /**\n * Processed current value of the configuration option as exposed in the\n * service code.\n */\n current: any;\n /**\n * Formatted name of the configuration option.\n */\n title: string;\n /**\n * Human-readable description of the configuration option.\n */\n description?: string;\n /**\n * Whether the configuration option must be set in order for the service\n * to be operational.\n */\n required: boolean;\n /**\n * Default value of the configuration option.\n */\n default?: any;\n};\n\n/**\n * Object describing a single-service dependency defined by a Foxx service.\n */\nexport type SingleServiceDependency = {\n /**\n * Whether this is a multi-service dependency.\n */\n multiple: false;\n /**\n * Current mount point the dependency is resolved to.\n */\n current?: string;\n /**\n * Formatted name of the dependency.\n */\n title: string;\n /**\n * Name of the service the dependency expects to match.\n */\n name: string;\n /**\n * Version of the service the dependency expects to match.\n */\n version: string;\n /**\n * Human-readable description of the dependency.\n */\n description?: string;\n /**\n * Whether the dependency must be matched in order for the service\n * to be operational.\n */\n required: boolean;\n};\n\n/**\n * Object describing a multi-service dependency defined by a Foxx service.\n */\nexport type MultiServiceDependency = {\n /**\n * Whether this is a multi-service dependency.\n */\n multiple: true;\n /**\n * Current mount points the dependency is resolved to.\n */\n current?: string[];\n /**\n * Formatted name of the dependency.\n */\n title: string;\n /**\n * Name of the service the dependency expects to match.\n */\n name: string;\n /**\n * Version of the service the dependency expects to match.\n */\n version: string;\n /**\n * Human-readable description of the dependency.\n */\n description?: string;\n /**\n * Whether the dependency must be matched in order for the service\n * to be operational.\n */\n required: boolean;\n};\n\n/**\n * Test stats for a Foxx service's tests.\n */\nexport type ServiceTestStats = {\n /**\n * Total number of tests found.\n */\n tests: number;\n /**\n * Number of tests that ran successfully.\n */\n passes: number;\n /**\n * Number of tests that failed.\n */\n failures: number;\n /**\n * Number of tests skipped or not executed.\n */\n pending: number;\n /**\n * Total test duration in milliseconds.\n */\n duration: number;\n};\n\n/**\n * Test results for a single test case using the stream reporter.\n */\nexport type ServiceTestStreamTest = {\n title: string;\n fullTitle: string;\n duration: number;\n err?: string;\n};\n\n/**\n * Test results for a Foxx service's tests using the stream reporter.\n */\nexport type ServiceTestStreamReport = (\n | [\"start\", { total: number }]\n | [\"pass\", ServiceTestStreamTest]\n | [\"fail\", ServiceTestStreamTest]\n | [\"end\", ServiceTestStats]\n)[];\n\n/**\n * Test results for a single test case using the suite reporter.\n */\nexport type ServiceTestSuiteTest = {\n result: \"pending\" | \"pass\" | \"fail\";\n title: string;\n duration: number;\n err?: any;\n};\n\n/**\n * Test results for a single test suite using the suite reporter.\n */\nexport type ServiceTestSuite = {\n title: string;\n suites: ServiceTestSuite[];\n tests: ServiceTestSuiteTest[];\n};\n\n/**\n * Test results for a Foxx service's tests using the suite reporter.\n */\nexport type ServiceTestSuiteReport = {\n stats: ServiceTestStats;\n suites: ServiceTestSuite[];\n tests: ServiceTestSuiteTest[];\n};\n\n/**\n * Test results for a single test case in XUnit format using the JSONML\n * representation.\n */\nexport type ServiceTestXunitTest =\n | [\"testcase\", { classname: string; name: string; time: number }]\n | [\n \"testcase\",\n { classname: string; name: string; time: number },\n [\"failure\", { message: string; type: string }, string]\n ];\n\n/**\n * Test results for a Foxx service's tests in XUnit format using the JSONML\n * representation.\n */\nexport type ServiceTestXunitReport = [\n \"testsuite\",\n {\n timestamp: number;\n tests: number;\n errors: number;\n failures: number;\n skip: number;\n time: number;\n },\n ...ServiceTestXunitTest[]\n];\n\n/**\n * Test results for a Foxx service's tests in TAP format.\n */\nexport type ServiceTestTapReport = string[];\n\n/**\n * Test results for a single test case using the default reporter.\n */\nexport type ServiceTestDefaultTest = {\n title: string;\n fullTitle: string;\n duration: number;\n err?: string;\n};\n\n/**\n * Test results for a Foxx service's tests using the default reporter.\n */\nexport type ServiceTestDefaultReport = {\n stats: ServiceTestStats;\n tests: ServiceTestDefaultTest[];\n pending: ServiceTestDefaultTest[];\n failures: ServiceTestDefaultTest[];\n passes: ServiceTestDefaultTest[];\n};\n\n/**\n * OpenAPI 2.0 description of a Foxx service.\n */\nexport type SwaggerJson = {\n [key: string]: any;\n info: {\n title: string;\n description: string;\n version: string;\n license: string;\n };\n path: {\n [key: string]: any;\n };\n};\n\n/**\n * Access level for an ArangoDB user's access to a collection or database.\n */\nexport type AccessLevel = \"rw\" | \"ro\" | \"none\";\n\n/**\n * Properties of an ArangoDB user object.\n */\nexport type ArangoUser = {\n /**\n * ArangoDB username of the user.\n */\n user: string;\n /**\n * Whether the ArangoDB user account is enabled and can authenticate.\n */\n active: boolean;\n /**\n * Additional information to store about this user.\n */\n extra: Record<string, any>;\n};\n\n/**\n * Options for creating an ArangoDB user.\n */\nexport type CreateUserOptions = {\n /**\n * ArangoDB username of the user.\n */\n user: string;\n /**\n * Password the ArangoDB user will use for authentication.\n */\n passwd: string;\n /**\n * Whether the ArangoDB user account is enabled and can authenticate.\n *\n * Default: `true`\n */\n active?: boolean;\n /**\n * Additional information to store about this user.\n *\n * Default: `{}`\n */\n extra?: Record<string, any>;\n};\n\n/**\n * Options for modifying an ArangoDB user.\n */\nexport type UserOptions = {\n /**\n * Password the ArangoDB user will use for authentication.\n */\n passwd: string;\n /**\n * Whether the ArangoDB user account is enabled and can authenticate.\n *\n * Default: `true`\n */\n active?: boolean;\n /**\n * Additional information to store about this user.\n *\n * Default: `{}`\n */\n extra?: Record<string, any>;\n};\n\n/**\n * Options for accessing or manipulating access levels.\n */\nexport type UserAccessLevelOptions = {\n /**\n * The database to access or manipulate the access level of.\n *\n * If `collection` is an `ArangoCollection`, this option defaults to the\n * database the collection is contained in. Otherwise this option defaults to\n * the current database.\n */\n database?: Database | string;\n /**\n * The collection to access or manipulate the access level of.\n */\n collection?: ArangoCollection | string;\n};\n\n/**\n * An object providing methods for accessing queue time metrics of the most\n * recently received server responses if the server supports this feature.\n */\nexport type QueueTimeMetrics = {\n /**\n * Returns the queue time of the most recently received response in seconds.\n */\n getLatest: () => number | undefined;\n /**\n * Returns a list of the most recently received queue time values as tuples\n * of the timestamp of the response being processed in milliseconds and the\n * queue time in seconds.\n */\n getValues: () => [number, number][];\n /**\n * Returns the average queue time of the most recently received responses\n * in seconds.\n */\n getAvg: () => number;\n};\n\n/**\n * An object representing a single ArangoDB database. All arangojs collections,\n * cursors, analyzers and so on are linked to a `Database` object.\n */\nexport class Database {\n protected _connection: Connection;\n protected _name: string;\n protected _analyzers = new Map<string, Analyzer>();\n protected _collections = new Map<string, Collection>();\n protected _graphs = new Map<string, Graph>();\n protected _views = new Map<string, View>();\n\n /**\n * Creates a new `Database` instance with its own connection pool.\n *\n * See also {@link Database#database}.\n *\n * @param config - An object with configuration options.\n *\n * @example\n * ```js\n * const db = new Database({\n * url: \"http://127.0.0.1:8529\",\n * databaseName: \"my_database\",\n * auth: { username: \"admin\", password: \"hunter2\" },\n * });\n * ```\n */\n constructor(config?: Config);\n /**\n * Creates a new `Database` instance with its own connection pool.\n *\n * See also {@link Database#database}.\n *\n * @param url - Base URL of the ArangoDB server or list of server URLs.\n * Equivalent to the `url` option in {@link connection.Config}.\n *\n * @example\n * ```js\n * const db = new Database(\"http://127.0.0.1:8529\", \"my_database\");\n * db.useBasicAuth(\"admin\", \"hunter2\");\n * ```\n */\n constructor(url: string | string[], name?: string);\n /**\n * @internal\n */\n constructor(database: Database, name?: string);\n constructor(\n configOrDatabase: string | string[] | Config | Database = {},\n name?: string\n ) {\n if (isArangoDatabase(configOrDatabase)) {\n const connection = configOrDatabase._connection;\n const databaseName = (name || configOrDatabase.name).normalize(\"NFC\");\n this._connection = connection;\n this._name = databaseName;\n const database = connection.database(databaseName);\n if (database) return database;\n } else {\n const config = configOrDatabase;\n const { databaseName, ...options } =\n typeof config === \"string\" || Array.isArray(config)\n ? { databaseName: name, url: config }\n : config;\n this._connection = new Connection(options);\n this._name = databaseName?.normalize(\"NFC\") || \"_system\";\n }\n }\n\n //#region misc\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB database.\n */\n get isArangoDatabase(): true {\n return true;\n }\n\n /**\n * Name of the ArangoDB database this instance represents.\n */\n get name() {\n return this._name;\n }\n\n /**\n * Fetches version information from the ArangoDB server.\n *\n * @param details - If set to `true`, additional information about the\n * ArangoDB server will be available as the `details` property.\n *\n * @example\n * ```js\n * const db = new Database();\n * const version = await db.version();\n * // the version object contains the ArangoDB version information.\n * // license: \"community\" or \"enterprise\"\n * // version: ArangoDB version number\n * // server: description of the server\n * ```\n */\n version(details?: boolean): Promise<VersionInfo> {\n return this.request({\n method: \"GET\",\n path: \"/_api/version\",\n qs: { details },\n });\n }\n\n /**\n * Returns a new {@link route.Route} instance for the given path (relative to the\n * database) that can be used to perform arbitrary HTTP requests.\n *\n * @param path - The database-relative URL of the route. Defaults to the\n * database API root.\n * @param headers - Default headers that should be sent with each request to\n * the route.\n *\n * @example\n * ```js\n * const db = new Database();\n * const myFoxxService = db.route(\"my-foxx-service\");\n * const response = await myFoxxService.post(\"users\", {\n * username: \"admin\",\n * password: \"hunter2\"\n * });\n * // response.body is the result of\n * // POST /_db/_system/my-foxx-service/users\n * // with JSON request body '{\"username\": \"admin\", \"password\": \"hunter2\"}'\n * ```\n */\n route(path?: string, headers?: Headers): Route {\n return new Route(this, path, headers);\n }\n\n /**\n * @internal\n *\n * Performs an arbitrary HTTP request against the database.\n *\n * If `absolutePath` is set to `true`, the database path will not be\n * automatically prepended to the `basePath`.\n *\n * @param T - Return type to use. Defaults to the response object type.\n * @param options - Options for this request.\n * @param transform - An optional function to transform the low-level\n * response object to a more useful return value.\n */\n request<T = any>(\n options: RequestOptions & { absolutePath?: boolean },\n transform?: false | ((res: ArangojsResponse) => T)\n ): Promise<T>;\n request<T = any>(\n {\n absolutePath = false,\n basePath,\n ...opts\n }: RequestOptions & { absolutePath?: boolean },\n transform: false | ((res: ArangojsResponse) => T) = (res) => res.body\n ): Promise<T> {\n if (!absolutePath) {\n basePath = `/_db/${encodeURIComponent(this._name)}${basePath || \"\"}`;\n }\n return this._connection.request(\n { basePath, ...opts },\n transform || undefined\n );\n }\n\n /**\n * Updates the URL list by requesting a list of all coordinators in the\n * cluster and adding any endpoints not initially specified in the\n * {@link connection.Config}.\n *\n * For long-running processes communicating with an ArangoDB cluster it is\n * recommended to run this method periodically (e.g. once per hour) to make\n * sure new coordinators are picked up correctly and can be used for\n * fail-over or load balancing.\n *\n * @param overwrite - If set to `true`, the existing host list will be\n * replaced instead of extended.\n *\n * @example\n * ```js\n * const db = new Database();\n * const interval = setInterval(\n * () => db.acquireHostList(),\n * 5 * 60 * 1000 // every 5 minutes\n * );\n *\n * // later\n * clearInterval(interval);\n * system.close();\n * ```\n */\n async acquireHostList(overwrite = false): Promise<void> {\n const urls: string[] = await this.request(\n { path: \"/_api/cluster/endpoints\" },\n (res) => res.body.endpoints.map((endpoint: any) => endpoint.endpoint)\n );\n if (urls.length > 0) {\n if (overwrite) this._connection.setHostList(urls);\n else this._connection.addToHostList(urls);\n }\n }\n\n /**\n * Closes all active connections of this database instance.\n *\n * Can be used to clean up idling connections during longer periods of\n * inactivity.\n *\n * **Note**: This method currently has no effect in the browser version of\n * arangojs.\n *\n * @example\n * ```js\n * const db = new Database();\n * const sessions = db.collection(\"sessions\");\n * // Clean up expired sessions once per hour\n * setInterval(async () => {\n * await db.query(aql`\n * FOR session IN ${sessions}\n * FILTER session.expires < DATE_NOW()\n * REMOVE session IN ${sessions}\n * `);\n * // Making sure to close the connections because they're no longer used\n * system.close();\n * }, 1000 * 60 * 60);\n * ```\n */\n close(): void {\n this._connection.close();\n }\n\n /**\n * Performs a request against every known coordinator and returns when the\n * request has succeeded against every coordinator or the timeout is reached.\n *\n * **Note**: This method is primarily intended to make database setup easier\n * in cluster scenarios and requires all coordinators to be known to arangojs\n * before the method is invoked. The method is not useful in single-server or\n * leader-follower replication scenarios.\n *\n * @example\n * ```js\n * const db = new Database({ loadBalancingStrategy: \"ROUND_ROBIN\" });\n * await system.acquireHostList();\n * const analyzer = db.analyzer(\"my-analyzer\");\n * await analyzer.create();\n * await db.waitForPropagation(\n * { path: `/_api/analyzer/${encodeURIComponent(analyzer.name)}` },\n * 30000\n * );\n * // Analyzer has been propagated to all coordinators and can safely be used\n * ```\n *\n * @param request - Request to perform against each known coordinator.\n * @param timeout - Maximum number of milliseconds to wait for propagation.\n */\n async waitForPropagation(\n request: RequestOptions,\n timeout?: number\n ): Promise<void>;\n async waitForPropagation(\n { basePath, ...request }: RequestOptions,\n timeout?: number\n ): Promise<void> {\n await this._connection.waitForPropagation(\n {\n ...request,\n basePath: `/_db/${encodeURIComponent(this._name)}${basePath || \"\"}`,\n },\n timeout\n );\n }\n\n /**\n * Methods for accessing the server-reported queue times of the mostly\n * recently received responses.\n */\n get queueTime(): QueueTimeMetrics {\n return this._connection.queueTime;\n }\n\n /**\n * Sets the limit for the number of values of the most recently received\n * server-reported queue times that can be accessed using\n * {@link Database#queueTime}.\n *\n * @param responseQueueTimeSamples - Number of values to maintain.\n */\n setResponseQueueTimeSamples(responseQueueTimeSamples: number) {\n this._connection.setResponseQueueTimeSamples(responseQueueTimeSamples);\n }\n //#endregion\n\n //#region auth\n /**\n * Updates the underlying connection's `authorization` header to use Basic\n * authentication with the given `username` and `password`, then returns\n * itself.\n *\n * @param username - The username to authenticate with.\n * @param password - The password to authenticate with.\n *\n * @example\n * ```js\n * const db = new Database();\n * db.useBasicAuth(\"admin\", \"hunter2\");\n * // with the username \"admin\" and password \"hunter2\".\n * ```\n */\n useBasicAuth(username: string = \"root\", password: string = \"\"): this {\n this._connection.setBasicAuth({ username, password });\n return this;\n }\n\n /**\n * Updates the underlying connection's `authorization` header to use Bearer\n * authentication with the given authentication `token`, then returns itself.\n *\n * @param token - The token to authenticate with.\n *\n * @example\n * ```js\n * const db = new Database();\n * db.useBearerAuth(\"keyboardcat\");\n * // The database instance now uses Bearer authentication.\n * ```\n */\n useBearerAuth(token: string): this {\n this._connection.setBearerAuth({ token });\n return this;\n }\n\n /**\n * Validates the given database credentials and exchanges them for an\n * authentication token, then uses the authentication token for future\n * requests and returns it.\n *\n * @param username - The username to authenticate with.\n * @param password - The password to authenticate with.\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.login(\"admin\", \"hunter2\");\n * // with an authentication token for the \"admin\" user.\n * ```\n */\n login(username: string = \"root\", password: string = \"\"): Promise<string> {\n return this.request(\n {\n method: \"POST\",\n path: \"/_open/auth\",\n body: { username, password },\n },\n (res) => {\n this.useBearerAuth(res.body.jwt);\n return res.body.jwt;\n }\n );\n }\n //#endregion\n\n //#region databases\n /**\n * Creates a new `Database` instance for the given `databaseName` that\n * shares this database's connection pool.\n *\n * See also {@link Database:constructor}.\n *\n * @param databaseName - Name of the database.\n *\n * @example\n * ```js\n * const systemDb = new Database();\n * const myDb = system.database(\"my_database\");\n * ```\n */\n database(databaseName: string) {\n return new Database(this as any, databaseName);\n }\n\n /**\n * Fetches the database description for the active database from the server.\n *\n * @example\n * ```js\n * const db = new Database();\n * const info = await db.get();\n * // the database exists\n * ```\n */\n get(): Promise<DatabaseInfo> {\n return this.request(\n { path: \"/_api/database/current\" },\n (res) => res.body.result\n );\n }\n\n /**\n * Checks whether the database exists.\n *\n * @example\n * ```js\n * const db = new Database();\n * const result = await db.exists();\n * // result indicates whether the database exists\n * ```\n */\n async exists(): Promise<boolean> {\n try {\n await this.get();\n return true;\n } catch (err: any) {\n if (isArangoError(err) && err.errorNum === DATABASE_NOT_FOUND) {\n return false;\n }\n throw err;\n }\n }\n\n /**\n * Creates a new database with the given `databaseName` with the given\n * `options` and returns a `Database` instance for that database.\n *\n * @param databaseName - Name of the database to create.\n * @param options - Options for creating the database.\n *\n * @example\n * ```js\n * const db = new Database();\n * const info = await db.createDatabase(\"mydb\", {\n * users: [{ username: \"root\" }]\n * });\n * // the database has been created\n * ```\n */\n createDatabase(\n databaseName: string,\n options?: CreateDatabaseOptions\n ): Promise<Database>;\n /**\n * Creates a new database with the given `databaseName` with the given\n * `users` and returns a `Database` instance for that database.\n *\n * @param databaseName - Name of the database to create.\n * @param users - Database users to create with the database.\n *\n * @example\n * ```js\n * const db = new Database();\n * const info = await db.createDatabase(\"mydb\", [{ username: \"root\" }]);\n * // the database has been created\n * ```\n */\n createDatabase(\n databaseName: string,\n users: CreateDatabaseUser[]\n ): Promise<Database>;\n createDatabase(\n databaseName: string,\n usersOrOptions: CreateDatabaseUser[] | CreateDatabaseOptions = {}\n ): Promise<Database> {\n const { users, ...options } = Array.isArray(usersOrOptions)\n ? { users: usersOrOptions }\n : usersOrOptions;\n return this.request(\n {\n method: \"POST\",\n path: \"/_api/database\",\n body: { name: databaseName.normalize(\"NFC\"), users, options },\n },\n () => this.database(databaseName)\n );\n }\n\n /**\n * Fetches all databases from the server and returns an array of their names.\n *\n * See also {@link Database#databases} and\n * {@link Database#listUserDatabases}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const names = await db.listDatabases();\n * // databases is an array of database names\n * ```\n */\n listDatabases(): Promise<string[]> {\n return this.request({ path: \"/_api/database\" }, (res) => res.body.result);\n }\n\n /**\n * Fetches all databases accessible to the active user from the server and\n * returns an array of their names.\n *\n * See also {@link Database#userDatabases} and\n * {@link Database#listDatabases}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const names = await db.listUserDatabases();\n * // databases is an array of database names\n * ```\n */\n listUserDatabases(): Promise<string[]> {\n return this.request(\n { path: \"/_api/database/user\" },\n (res) => res.body.result\n );\n }\n\n /**\n * Fetches all databases from the server and returns an array of `Database`\n * instances for those databases.\n *\n * See also {@link Database#listDatabases} and\n * {@link Database#userDatabases}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const names = await db.databases();\n * // databases is an array of databases\n * ```\n */\n databases(): Promise<Database[]> {\n return this.request({ path: \"/_api/database\" }, (res) =>\n (res.body.result as string[]).map((databaseName) =>\n this.database(databaseName)\n )\n );\n }\n\n /**\n * Fetches all databases accessible to the active user from the server and\n * returns an array of `Database` instances for those databases.\n *\n * See also {@link Database#listUserDatabases} and\n * {@link Database#databases}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const names = await db.userDatabases();\n * // databases is an array of databases\n * ```\n */\n userDatabases(): Promise<Database[]> {\n return this.request({ path: \"/_api/database/user\" }, (res) =>\n (res.body.result as string[]).map((databaseName) =>\n this.database(databaseName)\n )\n );\n }\n\n /**\n * Deletes the database with the given `databaseName` from the server.\n *\n * @param databaseName - Name of the database to delete.\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.dropDatabase(\"mydb\");\n * // database \"mydb\" no longer exists\n * ```\n */\n dropDatabase(databaseName: string): Promise<boolean> {\n databaseName = databaseName.normalize(\"NFC\");\n return this.request(\n {\n method: \"DELETE\",\n path: `/_api/database/${encodeURIComponent(databaseName)}`,\n },\n (res) => res.body.result\n );\n }\n //#endregion\n\n //#region collections\n /**\n * Returns a `Collection` instance for the given collection name.\n *\n * In TypeScript the collection implements both the\n * {@link collection.DocumentCollection} and {@link collection.EdgeCollection}\n * interfaces and can be cast to either type to enforce a stricter API.\n *\n * @param T - Type to use for document data. Defaults to `any`.\n * @param collectionName - Name of the edge collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"potatoes\");\n * ```\n *\n * @example\n * ```ts\n * interface Person {\n * name: string;\n * }\n * const db = new Database();\n * const persons = db.collection<Person>(\"persons\");\n * ```\n *\n * @example\n * ```ts\n * interface Person {\n * name: string;\n * }\n * interface Friend {\n * startDate: number;\n * endDate?: number;\n * }\n * const db = new Database();\n * const documents = db.collection(\"persons\") as DocumentCollection<Person>;\n * const edges = db.collection(\"friends\") as EdgeCollection<Friend>;\n * ```\n */\n collection<T extends Record<string, any> = any>(\n collectionName: string\n ): DocumentCollection<T> & EdgeCollection<T> {\n collectionName = collectionName.normalize(\"NFC\");\n if (!this._collections.has(collectionName)) {\n this._collections.set(\n collectionName,\n new Collection(this, collectionName)\n );\n }\n return this._collections.get(collectionName)!;\n }\n\n /**\n * Creates a new collection with the given `collectionName` and `options`,\n * then returns a {@link collection.DocumentCollection} instance for the new collection.\n *\n * @param T - Type to use for document data. Defaults to `any`.\n * @param collectionName - Name of the new collection.\n * @param options - Options for creating the collection.\n *\n * @example\n * ```ts\n * const db = new Database();\n * const documents = db.createCollection(\"persons\");\n * ```\n *\n * @example\n * ```ts\n * interface Person {\n * name: string;\n * }\n * const db = new Database();\n * const documents = db.createCollection<Person>(\"persons\");\n * ```\n */\n async createCollection<T extends Record<string, any> = any>(\n collectionName: string,\n options?: CreateCollectionOptions & {\n type?: CollectionType.DOCUMENT_COLLECTION;\n }\n ): Promise<DocumentCollection<T>>;\n /**\n * Creates a new edge collection with the given `collectionName` and\n * `options`, then returns an {@link collection.EdgeCollection} instance for the new\n * edge collection.\n *\n * @param T - Type to use for edge document data. Defaults to `any`.\n * @param collectionName - Name of the new collection.\n * @param options - Options for creating the collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const edges = db.createCollection(\"friends\", {\n * type: CollectionType.EDGE_COLLECTION\n * });\n * ```\n *\n * @example\n * ```ts\n * interface Friend {\n * startDate: number;\n * endDate?: number;\n * }\n * const db = new Database();\n * const edges = db.createCollection<Friend>(\"friends\", {\n * type: CollectionType.EDGE_COLLECTION\n * });\n * ```\n */\n async createCollection<T extends Record<string, any> = any>(\n collectionName: string,\n options: CreateCollectionOptions & {\n type: CollectionType.EDGE_COLLECTION;\n }\n ): Promise<EdgeCollection<T>>;\n async createCollection<T extends Record<string, any> = any>(\n collectionName: string,\n options?: CreateCollectionOptions & { type?: CollectionType }\n ): Promise<DocumentCollection<T> & EdgeCollection<T>> {\n const collection = this.collection(collectionName);\n await collection.create(options);\n return collection;\n }\n\n /**\n * Creates a new edge collection with the given `collectionName` and\n * `options`, then returns an {@link collection.EdgeCollection} instance for the new\n * edge collection.\n *\n * This is a convenience method for calling {@link Database#createCollection}\n * with `options.type` set to `EDGE_COLLECTION`.\n *\n * @param T - Type to use for edge document data. Defaults to `any`.\n * @param collectionName - Name of the new collection.\n * @param options - Options for creating the collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const edges = db.createEdgeCollection(\"friends\");\n * ```\n *\n * @example\n * ```ts\n * interface Friend {\n * startDate: number;\n * endDate?: number;\n * }\n * const db = new Database();\n * const edges = db.createEdgeCollection<Friend>(\"friends\");\n * ```\n */\n async createEdgeCollection<T extends Record<string, any> = any>(\n collectionName: string,\n options?: CreateCollectionOptions\n ): Promise<EdgeCollection<T>> {\n return this.createCollection(collectionName, {\n ...options,\n type: CollectionType.EDGE_COLLECTION,\n });\n }\n\n /**\n * Renames the collection `collectionName` to `newName`.\n *\n * Additionally removes any stored `Collection` instance for\n * `collectionName` from the `Database` instance's internal cache.\n *\n * **Note**: Renaming collections may not be supported when ArangoDB is\n * running in a cluster configuration.\n *\n * @param collectionName - Current name of the collection.\n * @param newName - The new name of the collection.\n */\n async renameCollection(\n collectionName: string,\n newName: string\n ): Promise<ArangoApiResponse<CollectionMetadata>> {\n collectionName = collectionName.normalize(\"NFC\");\n const result = await this.request({\n method: \"PUT\",\n path: `/_api/collection/${encodeURIComponent(collectionName)}/rename`,\n body: { name: newName.normalize(\"NFC\") },\n });\n this._collections.delete(collectionName);\n return result;\n }\n\n /**\n * Fetches all collections from the database and returns an array of\n * collection descriptions.\n *\n * See also {@link Database#collections}.\n *\n * @param excludeSystem - Whether system collections should be excluded.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collections = await db.listCollections();\n * // collections is an array of collection descriptions\n * // not including system collections\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collections = await db.listCollections(false);\n * // collections is an array of collection descriptions\n * // including system collections\n * ```\n */\n listCollections(\n excludeSystem: boolean = true\n ): Promise<CollectionMetadata[]> {\n return this.request(\n {\n path: \"/_api/collection\",\n qs: { excludeSystem },\n },\n (res) => res.body.result\n );\n }\n\n /**\n * Fetches all collections from the database and returns an array of\n * `Collection` instances.\n *\n * In TypeScript these instances implement both the\n * {@link collection.DocumentCollection} and {@link collection.EdgeCollection}\n * interfaces and can be cast to either type to enforce a stricter API.\n *\n * See also {@link Database#listCollections}.\n *\n * @param excludeSystem - Whether system collections should be excluded.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collections = await db.collections();\n * // collections is an array of DocumentCollection and EdgeCollection\n * // instances not including system collections\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collections = await db.collections(false);\n * // collections is an array of DocumentCollection and EdgeCollection\n * // instances including system collections\n * ```\n */\n async collections(\n excludeSystem: boolean = true\n ): Promise<Array<DocumentCollection & EdgeCollection>> {\n const collections = await this.listCollections(excludeSystem);\n return collections.map((data) => this.collection(data.name));\n }\n //#endregion\n\n //#region graphs\n /**\n * Returns a {@link graph.Graph} instance representing the graph with the given\n * `graphName`.\n *\n * @param graphName - Name of the graph.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * ```\n */\n graph(graphName: string): Graph {\n graphName = graphName.normalize(\"NFC\");\n if (!this._graphs.has(graphName)) {\n this._graphs.set(graphName, new Graph(this, graphName));\n }\n return this._graphs.get(graphName)!;\n }\n\n /**\n * Creates a graph with the given `graphName` and `edgeDefinitions`, then\n * returns a {@link graph.Graph} instance for the new graph.\n *\n * @param graphName - Name of the graph to be created.\n * @param edgeDefinitions - An array of edge definitions.\n * @param options - An object defining the properties of the graph.\n */\n async createGraph(\n graphName: string,\n edgeDefinitions: EdgeDefinitionOptions[],\n options?: CreateGraphOptions\n ): Promise<Graph> {\n const graph = this.graph(graphName.normalize(\"NFC\"));\n await graph.create(edgeDefinitions, options);\n return graph;\n }\n\n /**\n * Fetches all graphs from the database and returns an array of graph\n * descriptions.\n *\n * See also {@link Database#graphs}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graphs = await db.listGraphs();\n * // graphs is an array of graph descriptions\n * ```\n */\n listGraphs(): Promise<GraphInfo[]> {\n return this.request({ path: \"/_api/gharial\" }, (res) => res.body.graphs);\n }\n\n /**\n * Fetches all graphs from the database and returns an array of {@link graph.Graph}\n * instances for those graphs.\n *\n * See also {@link Database#listGraphs}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graphs = await db.graphs();\n * // graphs is an array of Graph instances\n * ```\n */\n async graphs(): Promise<Graph[]> {\n const graphs = await this.listGraphs();\n return graphs.map((data: any) => this.graph(data._key));\n }\n //#endregion\n\n //#region views\n /**\n * Returns a {@link view.View} instance for the given `viewName`.\n *\n * @param viewName - Name of the ArangoSearch or SearchAlias View.\n *\n * @example\n * ```js\n * const db = new Database();\n * const view = db.view(\"potatoes\");\n * ```\n */\n view(viewName: string): View {\n viewName = viewName.normalize(\"NFC\");\n if (!this._views.has(viewName)) {\n this._views.set(viewName, new View(this, viewName));\n }\n return this._views.get(viewName)!;\n }\n\n /**\n * Creates a new View with the given `viewName` and `options`, then returns a\n * {@link view.View} instance for the new View.\n *\n * @param viewName - Name of the View.\n * @param options - An object defining the properties of the View.\n *\n * @example\n * ```js\n * const db = new Database();\n * const view = await db.createView(\"potatoes\", { type: \"arangosearch\" });\n * // the ArangoSearch View \"potatoes\" now exists\n * ```\n */\n async createView(\n viewName: string,\n options: CreateViewOptions\n ): Promise<View> {\n const view = this.view(viewName.normalize(\"NFC\"));\n await view.create(options);\n return view;\n }\n\n /**\n * Renames the view `viewName` to `newName`.\n *\n * Additionally removes any stored {@link view.View} instance for `viewName` from\n * the `Database` instance's internal cache.\n *\n * **Note**: Renaming views may not be supported when ArangoDB is running in\n * a cluster configuration.\n *\n * @param viewName - Current name of the view.\n * @param newName - The new name of the view.\n */\n async renameView(\n viewName: string,\n newName: string\n ): Promise<ArangoApiResponse<ViewDescription>> {\n viewName = viewName.normalize(\"NFC\");\n const result = await this.request({\n method: \"PUT\",\n path: `/_api/view/${encodeURIComponent(viewName)}/rename`,\n body: { name: newName.normalize(\"NFC\") },\n });\n this._views.delete(viewName);\n return result;\n }\n\n /**\n * Fetches all Views from the database and returns an array of View\n * descriptions.\n *\n * See also {@link Database#views}.\n *\n * @example\n * ```js\n * const db = new Database();\n *\n * const views = await db.listViews();\n * // views is an array of View descriptions\n * ```\n */\n listViews(): Promise<ViewDescription[]> {\n return this.request({ path: \"/_api/view\" }, (res) => res.body.result);\n }\n\n /**\n * Fetches all Views from the database and returns an array of\n * {@link view.View} instances\n * for the Views.\n *\n * See also {@link Database#listViews}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const views = await db.views();\n * // views is an array of ArangoSearch View instances\n * ```\n */\n async views(): Promise<View[]> {\n const views = await this.listViews();\n return views.map((data) => this.view(data.name));\n }\n //#endregion\n\n //#region analyzers\n /**\n * Returns an {@link analyzer.Analyzer} instance representing the Analyzer with the\n * given `analyzerName`.\n *\n * @example\n * ```js\n * const db = new Database();\n * const analyzer = db.analyzer(\"some-analyzer\");\n * const info = await analyzer.get();\n * ```\n */\n analyzer(analyzerName: string): Analyzer {\n analyzerName = analyzerName.normalize(\"NFC\");\n if (!this._analyzers.has(analyzerName)) {\n this._analyzers.set(analyzerName, new Analyzer(this, analyzerName));\n }\n return this._analyzers.get(analyzerName)!;\n }\n\n /**\n * Creates a new Analyzer with the given `analyzerName` and `options`, then\n * returns an {@link analyzer.Analyzer} instance for the new Analyzer.\n *\n * @param analyzerName - Name of the Analyzer.\n * @param options - An object defining the properties of the Analyzer.\n *\n * @example\n * ```js\n * const db = new Database();\n * const analyzer = await db.createAnalyzer(\"potatoes\", { type: \"identity\" });\n * // the identity Analyzer \"potatoes\" now exists\n * ```\n */\n async createAnalyzer(\n analyzerName: string,\n options: CreateAnalyzerOptions\n ): Promise<Analyzer> {\n const analyzer = this.analyzer(analyzerName);\n await analyzer.create(options);\n return analyzer;\n }\n\n /**\n * Fetches all Analyzers visible in the database and returns an array of\n * Analyzer descriptions.\n *\n * See also {@link Database#analyzers}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const analyzers = await db.listAnalyzers();\n * // analyzers is an array of Analyzer descriptions\n * ```\n */\n listAnalyzers(): Promise<AnalyzerDescription[]> {\n return this.request({ path: \"/_api/analyzer\" }, (res) => res.body.result);\n }\n\n /**\n * Fetches all Analyzers visible in the database and returns an array of\n * {@link analyzer.Analyzer} instances for those Analyzers.\n *\n * See also {@link Database#listAnalyzers}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const analyzers = await db.analyzers();\n * // analyzers is an array of Analyzer instances\n * ```\n */\n async analyzers(): Promise<Analyzer[]> {\n const analyzers = await this.listAnalyzers();\n return analyzers.map((data) => this.analyzer(data.name));\n }\n //#endregion\n\n //#region users\n /**\n * Fetches all ArangoDB users visible to the authenticated user and returns\n * an array of user objects.\n *\n * @example\n * ```js\n * const db = new Database();\n * const users = await db.listUsers();\n * // users is an array of user objects\n * ```\n */\n listUsers(): Promise<ArangoUser[]> {\n return this.request({\n absolutePath: true,\n path: \"/_api/user\",\n });\n }\n\n /**\n * Fetches the user data of a single ArangoDB user.\n *\n * @param username - Name of the ArangoDB user to fetch.\n *\n * @example\n * ```js\n * const db = new Database();\n * const user = await db.getUser(\"steve\");\n * // user is the user object for the user named \"steve\"\n * ```\n */\n getUser(username: string): Promise<ArangoApiResponse<ArangoUser>> {\n return this.request({\n absolutePath: true,\n path: `/_api/user/${encodeURIComponent(username)}`,\n });\n }\n\n /**\n * Creates a new ArangoDB user with the given password.\n *\n * @param username - Name of the ArangoDB user to create.\n * @param passwd - Password of the new ArangoDB user.\n *\n * @example\n * ```js\n * const db = new Database();\n * const user = await db.createUser(\"steve\", \"hunter2\");\n * // The user \"steve\" has been created\n * ```\n */\n createUser(\n username: string,\n passwd: string\n ): Promise<ArangoApiResponse<ArangoUser>>;\n /**\n * Creates a new ArangoDB user with the given options.\n *\n * @param username - Name of the ArangoDB user to create.\n * @param options - Additional options for creating the ArangoDB user.\n *\n * @example\n * ```js\n * const db = new Database();\n * const user = await db.createUser(\"steve\", { passwd: \"hunter2\" });\n * // The user \"steve\" has been created\n * ```\n */\n createUser(\n username: string,\n options: UserOptions\n ): Promise<ArangoApiResponse<ArangoUser>>;\n createUser(\n username: string,\n options: string | UserOptions\n ): Promise<ArangoApiResponse<ArangoUser>> {\n if (typeof options === \"string\") {\n options = { passwd: options };\n }\n return this.request(\n {\n absolutePath: true,\n method: \"POST\",\n path: \"/_api/user\",\n body: { user: username, ...options },\n },\n (res) => res.body\n );\n }\n\n /**\n * Sets the password of a given ArangoDB user to the new value.\n *\n * @param username - Name of the ArangoDB user to change the password for.\n * @param passwd - New password for the ArangoDB user.\n *\n * @example\n * ```js\n * const db = new Database();\n * const user = await db.updateUser(\"steve\", \"hunter2\");\n * // The user \"steve\" has received a new password\n * ```\n */\n updateUser(\n username: string,\n passwd: string\n ): Promise<ArangoApiResponse<ArangoUser>>;\n /**\n * Updates the ArangoDB user with the new options.\n *\n * @param username - Name of the ArangoDB user to modify.\n * @param options - Options of the ArangoDB user to modify.\n *\n * @example\n * ```js\n * const db = new Database();\n * const user = await db.updateUser(\"steve\", { active: false });\n * // The user \"steve\" has been set to inactive\n * ```\n */\n updateUser(\n username: string,\n options: Partial<UserOptions>\n ): Promise<ArangoApiResponse<ArangoUser>>;\n updateUser(\n username: string,\n options: string | Partial<UserOptions>\n ): Promise<ArangoApiResponse<ArangoUser>> {\n if (typeof options === \"string\") {\n options = { passwd: options };\n }\n return this.request(\n {\n absolutePath: true,\n method: \"PATCH\",\n path: `/api/user/${encodeURIComponent(username)}`,\n body: options,\n },\n (res) => res.body\n );\n }\n\n /**\n * Replaces the ArangoDB user's option with the new options.\n *\n * @param username - Name of the ArangoDB user to modify.\n * @param options - New options to replace the user's existing options.\n *\n * @example\n * ```js\n * const db = new Database();\n * const user = await db.replaceUser(\"steve\", { passwd: \"\", active: false });\n * // The user \"steve\" has been set to inactive with an empty password\n * ```\n */\n replaceUser(\n username: string,\n options: UserOptions\n ): Promise<ArangoApiResponse<ArangoUser>> {\n if (typeof options === \"string\") {\n options = { passwd: options };\n }\n return this.request(\n {\n absolutePath: true,\n method: \"PUT\",\n path: `/api/user/${encodeURIComponent(username)}`,\n body: options,\n },\n (res) => res.body\n );\n }\n\n /**\n * Removes the ArangoDB user with the given username from the server.\n *\n * @param username - Name of the ArangoDB user to remove.\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.removeUser(\"steve\");\n * // The user \"steve\" has been removed\n * ```\n */\n removeUser(\n username: string\n ): Promise<ArangoApiResponse<Record<string, never>>> {\n return this.request(\n {\n absolutePath: true,\n method: \"DELETE\",\n path: `/_api/user/${encodeURIComponent(username)}`,\n },\n (res) => res.body\n );\n }\n\n /**\n * Fetches the given ArangoDB user's access level for the database, or the\n * given collection in the given database.\n *\n * @param username - Name of the ArangoDB user to fetch the access level for.\n * @param database - Database to fetch the access level for.\n * @param collection - Collection to fetch the access level for.\n *\n * @example\n * ```js\n * const db = new Database();\n * const accessLevel = await db.getUserAccessLevel(\"steve\");\n * // The access level of the user \"steve\" has been fetched for the current\n * // database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const accessLevel = await db.getUserAccessLevel(\"steve\", {\n * database: \"staging\"\n * });\n * // The access level of the user \"steve\" has been fetched for the \"staging\"\n * // database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const accessLevel = await db.getUserAccessLevel(\"steve\", {\n * collection: \"pokemons\"\n * });\n * // The access level of the user \"steve\" has been fetched for the\n * // \"pokemons\" collection in the current database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const accessLevel = await db.getUserAccessLevel(\"steve\", {\n * database: \"staging\",\n * collection: \"pokemons\"\n * });\n * // The access level of the user \"steve\" has been fetched for the\n * // \"pokemons\" collection in the \"staging\" database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const staging = db.database(\"staging\");\n * const accessLevel = await db.getUserAccessLevel(\"steve\", {\n * database: staging\n * });\n * // The access level of the user \"steve\" has been fetched for the \"staging\"\n * // database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const staging = db.database(\"staging\");\n * const accessLevel = await db.getUserAccessLevel(\"steve\", {\n * collection: staging.collection(\"pokemons\")\n * });\n * // The access level of the user \"steve\" has been fetched for the\n * // \"pokemons\" collection in database \"staging\".\n * ```\n */\n getUserAccessLevel(\n username: string,\n { database, collection }: UserAccessLevelOptions\n ): Promise<AccessLevel> {\n const databaseName = isArangoDatabase(database)\n ? database.name\n : database?.normalize(\"NFC\") ??\n (isArangoCollection(collection)\n ? ((collection as any)._db as Database).name\n : this._name);\n const suffix = collection\n ? `/${encodeURIComponent(\n isArangoCollection(collection)\n ? collection.name\n : collection.normalize(\"NFC\")\n )}`\n : \"\";\n return this.request(\n {\n absolutePath: true,\n path: `/_api/user/${encodeURIComponent(\n username\n )}/database/${encodeURIComponent(databaseName)}${suffix}`,\n },\n (res) => res.body.result\n );\n }\n\n /**\n * Sets the given ArangoDB user's access level for the database, or the\n * given collection in the given database.\n *\n * @param username - Name of the ArangoDB user to set the access level for.\n * @param database - Database to set the access level for.\n * @param collection - Collection to set the access level for.\n * @param grant - Access level to set for the given user.\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.setUserAccessLevel(\"steve\", { grant: \"rw\" });\n * // The user \"steve\" now has read-write access to the current database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.setUserAccessLevel(\"steve\", {\n * database: \"staging\",\n * grant: \"rw\"\n * });\n * // The user \"steve\" now has read-write access to the \"staging\" database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.setUserAccessLevel(\"steve\", {\n * collection: \"pokemons\",\n * grant: \"rw\"\n * });\n * // The user \"steve\" now has read-write access to the \"pokemons\" collection\n * // in the current database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.setUserAccessLevel(\"steve\", {\n * database: \"staging\",\n * collection: \"pokemons\",\n * grant: \"rw\"\n * });\n * // The user \"steve\" now has read-write access to the \"pokemons\" collection\n * // in the \"staging\" database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const staging = db.database(\"staging\");\n * await db.setUserAccessLevel(\"steve\", {\n * database: staging,\n * grant: \"rw\"\n * });\n * // The user \"steve\" now has read-write access to the \"staging\" database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const staging = db.database(\"staging\");\n * await db.setUserAccessLevel(\"steve\", {\n * collection: staging.collection(\"pokemons\"),\n * grant: \"rw\"\n * });\n * // The user \"steve\" now has read-write access to the \"pokemons\" collection\n * // in database \"staging\".\n * ```\n */\n setUserAccessLevel(\n username: string,\n {\n database,\n collection,\n grant,\n }: UserAccessLevelOptions & { grant: AccessLevel }\n ): Promise<ArangoApiResponse<Record<string, AccessLevel>>> {\n const databaseName = isArangoDatabase(database)\n ? database.name\n : database?.normalize(\"NFC\") ??\n (isArangoCollection(collection)\n ? ((collection as any)._db as Database).name\n : this._name);\n const suffix = collection\n ? `/${encodeURIComponent(\n isArangoCollection(collection)\n ? collection.name\n : collection.normalize(\"NFC\")\n )}`\n : \"\";\n return this.request(\n {\n absolutePath: true,\n method: \"PUT\",\n path: `/_api/user/${encodeURIComponent(\n username\n )}/database/${encodeURIComponent(databaseName)}${suffix}`,\n body: { grant },\n },\n (res) => res.body\n );\n }\n\n /**\n * Clears the given ArangoDB user's access level for the database, or the\n * given collection in the given database.\n *\n * @param username - Name of the ArangoDB user to clear the access level for.\n * @param database - Database to clear the access level for.\n * @param collection - Collection to clear the access level for.\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.clearUserAccessLevel(\"steve\");\n * // The access level of the user \"steve\" has been cleared for the current\n * // database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.clearUserAccessLevel(\"steve\", { database: \"staging\" });\n * // The access level of the user \"steve\" has been cleared for the \"staging\"\n * // database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.clearUserAccessLevel(\"steve\", { collection: \"pokemons\" });\n * // The access level of the user \"steve\" has been cleared for the\n * // \"pokemons\" collection in the current database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.clearUserAccessLevel(\"steve\", {\n * database: \"staging\",\n * collection: \"pokemons\"\n * });\n * // The access level of the user \"steve\" has been cleared for the\n * // \"pokemons\" collection in the \"staging\" database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const staging = db.database(\"staging\");\n * await db.clearUserAccessLevel(\"steve\", { database: staging });\n * // The access level of the user \"steve\" has been cleared for the \"staging\"\n * // database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const staging = db.database(\"staging\");\n * await db.clearUserAccessLevel(\"steve\", {\n * collection: staging.collection(\"pokemons\")\n * });\n * // The access level of the user \"steve\" has been cleared for the\n * // \"pokemons\" collection in database \"staging\".\n * ```\n */\n clearUserAccessLevel(\n username: string,\n { database, collection }: UserAccessLevelOptions\n ): Promise<ArangoApiResponse<Record<string, AccessLevel>>> {\n const databaseName = isArangoDatabase(database)\n ? database.name\n : database?.normalize(\"NFC\") ??\n (isArangoCollection(collection)\n ? ((collection as any)._db as Database).name\n : this._name);\n const suffix = collection\n ? `/${encodeURIComponent(\n isArangoCollection(collection)\n ? collection.name\n : collection.normalize(\"NFC\")\n )}`\n : \"\";\n return this.request(\n {\n absolutePath: true,\n method: \"DELETE\",\n path: `/_api/user/${encodeURIComponent(\n username\n )}/database/${encodeURIComponent(databaseName)}${suffix}`,\n },\n (res) => res.body\n );\n }\n\n /**\n * Fetches an object mapping names of databases to the access level of the\n * given ArangoDB user for those databases.\n *\n * @param username - Name of the ArangoDB user to fetch the access levels for.\n * @param full - Whether access levels for collections should be included.\n *\n * @example\n * ```js\n * const db = new Database();\n * const accessLevels = await db.getUserDatabases(\"steve\");\n * for (const [databaseName, accessLevel] of Object.entries(accessLevels)) {\n * console.log(`${databaseName}: ${accessLevel}`);\n * }\n * ```\n */\n getUserDatabases(\n username: string,\n full?: false\n ): Promise<Record<string, AccessLevel>>;\n /**\n * Fetches an object mapping names of databases to the access level of the\n * given ArangoDB user for those databases and the collections within each\n * database.\n *\n * @param username - Name of the ArangoDB user to fetch the access levels for.\n * @param full - Whether access levels for collections should be included.\n *\n * @example\n * ```js\n * const db = new Database();\n * const accessLevels = await db.getUserDatabases(\"steve\", true);\n * for (const [databaseName, obj] of Object.entries(accessLevels)) {\n * console.log(`${databaseName}: ${obj.permission}`);\n * for (const [collectionName, accessLevel] of Object.entries(obj.collections)) {\n * console.log(`${databaseName}/${collectionName}: ${accessLevel}`);\n * }\n * }\n * ```\n */\n getUserDatabases(\n username: string,\n full: true\n ): Promise<\n Record<\n string,\n {\n permission: AccessLevel;\n collections: Record<string, AccessLevel | \"undefined\">;\n }\n >\n >;\n getUserDatabases(username: string, full?: boolean) {\n return this.request(\n {\n absolutePath: true,\n path: `/_api/user/${encodeURIComponent(username)}/database`,\n qs: { full },\n },\n (res) => res.body.result\n );\n }\n //#endregion\n\n //#region transactions\n /**\n * Performs a server-side JavaScript transaction and returns its return\n * value.\n *\n * Collections can be specified as collection names (strings) or objects\n * implementing the {@link collection.ArangoCollection} interface: `Collection`,\n * {@link graph.GraphVertexCollection}, {@link graph.GraphEdgeCollection} as well as\n * (in TypeScript) {@link collection.DocumentCollection} and {@link collection.EdgeCollection}.\n *\n * **Note**: The `action` function will be evaluated and executed on the\n * server inside ArangoDB's embedded JavaScript environment and can not\n * access any values other than those passed via the `params` option.\n *\n * See the official ArangoDB documentation for\n * [the JavaScript `@arangodb` module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html)\n * for information about accessing the database from within ArangoDB's\n * server-side JavaScript environment.\n *\n * @param collections - Collections involved in the transaction.\n * @param action - A string evaluating to a JavaScript function to be\n * executed on the server.\n * @param options - Options for the transaction. If `options.allowImplicit`\n * is specified, it will be used if `collections.allowImplicit` was not\n * specified.\n *\n * @example\n * ```js\n * const db = new Database();\n *\n * const action = `\n * function(params) {\n * // This code will be executed inside ArangoDB!\n * const { query } = require(\"@arangodb\");\n * return query\\`\n * FOR user IN _users\n * FILTER user.age > ${params.age}\n * RETURN u.user\n * \\`.toArray();\n * }\n * `);\n *\n * const result = await db.executeTransaction({\n * read: [\"_users\"]\n * }, action, {\n * params: { age: 12 }\n * });\n * // result contains the return value of the action\n * ```\n */\n executeTransaction(\n collections: TransactionCollections & { allowImplicit?: boolean },\n action: string,\n options?: TransactionOptions & { params?: any }\n ): Promise<any>;\n /**\n * Performs a server-side transaction and returns its return value.\n *\n * Collections can be specified as collection names (strings) or objects\n * implementing the {@link collection.ArangoCollection} interface: `Collection`,\n * {@link graph.GraphVertexCollection}, {@link graph.GraphEdgeCollection} as well as\n * (in TypeScript) {@link collection.DocumentCollection} and {@link collection.EdgeCollection}.\n *\n * **Note**: The `action` function will be evaluated and executed on the\n * server inside ArangoDB's embedded JavaScript environment and can not\n * access any values other than those passed via the `params` option.\n * See the official ArangoDB documentation for\n * [the JavaScript `@arangodb` module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html)\n * for information about accessing the database from within ArangoDB's\n * server-side JavaScript environment.\n *\n * @param collections - Collections that can be read from and written to\n * during the transaction.\n * @param action - A string evaluating to a JavaScript function to be\n * executed on the server.\n * @param options - Options for the transaction.\n *\n * @example\n * ```js\n * const db = new Database();\n *\n * const action = `\n * function(params) {\n * // This code will be executed inside ArangoDB!\n * const { query } = require(\"@arangodb\");\n * return query\\`\n * FOR user IN _users\n * FILTER user.age > ${params.age}\n * RETURN u.user\n * \\`.toArray();\n * }\n * `);\n *\n * const result = await db.executeTransaction([\"_users\"], action, {\n * params: { age: 12 }\n * });\n * // result contains the return value of the action\n * ```\n */\n executeTransaction(\n collections: (string | ArangoCollection)[],\n action: string,\n options?: TransactionOptions & { params?: any }\n ): Promise<any>;\n /**\n * Performs a server-side transaction and returns its return value.\n *\n * The Collection can be specified as a collection name (string) or an object\n * implementing the {@link collection.ArangoCollection} interface: `Collection`,\n * {@link graph.GraphVertexCollection}, {@link graph.GraphEdgeCollection} as well as\n * (in TypeScript) {@link collection.DocumentCollection} and {@link collection.EdgeCollection}.\n *\n * **Note**: The `action` function will be evaluated and executed on the\n * server inside ArangoDB's embedded JavaScript environment and can not\n * access any values other than those passed via the `params` option.\n * See the official ArangoDB documentation for\n * [the JavaScript `@arangodb` module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html)\n * for information about accessing the database from within ArangoDB's\n * server-side JavaScript environment.\n *\n * @param collection - A collection that can be read from and written to\n * during the transaction.\n * @param action - A string evaluating to a JavaScript function to be\n * executed on the server.\n * @param options - Options for the transaction.\n *\n * @example\n * ```js\n * const db = new Database();\n *\n * const action = `\n * function(params) {\n * // This code will be executed inside ArangoDB!\n * const { query } = require(\"@arangodb\");\n * return query\\`\n * FOR user IN _users\n * FILTER user.age > ${params.age}\n * RETURN u.user\n * \\`.toArray();\n * }\n * `);\n *\n * const result = await db.executeTransaction(\"_users\", action, {\n * params: { age: 12 }\n * });\n * // result contains the return value of the action\n * ```\n */\n executeTransaction(\n collection: string | ArangoCollection,\n action: string,\n options?: TransactionOptions & { params?: any }\n ): Promise<any>;\n executeTransaction(\n collections:\n | (TransactionCollections & { allowImplicit?: boolean })\n | (string | ArangoCollection)[]\n | string\n | ArangoCollection,\n action: string,\n options: TransactionOptions & { params?: any } = {}\n ): Promise<any> {\n const { allowDirtyRead = undefined, ...opts } = options;\n return this.request(\n {\n method: \"POST\",\n path: \"/_api/transaction\",\n allowDirtyRead,\n body: {\n collections: coerceTransactionCollections(collections),\n action,\n ...opts,\n },\n },\n (res) => res.body.result\n );\n }\n\n /**\n * Returns a {@link transaction.Transaction} instance for an existing streaming\n * transaction with the given `id`.\n *\n * See also {@link Database#beginTransaction}.\n *\n * @param id - The `id` of an existing stream transaction.\n *\n * @example\n * ```js\n * const trx1 = await db.beginTransaction(collections);\n * const id = trx1.id;\n * // later\n * const trx2 = db.transaction(id);\n * await trx2.commit();\n * ```\n */\n transaction(transactionId: string): Transaction {\n return new Transaction(this, transactionId);\n }\n\n /**\n * Begins a new streaming transaction for the given collections, then returns\n * a {@link transaction.Transaction} instance for the transaction.\n *\n * Collections can be specified as collection names (strings) or objects\n * implementing the {@link collection.ArangoCollection} interface: `Collection`,\n * {@link graph.GraphVertexCollection}, {@link graph.GraphEdgeCollection} as\n * well as (in TypeScript) {@link collection.DocumentCollection} and\n * {@link collection.EdgeCollection}.\n *\n * @param collections - Collections involved in the transaction.\n * @param options - Options for the transaction.\n *\n * @example\n * ```js\n * const vertices = db.collection(\"vertices\");\n * const edges = db.collection(\"edges\");\n * const trx = await db.beginTransaction({\n * read: [\"vertices\"],\n * write: [edges] // collection instances can be passed directly\n * });\n * const start = await trx.step(() => vertices.document(\"a\"));\n * const end = await trx.step(() => vertices.document(\"b\"));\n * await trx.step(() => edges.save({ _from: start._id, _to: end._id }));\n * await trx.commit();\n * ```\n */\n beginTransaction(\n collections: TransactionCollections,\n options?: TransactionOptions\n ): Promise<Transaction>;\n /**\n * Begins a new streaming transaction for the given collections, then returns\n * a {@link transaction.Transaction} instance for the transaction.\n *\n * Collections can be specified as collection names (strings) or objects\n * implementing the {@link collection.ArangoCollection} interface: `Collection`,\n * {@link graph.GraphVertexCollection}, {@link graph.GraphEdgeCollection} as well as\n * (in TypeScript) {@link collection.DocumentCollection} and {@link collection.EdgeCollection}.\n *\n * @param collections - Collections that can be read from and written to\n * during the transaction.\n * @param options - Options for the transaction.\n *\n * @example\n * ```js\n * const vertices = db.collection(\"vertices\");\n * const edges = db.collection(\"edges\");\n * const trx = await db.beginTransaction([\n * \"vertices\",\n * edges // collection instances can be passed directly\n * ]);\n * const start = await trx.step(() => vertices.document(\"a\"));\n * const end = await trx.step(() => vertices.document(\"b\"));\n * await trx.step(() => edges.save({ _from: start._id, _to: end._id }));\n * await trx.commit();\n * ```\n */\n beginTransaction(\n collections: (string | ArangoCollection)[],\n options?: TransactionOptions\n ): Promise<Transaction>;\n /**\n * Begins a new streaming transaction for the given collections, then returns\n * a {@link transaction.Transaction} instance for the transaction.\n *\n * The Collection can be specified as a collection name (string) or an object\n * implementing the {@link collection.ArangoCollection} interface: `Collection`,\n * {@link graph.GraphVertexCollection}, {@link graph.GraphEdgeCollection} as well as\n * (in TypeScript) {@link collection.DocumentCollection} and {@link collection.EdgeCollection}.\n *\n * @param collections - A collection that can be read from and written to\n * during the transaction.\n * @param options - Options for the transaction.\n *\n * @example\n * ```js\n * const vertices = db.collection(\"vertices\");\n * const start = vertices.document(\"a\");\n * const end = vertices.document(\"b\");\n * const edges = db.collection(\"edges\");\n * const trx = await db.beginTransaction(\n * edges // collection instances can be passed directly\n * );\n * await trx.step(() => edges.save({ _from: start._id, _to: end._id }));\n * await trx.commit();\n * ```\n */\n beginTransaction(\n collection: string | ArangoCollection,\n options?: TransactionOptions\n ): Promise<Transaction>;\n beginTransaction(\n collections:\n | TransactionCollections\n | (string | ArangoCollection)[]\n | string\n | ArangoCollection,\n options: TransactionOptions = {}\n ): Promise<Transaction> {\n const { allowDirtyRead = undefined, ...opts } = options;\n return this.request(\n {\n method: \"POST\",\n path: \"/_api/transaction/begin\",\n allowDirtyRead,\n body: {\n collections: coerceTransactionCollections(collections),\n ...opts,\n },\n },\n (res) => new Transaction(this, res.body.result.id)\n );\n }\n\n /**\n * Fetches all active transactions from the database and returns an array of\n * transaction descriptions.\n *\n * See also {@link Database#transactions}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const transactions = await db.listTransactions();\n * // transactions is an array of transaction descriptions\n * ```\n */\n listTransactions(): Promise<TransactionDetails[]> {\n return this._connection.request(\n { path: \"/_api/transaction\" },\n (res) => res.body.transactions\n );\n }\n\n /**\n * Fetches all active transactions from the database and returns an array of\n * {@link transaction.Transaction} instances for those transactions.\n *\n * See also {@link Database#listTransactions}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const transactions = await db.transactions();\n * // transactions is an array of transactions\n * ```\n */\n async transactions(): Promise<Transaction[]> {\n const transactions = await this.listTransactions();\n return transactions.map((data) => this.transaction(data.id));\n }\n //#endregion\n\n //#region queries\n /**\n * Performs a database query using the given `query`, then returns a new\n * {@link cursor.ArrayCursor} instance for the result set.\n *\n * See the {@link aql!aql} template string handler for information about how\n * to create a query string without manually defining bind parameters nor\n * having to worry about escaping variables.\n *\n * @param query - An object containing an AQL query string and bind\n * parameters, e.g. the object returned from an {@link aql!aql} template string.\n * @param options - Options for the query execution.\n *\n * @example\n * ```js\n * const db = new Database();\n * const active = true;\n * const Users = db.collection(\"_users\");\n *\n * // Using an aql template string:\n * // Bind parameters are automatically extracted and arangojs collections\n * // are automatically passed as collection bind parameters.\n * const cursor = await db.query(aql`\n * FOR u IN ${Users}\n * FILTER u.authData.active == ${active}\n * RETURN u.user\n * `);\n * // cursor is a cursor for the query result\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const active = true;\n * const Users = db.collection(\"_users\");\n *\n * // Using an object with a regular multi-line string\n * const cursor = await db.query({\n * query: `\n * FOR u IN @@users\n * FILTER u.authData.active == @active\n * RETURN u.user\n * `,\n * bindVars: { active: active, \"@users\": Users.name }\n * });\n * ```\n */\n query<T = any>(\n query: AqlQuery,\n options?: QueryOptions\n ): Promise<ArrayCursor<T>>;\n /**\n * Performs a database query using the given `query` and `bindVars`, then\n * returns a new {@link cursor.ArrayCursor} instance for the result set.\n *\n * See the {@link aql!aql} template string handler for a safer and easier\n * alternative to passing strings directly.\n *\n * @param query - An AQL query string.\n * @param bindVars - An object defining bind parameters for the query.\n * @param options - Options for the query execution.\n *\n * @example\n * ```js\n * const db = new Database();\n * const active = true;\n * const Users = db.collection(\"_users\");\n *\n * const cursor = await db.query(\n * // A normal multi-line string\n * `\n * FOR u IN @@users\n * FILTER u.authData.active == @active\n * RETURN u.user\n * `,\n * { active: active, \"@users\": Users.name }\n * );\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const active = true;\n * const Users = db.collection(\"_users\");\n *\n * const cursor = await db.query(\n * // An AQL literal created from a normal multi-line string\n * aql.literal(`\n * FOR u IN @@users\n * FILTER u.authData.active == @active\n * RETURN u.user\n * `),\n * { active: active, \"@users\": Users.name }\n * );\n * ```\n */\n query<T = any>(\n query: string | AqlLiteral,\n bindVars?: Record<string, any>,\n options?: QueryOptions\n ): Promise<ArrayCursor<T>>;\n query<T = any>(\n query: string | AqlQuery | AqlLiteral,\n bindVars?: Record<string, any>,\n options: QueryOptions = {}\n ): Promise<ArrayCursor<T>> {\n if (isAqlQuery(query)) {\n options = bindVars ?? {};\n bindVars = query.bindVars;\n query = query.query;\n } else if (isAqlLiteral(query)) {\n query = query.toAQL();\n }\n const {\n allowDirtyRead,\n retryOnConflict,\n count,\n batchSize,\n cache,\n memoryLimit,\n ttl,\n timeout,\n ...opts\n } = options;\n return this.request(\n {\n method: \"POST\",\n path: \"/_api/cursor\",\n body: {\n query,\n bindVars,\n count,\n batchSize,\n cache,\n memoryLimit,\n ttl,\n options: opts,\n },\n allowDirtyRead,\n retryOnConflict,\n timeout,\n },\n (res) =>\n new BatchedArrayCursor<T>(\n this,\n res.body,\n res.arangojsHostUrl,\n allowDirtyRead\n ).items\n );\n }\n\n /**\n * Explains a database query using the given `query`.\n *\n * See the {@link aql!aql} template string handler for information about how\n * to create a query string without manually defining bind parameters nor\n * having to worry about escaping variables.\n *\n * @param query - An object containing an AQL query string and bind\n * parameters, e.g. the object returned from an {@link aql!aql} template string.\n * @param options - Options for explaining the query.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const explanation = await db.explain(aql`\n * FOR doc IN ${collection}\n * FILTER doc.flavor == \"strawberry\"\n * RETURN doc._key\n * `);\n * ```\n */\n explain(\n query: AqlQuery,\n options?: ExplainOptions & { allPlans?: false }\n ): Promise<ArangoApiResponse<SingleExplainResult>>;\n /**\n * Explains a database query using the given `query`.\n *\n * See the {@link aql!aql} template string handler for information about how\n * to create a query string without manually defining bind parameters nor\n * having to worry about escaping variables.\n *\n * @param query - An object containing an AQL query string and bind\n * parameters, e.g. the object returned from an {@link aql!aql} template string.\n * @param options - Options for explaining the query.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const explanation = await db.explain(\n * aql`\n * FOR doc IN ${collection}\n * FILTER doc.flavor == \"strawberry\"\n * RETURN doc._key\n * `,\n * { allPlans: true }\n * );\n * ```\n */\n explain(\n query: AqlQuery,\n options?: ExplainOptions & { allPlans: true }\n ): Promise<ArangoApiResponse<MultiExplainResult>>;\n /**\n * Explains a database query using the given `query` and `bindVars`.\n *\n * See the {@link aql!aql} template string handler for a safer and easier\n * alternative to passing strings directly.\n *\n * @param query - An AQL query string.\n * @param bindVars - An object defining bind parameters for the query.\n * @param options - Options for explaining the query.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const explanation = await db.explain(\n * `\n * FOR doc IN @@collection\n * FILTER doc.flavor == \"strawberry\"\n * RETURN doc._key\n * `,\n * { \"@collection\": collection.name }\n * );\n * ```\n */\n explain(\n query: string | AqlLiteral,\n bindVars?: Record<string, any>,\n options?: ExplainOptions & { allPlans?: false }\n ): Promise<ArangoApiResponse<SingleExplainResult>>;\n /**\n * Explains a database query using the given `query` and `bindVars`.\n *\n * See the {@link aql!aql} template string handler for a safer and easier\n * alternative to passing strings directly.\n *\n * @param query - An AQL query string.\n * @param bindVars - An object defining bind parameters for the query.\n * @param options - Options for explaining the query.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const explanation = await db.explain(\n * `\n * FOR doc IN @@collection\n * FILTER doc.flavor == \"strawberry\"\n * RETURN doc._key\n * `,\n * { \"@collection\": collection.name },\n * { allPlans: true }\n * );\n * ```\n */\n explain(\n query: string | AqlLiteral,\n bindVars?: Record<string, any>,\n options?: ExplainOptions & { allPlans: true }\n ): Promise<ArangoApiResponse<MultiExplainResult>>;\n explain(\n query: string | AqlQuery | AqlLiteral,\n bindVars?: Record<string, any>,\n options?: ExplainOptions\n ): Promise<ArangoApiResponse<SingleExplainResult | MultiExplainResult>> {\n if (isAqlQuery(query)) {\n options = bindVars;\n bindVars = query.bindVars;\n query = query.query;\n } else if (isAqlLiteral(query)) {\n query = query.toAQL();\n }\n return this.request({\n method: \"POST\",\n path: \"/_api/explain\",\n body: { query, bindVars, options },\n });\n }\n\n /**\n * Parses the given query and returns the result.\n *\n * See the {@link aql!aql} template string handler for information about how\n * to create a query string without manually defining bind parameters nor\n * having to worry about escaping variables.\n *\n * @param query - An AQL query string or an object containing an AQL query\n * string and bind parameters, e.g. the object returned from an {@link aql!aql}\n * template string.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const ast = await db.parse(aql`\n * FOR doc IN ${collection}\n * FILTER doc.flavor == \"strawberry\"\n * RETURN doc._key\n * `);\n * ```\n */\n parse(query: string | AqlQuery | AqlLiteral): Promise<ParseResult> {\n if (isAqlQuery(query)) {\n query = query.query;\n } else if (isAqlLiteral(query)) {\n query = query.toAQL();\n }\n return this.request({\n method: \"POST\",\n path: \"/_api/query\",\n body: { query },\n });\n }\n\n /**\n * Fetches the available optimizer rules.\n *\n * @example\n * ```js\n * const db = new Database();\n * const rules = await db.queryRules();\n * for (const rule of rules) {\n * console.log(rule.name);\n * }\n * ```\n */\n queryRules(): Promise<QueryOptimizerRule[]> {\n return this.request({\n path: \"/_api/query/rules\",\n });\n }\n\n /**\n * Fetches the query tracking properties.\n *\n * @example\n * ```js\n * const db = new Database();\n * const tracking = await db.queryTracking();\n * console.log(tracking.enabled);\n * ```\n */\n queryTracking(): Promise<QueryTracking>;\n /**\n * Modifies the query tracking properties.\n *\n * @param options - Options for query tracking.\n *\n * @example\n * ```js\n * const db = new Database();\n * // track up to 5 slow queries exceeding 5 seconds execution time\n * await db.setQueryTracking({\n * enabled: true,\n * trackSlowQueries: true,\n * maxSlowQueries: 5,\n * slowQueryThreshold: 5\n * });\n * ```\n */\n queryTracking(options: QueryTrackingOptions): Promise<QueryTracking>;\n queryTracking(options?: QueryTrackingOptions): Promise<QueryTracking> {\n return this.request(\n options\n ? {\n method: \"PUT\",\n path: \"/_api/query/properties\",\n body: options,\n }\n : {\n method: \"GET\",\n path: \"/_api/query/properties\",\n }\n );\n }\n\n /**\n * Fetches a list of information for all currently running queries.\n *\n * See also {@link Database#listSlowQueries} and {@link Database#killQuery}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const queries = await db.listRunningQueries();\n * ```\n */\n listRunningQueries(): Promise<QueryInfo[]> {\n return this.request({\n method: \"GET\",\n path: \"/_api/query/current\",\n });\n }\n\n /**\n * Fetches a list of information for all recent slow queries.\n *\n * See also {@link Database#listRunningQueries} and\n * {@link Database#clearSlowQueries}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const queries = await db.listSlowQueries();\n * // Only works if slow query tracking is enabled\n * ```\n */\n listSlowQueries(): Promise<QueryInfo[]> {\n return this.request({\n method: \"GET\",\n path: \"/_api/query/slow\",\n });\n }\n\n /**\n * Clears the list of recent slow queries.\n *\n * See also {@link Database#listSlowQueries}.\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.clearSlowQueries();\n * // Slow query list is now cleared\n * ```\n */\n clearSlowQueries(): Promise<void> {\n return this.request(\n {\n method: \"DELETE\",\n path: \"/_api/query/slow\",\n },\n () => undefined\n );\n }\n\n /**\n * Kills a running query with the given `queryId`.\n *\n * See also {@link Database#listRunningQueries}.\n *\n * @param queryId - The ID of a currently running query.\n *\n * @example\n * ```js\n * const db = new Database();\n * const queries = await db.listRunningQueries();\n * await Promise.all(queries.map(\n * async (query) => {\n * if (query.state === \"executing\") {\n * await db.killQuery(query.id);\n * }\n * }\n * ));\n * ```\n */\n killQuery(queryId: string): Promise<void> {\n return this.request(\n {\n method: \"DELETE\",\n path: `/_api/query/${encodeURIComponent(queryId)}`,\n },\n () => undefined\n );\n }\n //#endregion\n\n //#region functions\n /**\n * Fetches a list of all AQL user functions registered with the database.\n *\n * @example\n * ```js\n * const db = new Database();\n * const functions = await db.listFunctions();\n * const names = functions.map(fn => fn.name);\n * ```\n */\n listFunctions(): Promise<AqlUserFunction[]> {\n return this.request(\n { path: \"/_api/aqlfunction\" },\n (res) => res.body.result\n );\n }\n\n /**\n * Creates an AQL user function with the given _name_ and _code_ if it does\n * not already exist or replaces it if a function with the same name already\n * existed.\n *\n * @param name - A valid AQL function name. The function name must consist\n * of at least two alphanumeric identifiers separated with double colons.\n * @param code - A string evaluating to a JavaScript function (not a\n * JavaScript function object).\n * @param isDeterministic - If set to `true`, the function is expected to\n * always return the same result for equivalent inputs. This option currently\n * has no effect but may allow for optimizations in the future.\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.createFunction(\n * \"ACME::ACCOUNTING::CALCULATE_VAT\",\n * \"(price) => price * 0.19\"\n * );\n * // Use the new function in an AQL query with template handler:\n * const cursor = await db.query(aql`\n * FOR product IN products\n * RETURN MERGE(\n * { vat: ACME::ACCOUNTING::CALCULATE_VAT(product.price) },\n * product\n * )\n * `);\n * // cursor is a cursor for the query result\n * ```\n */\n createFunction(\n name: string,\n code: string,\n isDeterministic: boolean = false\n ): Promise<ArangoApiResponse<{ isNewlyCreated: boolean }>> {\n return this.request({\n method: \"POST\",\n path: \"/_api/aqlfunction\",\n body: { name, code, isDeterministic },\n });\n }\n\n /**\n * Deletes the AQL user function with the given name from the database.\n *\n * @param name - The name of the user function to drop.\n * @param group - If set to `true`, all functions with a name starting with\n * `name` will be deleted, otherwise only the function with the exact name\n * will be deleted.\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.dropFunction(\"ACME::ACCOUNTING::CALCULATE_VAT\");\n * // the function no longer exists\n * ```\n */\n dropFunction(\n name: string,\n group: boolean = false\n ): Promise<ArangoApiResponse<{ deletedCount: number }>> {\n return this.request({\n method: \"DELETE\",\n path: `/_api/aqlfunction/${encodeURIComponent(name)}`,\n qs: { group },\n });\n }\n //#endregion\n\n //#region services\n /**\n * Fetches a list of all installed service.\n *\n * @param excludeSystem - Whether system services should be excluded.\n *\n * @example\n * ```js\n * const db = new Database();\n * const services = await db.listServices();\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const services = await db.listServices(false); // all services\n * ```\n */\n listServices(excludeSystem: boolean = true): Promise<ServiceSummary[]> {\n return this.request({\n path: \"/_api/foxx\",\n qs: { excludeSystem },\n });\n }\n\n /**\n * Installs a new service.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param source - The service bundle to install.\n * @param options - Options for installing the service.\n *\n * @example\n * ```js\n * const db = new Database();\n * // Using a node.js file stream as source\n * const source = fs.createReadStream(\"./my-foxx-service.zip\");\n * const info = await db.installService(\"/hello\", source);\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * // Using a node.js Buffer as source\n * const source = fs.readFileSync(\"./my-foxx-service.zip\");\n * const info = await db.installService(\"/hello\", source);\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * // Using a File (Blob) from a browser file input\n * const element = document.getElementById(\"my-file-input\");\n * const source = element.files[0];\n * const info = await db.installService(\"/hello\", source);\n * ```\n */\n async installService(\n mount: string,\n source: Readable | Buffer | Blob | string,\n options: InstallServiceOptions = {}\n ): Promise<ServiceInfo> {\n const { configuration, dependencies, ...qs } = options;\n const req = await toForm({\n configuration,\n dependencies,\n source,\n });\n return await this.request({\n ...req,\n method: \"POST\",\n path: \"/_api/foxx\",\n isBinary: true,\n qs: { ...qs, mount },\n });\n }\n\n /**\n * Replaces an existing service with a new service by completely removing the\n * old service and installing a new service at the same mount point.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param source - The service bundle to install.\n * @param options - Options for replacing the service.\n *\n * @example\n * ```js\n * const db = new Database();\n * // Using a node.js file stream as source\n * const source = fs.createReadStream(\"./my-foxx-service.zip\");\n * const info = await db.replaceService(\"/hello\", source);\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * // Using a node.js Buffer as source\n * const source = fs.readFileSync(\"./my-foxx-service.zip\");\n * const info = await db.replaceService(\"/hello\", source);\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * // Using a File (Blob) from a browser file input\n * const element = document.getElementById(\"my-file-input\");\n * const source = element.files[0];\n * const info = await db.replaceService(\"/hello\", source);\n * ```\n */\n async replaceService(\n mount: string,\n source: Readable | Buffer | Blob | string,\n options: ReplaceServiceOptions = {}\n ): Promise<ServiceInfo> {\n const { configuration, dependencies, ...qs } = options;\n const req = await toForm({\n configuration,\n dependencies,\n source,\n });\n return await this.request({\n ...req,\n method: \"PUT\",\n path: \"/_api/foxx/service\",\n isBinary: true,\n qs: { ...qs, mount },\n });\n }\n\n /**\n * Replaces an existing service with a new service while retaining the old\n * service's configuration and dependencies.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param source - The service bundle to install.\n * @param options - Options for upgrading the service.\n *\n * @example\n * ```js\n * const db = new Database();\n * // Using a node.js file stream as source\n * const source = fs.createReadStream(\"./my-foxx-service.zip\");\n * const info = await db.upgradeService(\"/hello\", source);\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * // Using a node.js Buffer as source\n * const source = fs.readFileSync(\"./my-foxx-service.zip\");\n * const info = await db.upgradeService(\"/hello\", source);\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * // Using a File (Blob) from a browser file input\n * const element = document.getElementById(\"my-file-input\");\n * const source = element.files[0];\n * const info = await db.upgradeService(\"/hello\", source);\n * ```\n */\n async upgradeService(\n mount: string,\n source: Readable | Buffer | Blob | string,\n options: UpgradeServiceOptions = {}\n ): Promise<ServiceInfo> {\n const { configuration, dependencies, ...qs } = options;\n const req = await toForm({\n configuration,\n dependencies,\n source,\n });\n return await this.request({\n ...req,\n method: \"PATCH\",\n path: \"/_api/foxx/service\",\n isBinary: true,\n qs: { ...qs, mount },\n });\n }\n\n /**\n * Completely removes a service from the database.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param options - Options for uninstalling the service.\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.uninstallService(\"/my-foxx\");\n * ```\n */\n uninstallService(\n mount: string,\n options?: UninstallServiceOptions\n ): Promise<void> {\n return this.request(\n {\n method: \"DELETE\",\n path: \"/_api/foxx/service\",\n qs: { ...options, mount },\n },\n () => undefined\n );\n }\n\n /**\n * Retrieves information about a mounted service.\n *\n * @param mount - The service's mount point, relative to the database.\n *\n * @example\n * ```js\n * const db = new Database();\n * const info = await db.getService(\"/my-service\");\n * // info contains detailed information about the service\n * ```\n */\n getService(mount: string): Promise<ServiceInfo> {\n return this.request({\n path: \"/_api/foxx/service\",\n qs: { mount },\n });\n }\n\n /**\n * Retrieves information about the service's configuration options and their\n * current values.\n *\n * See also {@link Database#replaceServiceConfiguration} and\n * {@link Database#updateServiceConfiguration}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param minimal - If set to `true`, the result will only include each\n * configuration option's current value. Otherwise it will include the full\n * definition for each option.\n *\n * @example\n * ```js\n * const db = new Database();\n * const config = await db.getServiceConfiguration(\"/my-service\");\n * for (const [key, option] of Object.entries(config)) {\n * console.log(`${option.title} (${key}): ${option.current}`);\n * }\n * ```\n */\n getServiceConfiguration(\n mount: string,\n minimal?: false\n ): Promise<Record<string, ServiceConfiguration>>;\n /**\n * Retrieves information about the service's configuration options and their\n * current values.\n *\n * See also {@link Database#replaceServiceConfiguration} and\n * {@link Database#updateServiceConfiguration}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param minimal - If set to `true`, the result will only include each\n * configuration option's current value. Otherwise it will include the full\n * definition for each option.\n *\n * @example\n * ```js\n * const db = new Database();\n * const config = await db.getServiceConfiguration(\"/my-service\", true);\n * for (const [key, value] of Object.entries(config)) {\n * console.log(`${key}: ${value}`);\n * }\n * ```\n */\n getServiceConfiguration(\n mount: string,\n minimal: true\n ): Promise<Record<string, any>>;\n getServiceConfiguration(mount: string, minimal: boolean = false) {\n return this.request({\n path: \"/_api/foxx/configuration\",\n qs: { mount, minimal },\n });\n }\n\n /**\n * Replaces the configuration of the given service, discarding any existing\n * values for options not specified.\n *\n * See also {@link Database#updateServiceConfiguration} and\n * {@link Database#getServiceConfiguration}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param cfg - An object mapping configuration option names to values.\n * @param minimal - If set to `true`, the result will only include each\n * configuration option's current value and warning (if any).\n * Otherwise it will include the full definition for each option.\n *\n * @example\n * ```js\n * const db = new Database();\n * const config = { currency: \"USD\", locale: \"en-US\" };\n * const info = await db.replaceServiceConfiguration(\"/my-service\", config);\n * for (const [key, option] of Object.entries(info)) {\n * console.log(`${option.title} (${key}): ${option.value}`);\n * if (option.warning) console.warn(`Warning: ${option.warning}`);\n * }\n * ```\n */\n replaceServiceConfiguration(\n mount: string,\n cfg: Record<string, any>,\n minimal?: false\n ): Promise<Record<string, ServiceConfiguration & { warning?: string }>>;\n /**\n * Replaces the configuration of the given service, discarding any existing\n * values for options not specified.\n *\n * See also {@link Database#updateServiceConfiguration} and\n * {@link Database#getServiceConfiguration}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param cfg - An object mapping configuration option names to values.\n * @param minimal - If set to `true`, the result will only include each\n * configuration option's current value and warning (if any).\n * Otherwise it will include the full definition for each option.\n *\n * @example\n * ```js\n * const db = new Database();\n * const config = { currency: \"USD\", locale: \"en-US\" };\n * const info = await db.replaceServiceConfiguration(\"/my-service\", config);\n * for (const [key, value] of Object.entries(info.values)) {\n * console.log(`${key}: ${value}`);\n * if (info.warnings[key]) console.warn(`Warning: ${info.warnings[key]}`);\n * }\n * ```\n */\n replaceServiceConfiguration(\n mount: string,\n cfg: Record<string, any>,\n minimal: true\n ): Promise<{\n values: Record<string, any>;\n warnings: Record<string, string>;\n }>;\n replaceServiceConfiguration(\n mount: string,\n cfg: Record<string, any>,\n minimal: boolean = false\n ) {\n return this.request({\n method: \"PUT\",\n path: \"/_api/foxx/configuration\",\n body: cfg,\n qs: { mount, minimal },\n });\n }\n\n /**\n * Updates the configuration of the given service while maintaining any\n * existing values for options not specified.\n *\n * See also {@link Database#replaceServiceConfiguration} and\n * {@link Database#getServiceConfiguration}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param cfg - An object mapping configuration option names to values.\n * @param minimal - If set to `true`, the result will only include each\n * configuration option's current value and warning (if any).\n * Otherwise it will include the full definition for each option.\n *\n * @example\n * ```js\n * const db = new Database();\n * const config = { currency: \"USD\", locale: \"en-US\" };\n * const info = await db.updateServiceConfiguration(\"/my-service\", config);\n * for (const [key, option] of Object.entries(info)) {\n * console.log(`${option.title} (${key}): ${option.value}`);\n * if (option.warning) console.warn(`Warning: ${option.warning}`);\n * }\n * ```\n */\n updateServiceConfiguration(\n mount: string,\n cfg: Record<string, any>,\n minimal?: false\n ): Promise<Record<string, ServiceConfiguration & { warning?: string }>>;\n /**\n * Updates the configuration of the given service while maintaining any\n * existing values for options not specified.\n *\n * See also {@link Database#replaceServiceConfiguration} and\n * {@link Database#getServiceConfiguration}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param cfg - An object mapping configuration option names to values.\n * @param minimal - If set to `true`, the result will only include each\n * configuration option's current value and warning (if any).\n * Otherwise it will include the full definition for each option.\n *\n * @example\n * ```js\n * const db = new Database();\n * const config = { currency: \"USD\", locale: \"en-US\" };\n * const info = await db.updateServiceConfiguration(\"/my-service\", config);\n * for (const [key, value] of Object.entries(info.values)) {\n * console.log(`${key}: ${value}`);\n * if (info.warnings[key]) console.warn(`Warning: ${info.warnings[key]}`);\n * }\n * ```\n */\n updateServiceConfiguration(\n mount: string,\n cfg: Record<string, any>,\n minimal: true\n ): Promise<{\n values: Record<string, any>;\n warnings: Record<string, string>;\n }>;\n updateServiceConfiguration(\n mount: string,\n cfg: Record<string, any>,\n minimal: boolean = false\n ) {\n return this.request({\n method: \"PATCH\",\n path: \"/_api/foxx/configuration\",\n body: cfg,\n qs: { mount, minimal },\n });\n }\n\n /**\n * Retrieves information about the service's dependencies and their current\n * mount points.\n *\n * See also {@link Database#replaceServiceDependencies} and\n * {@link Database#updateServiceDependencies}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param minimal - If set to `true`, the result will only include each\n * dependency's current mount point. Otherwise it will include the full\n * definition for each dependency.\n *\n * @example\n * ```js\n * const db = new Database();\n * const deps = await db.getServiceDependencies(\"/my-service\");\n * for (const [key, dep] of Object.entries(deps)) {\n * console.log(`${dep.title} (${key}): ${dep.current}`);\n * }\n * ```\n */\n getServiceDependencies(\n mount: string,\n minimal?: false\n ): Promise<Record<string, SingleServiceDependency | MultiServiceDependency>>;\n /**\n * Retrieves information about the service's dependencies and their current\n * mount points.\n *\n * See also {@link Database#replaceServiceDependencies} and\n * {@link Database#updateServiceDependencies}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param minimal - If set to `true`, the result will only include each\n * dependency's current mount point. Otherwise it will include the full\n * definition for each dependency.\n *\n * @example\n * ```js\n * const db = new Database();\n * const deps = await db.getServiceDependencies(\"/my-service\", true);\n * for (const [key, value] of Object.entries(deps)) {\n * console.log(`${key}: ${value}`);\n * }\n * ```\n */\n getServiceDependencies(\n mount: string,\n minimal: true\n ): Promise<Record<string, string | string[]>>;\n getServiceDependencies(mount: string, minimal: boolean = false) {\n return this.request({\n path: \"/_api/foxx/dependencies\",\n qs: { mount, minimal },\n });\n }\n\n /**\n * Replaces the dependencies of the given service, discarding any existing\n * mount points for dependencies not specified.\n *\n * See also {@link Database#updateServiceDependencies} and\n * {@link Database#getServiceDependencies}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param cfg - An object mapping dependency aliases to mount points.\n * @param minimal - If set to `true`, the result will only include each\n * dependency's current mount point. Otherwise it will include the full\n * definition for each dependency.\n *\n * @example\n * ```js\n * const db = new Database();\n * const deps = { mailer: \"/mailer-api\", auth: \"/remote-auth\" };\n * const info = await db.replaceServiceDependencies(\"/my-service\", deps);\n * for (const [key, dep] of Object.entries(info)) {\n * console.log(`${dep.title} (${key}): ${dep.current}`);\n * if (dep.warning) console.warn(`Warning: ${dep.warning}`);\n * }\n * ```\n */\n replaceServiceDependencies(\n mount: string,\n deps: Record<string, string>,\n minimal?: false\n ): Promise<\n Record<\n string,\n (SingleServiceDependency | MultiServiceDependency) & { warning?: string }\n >\n >;\n /**\n * Replaces the dependencies of the given service, discarding any existing\n * mount points for dependencies not specified.\n *\n * See also {@link Database#updateServiceDependencies} and\n * {@link Database#getServiceDependencies}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param cfg - An object mapping dependency aliases to mount points.\n * @param minimal - If set to `true`, the result will only include each\n * dependency's current mount point. Otherwise it will include the full\n * definition for each dependency.\n *\n * @example\n * ```js\n * const db = new Database();\n * const deps = { mailer: \"/mailer-api\", auth: \"/remote-auth\" };\n * const info = await db.replaceServiceDependencies(\n * \"/my-service\",\n * deps,\n * true\n * );\n * for (const [key, value] of Object.entries(info)) {\n * console.log(`${key}: ${value}`);\n * if (info.warnings[key]) console.warn(`Warning: ${info.warnings[key]}`);\n * }\n * ```\n */\n replaceServiceDependencies(\n mount: string,\n deps: Record<string, string>,\n minimal: true\n ): Promise<{\n values: Record<string, string>;\n warnings: Record<string, string>;\n }>;\n replaceServiceDependencies(\n mount: string,\n deps: Record<string, string>,\n minimal: boolean = false\n ) {\n return this.request({\n method: \"PUT\",\n path: \"/_api/foxx/dependencies\",\n body: deps,\n qs: { mount, minimal },\n });\n }\n\n /**\n * Updates the dependencies of the given service while maintaining any\n * existing mount points for dependencies not specified.\n *\n * See also {@link Database#replaceServiceDependencies} and\n * {@link Database#getServiceDependencies}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param cfg - An object mapping dependency aliases to mount points.\n * @param minimal - If set to `true`, the result will only include each\n * dependency's current mount point. Otherwise it will include the full\n * definition for each dependency.\n *\n * @example\n * ```js\n * const db = new Database();\n * const deps = { mailer: \"/mailer-api\", auth: \"/remote-auth\" };\n * const info = await db.updateServiceDependencies(\"/my-service\", deps);\n * for (const [key, dep] of Object.entries(info)) {\n * console.log(`${dep.title} (${key}): ${dep.current}`);\n * if (dep.warning) console.warn(`Warning: ${dep.warning}`);\n * }\n * ```\n */\n updateServiceDependencies(\n mount: string,\n deps: Record<string, string>,\n minimal?: false\n ): Promise<\n Record<\n string,\n (SingleServiceDependency | MultiServiceDependency) & { warning?: string }\n >\n >;\n /**\n * Updates the dependencies of the given service while maintaining any\n * existing mount points for dependencies not specified.\n *\n * See also {@link Database#replaceServiceDependencies} and\n * {@link Database#getServiceDependencies}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param cfg - An object mapping dependency aliases to mount points.\n * @param minimal - If set to `true`, the result will only include each\n * dependency's current mount point. Otherwise it will include the full\n * definition for each dependency.\n *\n * @example\n * ```js\n * const db = new Database();\n * const deps = { mailer: \"/mailer-api\", auth: \"/remote-auth\" };\n * const info = await db.updateServiceDependencies(\n * \"/my-service\",\n * deps,\n * true\n * );\n * for (const [key, value] of Object.entries(info)) {\n * console.log(`${key}: ${value}`);\n * if (info.warnings[key]) console.warn(`Warning: ${info.warnings[key]}`);\n * }\n * ```\n */\n updateServiceDependencies(\n mount: string,\n deps: Record<string, string>,\n minimal: true\n ): Promise<{\n values: Record<string, string>;\n warnings: Record<string, string>;\n }>;\n updateServiceDependencies(\n mount: string,\n deps: Record<string, string>,\n minimal: boolean = false\n ) {\n return this.request({\n method: \"PATCH\",\n path: \"/_api/foxx/dependencies\",\n body: deps,\n qs: { mount, minimal },\n });\n }\n\n /**\n * Enables or disables development mode for the given service.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param enabled - Whether development mode should be enabled or disabled.\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.setServiceDevelopmentMode(\"/my-service\", true);\n * // the service is now in development mode\n * await db.setServiceDevelopmentMode(\"/my-service\", false);\n * // the service is now in production mode\n * ```\n */\n setServiceDevelopmentMode(\n mount: string,\n enabled: boolean = true\n ): Promise<ServiceInfo> {\n return this.request({\n method: enabled ? \"POST\" : \"DELETE\",\n path: \"/_api/foxx/development\",\n qs: { mount },\n });\n }\n\n /**\n * Retrieves a list of scripts defined in the service manifest's \"scripts\"\n * section mapped to their human readable representations.\n *\n * @param mount - The service's mount point, relative to the database.\n *\n * @example\n * ```js\n * const db = new Database();\n * const scripts = await db.listServiceScripts(\"/my-service\");\n * for (const [name, title] of Object.entries(scripts)) {\n * console.log(`${name}: ${title}`);\n * }\n * ```\n */\n listServiceScripts(mount: string): Promise<Record<string, string>> {\n return this.request({\n path: \"/_api/foxx/scripts\",\n qs: { mount },\n });\n }\n\n /**\n * Executes a service script and retrieves its result exposed as\n * `module.exports` (if any).\n *\n * @param mount - The service's mount point, relative to the database.\n * @param name - Name of the service script to execute as defined in the\n * service manifest.\n * @param params - Arbitrary value that will be exposed to the script as\n * `argv[0]` in the service context (e.g. `module.context.argv[0]`).\n * Must be serializable to JSON.\n *\n * @example\n * ```js\n * const db = new Database();\n * const result = await db.runServiceScript(\n * \"/my-service\",\n * \"create-user\",\n * {\n * username: \"service_admin\",\n * password: \"hunter2\"\n * }\n * );\n * ```\n */\n runServiceScript(mount: string, name: string, params?: any): Promise<any> {\n return this.request({\n method: \"POST\",\n path: `/_api/foxx/scripts/${encodeURIComponent(name)}`,\n body: params,\n qs: { mount },\n });\n }\n\n /**\n * Runs the tests of a given service and returns the results using the\n * \"default\" reporter.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param options - Options for running the tests.\n *\n * @example\n * ```js\n * const db = new Database();\n * const testReport = await db.runServiceTests(\"/my-foxx\");\n * ```\n */\n runServiceTests(\n mount: string,\n options?: {\n reporter?: \"default\";\n /**\n * Whether the reporter should use \"idiomatic\" mode. Has no effect when\n * using the \"default\" or \"suite\" reporters.\n */\n idiomatic?: false;\n /**\n * If set, only tests with full names including this exact string will be\n * executed.\n */\n filter?: string;\n }\n ): Promise<ServiceTestDefaultReport>;\n /**\n * Runs the tests of a given service and returns the results using the\n * \"suite\" reporter, which groups the test result by test suite.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param options - Options for running the tests.\n *\n * @example\n * ```js\n * const db = new Database();\n * const suiteReport = await db.runServiceTests(\n * \"/my-foxx\",\n * { reporter: \"suite\" }\n * );\n * ```\n */\n runServiceTests(\n mount: string,\n options: {\n reporter: \"suite\";\n /**\n * Whether the reporter should use \"idiomatic\" mode. Has no effect when\n * using the \"default\" or \"suite\" reporters.\n */\n idiomatic?: false;\n /**\n * If set, only tests with full names including this exact string will be\n * executed.\n */\n filter?: string;\n }\n ): Promise<ServiceTestSuiteReport>;\n /**\n * Runs the tests of a given service and returns the results using the\n * \"stream\" reporter, which represents the results as a sequence of tuples\n * representing events.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param options - Options for running the tests.\n *\n * @example\n * ```js\n * const db = new Database();\n * const streamEvents = await db.runServiceTests(\n * \"/my-foxx\",\n * { reporter: \"stream\" }\n * );\n * ```\n */\n runServiceTests(\n mount: string,\n options: {\n reporter: \"stream\";\n /**\n * Whether the reporter should use \"idiomatic\" mode. If set to `true`,\n * the results will be returned as a formatted string.\n */\n idiomatic?: false;\n /**\n * If set, only tests with full names including this exact string will be\n * executed.\n */\n filter?: string;\n }\n ): Promise<ServiceTestStreamReport>;\n /**\n * Runs the tests of a given service and returns the results using the\n * \"tap\" reporter, which represents the results as an array of strings using\n * the \"tap\" format.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param options - Options for running the tests.\n *\n * @example\n * ```js\n * const db = new Database();\n * const tapLines = await db.runServiceTests(\n * \"/my-foxx\",\n * { reporter: \"tap\" }\n * );\n * ```\n */\n runServiceTests(\n mount: string,\n options: {\n reporter: \"tap\";\n /**\n * Whether the reporter should use \"idiomatic\" mode. If set to `true`,\n * the results will be returned as a formatted string.\n */\n idiomatic?: false;\n /**\n * If set, only tests with full names including this exact string will be\n * executed.\n */\n filter?: string;\n }\n ): Promise<ServiceTestTapReport>;\n /**\n * Runs the tests of a given service and returns the results using the\n * \"xunit\" reporter, which represents the results as an XML document using\n * the JSONML exchange format.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param options - Options for running the tests.\n *\n * @example\n * ```js\n * const db = new Database();\n * const jsonML = await db.runServiceTests(\n * \"/my-foxx\",\n * { reporter: \"xunit\" }\n * );\n * ```\n */\n runServiceTests(\n mount: string,\n options: {\n reporter: \"xunit\";\n /**\n * Whether the reporter should use \"idiomatic\" mode. If set to `true`,\n * the results will be returned as a formatted string.\n */\n idiomatic?: false;\n /**\n * If set, only tests with full names including this exact string will be\n * executed.\n */\n filter?: string;\n }\n ): Promise<ServiceTestXunitReport>;\n /**\n * Runs the tests of a given service and returns the results as a string\n * using the \"stream\" reporter in \"idiomatic\" mode, which represents the\n * results as a line-delimited JSON stream of tuples representing events.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param options - Options for running the tests.\n *\n * @example\n * ```js\n * const db = new Database();\n * const streamReport = await db.runServiceTests(\n * \"/my-foxx\",\n * { reporter: \"stream\", idiomatic: true }\n * );\n * ```\n */\n runServiceTests(\n mount: string,\n options: {\n reporter: \"stream\";\n /**\n * Whether the reporter should use \"idiomatic\" mode. If set to `false`,\n * the results will be returned as an array of tuples instead of a\n * string.\n */\n idiomatic: true;\n /**\n * If set, only tests with full names including this exact string will be\n * executed.\n */\n filter?: string;\n }\n ): Promise<string>;\n /**\n * Runs the tests of a given service and returns the results as a string\n * using the \"tap\" reporter in \"idiomatic\" mode, which represents the\n * results using the \"tap\" format.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param options - Options for running the tests.\n *\n * @example\n * ```js\n * const db = new Database();\n * const tapReport = await db.runServiceTests(\n * \"/my-foxx\",\n * { reporter: \"tap\", idiomatic: true }\n * );\n * ```\n */\n runServiceTests(\n mount: string,\n options: {\n reporter: \"tap\";\n /**\n * Whether the reporter should use \"idiomatic\" mode. If set to `false`,\n * the results will be returned as an array of strings instead of a\n * single string.\n */\n idiomatic: true;\n /**\n * If set, only tests with full names including this exact string will be\n * executed.\n */\n filter?: string;\n }\n ): Promise<string>;\n /**\n * Runs the tests of a given service and returns the results as a string\n * using the \"xunit\" reporter in \"idiomatic\" mode, which represents the\n * results as an XML document.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param options - Options for running the tests.\n *\n * @example\n * ```js\n * const db = new Database();\n * const xml = await db.runServiceTests(\n * \"/my-foxx\",\n * { reporter: \"xunit\", idiomatic: true }\n * );\n * ```\n */\n runServiceTests(\n mount: string,\n options: {\n reporter: \"xunit\";\n /**\n * Whether the reporter should use \"idiomatic\" mode. If set to `false`,\n * the results will be returned using the JSONML exchange format\n * instead of a string.\n */\n idiomatic: true;\n /**\n * If set, only tests with full names including this exact string will be\n * executed.\n */\n filter?: string;\n }\n ): Promise<string>;\n runServiceTests(\n mount: string,\n options?: {\n reporter?: string;\n idiomatic?: boolean;\n filter?: string;\n }\n ) {\n return this.request({\n method: \"POST\",\n path: \"/_api/foxx/tests\",\n qs: {\n ...options,\n mount,\n },\n });\n }\n\n /**\n * Retrieves the text content of the service's `README` or `README.md` file.\n *\n * Returns `undefined` if no such file could be found.\n *\n * @param mount - The service's mount point, relative to the database.\n *\n * @example\n * ```js\n * const db = new Database();\n * const readme = await db.getServiceReadme(\"/my-service\");\n * if (readme !== undefined) console.log(readme);\n * else console.warn(`No README found.`)\n * ```\n */\n getServiceReadme(mount: string): Promise<string | undefined> {\n return this.request({\n path: \"/_api/foxx/readme\",\n qs: { mount },\n });\n }\n\n /**\n * Retrieves an Open API compatible Swagger API description object for the\n * service installed at the given mount point.\n *\n * @param mount - The service's mount point, relative to the database.\n *\n * @example\n * ```js\n * const db = new Database();\n * const spec = await db.getServiceDocumentation(\"/my-service\");\n * // spec is a Swagger API description of the service\n * ```\n */\n getServiceDocumentation(mount: string): Promise<SwaggerJson> {\n return this.request({\n path: \"/_api/foxx/swagger\",\n qs: { mount },\n });\n }\n\n /**\n * Retrieves a zip bundle containing the service files.\n *\n * Returns a `Buffer` in node.js or `Blob` in the browser.\n *\n * @param mount - The service's mount point, relative to the database.\n *\n * @example\n * ```js\n * const db = new Database();\n * const serviceBundle = await db.downloadService(\"/my-foxx\");\n * ```\n */\n downloadService(mount: string): Promise<Buffer | Blob> {\n return this.request({\n method: \"POST\",\n path: \"/_api/foxx/download\",\n qs: { mount },\n expectBinary: true,\n });\n }\n\n /**\n * Writes all locally available services to the database and updates any\n * service bundles missing in the database.\n *\n * @param replace - If set to `true`, outdated services will also be\n * committed. This can be used to solve some consistency problems when\n * service bundles are missing in the database or were deleted manually.\n *\n * @example\n * ```js\n * await db.commitLocalServiceState();\n * // all services available on the coordinator have been written to the db\n * ```\n *\n * @example\n * ```js\n * await db.commitLocalServiceState(true);\n * // all service conflicts have been resolved in favor of this coordinator\n * ```\n */\n commitLocalServiceState(replace: boolean = false): Promise<void> {\n return this.request(\n {\n method: \"POST\",\n path: \"/_api/foxx/commit\",\n qs: { replace },\n },\n () => undefined\n );\n }\n //#endregion\n}\n","/**\n * ```ts\n * import type { Document, Edge } from \"arangojs/documents\";\n * ```\n *\n * The \"documents\" module provides document/edge related types for TypeScript.\n *\n * @packageDocumentation\n */\n\n/**\n * Common ArangoDB metadata properties of a document.\n */\nexport type DocumentMetadata = {\n /**\n * Key of the document, which uniquely identifies the document within its\n * collection.\n */\n _key: string;\n /**\n * Unique ID of the document, which is composed of the collection name\n * and the document `_key`.\n */\n _id: string;\n /**\n * Revision of the document data.\n */\n _rev: string;\n};\n\n/**\n * ArangoDB metadata defining the relations of an edge document.\n */\nexport type EdgeMetadata = {\n /**\n * Unique ID of the document that acts as the edge's start vertex.\n */\n _from: string;\n /**\n * Unique ID of the document that acts as the edge's end vertex.\n */\n _to: string;\n};\n\n/**\n * Type representing an object that can be stored in a collection.\n */\nexport type DocumentData<T extends Record<string, any> = any> = T &\n Partial<DocumentMetadata> &\n Partial<EdgeMetadata>;\n\n/**\n * Type representing an object that can be stored in an edge collection.\n */\nexport type EdgeData<T extends Record<string, any> = any> = T &\n Partial<DocumentMetadata> &\n EdgeMetadata;\n\n/**\n * Type representing a document stored in a collection.\n */\nexport type Document<T extends Record<string, any> = any> = T &\n DocumentMetadata &\n Partial<EdgeMetadata>;\n\n/**\n * Type representing an edge document stored in an edge collection.\n */\nexport type Edge<T extends Record<string, any> = any> = T &\n DocumentMetadata &\n EdgeMetadata;\n\n/**\n * Type representing patch data for a given object type to represent a payload\n * ArangoDB can apply in a document PATCH request (i.e. a partial update).\n *\n * This differs from `Partial` in that it also applies itself to any nested\n * objects recursively.\n */\nexport type Patch<T = Record<string, any>> = {\n [K in keyof T]?: T[K] | Patch<T[K]>;\n};\n\n/**\n * An object with an ArangoDB document `_id` property.\n *\n * See {@link documents.DocumentMetadata}.\n */\nexport type ObjectWithId = {\n [key: string]: any;\n _id: string;\n};\n\n/**\n * An object with an ArangoDB document `_key` property.\n *\n * See {@link documents.DocumentMetadata}.\n */\nexport type ObjectWithKey = {\n [key: string]: any;\n _key: string;\n};\n\n/**\n * A value that can be used to identify a document within a collection in\n * arangojs methods, i.e. a partial ArangoDB document or the value of a\n * document's `_key` or `_id`.\n *\n * See {@link documents.DocumentMetadata}.\n */\nexport type DocumentSelector = ObjectWithId | ObjectWithKey | string;\n\n/**\n * @internal\n */\nexport function _documentHandle(\n selector: DocumentSelector,\n collectionName: string,\n strict: boolean = true\n): string {\n if (typeof selector !== \"string\") {\n if (selector._id) {\n return _documentHandle(selector._id, collectionName);\n }\n if (selector._key) {\n return _documentHandle(selector._key, collectionName);\n }\n throw new Error(\n \"Document handle must be a string or an object with a _key or _id attribute\"\n );\n }\n if (selector.includes(\"/\")) {\n const [head, ...tail] = selector.split(\"/\");\n const normalizedHead = head.normalize(\"NFC\");\n if (strict && normalizedHead !== collectionName) {\n throw new Error(\n `Document ID \"${selector}\" does not match collection name \"${collectionName}\"`\n );\n }\n return [normalizedHead, ...tail].join(\"/\");\n }\n return `${collectionName}/${selector}`;\n}\n","/**\n * ```ts\n * import type { ArangoError, HttpError } from \"arangojs/error\";\n * ```\n *\n * The \"error\" module provides types and interfaces for TypeScript related\n * to arangojs error handling.\n *\n * @packageDocumentation\n */\n\nconst messages: { [key: number]: string } = {\n 0: \"Network Error\",\n 304: \"Not Modified\",\n 400: \"Bad Request\",\n 401: \"Unauthorized\",\n 402: \"Payment Required\",\n 403: \"Forbidden\",\n 404: \"Not Found\",\n 405: \"Method Not Allowed\",\n 406: \"Not Acceptable\",\n 407: \"Proxy Authentication Required\",\n 408: \"Request Timeout\",\n 409: \"Conflict\",\n 410: \"Gone\",\n 411: \"Length Required\",\n 412: \"Precondition Failed\",\n 413: \"Payload Too Large\",\n 414: \"Request-URI Too Long\",\n 415: \"Unsupported Media Type\",\n 416: \"Requested Range Not Satisfiable\",\n 417: \"Expectation Failed\",\n 418: \"I'm a teapot\",\n 421: \"Misdirected Request\",\n 422: \"Unprocessable Entity\",\n 423: \"Locked\",\n 424: \"Failed Dependency\",\n 426: \"Upgrade Required\",\n 428: \"Precondition Required\",\n 429: \"Too Many Requests\",\n 431: \"Request Header Fields Too Large\",\n 444: \"Connection Closed Without Response\",\n 451: \"Unavailable For Legal Reasons\",\n 499: \"Client Closed Request\",\n 500: \"Internal Server Error\",\n 501: \"Not Implemented\",\n 502: \"Bad Gateway\",\n 503: \"Service Unavailable\",\n 504: \"Gateway Timeout\",\n 505: \"HTTP Version Not Supported\",\n 506: \"Variant Also Negotiates\",\n 507: \"Insufficient Storage\",\n 508: \"Loop Detected\",\n 510: \"Not Extended\",\n 511: \"Network Authentication Required\",\n 599: \"Network Connect Timeout Error\",\n};\n\nconst nativeErrorKeys = [\n \"fileName\",\n \"lineNumber\",\n \"columnNumber\",\n \"stack\",\n \"description\",\n \"number\",\n] as (keyof Error)[];\n\n/**\n * Indicates whether the given value represents an {@link ArangoError}.\n *\n * @param error - A value that might be an `ArangoError`.\n */\nexport function isArangoError(error: any): error is ArangoError {\n return Boolean(error && error.isArangoError);\n}\n\n/**\n * Indicates whether the given value represents an ArangoDB error response.\n *\n * @internal\n */\nexport function isArangoErrorResponse(body: any): boolean {\n return (\n body &&\n body.hasOwnProperty(\"error\") &&\n body.hasOwnProperty(\"code\") &&\n body.hasOwnProperty(\"errorMessage\") &&\n body.hasOwnProperty(\"errorNum\")\n );\n}\n\n/**\n * Indicates whether the given value represents a Node.js `SystemError`.\n */\nexport function isSystemError(err: any): err is SystemError {\n return (\n Object.getPrototypeOf(err) === Error.prototype &&\n err.hasOwnProperty(\"code\") &&\n err.hasOwnProperty(\"errno\") &&\n err.hasOwnProperty(\"syscall\")\n );\n}\n\n/**\n * Interface representing a Node.js `SystemError`.\n */\nexport interface SystemError extends Error {\n code: string;\n errno: number | string;\n syscall: string;\n}\n\n/**\n * Represents an error returned by ArangoDB.\n */\nexport class ArangoError extends Error {\n name = \"ArangoError\";\n /**\n * ArangoDB error code.\n *\n * See [ArangoDB error documentation](https://www.arangodb.com/docs/stable/appendix-error-codes.html).\n */\n errorNum: number;\n /**\n * HTTP status code included in the server error response object.\n */\n code: number;\n /**\n * Server response object.\n */\n response: any;\n\n /**\n * @internal\n */\n constructor(response: any) {\n super();\n this.response = response;\n this.message = response.body.errorMessage;\n this.errorNum = response.body.errorNum;\n this.code = response.body.code;\n const err = new Error(this.message);\n err.name = this.name;\n for (const key of nativeErrorKeys) {\n if (err[key]) this[key] = err[key]!;\n }\n }\n\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB error.\n */\n get isArangoError(): true {\n return true;\n }\n\n toJSON() {\n return {\n error: true,\n errorMessage: this.message,\n errorNum: this.errorNum,\n code: this.code,\n };\n }\n}\n\n/**\n * Represents a plain HTTP error response.\n */\nexport class HttpError extends Error {\n name = \"HttpError\";\n /**\n * Server response object.\n */\n response: any;\n /**\n * HTTP status code of the server response.\n */\n code: number;\n\n /**\n * @internal\n */\n constructor(response: any) {\n super();\n this.response = response;\n this.code = response.statusCode || 500;\n this.message = messages[this.code] || messages[500];\n const err = new Error(this.message);\n err.name = this.name;\n for (const key of nativeErrorKeys) {\n if (err[key]) this[key] = err[key]!;\n }\n }\n\n toJSON() {\n return {\n error: true,\n code: this.code,\n };\n }\n}\n","/**\n * ```ts\n * import type {\n * Graph,\n * GraphVertexCollection,\n * GraphEdgeCollection,\n * } from \"arangojs/graph\";\n * ```\n *\n * The \"graph\" module provides graph related types and interfaces\n * for TypeScript.\n *\n * @packageDocumentation\n */\nimport {\n ArangoCollection,\n collectionToString,\n DocumentCollection,\n EdgeCollection,\n TraversalOptions,\n} from \"./collection\";\nimport { Headers } from \"./connection\";\nimport { Database } from \"./database\";\nimport {\n Document,\n DocumentData,\n DocumentMetadata,\n DocumentSelector,\n Edge,\n EdgeData,\n Patch,\n _documentHandle,\n} from \"./documents\";\nimport { isArangoError } from \"./error\";\nimport { DOCUMENT_NOT_FOUND, GRAPH_NOT_FOUND } from \"./lib/codes\";\n\n/**\n * Indicates whether the given value represents a {@link graph.Graph}.\n *\n * @param graph - A value that might be a Graph.\n */\nexport function isArangoGraph(graph: any): graph is Graph {\n return Boolean(graph && graph.isArangoGraph);\n}\n\n/**\n * @internal\n */\nfunction mungeGharialResponse(body: any, prop: \"vertex\" | \"edge\" | \"removed\") {\n const { new: newDoc, old: oldDoc, [prop]: doc, ...meta } = body;\n const result = { ...meta, ...doc };\n if (typeof newDoc !== \"undefined\") result.new = newDoc;\n if (typeof oldDoc !== \"undefined\") result.old = oldDoc;\n return result;\n}\n\n/**\n * @internal\n */\nfunction coerceEdgeDefinition(options: EdgeDefinitionOptions): EdgeDefinition {\n const edgeDefinition = {} as EdgeDefinition;\n edgeDefinition.collection = collectionToString(options.collection);\n edgeDefinition.from = Array.isArray(options.from)\n ? options.from.map(collectionToString)\n : [collectionToString(options.from)];\n edgeDefinition.to = Array.isArray(options.to)\n ? options.to.map(collectionToString)\n : [collectionToString(options.to)];\n return edgeDefinition;\n}\n\n/**\n * Options for retrieving a document from a graph collection.\n */\nexport type GraphCollectionReadOptions = {\n /**\n * If set to a document revision, the document will only be returned if its\n * `_rev` property matches this value.\n *\n * See also {@link documents.DocumentMetadata}.\n */\n rev?: string;\n /**\n * If set to `true`, `null` is returned instead of an exception being thrown\n * if the document does not exist.\n *\n * Default: `false`\n */\n graceful?: boolean;\n /**\n * If set to `true`, the request will explicitly permit ArangoDB to return a\n * potentially dirty or stale result and arangojs will load balance the\n * request without distinguishing between leaders and followers.\n *\n * Default: `false`\n */\n allowDirtyRead?: boolean;\n};\n\n/**\n * Options for inserting a document into a graph collection.\n */\nexport type GraphCollectionInsertOptions = {\n /**\n * If set to `true`, data will be synchronized to disk before returning.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * If set to `true`, the complete new document will be returned as the `new`\n * property on the result object.\n *\n * Default: `false`\n */\n returnNew?: boolean;\n};\n\n/**\n * Options for replacing a document in a graph collection.\n */\nexport type GraphCollectionReplaceOptions = {\n /**\n * If set to a document revision, the document will only be modified if its\n * `_rev` property matches this value.\n *\n * See also {@link documents.DocumentMetadata}.\n */\n rev?: string;\n /**\n * If set to `true`, data will be synchronized to disk before returning.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * If set to `false`, properties with a value of `null` will be removed from\n * the new document.\n *\n * Default: `true`\n */\n keepNull?: boolean;\n /**\n * If set to `true`, the complete old document will be returned as the `old`\n * property on the result object.\n *\n * Default: `false`\n */\n returnOld?: boolean;\n /**\n * If set to `true`, the complete new document will be returned as the `new`\n * property on the result object.\n *\n * Default: `false`\n */\n returnNew?: boolean;\n};\n\n/**\n * Options for removing a document from a graph collection.\n */\nexport type GraphCollectionRemoveOptions = {\n /**\n * If set to a document revision, the document will only be removed if its\n * `_rev` property matches this value.\n *\n * See also {@link documents.DocumentMetadata}.\n */\n rev?: string;\n /**\n * If set to `true`, data will be synchronized to disk before returning.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * If set to `true`, the complete old document will be returned as the `old`\n * property on the result object.\n *\n * Default: `false`\n */\n returnOld?: boolean;\n};\n\n/**\n * Definition of a relation in a {@link graph.Graph}.\n */\nexport type EdgeDefinition = {\n /**\n * Name of the collection containing the edges.\n */\n collection: string;\n /**\n * Array of names of collections containing the start vertices.\n */\n from: string[];\n /**\n * Array of names of collections containing the end vertices.\n */\n to: string[];\n};\n\n/**\n * An edge definition used to define a collection of edges in a {@link graph.Graph}.\n */\nexport type EdgeDefinitionOptions = {\n /**\n * Collection containing the edges.\n */\n collection: string | ArangoCollection;\n /**\n * Collection or collections containing the start vertices.\n */\n from: (string | ArangoCollection)[] | string | ArangoCollection;\n /**\n * Collection or collections containing the end vertices.\n */\n to: (string | ArangoCollection)[] | string | ArangoCollection;\n};\n\n/**\n * General information about a graph.\n */\nexport type GraphInfo = {\n /**\n * Key of the document internally representing this graph.\n *\n * See {@link documents.DocumentMetadata}.\n *\n * @internal\n */\n _key: string;\n /**\n * Unique identifier of the document internally representing this graph.\n *\n * See {@link documents.DocumentMetadata}.\n *\n * @internal\n */\n _id: string;\n /**\n * Revision of the document internally representing this graph.\n *\n * See {@link documents.DocumentMetadata}.\n *\n * @internal\n */\n _rev: string;\n /**\n * Name of the graph.\n */\n name: string;\n /**\n * Definitions for the relations of the graph.\n */\n edgeDefinitions: EdgeDefinition[];\n /**\n * Additional vertex collections. Documents within these collections do not\n * have edges within this graph.\n */\n orphanCollections: string[];\n\n /**\n * (Cluster only.) Number of shards that is used for every collection\n * within this graph.\n */\n numberOfShards?: number;\n /**\n * (Cluster only.) Replication factor used when initially creating\n * collections for this graph.\n */\n replicationFactor?: number;\n /**\n * (Cluster only.) Write concern for new collections in the graph.\n */\n writeConcern?: number;\n /**\n * (Enterprise Edition cluster only.) If set to `true`, the graph is a\n * SatelliteGraph.\n */\n isSatellite?: boolean;\n /**\n * (Enterprise Edition cluster only.) If set to `true`, the graph has been\n * created as a SmartGraph.\n */\n isSmart?: boolean;\n /**\n * (Enterprise Edition cluster only.) Attribute containing the shard key\n * value to use for smart sharding.\n */\n smartGraphAttribute?: string;\n /**\n * (Enterprise Edition cluster only.) If set to `true`, the graph has been\n * created as a Disjoint SmartGraph.\n */\n isDisjoint?: boolean;\n};\n\n/**\n * Option for creating a graph.\n */\nexport type CreateGraphOptions = {\n /**\n * If set to `true`, the request will wait until all modifications have been\n * synchronized to disk before returning successfully.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * Additional vertex collections. Documents within these collections do not\n * have edges within this graph.\n */\n orphanCollections?: (string | ArangoCollection)[] | string | ArangoCollection;\n\n /**\n * (Cluster only.) Number of shards that is used for every collection\n * within this graph.\n *\n * Has no effect when `replicationFactor` is set to `\"satellite\"`.\n */\n numberOfShards?: number;\n /**\n * (Cluster only.) Replication factor used when initially creating\n * collections for this graph.\n *\n * Default: `1`\n */\n replicationFactor?: number | \"satellite\";\n /**\n * (Cluster only.) Write concern for new collections in the graph.\n *\n * Has no effect when `replicationFactor` is set to `\"satellite\"`.\n */\n writeConcern?: number;\n\n // Extra options\n /**\n * (Enterprise Edition cluster only.) If set to `true`, the graph will be\n * created as a SmartGraph.\n *\n * Default: `false`\n */\n isSmart?: boolean;\n /**\n * (Enterprise Edition cluster only.) Attribute containing the shard key\n * value to use for smart sharding.\n */\n smartGraphAttribute?: string;\n /**\n * (Enterprise Edition cluster only.) If set to `true`, the graph will be\n * created as a Disjoint SmartGraph.\n *\n * Default: `false`\n */\n isDisjoint?: boolean;\n /**\n * (Enterprise Edition cluster only.) Collections to be included in a Hybrid\n * SmartGraph.\n */\n satellites?: (string | ArangoCollection)[];\n};\n\nexport type AddVertexCollectionOptions = {\n /**\n * (Enterprise Edition cluster only.) Collections to be included in a Hybrid\n * SmartGraph.\n */\n satellites?: (string | ArangoCollection)[];\n};\n\nexport type AddEdgeDefinitionOptions = {\n /**\n * (Enterprise Edition cluster only.) Collections to be included in a Hybrid\n * SmartGraph.\n */\n satellites?: (string | ArangoCollection)[];\n};\n\nexport type ReplaceEdgeDefinitionOptions = {\n /**\n * (Enterprise Edition cluster only.) Collections to be included in a Hybrid\n * SmartGraph.\n */\n satellites?: string[];\n};\n\n/**\n * Represents a {@link collection.DocumentCollection} of vertices in a {@link graph.Graph}.\n *\n * @param T - Type to use for document data. Defaults to `any`.\n */\nexport class GraphVertexCollection<T extends Record<string, any> = any>\n implements ArangoCollection\n{\n protected _db: Database;\n protected _name: string;\n protected _graph: Graph;\n protected _collection: DocumentCollection<T>;\n\n /**\n * @internal\n */\n constructor(db: Database, name: string, graph: Graph) {\n this._db = db;\n this._collection = db.collection(name);\n this._name = this._collection.name;\n this._graph = graph;\n }\n\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB collection.\n */\n get isArangoCollection(): true {\n return true;\n }\n\n /**\n * Name of the collection.\n */\n get name() {\n return this._name;\n }\n\n /**\n * A {@link collection.DocumentCollection} instance for this vertex collection.\n */\n get collection() {\n return this._collection;\n }\n\n /**\n * The {@link graph.Graph} instance this vertex collection is bound to.\n */\n get graph() {\n return this._graph;\n }\n\n /**\n * Checks whether a vertex matching the given key or id exists in this\n * collection.\n *\n * Throws an exception when passed a vertex or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a vertex from this collection).\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.vertexCollection(\"vertices\");\n * const exists = await collection.vertexExists(\"abc123\");\n * if (!exists) {\n * console.log(\"Vertex does not exist\");\n * }\n * ```\n */\n async vertexExists(selector: DocumentSelector): Promise<boolean> {\n try {\n return await this._db.request(\n {\n method: \"HEAD\",\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/vertex/${encodeURI(_documentHandle(selector, this._name))}`,\n },\n () => true\n );\n } catch (err: any) {\n if (err.code === 404) {\n return false;\n }\n throw err;\n }\n }\n\n /**\n * Retrieves the vertex matching the given key or id.\n *\n * Throws an exception when passed a vertex or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a vertex from this collection).\n * @param options - Options for retrieving the vertex.\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.vertexCollection(\"vertices\");\n * try {\n * const vertex = await collection.vertex(\"abc123\");\n * console.log(vertex);\n * } catch (e: any) {\n * console.error(\"Could not find vertex\");\n * }\n * ```\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.vertexCollection(\"vertices\");\n * const vertex = await collection.vertex(\"abc123\", { graceful: true });\n * if (vertex) {\n * console.log(vertex);\n * } else {\n * console.error(\"Could not find vertex\");\n * }\n * ```\n */\n async vertex(\n selector: DocumentSelector,\n options?: GraphCollectionReadOptions\n ): Promise<Document<T>>;\n /**\n * Retrieves the vertex matching the given key or id.\n *\n * Throws an exception when passed a vertex or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a vertex from this collection).\n * @param graceful - If set to `true`, `null` is returned instead of an\n * exception being thrown if the vertex does not exist.\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.vertexCollection(\"vertices\");\n * try {\n * const vertex = await collection.vertex(\"abc123\", false);\n * console.log(vertex);\n * } catch (e: any) {\n * console.error(\"Could not find vertex\");\n * }\n * ```\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.vertexCollection(\"vertices\");\n * const vertex = await collection.vertex(\"abc123\", true);\n * if (vertex) {\n * console.log(vertex);\n * } else {\n * console.error(\"Could not find vertex\");\n * }\n * ```\n */\n async vertex(\n selector: DocumentSelector,\n graceful: boolean\n ): Promise<Document<T>>;\n async vertex(\n selector: DocumentSelector,\n options: boolean | GraphCollectionReadOptions = {}\n ): Promise<Document<T> | null> {\n if (typeof options === \"boolean\") {\n options = { graceful: options };\n }\n const {\n allowDirtyRead = undefined,\n graceful = false,\n rev,\n ...qs\n } = options;\n const headers: Headers = {};\n if (rev) headers[\"if-match\"] = rev;\n const result = this._db.request(\n {\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/vertex/${encodeURI(_documentHandle(selector, this._name))}`,\n headers,\n qs,\n allowDirtyRead,\n },\n (res) => res.body.vertex\n );\n if (!graceful) return result;\n try {\n return await result;\n } catch (err: any) {\n if (isArangoError(err) && err.errorNum === DOCUMENT_NOT_FOUND) {\n return null;\n }\n throw err;\n }\n }\n\n /**\n * Inserts a new vertex with the given `data` into the collection.\n *\n * @param data - The contents of the new vertex.\n * @param options - Options for inserting the vertex.\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.vertexCollection(\"friends\");\n * const result = await collection.save(\n * { _key: \"a\", color: \"blue\", count: 1 },\n * { returnNew: true }\n * );\n * console.log(result.new.color, result.new.count); // \"blue\" 1\n * ```\n */\n save(\n data: DocumentData<T>,\n options?: GraphCollectionInsertOptions\n ): Promise<DocumentMetadata & { new?: Document<T> }>;\n save(data: DocumentData<T>, options?: GraphCollectionInsertOptions) {\n return this._db.request(\n {\n method: \"POST\",\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/vertex/${encodeURIComponent(this._name)}`,\n body: data,\n qs: options,\n },\n (res) => mungeGharialResponse(res.body, \"vertex\")\n );\n }\n\n /**\n * Replaces an existing vertex in the collection.\n *\n * Throws an exception when passed a vertex or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a vertex from this collection).\n * @param newData - The contents of the new vertex.\n * @param options - Options for replacing the vertex.\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.collection(\"vertices\");\n * await collection.save({ _key: \"a\", color: \"blue\", count: 1 });\n * const result = await collection.replace(\n * \"a\",\n * { color: \"red\" },\n * { returnNew: true }\n * );\n * console.log(result.new.color, result.new.count); // \"red\" undefined\n * ```\n */\n replace(\n selector: DocumentSelector,\n newValue: DocumentData<T>,\n options?: GraphCollectionReplaceOptions\n ): Promise<DocumentMetadata & { new?: Document<T>; old?: Document<T> }>;\n replace(\n selector: DocumentSelector,\n newValue: DocumentData<T>,\n options: GraphCollectionReplaceOptions = {}\n ) {\n if (typeof options === \"string\") {\n options = { rev: options };\n }\n const { rev, ...qs } = options;\n const headers: Headers = {};\n if (rev) headers[\"if-match\"] = rev;\n return this._db.request(\n {\n method: \"PUT\",\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/vertex/${encodeURI(_documentHandle(selector, this._name))}`,\n body: newValue,\n qs,\n headers,\n },\n (res) => mungeGharialResponse(res.body, \"vertex\")\n );\n }\n\n /**\n * Updates an existing vertex in the collection.\n *\n * Throws an exception when passed a vertex or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a vertex from this collection).\n * @param newData - The data for updating the vertex.\n * @param options - Options for updating the vertex.\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.collection(\"vertices\");\n * await collection.save({ _key: \"a\", color: \"blue\", count: 1 });\n * const result = await collection.update(\n * \"a\",\n * { count: 2 },\n * { returnNew: true }\n * );\n * console.log(result.new.color, result.new.count); // \"blue\" 2\n * ```\n */\n update(\n selector: DocumentSelector,\n newValue: Patch<DocumentData<T>>,\n options?: GraphCollectionReplaceOptions\n ): Promise<DocumentMetadata & { new?: Document<T>; old?: Document<T> }>;\n update(\n selector: DocumentSelector,\n newValue: Patch<DocumentData<T>>,\n options: GraphCollectionReplaceOptions = {}\n ) {\n if (typeof options === \"string\") {\n options = { rev: options };\n }\n const headers: Headers = {};\n const { rev, ...qs } = options;\n if (rev) headers[\"if-match\"] = rev;\n return this._db.request(\n {\n method: \"PATCH\",\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/vertex/${encodeURI(_documentHandle(selector, this._name))}`,\n body: newValue,\n qs,\n headers,\n },\n (res) => mungeGharialResponse(res.body, \"vertex\")\n );\n }\n\n /**\n * Removes an existing vertex from the collection.\n *\n * Throws an exception when passed a vertex or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a vertex from this collection).\n * @param options - Options for removing the vertex.\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.vertexCollection(\"vertices\");\n * await collection.remove(\"abc123\");\n * // document with key \"abc123\" deleted\n * ```\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.vertexCollection(\"vertices\");\n * const doc = await collection.vertex(\"abc123\");\n * await collection.remove(doc);\n * // document with key \"abc123\" deleted\n * ```\n */\n remove(\n selector: DocumentSelector,\n options?: GraphCollectionRemoveOptions\n ): Promise<DocumentMetadata & { old?: Document<T> }>;\n remove(\n selector: DocumentSelector,\n options: GraphCollectionRemoveOptions = {}\n ) {\n if (typeof options === \"string\") {\n options = { rev: options };\n }\n const headers: Headers = {};\n const { rev, ...qs } = options;\n if (rev) headers[\"if-match\"] = rev;\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/vertex/${encodeURI(_documentHandle(selector, this._name))}`,\n qs,\n headers,\n },\n (res) => mungeGharialResponse(res.body, \"removed\")\n );\n }\n}\n\n/**\n * Represents a {@link collection.EdgeCollection} of edges in a {@link graph.Graph}.\n *\n * @param T - Type to use for document data. Defaults to `any`.\n */\nexport class GraphEdgeCollection<T extends Record<string, any> = any>\n implements ArangoCollection\n{\n protected _db: Database;\n protected _name: string;\n protected _graph: Graph;\n protected _collection: EdgeCollection<T>;\n\n /**\n * @internal\n */\n constructor(db: Database, name: string, graph: Graph) {\n this._db = db;\n this._collection = db.collection(name);\n this._name = this._collection.name;\n this._graph = graph;\n }\n\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB collection.\n */\n get isArangoCollection(): true {\n return true;\n }\n\n /**\n * Name of the collection.\n */\n get name() {\n return this._name;\n }\n\n /**\n * A {@link collection.EdgeCollection} instance for this edge collection.\n */\n get collection() {\n return this._collection;\n }\n\n /**\n * The {@link graph.Graph} instance this edge collection is bound to.\n */\n get graph() {\n return this._graph;\n }\n\n /**\n * Checks whether a edge matching the given key or id exists in this\n * collection.\n *\n * Throws an exception when passed a edge or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a edge from this collection).\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.edgeCollection(\"friends\")\n * const exists = await collection.edgeExists(\"abc123\");\n * if (!exists) {\n * console.log(\"Edge does not exist\");\n * }\n * ```\n */\n async edgeExists(selector: DocumentSelector): Promise<boolean> {\n try {\n return await this._db.request(\n {\n method: \"HEAD\",\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/edge/${encodeURI(_documentHandle(selector, this._name))}`,\n },\n () => true\n );\n } catch (err: any) {\n if (err.code === 404) {\n return false;\n }\n throw err;\n }\n }\n\n /**\n * Retrieves the edge matching the given key or id.\n *\n * Throws an exception when passed a edge or `_id` from a different\n * collection, or if the edge does not exist.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a edge from this collection).\n * @param options - Options for retrieving the edge.\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.edgeCollection(\"friends\")\n * try {\n * const edge = await collection.edge(\"abc123\");\n * console.log(edge);\n * } catch (e: any) {\n * console.error(\"Could not find edge\");\n * }\n * ```\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.edgeCollection(\"friends\")\n * const edge = await collection.edge(\"abc123\", { graceful: true });\n * if (edge) {\n * console.log(edge);\n * } else {\n * console.error(\"Edge does not exist\");\n * }\n * ```\n */\n async edge(\n selector: DocumentSelector,\n options?: GraphCollectionReadOptions\n ): Promise<Edge<T>>;\n /**\n * Retrieves the edge matching the given key or id.\n *\n * Throws an exception when passed a edge or `_id` from a different\n * collection, or if the edge does not exist.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a edge from this collection).\n * @param graceful - If set to `true`, `null` is returned instead of an\n * exception being thrown if the edge does not exist.\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.edgeCollection(\"friends\")\n * try {\n * const edge = await collection.edge(\"abc123\", false);\n * console.log(edge);\n * } catch (e: any) {\n * console.error(\"Could not find edge\");\n * }\n * ```\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.edgeCollection(\"friends\")\n * const edge = await collection.edge(\"abc123\", true);\n * if (edge) {\n * console.log(edge);\n * } else {\n * console.error(\"Edge does not exist\");\n * }\n * ```\n */\n async edge(selector: DocumentSelector, graceful: boolean): Promise<Edge<T>>;\n async edge(\n selector: DocumentSelector,\n options: boolean | GraphCollectionReadOptions = {}\n ): Promise<Edge<T> | null> {\n if (typeof options === \"boolean\") {\n options = { graceful: options };\n }\n const {\n allowDirtyRead = undefined,\n graceful = false,\n rev,\n ...qs\n } = options;\n const headers: Headers = {};\n if (rev) headers[\"if-match\"] = rev;\n const result = this._db.request(\n {\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/edge/${encodeURI(_documentHandle(selector, this._name))}`,\n qs,\n allowDirtyRead,\n },\n (res) => res.body.edge\n );\n if (!graceful) return result;\n try {\n return await result;\n } catch (err: any) {\n if (isArangoError(err) && err.errorNum === DOCUMENT_NOT_FOUND) {\n return null;\n }\n throw err;\n }\n }\n\n /**\n * Inserts a new edge with the given `data` into the collection.\n *\n * @param data - The contents of the new edge.\n * @param options - Options for inserting the edge.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * const result = await collection.save(\n * { _from: \"users/rana\", _to: \"users/mudasir\", active: false },\n * { returnNew: true }\n * );\n * ```\n */\n save(\n data: EdgeData<T>,\n options?: GraphCollectionInsertOptions\n ): Promise<DocumentMetadata & { new?: Edge<T> }>;\n save(data: EdgeData<T>, options?: GraphCollectionInsertOptions) {\n return this._db.request(\n {\n method: \"POST\",\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/edge/${encodeURIComponent(this._name)}`,\n body: data,\n qs: options,\n },\n (res) => mungeGharialResponse(res.body, \"edge\")\n );\n }\n\n /**\n * Replaces an existing edge in the collection.\n *\n * Throws an exception when passed a edge or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a edge from this collection).\n * @param newData - The contents of the new edge.\n * @param options - Options for replacing the edge.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * await collection.save(\n * {\n * _key: \"musadir\",\n * _from: \"users/rana\",\n * _to: \"users/mudasir\",\n * active: true,\n * best: true\n * }\n * );\n * const result = await collection.replace(\n * \"musadir\",\n * { active: false },\n * { returnNew: true }\n * );\n * console.log(result.new.active, result.new.best); // false undefined\n * ```\n */\n replace(\n selector: DocumentSelector,\n newValue: EdgeData<T>,\n options?: GraphCollectionReplaceOptions\n ): Promise<DocumentMetadata & { new?: Edge<T>; old?: Edge<T> }>;\n replace(\n selector: DocumentSelector,\n newValue: EdgeData<T>,\n options: GraphCollectionReplaceOptions = {}\n ) {\n if (typeof options === \"string\") {\n options = { rev: options };\n }\n const { rev, ...qs } = options;\n const headers: Headers = {};\n if (rev) headers[\"if-match\"] = rev;\n return this._db.request(\n {\n method: \"PUT\",\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/edge/${encodeURI(_documentHandle(selector, this._name))}`,\n body: newValue,\n qs,\n headers,\n },\n (res) => mungeGharialResponse(res.body, \"edge\")\n );\n }\n\n /**\n * Updates an existing edge in the collection.\n *\n * Throws an exception when passed a edge or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a edge from this collection).\n * @param newData - The data for updating the edge.\n * @param options - Options for updating the edge.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * await collection.save(\n * {\n * _key: \"musadir\",\n * _from: \"users/rana\",\n * _to: \"users/mudasir\",\n * active: true,\n * best: true\n * }\n * );\n * const result = await collection.update(\n * \"musadir\",\n * { active: false },\n * { returnNew: true }\n * );\n * console.log(result.new.active, result.new.best); // false true\n * ```\n */\n update(\n selector: DocumentSelector,\n newValue: Patch<EdgeData<T>>,\n options?: GraphCollectionReplaceOptions\n ): Promise<DocumentMetadata & { new?: Edge<T>; old?: Edge<T> }>;\n update(\n selector: DocumentSelector,\n newValue: Patch<EdgeData<T>>,\n options: GraphCollectionReplaceOptions = {}\n ) {\n if (typeof options === \"string\") {\n options = { rev: options };\n }\n const { rev, ...qs } = options;\n const headers: Headers = {};\n if (rev) headers[\"if-match\"] = rev;\n return this._db.request(\n {\n method: \"PATCH\",\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/edge/${encodeURI(_documentHandle(selector, this._name))}`,\n body: newValue,\n qs,\n headers,\n },\n (res) => mungeGharialResponse(res.body, \"edge\")\n );\n }\n\n /**\n * Removes an existing edge from the collection.\n *\n * Throws an exception when passed a edge or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a edge from this collection).\n * @param options - Options for removing the edge.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * const doc = await collection.edge(\"musadir\");\n * await collection.remove(doc);\n * // edge with key \"musadir\" deleted\n * ```\n */\n remove(\n selector: DocumentSelector,\n options?: GraphCollectionRemoveOptions\n ): Promise<DocumentMetadata & { old?: Edge<T> }>;\n remove(\n selector: DocumentSelector,\n options: GraphCollectionRemoveOptions = {}\n ) {\n if (typeof options === \"string\") {\n options = { rev: options };\n }\n const { rev, ...qs } = options;\n const headers: Headers = {};\n if (rev) headers[\"if-match\"] = rev;\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/edge/${encodeURI(_documentHandle(selector, this._name))}`,\n qs,\n headers,\n },\n (res) => mungeGharialResponse(res.body, \"removed\")\n );\n }\n}\n\n/**\n * Represents a graph in a {@link database.Database}.\n */\nexport class Graph {\n protected _name: string;\n\n protected _db: Database;\n\n /**\n * @internal\n */\n constructor(db: Database, name: string) {\n this._name = name.normalize(\"NFC\");\n this._db = db;\n }\n\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB Graph.\n */\n get isArangoGraph(): true {\n return true;\n }\n\n /**\n * Name of the graph.\n */\n get name() {\n return this._name;\n }\n\n /**\n * Checks whether the graph exists.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const result = await graph.exists();\n * // result indicates whether the graph exists\n * ```\n */\n async exists(): Promise<boolean> {\n try {\n await this.get();\n return true;\n } catch (err: any) {\n if (isArangoError(err) && err.errorNum === GRAPH_NOT_FOUND) {\n return false;\n }\n throw err;\n }\n }\n\n /**\n * Retrieves general information about the graph.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const data = await graph.get();\n * // data contains general information about the graph\n * ```\n */\n get(): Promise<GraphInfo> {\n return this._db.request(\n { path: `/_api/gharial/${encodeURIComponent(this._name)}` },\n (res) => res.body.graph\n );\n }\n\n /**\n * Creates a graph with the given `edgeDefinitions` and `options` for this\n * graph's name.\n *\n * @param edgeDefinitions - Definitions for the relations of the graph.\n * @param options - Options for creating the graph.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const info = await graph.create([\n * {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * },\n * ]);\n * // graph now exists\n * ```\n */\n create(\n edgeDefinitions: EdgeDefinitionOptions[],\n options: CreateGraphOptions = {}\n ): Promise<GraphInfo> {\n const {\n orphanCollections,\n satellites,\n waitForSync,\n isSmart,\n isDisjoint,\n ...opts\n } = options;\n return this._db.request(\n {\n method: \"POST\",\n path: \"/_api/gharial\",\n body: {\n orphanCollections:\n orphanCollections &&\n (Array.isArray(orphanCollections)\n ? orphanCollections.map(collectionToString)\n : [collectionToString(orphanCollections)]),\n edgeDefinitions: edgeDefinitions.map(coerceEdgeDefinition),\n isSmart,\n isDisjoint,\n name: this._name,\n options: { ...opts, satellites: satellites?.map(collectionToString) },\n },\n qs: { waitForSync },\n },\n (res) => res.body.graph\n );\n }\n\n /**\n * Deletes the graph from the database.\n *\n * @param dropCollections - If set to `true`, the collections associated with\n * the graph will also be deleted.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * await graph.drop();\n * // the graph \"some-graph\" no longer exists\n * ```\n */\n drop(dropCollections: boolean = false): Promise<boolean> {\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/gharial/${encodeURIComponent(this._name)}`,\n qs: { dropCollections },\n },\n (res) => res.body.removed\n );\n }\n\n /**\n * Returns a {@link graph.GraphVertexCollection} instance for the given collection\n * name representing the collection in this graph.\n *\n * @param T - Type to use for document data. Defaults to `any`.\n * @param collection - Name of the vertex collection.\n */\n vertexCollection<T extends Record<string, any> = any>(\n collection: string | ArangoCollection\n ): GraphVertexCollection<T> {\n return new GraphVertexCollection<T>(\n this._db,\n collectionToString(collection),\n this\n );\n }\n\n /**\n * Fetches all vertex collections of this graph from the database and returns\n * an array of their names.\n *\n * See also {@link graph.Graph#vertexCollections}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const info = await graph.create([\n * {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * },\n * ]);\n * const vertexCollectionNames = await graph.listVertexCollections();\n * // [\"start-vertices\", \"end-vertices\"]\n * ```\n */\n listVertexCollections(): Promise<string[]> {\n return this._db.request(\n { path: `/_api/gharial/${encodeURIComponent(this._name)}/vertex` },\n (res) => res.body.collections\n );\n }\n\n /**\n * Fetches all vertex collections of this graph from the database and returns\n * an array of {@link graph.GraphVertexCollection} instances.\n *\n * See also {@link graph.Graph#listVertexCollections}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const info = await graph.create([\n * {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * },\n * ]);\n * const vertexCollections = await graph.vertexCollections();\n * for (const vertexCollection of vertexCollections) {\n * console.log(vertexCollection.name);\n * // \"start-vertices\"\n * // \"end-vertices\"\n * }\n * ```\n */\n async vertexCollections(): Promise<GraphVertexCollection[]> {\n const names = await this.listVertexCollections();\n return names.map((name) => new GraphVertexCollection(this._db, name, this));\n }\n\n /**\n * Adds the given collection to this graph as a vertex collection.\n *\n * @param collection - Collection to add to the graph.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * await graph.addVertexCollection(\"more-vertices\");\n * // The collection \"more-vertices\" has been added to the graph\n * const extra = db.collection(\"extra-vertices\");\n * await graph.addVertexCollection(extra);\n * // The collection \"extra-vertices\" has been added to the graph\n * ```\n */\n addVertexCollection(\n collection: string | ArangoCollection,\n options: AddVertexCollectionOptions = {}\n ): Promise<GraphInfo> {\n const { satellites, ...opts } = options;\n return this._db.request(\n {\n method: \"POST\",\n path: `/_api/gharial/${encodeURIComponent(this._name)}/vertex`,\n body: {\n collection: collectionToString(collection),\n options: { ...opts, satellites: satellites?.map(collectionToString) },\n },\n },\n (res) => res.body.graph\n );\n }\n\n /**\n * Removes the given collection from this graph as a vertex collection.\n *\n * @param collection - Collection to remove from the graph.\n * @param dropCollection - If set to `true`, the collection will also be\n * deleted from the database.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const info = await graph.create([\n * {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * },\n * ]);\n * await graph.removeVertexCollection(\"start-vertices\");\n * // The collection \"start-vertices\" is no longer part of the graph.\n * ```\n */\n removeVertexCollection(\n collection: string | ArangoCollection,\n dropCollection: boolean = false\n ): Promise<GraphInfo> {\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/gharial/${encodeURIComponent(\n this._name\n )}/vertex/${encodeURIComponent(collectionToString(collection))}`,\n qs: {\n dropCollection,\n },\n },\n (res) => res.body.graph\n );\n }\n\n /**\n * Returns a {@link graph.GraphEdgeCollection} instance for the given collection\n * name representing the collection in this graph.\n *\n * @param T - Type to use for document data. Defaults to `any`.\n * @param collection - Name of the edge collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const info = await graph.create([\n * {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * },\n * ]);\n * const graphEdgeCollection = graph.edgeCollection(\"edges\");\n * // Access the underlying EdgeCollection API:\n * const edgeCollection = graphEdgeCollection.collection;\n * ```\n */\n edgeCollection<T extends Record<string, any> = any>(\n collection: string | ArangoCollection\n ): GraphEdgeCollection<T> {\n return new GraphEdgeCollection<T>(\n this._db,\n collectionToString(collection),\n this\n );\n }\n\n /**\n * Fetches all edge collections of this graph from the database and returns\n * an array of their names.\n *\n * See also {@link graph.Graph#edgeCollections}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const info = await graph.create([\n * {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * },\n * ]);\n * const edgeCollectionNames = await graph.listEdgeCollections();\n * // [\"edges\"]\n * ```\n */\n listEdgeCollections(): Promise<string[]> {\n return this._db.request(\n { path: `/_api/gharial/${encodeURIComponent(this._name)}/edge` },\n (res) => res.body.collections\n );\n }\n\n /**\n * Fetches all edge collections of this graph from the database and returns\n * an array of {@link graph.GraphEdgeCollection} instances.\n *\n * See also {@link graph.Graph#listEdgeCollections}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const info = await graph.create([\n * {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * },\n * ]);\n * const graphEdgeCollections = await graph.edgeCollections();\n * for (const collection of graphEdgeCollection) {\n * console.log(collection.name);\n * // \"edges\"\n * }\n * ```\n */\n async edgeCollections(): Promise<GraphEdgeCollection[]> {\n const names = await this.listEdgeCollections();\n return names.map((name) => new GraphEdgeCollection(this._db, name, this));\n }\n\n /**\n * Adds an edge definition to this graph.\n *\n * @param edgeDefinition - Definition of a relation in this graph.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * await graph.addEdgeDefinition({\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * });\n * // The edge definition has been added to the graph\n * ```\n */\n addEdgeDefinition(\n edgeDefinition: EdgeDefinitionOptions,\n options: AddEdgeDefinitionOptions = {}\n ): Promise<GraphInfo> {\n const { satellites, ...opts } = options;\n return this._db.request(\n {\n method: \"POST\",\n path: `/_api/gharial/${encodeURIComponent(this._name)}/edge`,\n body: {\n ...coerceEdgeDefinition(edgeDefinition),\n options: { ...opts, satellites: satellites?.map(collectionToString) },\n },\n },\n (res) => res.body.graph\n );\n }\n\n /**\n * Replaces an edge definition in this graph. The existing edge definition\n * for the given edge collection will be overwritten.\n *\n * @param edgeDefinition - Definition of a relation in this graph.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const info = await graph.create([\n * {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * },\n * ]);\n * await graph.replaceEdgeDefinition({\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"other-vertices\"],\n * });\n * // The edge definition for \"edges\" has been replaced\n * ```\n */\n replaceEdgeDefinition(\n edgeDefinition: EdgeDefinitionOptions,\n options?: ReplaceEdgeDefinitionOptions\n ): Promise<GraphInfo>;\n /**\n * Replaces an edge definition in this graph. The existing edge definition\n * for the given edge collection will be overwritten.\n *\n * @param collection - Edge collection for which to replace the definition.\n * @param edgeDefinition - Definition of a relation in this graph.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const info = await graph.create([\n * {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * },\n * ]);\n * await graph.replaceEdgeDefinition(\"edges\", {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"other-vertices\"],\n * });\n * // The edge definition for \"edges\" has been replaced\n * ```\n */\n replaceEdgeDefinition(\n collection: string | ArangoCollection,\n edgeDefinition: EdgeDefinitionOptions,\n options?: ReplaceEdgeDefinitionOptions\n ): Promise<GraphInfo>;\n replaceEdgeDefinition(\n collectionOrEdgeDefinitionOptions:\n | string\n | ArangoCollection\n | EdgeDefinitionOptions,\n edgeDefinitionOrOptions?:\n | EdgeDefinitionOptions\n | ReplaceEdgeDefinitionOptions,\n options: ReplaceEdgeDefinitionOptions = {}\n ) {\n let collection = collectionOrEdgeDefinitionOptions as\n | string\n | ArangoCollection;\n let edgeDefinition = edgeDefinitionOrOptions as EdgeDefinitionOptions;\n if (\n edgeDefinitionOrOptions &&\n !edgeDefinitionOrOptions.hasOwnProperty(\"collection\")\n ) {\n options = edgeDefinitionOrOptions as ReplaceEdgeDefinitionOptions;\n edgeDefinitionOrOptions = undefined;\n }\n if (!edgeDefinitionOrOptions) {\n edgeDefinition =\n collectionOrEdgeDefinitionOptions as EdgeDefinitionOptions;\n collection = edgeDefinition.collection;\n }\n const { satellites, ...opts } = options;\n return this._db.request(\n {\n method: \"PUT\",\n path: `/_api/gharial/${encodeURIComponent(\n this._name\n )}/edge/${encodeURIComponent(collectionToString(collection))}`,\n body: {\n ...coerceEdgeDefinition(edgeDefinition),\n options: { ...opts, satellites: satellites?.map(collectionToString) },\n },\n },\n (res) => res.body.graph\n );\n }\n\n /**\n * Removes the edge definition for the given edge collection from this graph.\n *\n * @param collection - Edge collection for which to remove the definition.\n * @param dropCollection - If set to `true`, the collection will also be\n * deleted from the database.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const info = await graph.create([\n * {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * },\n * ]);\n * await graph.removeEdgeDefinition(\"edges\");\n * // The edge definition for \"edges\" has been replaced\n * ```\n */\n removeEdgeDefinition(\n collection: string | ArangoCollection,\n dropCollection: boolean = false\n ): Promise<GraphInfo> {\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/gharial/${encodeURIComponent(\n this._name\n )}/edge/${encodeURIComponent(collectionToString(collection))}`,\n qs: {\n dropCollection,\n },\n },\n (res) => res.body.graph\n );\n }\n\n /**\n * Performs a traversal starting from the given `startVertex` and following\n * edges contained in this graph.\n *\n * See also {@link collection.EdgeCollection#traversal}.\n *\n * @param startVertex - Document `_id` of a vertex in this graph.\n * @param options - Options for performing the traversal.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"my-graph\");\n * const collection = graph.edgeCollection(\"edges\").collection;\n * await collection.import([\n * [\"_key\", \"_from\", \"_to\"],\n * [\"x\", \"vertices/a\", \"vertices/b\"],\n * [\"y\", \"vertices/b\", \"vertices/c\"],\n * [\"z\", \"vertices/c\", \"vertices/d\"],\n * ]);\n * const startVertex = \"vertices/a\";\n * const cursor = await db.query(aql`\n * FOR vertex IN OUTBOUND ${startVertex} GRAPH ${graph}\n * RETURN vertex._key\n * `);\n * const result = await cursor.all();\n * console.log(result); // [\"a\", \"b\", \"c\", \"d\"]\n * ```\n */\n traversal(startVertex: string, options?: TraversalOptions): Promise<any> {\n return this._db.request(\n {\n method: \"POST\",\n path: `/_api/traversal`,\n body: {\n ...options,\n startVertex,\n graphName: this._name,\n },\n },\n (res) => res.body.result\n );\n }\n}\n","/**\n * Error codes handled by arangojs.\n *\n * See also [ArangoDB error documentation](https://www.arangodb.com/docs/stable/appendix-error-codes.html).\n *\n * @packageDocumentation\n * @internal\n */\n\nexport const TRANSACTION_NOT_FOUND = 10;\nexport const ERROR_ARANGO_MAINTENANCE_MODE = 503;\nexport const ERROR_ARANGO_CONFLICT = 1200;\nexport const ANALYZER_NOT_FOUND = 1202;\nexport const DOCUMENT_NOT_FOUND = 1202;\nexport const COLLECTION_NOT_FOUND = 1203;\nexport const VIEW_NOT_FOUND = 1203;\nexport const DATABASE_NOT_FOUND = 1228;\nexport const GRAPH_NOT_FOUND = 1924;\n","/**\n * ```ts\n * import type { ArangoSearchView } from \"arangojs/view\";\n * ```\n *\n * The \"view\" module provides View related types and interfaces for TypeScript.\n *\n * @packageDocumentation\n */\nimport { ArangoApiResponse } from \"./connection\";\nimport { Database } from \"./database\";\nimport { isArangoError } from \"./error\";\nimport { VIEW_NOT_FOUND } from \"./lib/codes\";\n\n/**\n * Indicates whether the given value represents a {@link View}.\n *\n * @param view - A value that might be a View.\n */\nexport function isArangoView(view: any): view is View {\n return Boolean(view && view.isArangoView);\n}\n\n/**\n * Sorting direction. Descending or ascending.\n */\nexport type Direction = \"desc\" | \"asc\";\n\n/**\n * Policy to consolidate based on segment byte size and live document count as\n * dictated by the customization attributes.\n *\n * @deprecated The `bytes_accum` consolidation policy was deprecated in\n * ArangoDB 3.7 and should be replaced with the `tier` consolidation policy.\n */\nexport type BytesAccumConsolidationPolicy = {\n /**\n * Type of consolidation policy.\n */\n type: \"bytes_accum\";\n /**\n * Must be in the range of `0.0` to `1.0`.\n */\n threshold?: number;\n};\n\n/**\n * Policy to consolidate if the sum of all candidate segment byte size is less\n * than the total segment byte size multiplied by a given threshold.\n */\nexport type TierConsolidationPolicy = {\n /**\n * Type of consolidation policy.\n */\n type: \"tier\";\n /**\n * Size below which all segments are treated as equivalent.\n *\n * Default: `2097152` (2 MiB)\n */\n segmentsBytesFloor?: number;\n /**\n * Maximum allowed size of all consolidation segments.\n *\n * Default: `5368709120` (5 GiB)\n */\n segmentsBytesMax?: number;\n /**\n * Maximum number of segments that are evaluated as candidates for\n * consolidation.\n *\n * Default: `10`\n */\n segmentsMax?: number;\n /**\n * Minimum number of segments that are evaluated as candidates for\n * consolidation.\n *\n * Default: `1`\n */\n segmentsMin?: number;\n /**\n * Consolidation candidates with a score less than this value will be\n * filtered out.\n *\n * Default: `0`\n */\n minScore?: number;\n};\n\n/**\n * Compression for storing data.\n */\nexport type Compression = \"lz4\" | \"none\";\n\n/**\n * Options for creating a View.\n */\nexport type CreateViewOptions =\n | CreateArangoSearchViewOptions\n | CreateSearchAliasViewOptions;\n\n/**\n * Options for replacing a View's properties.\n */\nexport type ViewPropertiesOptions =\n | ArangoSearchViewPropertiesOptions\n | SearchAliasViewPropertiesOptions;\n\n/**\n * Options for partially modifying a View's properties.\n */\nexport type ViewPatchPropertiesOptions =\n | ArangoSearchViewPropertiesOptions\n | SearchAliasViewPatchPropertiesOptions;\n\n/**\n * A link definition for an ArangoSearch View.\n */\nexport type ArangoSearchViewLinkOptions = {\n /**\n * A list of names of Analyzers to apply to values of processed document\n * attributes.\n *\n * Default: `[\"identity\"]`\n */\n analyzers?: string[];\n /**\n * An object mapping names of attributes to process for each document to\n * {@link ArangoSearchViewLinkOptions} definitions.\n */\n fields?: Record<string, ArangoSearchViewLinkOptions>;\n /**\n * If set to `true`, all document attributes will be processed, otherwise\n * only the attributes in `fields` will be processed.\n *\n * Default: `false`\n */\n includeAllFields?: boolean;\n /**\n * (Enterprise Edition only.) An object mapping attribute names to\n * {@link ArangoSearchViewLinkOptions} definitions to index sub-objects\n * stored in an array.\n */\n nested?: Record<string, ArangoSearchViewLinkOptions>;\n /**\n * If set to `true`, the position of values in array values will be tracked,\n * otherwise all values in an array will be treated as equal alternatives.\n */\n trackListPositions?: boolean;\n /**\n * Controls how the view should keep track of the attribute values.\n *\n * Default: `\"none\"`\n */\n storeValues?: \"none\" | \"id\";\n /**\n * If set to `true`, then no exclusive lock is used on the source collection\n * during View index creation, so that it remains basically available.\n *\n * Default: `false`\n */\n inBackground?: boolean;\n};\n\n/**\n * Options for modifying the properties of an ArangoSearch View.\n */\nexport type ArangoSearchViewPropertiesOptions = {\n /**\n * How many commits to wait between removing unused files.\n *\n * Default: `2`\n */\n cleanupIntervalStep?: number;\n /**\n * How long to wait between applying the `consolidationPolicy`.\n *\n * Default: `10000`\n */\n consolidationIntervalMsec?: number;\n /**\n * How long to wait between commiting View data store changes and making\n * documents visible to queries.\n *\n * Default: `1000`\n */\n commitIntervalMsec?: number;\n /**\n * Consolidation policy to apply for selecting which segments should be\n * merged.\n *\n * Default: `{ type: \"tier\" }`\n */\n consolidationPolicy?: TierConsolidationPolicy;\n /**\n * An object mapping names of linked collections to\n * {@link ArangoSearchViewLinkOptions} definitions.\n */\n links?: Record<string, Omit<ArangoSearchViewLinkOptions, \"nested\">>;\n};\n\n/**\n * Options for partially modifying the properties of an ArangoSearch View.\n */\nexport type ArangoSearchViewPatchPropertiesOptions =\n ArangoSearchViewPropertiesOptions;\n\n/**\n * Options for creating an ArangoSearch View.\n */\nexport type CreateArangoSearchViewOptions =\n ArangoSearchViewPropertiesOptions & {\n /**\n * Type of the View.\n */\n type: \"arangosearch\";\n /**\n * Maximum number of writers cached in the pool.\n *\n * Default: `64`\n */\n writebufferIdle?: number;\n /**\n * Maximum number of concurrent active writers that perform a transaction.\n *\n * Default: `0`\n */\n writebufferActive?: number;\n /**\n * Maximum memory byte size per writer before a writer flush is triggered.\n *\n * Default: `33554432` (32 MiB)\n */\n writebufferSizeMax?: number;\n /**\n * Attribute path (`field`) for the value of each document that will be\n * used for sorting.\n *\n * If `direction` is set to `\"asc\"` or `asc` is set to `true`,\n * the primary sorting order will be ascending.\n *\n * If `direction` is set to `\"desc\"` or `asc` is set to `false`,\n * the primary sorting order will be descending.\n */\n primarySort?: (\n | {\n /**\n * Attribute path for the value of each document to use for\n * sorting.\n */\n field: string;\n /**\n * If set to `\"asc\"`, the primary sorting order will be ascending.\n * If set to `\"desc\"`, the primary sorting order will be descending.\n */\n direction: Direction;\n }\n | {\n /**\n * Attribute path for the value of each document to use for\n * sorting.\n */\n field: string;\n /**\n * If set to `true`, the primary sorting order will be ascending.\n * If set to `false`, the primary sorting order will be descending.\n */\n asc: boolean;\n }\n )[];\n /**\n * Compression to use for the primary sort data.\n *\n * Default: `\"lz4\"`\n */\n primarySortCompression?: Compression;\n /**\n * Attribute paths for which values should be stored in the view index\n * in addition to those used for sorting via `primarySort`.\n */\n storedValues?: {\n /**\n * Attribute paths for which values should be stored in the view index\n * in addition to those used for sorting via `primarySort`.\n */\n fields: string[];\n /**\n * How the attribute values should be compressed.\n *\n * Default: `\"lz4\"`\n */\n compression?: Compression;\n }[];\n };\n\n/**\n * Options defining an index used in a SearchAlias View.\n */\nexport type SearchAliasViewIndexOptions = {\n /**\n * Name of a collection.\n */\n collection: string;\n /**\n * Name of an inverted index in the collection.\n */\n index: string;\n};\n\n/**\n * Options for modifying the properties of a SearchAlias View.\n */\nexport type SearchAliasViewPropertiesOptions = {\n /**\n * An array of inverted indexes to add to the View.\n */\n indexes: SearchAliasViewIndexOptions[];\n};\n\n/**\n * Options defining an index to be modified in a SearchAlias View.\n */\nexport type SearchAliasViewPatchIndexOptions = SearchAliasViewIndexOptions & {\n /**\n * Whether to add or remove the index.\n *\n * Default: `\"add\"`\n */\n operation?: \"add\" | \"del\";\n};\n\n/**\n * Options for partially modifying the properties of a SearchAlias View.\n */\nexport type SearchAliasViewPatchPropertiesOptions = {\n /**\n * An array of inverted indexes to add to the View.\n */\n indexes: SearchAliasViewPatchIndexOptions[];\n};\n\n/**\n * Options for creating a SearchAlias View.\n */\nexport type CreateSearchAliasViewOptions = SearchAliasViewPropertiesOptions & {\n /**\n * Type of the View.\n */\n type: \"search-alias\";\n};\n\n/**\n * Generic description of a View.\n */\nexport type GenericViewDescription = {\n /**\n * A globally unique identifier for this View.\n */\n globallyUniqueId: string;\n /**\n * An identifier for this View.\n */\n id: string;\n /**\n * Name of the View.\n */\n name: string;\n};\n\nexport type ViewDescription =\n | ArangoSearchViewDescription\n | SearchAliasViewDescription;\n\nexport type ArangoSearchViewDescription = GenericViewDescription & {\n type: \"arangosearch\";\n};\n\nexport type SearchAliasViewDescription = GenericViewDescription & {\n type: \"search-alias\";\n};\n\nexport type ViewProperties =\n | ArangoSearchViewProperties\n | SearchAliasViewProperties;\n\n/**\n * A link definition for an ArangoSearch View.\n */\nexport type ArangoSearchViewLink = {\n analyzers: string[];\n fields: Record<string, ArangoSearchViewLink>;\n includeAllFields: boolean;\n nested?: Record<string, ArangoSearchViewLink>;\n trackListPositions: boolean;\n storeValues: \"none\" | \"id\";\n};\n\n/**\n * Properties of an ArangoSearch View.\n */\nexport type ArangoSearchViewProperties = ArangoSearchViewDescription & {\n cleanupIntervalStep: number;\n consolidationIntervalMsec: number;\n commitIntervalMsec: number;\n writebufferIdle: number;\n writebufferActive: number;\n writebufferSizeMax: number;\n consolidationPolicy: TierConsolidationPolicy | BytesAccumConsolidationPolicy;\n primarySort: {\n field: string;\n direction: Direction;\n }[];\n primarySortCompression: Compression;\n storedValues: {\n fields: string[];\n compression: Compression;\n }[];\n links: Record<string, Omit<ArangoSearchViewLink, \"nested\">>;\n};\n\n/**\n * Properties of a SearchAlias View.\n */\nexport type SearchAliasViewProperties = SearchAliasViewDescription & {\n indexes: { collection: string; index: string }[];\n};\n\n/**\n * Represents a View in a {@link database.Database}.\n */\nexport class View {\n protected _name: string;\n protected _db: Database;\n\n /**\n * @internal\n */\n constructor(db: Database, name: string) {\n this._db = db;\n this._name = name.normalize(\"NFC\");\n }\n\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB View.\n */\n get isArangoView(): true {\n return true;\n }\n\n /**\n * Name of the View.\n */\n get name() {\n return this._name;\n }\n\n /**\n * Retrieves general information about the View.\n *\n * @example\n * ```js\n * const db = new Database();\n * const view = db.view(\"some-view\");\n * const data = await view.get();\n * // data contains general information about the View\n * ```\n */\n get(): Promise<ArangoApiResponse<ViewDescription>> {\n return this._db.request({\n path: `/_api/view/${encodeURIComponent(this._name)}`,\n });\n }\n\n /**\n * Checks whether the View exists.\n *\n * @example\n * ```js\n * const db = new Database();\n * const view = db.view(\"some-view\");\n * const exists = await view.exists();\n * console.log(exists); // indicates whether the View exists\n * ```\n */\n async exists(): Promise<boolean> {\n try {\n await this.get();\n return true;\n } catch (err: any) {\n if (isArangoError(err) && err.errorNum === VIEW_NOT_FOUND) {\n return false;\n }\n throw err;\n }\n }\n\n /**\n * Creates a View with the given `options` and the instance's name.\n *\n * See also {@link database.Database#createView}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const view = db.view(\"potatoes\");\n * await view.create();\n * // the ArangoSearch View \"potatoes\" now exists\n * ```\n */\n create<Options extends CreateViewOptions>(\n options: CreateViewOptions\n ): Promise<\n typeof options extends CreateArangoSearchViewOptions\n ? ArangoSearchViewDescription\n : Options extends CreateSearchAliasViewOptions\n ? SearchAliasViewDescription\n : ViewDescription\n > {\n return this._db.request({\n method: \"POST\",\n path: \"/_api/view\",\n body: {\n ...options,\n name: this._name,\n },\n });\n }\n\n /**\n * Renames the View and updates the instance's `name` to `newName`.\n *\n * Additionally removes the instance from the {@link database.Database}'s internal\n * cache.\n *\n * **Note**: Renaming Views may not be supported when ArangoDB is\n * running in a cluster configuration.\n *\n * @param newName - The new name of the View.\n *\n * @example\n * ```js\n * const db = new Database();\n * const view1 = db.view(\"some-view\");\n * await view1.rename(\"other-view\");\n * const view2 = db.view(\"some-view\");\n * const view3 = db.view(\"other-view\");\n * // Note all three View instances are different objects but\n * // view1 and view3 represent the same ArangoDB view!\n * ```\n */\n async rename(newName: string): Promise<ArangoApiResponse<ViewDescription>> {\n const result = this._db.renameView(this._name, newName);\n this._name = newName.normalize(\"NFC\");\n return result;\n }\n\n /**\n * Retrieves the View's properties.\n *\n * @example\n * ```js\n * const db = new Database();\n * const view = db.view(\"some-view\");\n * const data = await view.properties();\n * // data contains the View's properties\n * ```\n */\n properties(): Promise<ArangoApiResponse<ViewProperties>> {\n return this._db.request({\n path: `/_api/view/${encodeURIComponent(this._name)}/properties`,\n });\n }\n\n /**\n * Updates the properties of the View.\n *\n * @param properties - Properties of the View to update.\n *\n * @example\n * ```js\n * const db = new Database();\n * const view = db.view(\"some-view\");\n * const result = await view.updateProperties({\n * consolidationIntervalMsec: 234\n * });\n * console.log(result.consolidationIntervalMsec); // 234\n * ```\n */\n updateProperties<Properties extends ViewPatchPropertiesOptions | undefined>(\n properties?: Properties\n ): Promise<\n Properties extends ArangoSearchViewPatchPropertiesOptions\n ? ArangoSearchViewProperties\n : Properties extends SearchAliasViewPatchPropertiesOptions\n ? SearchAliasViewProperties\n : ViewProperties\n > {\n return this._db.request({\n method: \"PATCH\",\n path: `/_api/view/${encodeURIComponent(this._name)}/properties`,\n body: properties ?? {},\n });\n }\n\n /**\n * Replaces the properties of the View.\n *\n * @param properties - New properties of the View.\n *\n * @example\n * ```js\n * const db = new Database();\n * const view = db.view(\"some-view\");\n * const result = await view.replaceProperties({\n * consolidationIntervalMsec: 234\n * });\n * console.log(result.consolidationIntervalMsec); // 234\n * ```\n */\n replaceProperties<Properties extends ViewPropertiesOptions | undefined>(\n properties?: Properties\n ): Promise<\n Properties extends ArangoSearchViewPropertiesOptions\n ? ArangoSearchViewProperties\n : Properties extends SearchAliasViewPropertiesOptions\n ? SearchAliasViewProperties\n : ViewProperties\n > {\n return this._db.request({\n method: \"PUT\",\n path: `/_api/view/${encodeURIComponent(this._name)}/properties`,\n body: properties ?? {},\n });\n }\n\n /**\n * Deletes the View from the database.\n *\n * @example\n *\n * ```js\n * const db = new Database();\n * const view = db.view(\"some-view\");\n * await view.drop();\n * // the View \"some-view\" no longer exists\n * ```\n */\n drop(): Promise<boolean> {\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/view/${encodeURIComponent(this._name)}`,\n },\n (res) => res.body.result\n );\n }\n}\n","/* eslint-disable @typescript-eslint/no-var-requires */\n\"use strict\";\nconst { aql } = require(\"./aql\");\nconst { CollectionStatus, CollectionType } = require(\"./collection\");\nconst { ViewType } = require(\"./view\");\nconst { Database } = require(\"./database\");\n\nmodule.exports = exports = arangojs;\n\nfunction arangojs(config) {\n if (typeof config === \"string\" || Array.isArray(config)) {\n const url = config;\n return new Database(url);\n }\n return new Database(config);\n}\n\nObject.assign(arangojs, {\n aql,\n arangojs,\n CollectionStatus,\n CollectionType,\n Database,\n ViewType,\n});\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = function(module) {\n\tvar getter = module && module.__esModule ?\n\t\tfunction() { return module['default']; } :\n\t\tfunction() { return module; };\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = function(exports, definition) {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }","// define __esModule on exports\n__webpack_require__.r = function(exports) {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","// startup\n// Load entry module and return exports\n// This entry module is referenced by other modules so it can't be inlined\n__webpack_require__(588);\nvar __webpack_exports__ = __webpack_require__(293);\n"],"names":["root","factory","exports","module","define","amd","self","win","window","global","fn","string","toString","call","setTimeout","alert","confirm","prompt","Object","prototype","trim","replace","headers","arg","result","headersArr","split","i","length","row","index","indexOf","key","slice","toLowerCase","value","push","runtime","undefined","Op","hasOwn","hasOwnProperty","defineProperty","obj","desc","$Symbol","Symbol","iteratorSymbol","iterator","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","enumerable","configurable","writable","err","wrap","innerFn","outerFn","tryLocsList","protoGenerator","Generator","generator","create","context","Context","makeInvokeMethod","tryCatch","type","GenStateSuspendedStart","GenStateExecuting","GenStateCompleted","ContinueSentinel","GeneratorFunction","GeneratorFunctionPrototype","IteratorPrototype","this","getProto","getPrototypeOf","NativeIteratorPrototype","values","Gp","defineIteratorMethods","forEach","method","_invoke","AsyncIterator","PromiseImpl","invoke","resolve","reject","record","__await","then","unwrapped","error","previousPromise","callInvokeWithMethodAndArg","state","Error","doneResult","delegate","delegateResult","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","done","TypeError","info","resultName","next","nextLoc","pushTryEntry","locs","entry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","resetTryEntry","completion","reset","iterable","iteratorMethod","isNaN","displayName","isGeneratorFunction","genFun","ctor","constructor","name","mark","setPrototypeOf","__proto__","awrap","async","Promise","iter","keys","val","object","reverse","pop","skipTempReset","prev","charAt","stop","rootRecord","rval","exception","handle","loc","caught","hasCatch","hasFinally","finallyEntry","complete","finish","thrown","delegateYield","regeneratorRuntime","accidentalStrictMode","globalThis","Function","LinkedList","item","first","behind","last","before","clear","unchain","unlink","every","callback","thisArg","bind","filter","newList","find","findItem","includes","fromIndex","current","getItemByIndex","itemOf","searchedValue","lastItemOf","map","reduce","initialValue","reduceRight","some","join","separator","concat","others","other","LinkedListItem_1","unlinkCleanup","insertBehind","unshift","remove","removeAllOccurrences","foundSomethingToDelete","shift","entries","insertBefore","itemChainEnd","__export","require","isFunction","parseHeaders","xtend","initParams","uri","options","params","createXHR","_createXHR","called","response","body","getBody","xhr","responseText","responseType","responseXML","firefoxBugTakenEffect","documentElement","nodeName","e","getXml","isJson","JSON","parse","errorFunc","evt","clearTimeout","timeoutTimer","statusCode","failureResponse","loadFunc","aborted","status","useXDR","url","rawRequest","getAllResponseHeaders","cors","XDomainRequest","XMLHttpRequest","data","sync","json","stringify","onreadystatechange","readyState","onload","onerror","onprogress","onabort","ontimeout","open","username","password","withCredentials","timeout","abort","code","setRequestHeader","isEmpty","beforeSend","send","array","forEachArray","toUpperCase","target","arguments","source","isArangoAnalyzer","analyzer","Boolean","Analyzer","db","_db","_name","normalize","get","isArangoError","errorNum","ANALYZER_NOT_FOUND","request","path","encodeURIComponent","drop","force","qs","isAqlQuery","query","bindVars","isGeneratedAqlQuery","_source","isAqlLiteral","literal","toAQL","aql","templateStrings","args","strings","bindValues","rawValue","src","splice","isKnown","isArangoCollection","isArangoGraph","isArangoView","String","sep","Array","fill","_indexHandle","selector","collectionName","id","head","tail","normalizedHead","collection","collectionToString","CollectionType","CollectionStatus","Collection","COLLECTION_NOT_FOUND","waitForSyncReplication","enforceReplicationFactor","opts","computedValues","computedValue","expression","properties","count","res","figures","details","revision","checksum","newName","renameCollection","truncate","getResponsibleShard","document","shardId","documentId","_documentHandle","ifMatch","ifNoneMatch","encodeURI","HttpError","documents","selectors","allowDirtyRead","onlyget","graceful","DOCUMENT_NOT_FOUND","save","silent","saveAll","newData","replaceAll","update","updateAll","removeAll","import","isArray","line","isBinary","_edges","direction","vertex","edges","inEdges","outEdges","traversal","startVertex","edgeCollection","list","BatchedArrayCursor","arangojsHostUrl","items","all","any","byExample","example","firstExample","removeByExample","replaceByExample","newValue","updateByExample","lookupByKeys","removeByKeys","indexes","ensureIndex","dropIndex","fulltext","attribute","compact","hostUrl","batches","_batches","_id","_hasMore","hasMore","_hostUrl","_count","_extra","extra","_allowDirtyRead","_itemsCursor","ArrayCursor","more","_more","batch","hasNext","currentBatch","reducer","batchedCursor","view","_view","flatMap","v","kill","base64Encode","str","btoa","normalizeUrl","raw","match","unix","errorToJSON","message","createRequest","baseUrl","agentOptions","base","URL","auth","omit","cb","reqUrl","expectBinary","pathname","search","req","toJSON","after","MIME_JSON","Connection","config","Map","URLS","MAX_SOCKETS","loadBalancingStrategy","arangoVersion","_arangoVersion","_agent","agent","_agentOptions","maxSockets","_maxTasks","_headers","_loadBalancingStrategy","_precaptureStackTraces","precaptureStackTraces","_responseQueueTimeSamples","responseQueueTimeSamples","_retryOnConflict","retryOnConflict","Infinity","maxRetries","_maxRetries","Number","addToHostList","setBearerAuth","setBasicAuth","_activeHostUrl","_hostUrls","Math","floor","random","_activeDirtyHostUrl","isArangoConnection","queueTime","getLatest","_queueTimes","getValues","from","getAvg","avg","_runQueue","_queue","_activeTasks","task","LEADER_ENDPOINT_HEADER","cleanUrl","contentType","Date","now","parsedBody","stack","isArangoErrorResponse","ArangoError","transform","_hosts","ERROR_ARANGO_CONFLICT","isSystemError","syscall","ERROR_ARANGO_MAINTENANCE_MODE","retries","_buildUrl","basePath","querystringify","setHeader","token","setResponseQueueTimeSamples","database","databaseName","_databases","set","delete","setHostList","urls","cleanUrls","newUrls","setTransactionId","transactionId","_transactionId","clearTransactionId","headerName","close","host","numHosts","propagated","started","urlInfo","extraHeaders","captureStackTrace","capture","generateStackTrace","toForm","fields","form","FormData","Blob","append","Route","_path","route","patch","post","put","Transaction","isArangoTransaction","TRANSACTION_NOT_FOUND","commit","step","conn","_connection","promise","isArangoDatabase","coerceTransactionCollections","collections","write","cols","allowImplicit","read","exclusive","Database","configOrDatabase","connection","version","absolutePath","overwrite","endpoints","endpoint","waitForPropagation","useBasicAuth","useBearerAuth","login","jwt","DATABASE_NOT_FOUND","createDatabase","usersOrOptions","users","listDatabases","listUserDatabases","databases","userDatabases","dropDatabase","_collections","has","createCollection","listCollections","excludeSystem","graph","graphName","_graphs","Graph","edgeDefinitions","listGraphs","graphs","_key","viewName","_views","View","listViews","analyzerName","_analyzers","listAnalyzers","listUsers","getUser","createUser","passwd","user","updateUser","replaceUser","removeUser","getUserAccessLevel","suffix","setUserAccessLevel","grant","clearUserAccessLevel","getUserDatabases","full","executeTransaction","action","transaction","beginTransaction","listTransactions","transactions","batchSize","cache","memoryLimit","ttl","explain","queryRules","queryTracking","listRunningQueries","listSlowQueries","clearSlowQueries","killQuery","queryId","listFunctions","createFunction","isDeterministic","dropFunction","group","listServices","mount","configuration","dependencies","uninstallService","getService","getServiceConfiguration","minimal","replaceServiceConfiguration","cfg","updateServiceConfiguration","getServiceDependencies","replaceServiceDependencies","deps","updateServiceDependencies","setServiceDevelopmentMode","enabled","listServiceScripts","runServiceScript","runServiceTests","getServiceReadme","getServiceDocumentation","downloadService","commitLocalServiceState","strict","messages","nativeErrorKeys","super","errorMessage","mungeGharialResponse","prop","new","newDoc","old","oldDoc","doc","meta","coerceEdgeDefinition","edgeDefinition","to","GraphVertexCollection","_collection","_graph","rev","GraphEdgeCollection","edge","GRAPH_NOT_FOUND","orphanCollections","satellites","waitForSync","isSmart","isDisjoint","dropCollections","removed","vertexCollection","listVertexCollections","addVertexCollection","removeVertexCollection","dropCollection","listEdgeCollections","addEdgeDefinition","replaceEdgeDefinition","collectionOrEdgeDefinitionOptions","edgeDefinitionOrOptions","removeEdgeDefinition","VIEW_NOT_FOUND","renameView","updateProperties","replaceProperties","ViewType","arangojs","assign","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","n","getter","__esModule","d","a","definition","o","g","r"],"sourceRoot":""}
1
+ {"version":3,"file":"web.js","mappings":"CAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAkB,SAAID,IAEtBD,EAAe,SAAIC,GACpB,CATD,CASGK,MAAM,WACT,O,sCCVA,IAAIC,EAGAA,EADkB,oBAAXC,OACDA,YACmB,IAAXC,EAAAA,EACRA,EAAAA,EACiB,oBAATH,KACRA,KAEA,CAAC,EAGXH,EAAOD,QAAUK,C,kBCZjBJ,EAAOD,QAIP,SAAqBQ,GACnB,IAAKA,EACH,OAAO,EAET,IAAIC,EAASC,EAASC,KAAKH,GAC3B,MAAkB,sBAAXC,GACU,mBAAPD,GAAgC,oBAAXC,GACV,oBAAXH,SAENE,IAAOF,OAAOM,YACdJ,IAAOF,OAAOO,OACdL,IAAOF,OAAOQ,SACdN,IAAOF,OAAOS,OACpB,EAfA,IAAIL,EAAWM,OAAOC,UAAUP,Q,iBCFhC,IAAIQ,EAAO,SAAST,GAClB,OAAOA,EAAOU,QAAQ,aAAc,GACtC,EAKAlB,EAAOD,QAAU,SAAUoB,GAC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,OAAOM,aAC1ClC,OAAOwB,eAAexC,EAAS4C,OAAOM,YAAa,CAAEjB,MAAO,WAE7DjB,OAAOwB,eAAexC,EAAS,aAAc,CAAEiC,OAAO,GACvD,ECHA4rB,EAAoB,KACMA,EAAoB,I","sources":["webpack://arangojs/webpack/universalModuleDefinition","webpack://arangojs/./node_modules/global/window.js","webpack://arangojs/./node_modules/is-function/index.js","webpack://arangojs/./node_modules/parse-headers/parse-headers.js","webpack://arangojs/./node_modules/regenerator-runtime/runtime.js","webpack://arangojs/../src/LinkedList.ts","webpack://arangojs/../src/LinkedListItem.ts","webpack://arangojs/../src/index.ts","webpack://arangojs/./node_modules/xhr/index.js","webpack://arangojs/./node_modules/xtend/immutable.js","webpack://arangojs/./src/analyzer.ts","webpack://arangojs/./src/aql.ts","webpack://arangojs/./src/indexes.ts","webpack://arangojs/./src/collection.ts","webpack://arangojs/./src/cursor.ts","webpack://arangojs/./src/lib/btoa.web.ts","webpack://arangojs/./src/lib/normalizeUrl.ts","webpack://arangojs/./src/lib/xhr.ts","webpack://arangojs/./src/lib/request.web.ts","webpack://arangojs/./src/lib/omit.ts","webpack://arangojs/./src/connection.ts","webpack://arangojs/./src/lib/querystringify.web.ts","webpack://arangojs/./src/lib/multipart.web.ts","webpack://arangojs/./src/route.ts","webpack://arangojs/./src/transaction.ts","webpack://arangojs/./src/database.ts","webpack://arangojs/./src/documents.ts","webpack://arangojs/./src/error.ts","webpack://arangojs/./src/graph.ts","webpack://arangojs/./src/lib/codes.ts","webpack://arangojs/./src/view.ts","webpack://arangojs/./src/web.js","webpack://arangojs/webpack/bootstrap","webpack://arangojs/webpack/runtime/compat get default export","webpack://arangojs/webpack/runtime/define property getters","webpack://arangojs/webpack/runtime/global","webpack://arangojs/webpack/runtime/hasOwnProperty shorthand","webpack://arangojs/webpack/runtime/make namespace object","webpack://arangojs/webpack/startup"],"sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"arangojs\"] = factory();\n\telse\n\t\troot[\"arangojs\"] = factory();\n})(self, function() {\nreturn ","var win;\n\nif (typeof window !== \"undefined\") {\n win = window;\n} else if (typeof global !== \"undefined\") {\n win = global;\n} else if (typeof self !== \"undefined\"){\n win = self;\n} else {\n win = {};\n}\n\nmodule.exports = win;\n","module.exports = isFunction\n\nvar toString = Object.prototype.toString\n\nfunction isFunction (fn) {\n if (!fn) {\n return false\n }\n var string = toString.call(fn)\n return string === '[object Function]' ||\n (typeof fn === 'function' && string !== '[object RegExp]') ||\n (typeof window !== 'undefined' &&\n // IE8 and below\n (fn === window.setTimeout ||\n fn === window.alert ||\n fn === window.confirm ||\n fn === window.prompt))\n};\n","var trim = function(string) {\n return string.replace(/^\\s+|\\s+$/g, '');\n}\n , isArray = function(arg) {\n return Object.prototype.toString.call(arg) === '[object Array]';\n }\n\nmodule.exports = function (headers) {\n if (!headers)\n return {}\n\n var result = {}\n\n var headersArr = trim(headers).split('\\n')\n\n for (var i = 0; i < headersArr.length; i++) {\n var row = headersArr[i]\n var index = row.indexOf(':')\n , key = trim(row.slice(0, index)).toLowerCase()\n , value = trim(row.slice(index + 1))\n\n if (typeof(result[key]) === 'undefined') {\n result[key] = value\n } else if (isArray(result[key])) {\n result[key].push(value)\n } else {\n result[key] = [ result[key], value ]\n }\n }\n\n return result\n}\n","/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar runtime = (function (exports) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; };\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n function define(obj, key, value) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n return obj[key];\n }\n try {\n // IE 8 has a broken Object.defineProperty that only works on DOM objects.\n define({}, \"\");\n } catch (err) {\n define = function(obj, key, value) {\n return obj[key] = value;\n };\n }\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n defineProperty(generator, \"_invoke\", { value: makeInvokeMethod(innerFn, self, context) });\n\n return generator;\n }\n exports.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n define(IteratorPrototype, iteratorSymbol, function () {\n return this;\n });\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = GeneratorFunctionPrototype;\n defineProperty(Gp, \"constructor\", { value: GeneratorFunctionPrototype, configurable: true });\n defineProperty(\n GeneratorFunctionPrototype,\n \"constructor\",\n { value: GeneratorFunction, configurable: true }\n );\n GeneratorFunction.displayName = define(\n GeneratorFunctionPrototype,\n toStringTagSymbol,\n \"GeneratorFunction\"\n );\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n define(prototype, method, function(arg) {\n return this._invoke(method, arg);\n });\n });\n }\n\n exports.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n exports.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n define(genFun, toStringTagSymbol, \"GeneratorFunction\");\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n // meant to be awaited.\n exports.awrap = function(arg) {\n return { __await: arg };\n };\n\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return PromiseImpl.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return PromiseImpl.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration.\n result.value = unwrapped;\n resolve(result);\n }, function(error) {\n // If a rejected Promise was yielded, throw the rejection back\n // into the async generator function so it can be handled there.\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n defineProperty(this, \"_invoke\", { value: enqueue });\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n define(AsyncIterator.prototype, asyncIteratorSymbol, function () {\n return this;\n });\n exports.AsyncIterator = AsyncIterator;\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n if (PromiseImpl === void 0) PromiseImpl = Promise;\n\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList),\n PromiseImpl\n );\n\n return exports.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n }\n\n // Call delegate.iterator[context.method](context.arg) and handle the\n // result, either by returning a { value, done } result from the\n // delegate iterator, or by modifying context.method and context.arg,\n // setting context.delegate to null, and returning the ContinueSentinel.\n function maybeInvokeDelegate(delegate, context) {\n var method = delegate.iterator[context.method];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method always terminates the yield* loop.\n context.delegate = null;\n\n if (context.method === \"throw\") {\n // Note: [\"return\"] must be used for ES3 parsing compatibility.\n if (delegate.iterator[\"return\"]) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a 'throw' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n define(Gp, toStringTagSymbol, \"Generator\");\n\n // A Generator should always return itself as the iterator object when the\n // @@iterator function is called on it. Some browsers' implementations of the\n // iterator prototype chain incorrectly implement this, causing the Generator\n // object to not be returned from this call. This ensures that doesn't happen.\n // See https://github.com/facebook/regenerator/issues/274 for more details.\n define(Gp, iteratorSymbol, function() {\n return this;\n });\n\n define(Gp, \"toString\", function() {\n return \"[object Generator]\";\n });\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n exports.keys = function(val) {\n var object = Object(val);\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n exports.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n };\n\n // Regardless of whether this script is executing as a CommonJS module\n // or not, return the runtime object so that we can declare the variable\n // regeneratorRuntime in the outer scope, which allows this module to be\n // injected easily by `bin/regenerator --include-runtime script.js`.\n return exports;\n\n}(\n // If this script is executing as a CommonJS module, use module.exports\n // as the regeneratorRuntime namespace. Otherwise create a new empty\n // object. Either way, the resulting object will be used to initialize\n // the regeneratorRuntime variable at the top of this file.\n typeof module === \"object\" ? module.exports : {}\n));\n\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n // This module should not be running in strict mode, so the above\n // assignment should always work unless something is misconfigured. Just\n // in case runtime.js accidentally runs in strict mode, in modern engines\n // we can explicitly access globalThis. In older engines we can escape\n // strict mode using a global Function call. This could conceivably fail\n // if a Content Security Policy forbids using Function, but in that case\n // the proper solution is to fix the accidental strict mode problem. If\n // you've misconfigured your bundler to force strict mode and applied a\n // CSP to forbid Function, and you're not willing to fix either of those\n // problems, please detail your unique predicament in a GitHub issue.\n if (typeof globalThis === \"object\") {\n globalThis.regeneratorRuntime = runtime;\n } else {\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n }\n}\n",null,null,null,"\"use strict\";\nvar window = require(\"global/window\")\nvar isFunction = require(\"is-function\")\nvar parseHeaders = require(\"parse-headers\")\nvar xtend = require(\"xtend\")\n\nmodule.exports = createXHR\n// Allow use of default import syntax in TypeScript\nmodule.exports.default = createXHR;\ncreateXHR.XMLHttpRequest = window.XMLHttpRequest || noop\ncreateXHR.XDomainRequest = \"withCredentials\" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest\n\nforEachArray([\"get\", \"put\", \"post\", \"patch\", \"head\", \"delete\"], function(method) {\n createXHR[method === \"delete\" ? \"del\" : method] = function(uri, options, callback) {\n options = initParams(uri, options, callback)\n options.method = method.toUpperCase()\n return _createXHR(options)\n }\n})\n\nfunction forEachArray(array, iterator) {\n for (var i = 0; i < array.length; i++) {\n iterator(array[i])\n }\n}\n\nfunction isEmpty(obj){\n for(var i in obj){\n if(obj.hasOwnProperty(i)) return false\n }\n return true\n}\n\nfunction initParams(uri, options, callback) {\n var params = uri\n\n if (isFunction(options)) {\n callback = options\n if (typeof uri === \"string\") {\n params = {uri:uri}\n }\n } else {\n params = xtend(options, {uri: uri})\n }\n\n params.callback = callback\n return params\n}\n\nfunction createXHR(uri, options, callback) {\n options = initParams(uri, options, callback)\n return _createXHR(options)\n}\n\nfunction _createXHR(options) {\n if(typeof options.callback === \"undefined\"){\n throw new Error(\"callback argument missing\")\n }\n\n var called = false\n var callback = function cbOnce(err, response, body){\n if(!called){\n called = true\n options.callback(err, response, body)\n }\n }\n\n function readystatechange() {\n if (xhr.readyState === 4) {\n setTimeout(loadFunc, 0)\n }\n }\n\n function getBody() {\n // Chrome with requestType=blob throws errors arround when even testing access to responseText\n var body = undefined\n\n if (xhr.response) {\n body = xhr.response\n } else {\n body = xhr.responseText || getXml(xhr)\n }\n\n if (isJson) {\n try {\n body = JSON.parse(body)\n } catch (e) {}\n }\n\n return body\n }\n\n function errorFunc(evt) {\n clearTimeout(timeoutTimer)\n if(!(evt instanceof Error)){\n evt = new Error(\"\" + (evt || \"Unknown XMLHttpRequest Error\") )\n }\n evt.statusCode = 0\n return callback(evt, failureResponse)\n }\n\n // will load the data & process the response in a special response object\n function loadFunc() {\n if (aborted) return\n var status\n clearTimeout(timeoutTimer)\n if(options.useXDR && xhr.status===undefined) {\n //IE8 CORS GET successful response doesn't have a status field, but body is fine\n status = 200\n } else {\n status = (xhr.status === 1223 ? 204 : xhr.status)\n }\n var response = failureResponse\n var err = null\n\n if (status !== 0){\n response = {\n body: getBody(),\n statusCode: status,\n method: method,\n headers: {},\n url: uri,\n rawRequest: xhr\n }\n if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE\n response.headers = parseHeaders(xhr.getAllResponseHeaders())\n }\n } else {\n err = new Error(\"Internal XMLHttpRequest Error\")\n }\n return callback(err, response, response.body)\n }\n\n var xhr = options.xhr || null\n\n if (!xhr) {\n if (options.cors || options.useXDR) {\n xhr = new createXHR.XDomainRequest()\n }else{\n xhr = new createXHR.XMLHttpRequest()\n }\n }\n\n var key\n var aborted\n var uri = xhr.url = options.uri || options.url\n var method = xhr.method = options.method || \"GET\"\n var body = options.body || options.data\n var headers = xhr.headers = options.headers || {}\n var sync = !!options.sync\n var isJson = false\n var timeoutTimer\n var failureResponse = {\n body: undefined,\n headers: {},\n statusCode: 0,\n method: method,\n url: uri,\n rawRequest: xhr\n }\n\n if (\"json\" in options && options.json !== false) {\n isJson = true\n headers[\"accept\"] || headers[\"Accept\"] || (headers[\"Accept\"] = \"application/json\") //Don't override existing accept header declared by user\n if (method !== \"GET\" && method !== \"HEAD\") {\n headers[\"content-type\"] || headers[\"Content-Type\"] || (headers[\"Content-Type\"] = \"application/json\") //Don't override existing accept header declared by user\n body = JSON.stringify(options.json === true ? body : options.json)\n }\n }\n\n xhr.onreadystatechange = readystatechange\n xhr.onload = loadFunc\n xhr.onerror = errorFunc\n // IE9 must have onprogress be set to a unique function.\n xhr.onprogress = function () {\n // IE must die\n }\n xhr.onabort = function(){\n aborted = true;\n }\n xhr.ontimeout = errorFunc\n xhr.open(method, uri, !sync, options.username, options.password)\n //has to be after open\n if(!sync) {\n xhr.withCredentials = !!options.withCredentials\n }\n // Cannot set timeout with sync request\n // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly\n // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent\n if (!sync && options.timeout > 0 ) {\n timeoutTimer = setTimeout(function(){\n if (aborted) return\n aborted = true//IE9 may still call readystatechange\n xhr.abort(\"timeout\")\n var e = new Error(\"XMLHttpRequest timeout\")\n e.code = \"ETIMEDOUT\"\n errorFunc(e)\n }, options.timeout )\n }\n\n if (xhr.setRequestHeader) {\n for(key in headers){\n if(headers.hasOwnProperty(key)){\n xhr.setRequestHeader(key, headers[key])\n }\n }\n } else if (options.headers && !isEmpty(options.headers)) {\n throw new Error(\"Headers cannot be set on an XDomainRequest object\")\n }\n\n if (\"responseType\" in options) {\n xhr.responseType = options.responseType\n }\n\n if (\"beforeSend\" in options &&\n typeof options.beforeSend === \"function\"\n ) {\n options.beforeSend(xhr)\n }\n\n // Microsoft Edge browser sends \"undefined\" when send is called with undefined value.\n // XMLHttpRequest spec says to pass null as body to indicate no body\n // See https://github.com/naugtur/xhr/issues/100.\n xhr.send(body || null)\n\n return xhr\n\n\n}\n\nfunction getXml(xhr) {\n // xhr.responseXML will throw Exception \"InvalidStateError\" or \"DOMException\"\n // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML.\n try {\n if (xhr.responseType === \"document\") {\n return xhr.responseXML\n }\n var firefoxBugTakenEffect = xhr.responseXML && xhr.responseXML.documentElement.nodeName === \"parsererror\"\n if (xhr.responseType === \"\" && !firefoxBugTakenEffect) {\n return xhr.responseXML\n }\n } catch (e) {}\n\n return null\n}\n\nfunction noop() {}\n","module.exports = extend\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nfunction extend() {\n var target = {}\n\n for (var i = 0; i < arguments.length; i++) {\n var source = arguments[i]\n\n for (var key in source) {\n if (hasOwnProperty.call(source, key)) {\n target[key] = source[key]\n }\n }\n }\n\n return target\n}\n","/**\n * ```ts\n * import type { Analyzer } from \"arangojs/analyzer\";\n * ```\n *\n * The \"analyzer\" module provides analyzer related types and interfaces\n * for TypeScript.\n *\n * @packageDocumentation\n */\nimport { ArangoApiResponse } from \"./connection\";\nimport { Database } from \"./database\";\nimport { isArangoError } from \"./error\";\nimport { ANALYZER_NOT_FOUND } from \"./lib/codes\";\n\n/**\n * Indicates whether the given value represents an {@link Analyzer}.\n *\n * @param analyzer - A value that might be an Analyzer.\n */\nexport function isArangoAnalyzer(analyzer: any): analyzer is Analyzer {\n return Boolean(analyzer && analyzer.isArangoAnalyzer);\n}\n\n/**\n * Name of a feature enabled for an Analyzer.\n */\nexport type AnalyzerFeature = \"frequency\" | \"norm\" | \"position\" | \"offset\";\n\n/**\n * Analyzer type and its type-specific properties.\n */\nexport type CreateAnalyzerOptions =\n | CreateIdentityAnalyzerOptions\n | CreateDelimiterAnalyzerOptions\n | CreateStemAnalyzerOptions\n | CreateNormAnalyzerOptions\n | CreateNgramAnalyzerOptions\n | CreateTextAnalyzerOptions\n | CreateSegmentationAnalyzerOptions\n | CreateAqlAnalyzerOptions\n | CreatePipelineAnalyzerOptions\n | CreateStopwordsAnalyzerOptions\n | CreateCollationAnalyzerOptions\n | CreateMinHashAnalyzerOptions\n | CreateClassificationAnalyzerOptions\n | CreateNearestNeighborsAnalyzerOptions\n | CreateGeoJsonAnalyzerOptions\n | CreateGeoPointAnalyzerOptions;\n\n/**\n * Options for creating an Identity Analyzer.\n */\nexport type CreateIdentityAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"identity\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n *\n * The `identity` Analyzer does not take additional properties.\n */\n properties?: Record<string, never>;\n};\n\n/**\n * Options for creating a Delimiter Analyzer.\n */\nexport type CreateDelimiterAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"delimiter\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n *\n * The value will be used as delimiter to split text into tokens as specified\n * in RFC 4180, without starting new records on newlines.\n */\n properties: string | { delimiter: string };\n};\n\n/**\n * Options for creating a Stem Analyzer.\n */\nexport type CreateStemAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"stem\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n *\n * The value defines the text locale.\n *\n * Format: `language[_COUNTRY][.encoding][@variant]`\n */\n properties: { locale: string };\n};\n\n/**\n * Options for creating a Norm Analyzer.\n */\nexport type CreateNormAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"norm\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * Text locale.\n *\n * Format: `language[_COUNTRY][.encoding][@variant]`\n */\n locale: string;\n /**\n * Case conversion.\n *\n * Default: `\"lower\"`\n */\n case?: \"lower\" | \"none\" | \"upper\";\n /**\n * Preserve accents in returned words.\n *\n * Default: `false`\n */\n accent?: boolean;\n };\n};\n\n/**\n * Options for creating an Ngram Analyzer.\n */\nexport type CreateNgramAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"ngram\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * Maximum n-gram length.\n */\n max: number;\n /**\n * Minimum n-gram length.\n */\n min: number;\n /**\n * Output the original value as well.\n */\n preserveOriginal: boolean;\n };\n};\n\n/**\n * Options for creating a Text Analyzer.\n */\nexport type CreateTextAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"text\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * Text locale.\n *\n * Format: `language[_COUNTRY][.encoding][@variant]`\n */\n locale: string;\n /**\n * Case conversion.\n *\n * Default: `\"lower\"`\n */\n case?: \"lower\" | \"none\" | \"upper\";\n /**\n * Words to omit from result.\n *\n * Defaults to the words loaded from the file at `stopwordsPath`.\n */\n stopwords?: string[];\n /**\n * Path with a `language` sub-directory containing files with words to omit.\n *\n * Defaults to the path specified in the server-side environment variable\n * `IRESEARCH_TEXT_STOPWORD_PATH` or the current working directory of the\n * ArangoDB process.\n */\n stopwordsPath?: string;\n /**\n * Preserve accents in returned words.\n *\n * Default: `false`\n */\n accent?: boolean;\n /**\n * Apply stemming on returned words.\n *\n * Default: `true`\n */\n stemming?: boolean;\n /**\n * If present, then edge n-grams are generated for each token (word).\n */\n edgeNgram?: { min?: number; max?: number; preserveOriginal?: boolean };\n };\n};\n\n/**\n * Options for creating a Segmentation Analyzer\n */\nexport type CreateSegmentationAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"segmentation\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * Which tokens should be returned.\n *\n * Default: `\"alpha\"`\n */\n break?: \"all\" | \"alpha\" | \"graphic\";\n /**\n * What case all returned tokens should be converted to if applicable.\n *\n * Default: `\"none\"`\n */\n case?: \"lower\" | \"upper\" | \"none\";\n };\n};\n\n/**\n * Options for creating an AQL Analyzer\n */\nexport type CreateAqlAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"aql\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * AQL query to be executed.\n */\n queryString: string;\n /**\n * If set to `true`, the position is set to `0` for all members of the query result array.\n *\n * Default: `false`\n */\n collapsePositions?: boolean;\n /**\n * If set to `false`, `null` values will be discarded from the View index.\n *\n * Default: `true`\n */\n keepNull?: boolean;\n /**\n * Number between `1` and `1000` that determines the batch size for reading\n * data from the query.\n *\n * Default: `1`\n */\n batchSize?: number;\n /**\n * Memory limit for query execution in bytes.\n *\n * Default: `1048576` (1 MiB)\n */\n memoryLimit?: number;\n /**\n * Data type of the returned tokens.\n *\n * Default: `\"string\"`\n */\n returnType?: \"string\" | \"number\" | \"bool\";\n };\n};\n\n/**\n * Options for creating a Pipeline Analyzer\n */\nexport type CreatePipelineAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"pipeline\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * Definitions for Analyzers to chain in this Pipeline Analyzer.\n */\n pipeline: Omit<CreateAnalyzerOptions, \"features\">[];\n };\n};\n\n/**\n * Options for creating a Stopwords Analyzer\n */\nexport type CreateStopwordsAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"stopwords\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * Array of strings that describe the tokens to be discarded.\n */\n stopwords: string[];\n /**\n * Whether stopword values should be interpreted as hex-encoded strings.\n *\n * Default: `false`\n */\n hex?: boolean;\n };\n};\n\n/**\n * Options for creating a Collation Analyzer\n */\nexport type CreateCollationAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"collation\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * Text locale.\n *\n * Format: `language[_COUNTRY][.encoding][@variant]`\n */\n locale: string;\n };\n};\n\n/**\n * Options for creating a MinHash Analyzer\n */\nexport type CreateMinHashAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"minhash\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * An Analyzer definition-like object with `type` and `properties` attributes.\n */\n analyzer: Omit<CreateAnalyzerOptions, \"features\">;\n /**\n * Size of the MinHash signature.\n */\n numHashes: number;\n };\n};\n\n/**\n * Options for creating a Classification Analyzer\n */\nexport type CreateClassificationAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"classification\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * On-disk path to the trained fastText supervised model.\n */\n model_location: string;\n /**\n * Number of class labels that will be produced per input.\n *\n * Default: `1`\n */\n top_k?: number;\n /**\n * Probability threshold for which a label will be assigned to an input.\n *\n * Default: `0.99`\n */\n threshold?: number;\n };\n};\n\n/**\n * Options for creating a NearestNeighbors Analyzer\n */\nexport type CreateNearestNeighborsAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"nearest_neighbors\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * On-disk path to the trained fastText supervised model.\n */\n model_location: string;\n /**\n * Number of class labels that will be produced per input.\n *\n * Default: `1`\n */\n top_k?: number;\n };\n};\n\n/**\n * Options for creating a GeoJSON Analyzer\n */\nexport type CreateGeoJsonAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"geojson\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * If set to `\"centroid\"`, only the centroid of the input geometry will be\n * computed and indexed.\n *\n * If set to `\"point\"` only GeoJSON objects of type Point will be indexed and\n * all other geometry types will be ignored.\n *\n * Default: `\"shape\"`\n */\n type?: \"shape\" | \"centroid\" | \"point\";\n /**\n * Options for fine-tuning geo queries.\n *\n * Default: `{ maxCells: 20, minLevel: 4, maxLevel: 23 }`\n */\n options?: { maxCells?: number; minLevel?: number; maxLevel?: number };\n };\n};\n\n/**\n * Options for creating a GeoPoint Analyzer\n */\nexport type CreateGeoPointAnalyzerOptions = {\n /**\n * Type of the Analyzer.\n */\n type: \"geopoint\";\n /**\n * Features to enable for this Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * Additional properties for the Analyzer.\n */\n properties: {\n /**\n * Attribute paths of the latitude value relative to the field for which the\n * Analyzer is defined in the View.\n */\n latitude?: string[];\n /**\n * Attribute paths of the longitude value relative to the field for which the\n * Analyzer is defined in the View.\n */\n longitude?: string[];\n /**\n * Options for fine-tuning geo queries.\n *\n * Default: `{ maxCells: 20, minLevel: 4, maxLevel: 23 }`\n */\n options?: { minCells?: number; minLevel?: number; maxLevel?: number };\n };\n};\n\n/**\n * Shared attributes of all Analyzer descriptions.\n */\nexport type GenericAnalyzerDescription = {\n /**\n * A unique name for this Analyzer.\n */\n name: string;\n /**\n * Features enabled for this Analyzer.\n */\n features: AnalyzerFeature[];\n};\n\n/**\n * An object describing an Analyzer.\n */\nexport type AnalyzerDescription =\n | IdentityAnalyzerDescription\n | DelimiterAnalyzerDescription\n | StemAnalyzerDescription\n | NormAnalyzerDescription\n | NgramAnalyzerDescription\n | TextAnalyzerDescription\n | SegmentationAnalyzerDescription\n | AqlAnalyzerDescription\n | PipelineAnalyzerDescription\n | StopwordsAnalyzerDescription\n | CollationAnalyzerDescription\n | MinHashAnalyzerDescription\n | ClassificationAnalyzerDescription\n | NearestNeighborsAnalyzerDescription\n | GeoJsonAnalyzerDescription\n | GeoPointAnalyzerDescription;\n\n/**\n * An object describing an Identity Analyzer.\n */\nexport type IdentityAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"identity\";\n properties: Record<string, never>;\n};\n\n/**\n * An object describing a Delimiter Analyzer.\n */\nexport type DelimiterAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"delimiter\";\n properties: { delimiter: string };\n};\n\n/**\n * An object describing a Stem Analyzer.\n */\nexport type StemAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"stem\";\n properties: { locale: string };\n};\n\n/**\n * An object describing a Norm Analyzer.\n */\nexport type NormAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"norm\";\n properties: {\n locale: string;\n case: \"lower\" | \"none\" | \"upper\";\n accent: boolean;\n };\n};\n\n/**\n * An object describing an Ngram Analyzer.\n */\nexport type NgramAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"ngram\";\n properties: {\n max: number;\n min: number;\n preserveOriginal: boolean;\n };\n};\n\n/**\n * An object describing a Text Analyzer.\n */\nexport type TextAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"text\";\n properties: {\n locale: string;\n case: \"lower\" | \"none\" | \"upper\";\n stopwords: string[];\n stopwordsPath: string;\n accent: boolean;\n stemming: boolean;\n edgeNgram: { min: number; max: number; preserveOriginal: boolean };\n };\n};\n\n/**\n * An object describing a Segmentation Analyzer\n */\nexport type SegmentationAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"segmentation\";\n properties: {\n break: \"all\" | \"alpha\" | \"graphic\";\n case: \"lower\" | \"upper\" | \"none\";\n };\n};\n\n/**\n * An object describing an AQL Analyzer\n */\nexport type AqlAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"aql\";\n properties: {\n queryString: string;\n collapsePositions: boolean;\n keepNull: boolean;\n batchSize: number;\n memoryLimit: number;\n returnType: \"string\" | \"number\" | \"bool\";\n };\n};\n\n/**\n * An object describing a Pipeline Analyzer\n */\nexport type PipelineAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"pipeline\";\n properties: {\n pipeline: Omit<AnalyzerDescription, \"name\" | \"features\">[];\n };\n};\n\n/**\n * An object describing a Stopwords Analyzer\n */\nexport type StopwordsAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"stopwords\";\n properties: {\n stopwords: string[];\n hex: boolean;\n };\n};\n\n/**\n * An object describing a Collation Analyzer\n */\nexport type CollationAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"collation\";\n properties: {\n locale: string;\n };\n};\n\n/**\n * (Enterprise Edition only.) An object describing a MinHash Analyzer\n */\nexport type MinHashAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"minhash\";\n properties: {\n analyzer: Omit<AnalyzerDescription, \"name\" | \"features\">;\n numHashes: number;\n };\n};\n\n/**\n * (Enterprise Edition only.) An object describing a Classification Analyzer\n */\nexport type ClassificationAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"classification\";\n properties: {\n model_location: string;\n top_k: number;\n threshold: number;\n };\n};\n\n/**\n * (Enterprise Edition only.) An object describing a NearestNeighbors Analyzer\n */\nexport type NearestNeighborsAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"nearest_neighbors\";\n properties: {\n model_location: string;\n top_k: number;\n };\n};\n\n/**\n * An object describing a GeoJSON Analyzer\n */\nexport type GeoJsonAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"geojson\";\n properties: {\n type: \"shape\" | \"centroid\" | \"point\";\n description: { maxCells: number; minLevel: number; maxLevel: number };\n };\n};\n\n/**\n * An object describing a GeoPoint Analyzer\n */\nexport type GeoPointAnalyzerDescription = GenericAnalyzerDescription & {\n type: \"geopoint\";\n properties: {\n latitude: string[];\n longitude: string[];\n description: { minCells: number; minLevel: number; maxLevel: number };\n };\n};\n\n/**\n * Represents an Analyzer in a {@link database.Database}.\n */\nexport class Analyzer {\n protected _name: string;\n protected _db: Database;\n\n /**\n * @internal\n */\n constructor(db: Database, name: string) {\n this._db = db;\n this._name = name.normalize(\"NFC\");\n }\n\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB Analyzer.\n */\n get isArangoAnalyzer(): true {\n return true;\n }\n\n /**\n * Name of this Analyzer.\n *\n * See also {@link database.Database}.\n */\n get name() {\n return this._name;\n }\n\n /**\n * Checks whether the Analyzer exists.\n *\n * @example\n * ```js\n * const db = new Database();\n * const analyzer = db.analyzer(\"some-analyzer\");\n * const result = await analyzer.exists();\n * // result indicates whether the Analyzer exists\n * ```\n */\n async exists(): Promise<boolean> {\n try {\n await this.get();\n return true;\n } catch (err: any) {\n if (isArangoError(err) && err.errorNum === ANALYZER_NOT_FOUND) {\n return false;\n }\n throw err;\n }\n }\n\n /**\n * Retrieves the Analyzer definition for the Analyzer.\n *\n * @example\n * ```js\n * const db = new Database();\n * const analyzer = db.analyzer(\"some-analyzer\");\n * const definition = await analyzer.get();\n * // definition contains the Analyzer definition\n * ```\n */\n get(): Promise<ArangoApiResponse<AnalyzerDescription>> {\n return this._db.request({\n path: `/_api/analyzer/${encodeURIComponent(this._name)}`,\n });\n }\n\n /**\n * Creates a new Analyzer with the given `options` and the instance's name.\n *\n * See also {@link database.Database#createAnalyzer}.\n *\n * @param options - Options for creating the Analyzer.\n *\n * @example\n * ```js\n * const db = new Database();\n * const analyzer = db.analyzer(\"potatoes\");\n * await analyzer.create({ type: \"identity\" });\n * // the identity Analyzer \"potatoes\" now exists\n * ```\n */\n create<Options extends CreateAnalyzerOptions>(\n options: Options\n ): Promise<\n Options extends CreateIdentityAnalyzerOptions\n ? IdentityAnalyzerDescription\n : Options extends CreateDelimiterAnalyzerOptions\n ? DelimiterAnalyzerDescription\n : Options extends CreateStemAnalyzerOptions\n ? StemAnalyzerDescription\n : Options extends CreateNormAnalyzerOptions\n ? NormAnalyzerDescription\n : Options extends CreateNgramAnalyzerOptions\n ? NgramAnalyzerDescription\n : Options extends CreateTextAnalyzerOptions\n ? TextAnalyzerDescription\n : Options extends CreateSegmentationAnalyzerOptions\n ? SegmentationAnalyzerDescription\n : Options extends CreateAqlAnalyzerOptions\n ? AqlAnalyzerDescription\n : Options extends CreatePipelineAnalyzerOptions\n ? PipelineAnalyzerDescription\n : Options extends CreateStopwordsAnalyzerOptions\n ? StopwordsAnalyzerDescription\n : Options extends CreateCollationAnalyzerOptions\n ? CollationAnalyzerDescription\n : Options extends CreateMinHashAnalyzerOptions\n ? MinHashAnalyzerDescription\n : Options extends CreateClassificationAnalyzerOptions\n ? ClassificationAnalyzerDescription\n : Options extends CreateNearestNeighborsAnalyzerOptions\n ? NearestNeighborsAnalyzerDescription\n : Options extends CreateGeoJsonAnalyzerOptions\n ? GeoJsonAnalyzerDescription\n : Options extends CreateGeoPointAnalyzerOptions\n ? GeoPointAnalyzerDescription\n : AnalyzerDescription\n > {\n return this._db.request({\n method: \"POST\",\n path: \"/_api/analyzer\",\n body: { name: this._name, ...options },\n });\n }\n\n /**\n * Deletes the Analyzer from the database.\n *\n * @param force - Whether the Analyzer should still be deleted even if it\n * is currently in use.\n *\n * @example\n * ```js\n * const db = new Database();\n * const analyzer = db.analyzer(\"some-analyzer\");\n * await analyzer.drop();\n * // the Analyzer \"some-analyzer\" no longer exists\n * ```\n */\n drop(force: boolean = false): Promise<ArangoApiResponse<{ name: string }>> {\n return this._db.request({\n method: \"DELETE\",\n path: `/_api/analyzer/${encodeURIComponent(this._name)}`,\n qs: { force },\n });\n }\n}\n","/**\n * ```js\n * import { aql } from \"arangojs/aql\";\n * ```\n *\n * The \"aql\" module provides the {@link aql} template string handler and\n * helper functions, as well as associated types and interfaces for TypeScript.\n *\n * The aql function and namespace is also re-exported by the \"index\" module.\n *\n * @packageDocumentation\n */\nimport { isArangoAnalyzer } from \"./analyzer\";\nimport { ArangoCollection, isArangoCollection } from \"./collection\";\nimport { Graph, isArangoGraph } from \"./graph\";\nimport { isArangoView, View } from \"./view\";\n\n/**\n * Generic AQL query object consisting of an AQL query string and its bind\n * parameters.\n */\nexport interface AqlQuery {\n /**\n * An AQL query string.\n */\n query: string;\n /**\n * An object mapping AQL bind parameter names to their respective values.\n *\n * Names of parameters representing collections are prefixed with an\n * at-symbol.\n */\n bindVars: Record<string, any>;\n}\n\n/**\n * Derived type representing AQL query objects generated by the AQL helper\n * functions and the AQL template string handler. These objects can be fed\n * back into these helper functions to be inlined or merged in complex queries.\n *\n * @internal\n */\nexport interface GeneratedAqlQuery extends AqlQuery {\n /**\n * @internal\n */\n _source: () => { strings: string[]; args: AqlValue[] };\n}\n\n/**\n * An object representing a trusted AQL literal that will be inlined directly\n * when used in an AQL template or passed to AQL helper functions.\n *\n * Arbitrary values can be converted to trusted AQL literals by passing them\n * to the {@link literal} helper function.\n */\nexport interface AqlLiteral {\n /**\n * @internal\n *\n * Returns a string representation of this AQL literal that can be inlined\n * in an AQL template.\n */\n toAQL: () => string;\n}\n\n/**\n * A value that can be used in an AQL template string or passed to an AQL\n * helper function.\n */\nexport type AqlValue =\n | ArangoCollection\n | View\n | Graph\n | GeneratedAqlQuery\n | AqlLiteral\n | string\n | number\n | boolean\n | null\n | undefined\n | Record<string, any>\n | any[];\n\n/**\n * Indicates whether the given value is an {@link AqlQuery}.\n *\n * @param query - A value that might be an `AqlQuery`.\n */\nexport function isAqlQuery(query: any): query is AqlQuery {\n return Boolean(query && typeof query.query === \"string\" && query.bindVars);\n}\n\n/**\n * Indicates whether the given value is a {@link GeneratedAqlQuery}.\n *\n * @param query - A value that might be a `GeneratedAqlQuery`.\n *\n * @internal\n */\nexport function isGeneratedAqlQuery(query: any): query is GeneratedAqlQuery {\n return isAqlQuery(query) && typeof (query as any)._source === \"function\";\n}\n\n/**\n * Indicates whether the given value is an {@link AqlLiteral}.\n *\n * @param literal - A value that might be an `AqlLiteral`.\n */\nexport function isAqlLiteral(literal: any): literal is AqlLiteral {\n return Boolean(literal && typeof literal.toAQL === \"function\");\n}\n\n/**\n * Template string handler (template tag) for AQL queries.\n *\n * The `aql` tag can be used to write complex AQL queries as multi-line strings\n * without having to worry about `bindVars` and the distinction between\n * collections and regular parameters.\n *\n * Tagged template strings will return an {@link AqlQuery} object with\n * `query` and `bindVars` attributes reflecting any interpolated values.\n *\n * Any {@link collection.ArangoCollection} instance used in a query string will\n * be recognized as a collection reference and generate an AQL collection bind\n * parameter instead of a regular AQL value bind parameter.\n *\n * **Note**: you should always use the `aql` template tag when writing\n * dynamic AQL queries instead of using untagged (normal) template strings.\n * Untagged template strings will inline any interpolated values and return\n * a plain string as result. The `aql` template tag will only inline references\n * to the interpolated values and produce an AQL query object containing both\n * the query and the values. This prevents most injection attacks when using\n * untrusted values in dynamic queries.\n *\n * @example\n * ```js\n * // Some user-supplied string that may be malicious\n * const untrustedValue = req.body.email;\n *\n * // Without aql tag: BAD! DO NOT DO THIS!\n * const badQuery = `\n * FOR user IN users\n * FILTER user.email == \"${untrustedValue}\"\n * RETURN user\n * `;\n * // e.g. if untrustedValue is '\" || user.admin == true || \"':\n * // Query:\n * // FOR user IN users\n * // FILTER user.email == \"\" || user.admin == true || \"\"\n * // RETURN user\n *\n * // With the aql tag: GOOD! MUCH SAFER!\n * const betterQuery = aql`\n * FOR user IN users\n * FILTER user.email == ${untrustedValue}\n * RETURN user\n * `;\n * // Query:\n * // FOR user IN users\n * // FILTER user.email == @value0\n * // RETURN user\n * // Bind parameters:\n * // value0 -> untrustedValue\n * ```\n *\n * @example\n * ```js\n * const collection = db.collection(\"some-collection\");\n * const minValue = 23;\n * const result = await db.query(aql`\n * FOR d IN ${collection}\n * FILTER d.num > ${minValue}\n * RETURN d\n * `);\n *\n * // Equivalent raw query object\n * const result2 = await db.query({\n * query: `\n * FOR d IN @@collection\n * FILTER d.num > @minValue\n * RETURN d\n * `,\n * bindVars: {\n * \"@collection\": collection.name,\n * minValue: minValue\n * }\n * });\n * ```\n *\n * @example\n * ```js\n * const collection = db.collection(\"some-collection\");\n * const color = \"green\";\n * const filter = aql`FILTER d.color == ${color}'`;\n * const result = await db.query(aql`\n * FOR d IN ${collection}\n * ${filter}\n * RETURN d\n * `);\n * ```\n */\nexport function aql(\n templateStrings: TemplateStringsArray,\n ...args: AqlValue[]\n): GeneratedAqlQuery {\n const strings = [...templateStrings];\n const bindVars: Record<string, any> = {};\n const bindValues = [];\n let query = strings[0];\n for (let i = 0; i < args.length; i++) {\n const rawValue = args[i];\n let value = rawValue;\n if (isGeneratedAqlQuery(rawValue)) {\n const src = rawValue._source();\n if (src.args.length) {\n query += src.strings[0];\n args.splice(i, 1, ...src.args);\n strings.splice(\n i,\n 2,\n strings[i] + src.strings[0],\n ...src.strings.slice(1, src.args.length),\n src.strings[src.args.length] + strings[i + 1]\n );\n } else {\n query += rawValue.query + strings[i + 1];\n args.splice(i, 1);\n strings.splice(i, 2, strings[i] + rawValue.query + strings[i + 1]);\n }\n i -= 1;\n continue;\n }\n if (rawValue === undefined) {\n query += strings[i + 1];\n continue;\n }\n if (isAqlLiteral(rawValue)) {\n query += `${rawValue.toAQL()}${strings[i + 1]}`;\n continue;\n }\n const index = bindValues.indexOf(rawValue);\n const isKnown = index !== -1;\n let name = `value${isKnown ? index : bindValues.length}`;\n if (\n isArangoCollection(rawValue) ||\n isArangoGraph(rawValue) ||\n isArangoView(rawValue) ||\n isArangoAnalyzer(rawValue)\n ) {\n name = `@${name}`;\n value = rawValue.name;\n }\n if (!isKnown) {\n bindValues.push(rawValue);\n bindVars[name] = value;\n }\n query += `@${name}${strings[i + 1]}`;\n }\n return {\n query,\n bindVars,\n _source: () => ({ strings, args }),\n };\n}\n\n/**\n * Marks an arbitrary scalar value (i.e. a string, number or boolean) as\n * safe for being inlined directly into AQL queries when used in an `aql`\n * template string, rather than being converted into a bind parameter.\n *\n * **Note**: Nesting `aql` template strings is a much safer alternative for\n * most use cases. This low-level helper function only exists to help with\n * rare edge cases where a trusted AQL query fragment must be read from a\n * string (e.g. when reading query fragments from JSON) and should only be\n * used as a last resort.\n *\n * @example\n * ```js\n * // BAD! DO NOT DO THIS!\n * const sortDirection = literal('ASC');\n *\n * // GOOD! DO THIS INSTEAD!\n * const sortDirection = aql`ASC`;\n * ```\n *\n * @example\n * ```js\n * // BAD! DO NOT DO THIS!\n * const filterColor = literal('FILTER d.color == \"green\"');\n * const result = await db.query(aql`\n * FOR d IN some-collection\n * ${filterColor}\n * RETURN d\n * `);\n *\n * // GOOD! DO THIS INSTEAD!\n * const color = \"green\";\n * const filterColor = aql`FILTER d.color === ${color}`;\n * const result = await db.query(aql`\n * FOR d IN some-collection\n * ${filterColor}\n * RETURN d\n * `);\n * ```\n *\n * @example\n * ```js\n * // WARNING: We explicitly trust the environment variable to be safe!\n * const filter = literal(process.env.FILTER_STATEMENT);\n * const users = await db.query(aql`\n * FOR user IN users\n * ${filter}\n * RETURN user\n * `);\n * ```\n */\nexport function literal(\n value: string | number | boolean | AqlLiteral | null | undefined\n): AqlLiteral {\n if (isAqlLiteral(value)) {\n return value;\n }\n return {\n toAQL() {\n if (value === undefined) {\n return \"\";\n }\n return String(value);\n },\n };\n}\n\n/**\n * Constructs {@link AqlQuery} objects from an array of arbitrary values.\n *\n * **Note**: Nesting `aql` template strings is a much safer alternative\n * for most use cases. This low-level helper function only exists to\n * complement the `aql` tag when constructing complex queries from dynamic\n * arrays of query fragments.\n *\n * @param values - Array of values to join. These values will behave exactly\n * like values interpolated in an `aql` template string.\n * @param sep - Seperator to insert between values. This value will behave\n * exactly like a value passed to {@link literal}, i.e. it will be\n * inlined as-is, rather than being converted into a bind parameter.\n *\n * @example\n * ```js\n * const users = db.collection(\"users\");\n * const filters = [];\n * if (adminsOnly) filters.push(aql`FILTER user.admin`);\n * if (activeOnly) filters.push(aql`FILTER user.active`);\n * const result = await db.query(aql`\n * FOR user IN ${users}\n * ${join(filters)}\n * RETURN user\n * `);\n * ```\n *\n * @example\n * ```js\n * const users = db.collection(\"users\");\n * const keys = [\"jreyes\", \"ghermann\"];\n *\n * // BAD! NEEDLESSLY COMPLEX!\n * const docs = keys.map(key => aql`DOCUMENT(${users}, ${key}`));\n * const result = await db.query(aql`\n * FOR user IN [\n * ${join(docs, \", \")}\n * ]\n * RETURN user\n * `);\n * // Query:\n * // FOR user IN [\n * // DOCUMENT(@@value0, @value1), DOCUMENT(@@value0, @value2)\n * // ]\n * // RETURN user\n * // Bind parameters:\n * // @value0 -> \"users\"\n * // value1 -> \"jreyes\"\n * // value2 -> \"ghermann\"\n *\n * // GOOD! MUCH SIMPLER!\n * const result = await db.query(aql`\n * FOR key IN ${keys}\n * LET user = DOCUMENT(${users}, key)\n * RETURN user\n * `);\n * // Query:\n * // FOR user IN @value0\n * // LET user = DOCUMENT(@@value1, key)\n * // RETURN user\n * // Bind parameters:\n * // value0 -> [\"jreyes\", \"ghermann\"]\n * // @value1 -> \"users\"\n * ```\n */\nexport function join(values: AqlValue[], sep: string = \" \"): GeneratedAqlQuery {\n if (!values.length) {\n return aql``;\n }\n if (values.length === 1) {\n return aql`${values[0]}`;\n }\n return aql([\"\", ...Array(values.length - 1).fill(sep), \"\"] as any, ...values);\n}\n","/**\n * ```ts\n * import type {\n * FulltextIndex,\n * GeoIndex,\n * PersistentIndex,\n * PrimaryIndex,\n * TtlIndex,\n * ZkdIndex,\n * } from \"arangojs/indexes\";\n * ```\n *\n * The \"indexes\" module provides index-related types for TypeScript.\n *\n * @packageDocumentation\n */\n\nimport { AnalyzerFeature } from \"./analyzer\";\nimport { Compression, Direction, TierConsolidationPolicy } from \"./view\";\n\n/**\n * Options for creating a persistent index.\n */\nexport type EnsurePersistentIndexOptions = {\n /**\n * Type of this index.\n */\n type: \"persistent\";\n /**\n * An array of attribute paths.\n */\n fields: string[];\n /**\n * A unique name for this index.\n */\n name?: string;\n /**\n * If set to `true`, a unique index will be created.\n *\n * Default: `false`\n */\n unique?: boolean;\n /**\n * If set to `true`, the index will omit documents that do not contain at\n * least one of the attribute paths in `fields` and these documents will be\n * ignored for uniqueness checks.\n *\n * Default: `false`\n */\n sparse?: boolean;\n /**\n * If set to `false`, inserting duplicate index values from the same\n * document will lead to a unique constraint error if this is a unique index.\n *\n * Default: `true`\n */\n deduplicate?: boolean;\n /**\n * If set to `false`, index selectivity estimates will be disabled for this\n * index.\n *\n * Default: `true`\n */\n estimates?: boolean;\n /**\n * If set to `true`, the index will be created in the background to reduce\n * the write-lock duration for the collection during index creation.\n *\n * Default: `false`\n */\n inBackground?: boolean;\n /**\n * If set to `true`, an in-memory hash cache will be put in front of the\n * persistent index.\n *\n * Default: `false`\n */\n cacheEnabled?: boolean;\n /**\n * An array of attribute paths that will be stored in the index but can not\n * be used for index lookups or sorting but can avoid full document lookups.\n */\n storedValues?: string[];\n};\n\n/**\n * Options for creating a geo index.\n */\nexport type EnsureGeoIndexOptions =\n | {\n type: \"geo\";\n /**\n * If set to `true`, `fields` must be an array containing a single attribute\n * path and the attribute value must be an array with two values, the first\n * of which will be interpreted as the longitude and the second of which will\n * be interpreted as the latitude of the document.\n *\n * Default: `false`\n */\n geoJson?: false;\n /**\n * If set to `true`, the index will use pre-3.10 rules for parsing\n * GeoJSON polygons. This option is always implicitly `true` when using\n * ArangoDB 3.9 or lower.\n */\n legacyPolygons?: boolean;\n /**\n * Attribute paths for the document's latitude and longitude values.\n */\n fields: [string, string];\n /**\n * A unique name for this index.\n */\n name?: string;\n /**\n * If set to `true`, the index will be created in the background to reduce\n * the write-lock duration for the collection during index creation.\n *\n * Default: `false`\n */\n inBackground?: boolean;\n }\n | {\n type: \"geo\";\n /**\n * If set to `true`, `fields` must be an array containing a single attribute\n * path and the attribute value must be an array with two values, the first\n * of which will be interpreted as the longitude and the second of which will\n * be interpreted as the latitude of the document.\n *\n * Default: `false`\n */\n geoJson?: boolean;\n /**\n * If set to `true`, the index will use pre-3.10 rules for parsing\n * GeoJSON polygons. This option is always implicitly `true` when using\n * ArangoDB 3.9 or lower.\n */\n legacyPolygons?: boolean;\n /**\n * An array containing the attribute path for an array containing two values,\n * the first of which will be interpreted as the latitude, the second as the\n * longitude. If `geoJson` is set to `true`, the order is reversed to match\n * the GeoJSON format.\n */\n fields: [string];\n /**\n * A unique name for this index.\n */\n name?: string;\n /**\n * If set to `true`, the index will be created in the background to reduce\n * the write-lock duration for the collection during index creation.\n *\n * Default: `false`\n */\n inBackground?: boolean;\n };\n\n/**\n * Options for creating a fulltext index.\n *\n * @deprecated Fulltext indexes have been deprecated in ArangoDB 3.10 and\n * should be replaced with ArangoSearch.\n */\nexport type EnsureFulltextIndexOptions = {\n /**\n * Type of this index.\n */\n type: \"fulltext\";\n /**\n * An array containing exactly one attribute path.\n */\n fields: [string];\n /**\n * A unique name for this index.\n */\n name?: string;\n /**\n * Minimum character length of words to index.\n */\n minLength?: number;\n /**\n * If set to `true`, the index will be created in the background to reduce\n * the write-lock duration for the collection during index creation.\n *\n * Default: `false`\n */\n inBackground?: boolean;\n};\n\n/**\n * Options for creating a TTL index.\n */\nexport type EnsureTtlIndexOptions = {\n /**\n * Type of this index.\n */\n type: \"ttl\";\n /**\n * An array containing exactly one attribute path.\n */\n fields: [string];\n /**\n * A unique name for this index.\n */\n name?: string;\n /**\n * Duration in seconds after the attribute value at which the document will\n * be considered as expired.\n */\n expireAfter: number;\n /**\n * If set to `true`, the index will be created in the background to reduce\n * the write-lock duration for the collection during index creation.\n *\n * Default: `false`\n */\n inBackground?: boolean;\n};\n\n/**\n * Options for creating a ZKD index.\n */\nexport type EnsureZkdIndexOptions = {\n /**\n * Type of this index.\n */\n type: \"zkd\";\n /**\n * An array containing attribute paths for the dimensions.\n */\n fields: string[];\n /**\n * Data type of the dimension attributes.\n */\n fieldValueTypes: \"double\";\n /**\n * A unique name for this index.\n */\n name?: string;\n /**\n * If set to `true`, a unique index will be created.\n *\n * Default: `false`\n */\n unique?: boolean;\n /**\n * If set to `true`, the index will be created in the background to reduce\n * the write-lock duration for the collection during index creation.\n *\n * Default: `false`\n */\n inBackground?: boolean;\n};\n\n/**\n * (Enterprise Edition only.) Options for a nested field in an inverted index.\n */\nexport type InvertedIndexNestedFieldOptions = {\n /**\n * An attribute path.\n */\n name: string;\n /**\n * Name of the Analyzer to apply to the values of this field.\n *\n * Defaults to the `analyzer` specified on the parent options or on the index\n * itself.\n */\n analyzer?: string;\n /**\n * List of Analyzer features to enable for this field's Analyzer.\n *\n * Defaults to the features of the Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * If set to `true` array values will be indexed using the same behavior as\n * ArangoSearch Views. This option only applies when using the index in a\n * SearchAlias View.\n *\n * Defaults to the value of `searchField` specified on the index itself.\n */\n searchField?: boolean;\n /**\n * Sub-objects to index to allow querying for co-occurring values.\n */\n nested?: (string | InvertedIndexNestedFieldOptions)[];\n};\n\n/**\n * Options for an attribute path in an inverted index.\n */\nexport type InvertedIndexFieldOptions = {\n /**\n * An attribute path.\n */\n name: string;\n /**\n * Name of the Analyzer to apply to the values of this field.\n *\n * Defaults to the `analyzer` specified on the index itself.\n */\n analyzer?: string;\n /**\n * List of Analyzer features to enable for this field's Analyzer.\n *\n * Defaults to the features of the Analyzer.\n */\n features?: AnalyzerFeature[];\n /**\n * If set to `true`, all document attributes are indexed, excluding any\n * sub-attributes configured in the `fields` array. The `analyzer` and\n * `features` properties apply to the sub-attributes. This option only\n * applies when using the index in a SearchAlias View.\n *\n * Defaults to the value of `includeAllFields` specified on the index itself.\n */\n includeAllFields?: boolean;\n /**\n * If set to `true` array values will be indexed using the same behavior as\n * ArangoSearch Views. This option only applies when using the index in a\n * SearchAlias View.\n *\n * Defaults to the value of `searchField` specified on the index itself.\n */\n searchField?: boolean;\n /**\n * If set to `true`, the position of values in array values are tracked and\n * need to be specified in queries. Otherwise all values in an array are\n * treated as equivalent. This option only applies when using the index in a\n * SearchAlias View.\n *\n * Defaults to the value of `trackListPositions` specified on the index\n * itself.\n */\n trackListPositions?: boolean;\n /**\n * (Enterprise Edition only.) Sub-objects to index to allow querying for\n * co-occurring values.\n */\n nested?: (string | InvertedIndexNestedFieldOptions)[];\n};\n\n/**\n * Options for defining a stored value on an inverted index.\n */\nexport type InvertedIndexStoredValueOptions = {\n /**\n * The attribute paths to store.\n */\n fields: string[];\n /**\n * How the attribute values should be compressed.\n *\n * Default: `\"lz4\"`\n */\n compression?: Compression;\n};\n\n/**\n * Options for defining a primary sort field on an inverted index.\n */\nexport type InvertedIndexPrimarySortFieldOptions = {\n /**\n * The attribute path to sort by.\n */\n field: string;\n /**\n * The sorting direction.\n */\n direction: Direction;\n};\n\n/**\n * Options for creating an inverted index.\n */\nexport type EnsureInvertedIndexOptions = {\n /**\n * Type of this index.\n */\n type: \"inverted\";\n /**\n * An array of attribute paths or objects specifying options for the fields.\n */\n fields: (string | InvertedIndexFieldOptions)[];\n /**\n * A unique name for this index.\n */\n name?: string;\n /**\n * If set to `true` array values will by default be indexed using the same\n * behavior as ArangoSearch Views. This option only applies when using the\n * index in a SearchAlias View.\n *\n * Default: `false`\n */\n searchField?: boolean;\n /**\n * An array of attribute paths that will be stored in the index but can not\n * be used for index lookups or sorting but can avoid full document lookups.\n */\n storedValues?: InvertedIndexStoredValueOptions[];\n /**\n * Primary sort order to optimize AQL queries using a matching sort order.\n */\n primarySort?: {\n /**\n * An array of fields to sort the index by.\n */\n fields: InvertedIndexPrimarySortFieldOptions[];\n /**\n * How the primary sort data should be compressed.\n *\n * Default: `\"lz4\"`\n */\n compression?: Compression;\n };\n /**\n * Name of the default Analyzer to apply to the values of indexed fields.\n *\n * Default: `\"identity\"`\n */\n analyzer?: string;\n /**\n * List of Analyzer features to enable for the default Analyzer.\n *\n * Defaults to the Analyzer's features.\n */\n features?: AnalyzerFeature[];\n /**\n * If set to `true`, all document attributes are indexed, excluding any\n * sub-attributes configured in the `fields` array. The `analyzer` and\n * `features` properties apply to the sub-attributes. This option only\n * applies when using the index in a SearchAlias View.\n *\n * Default: `false`\n */\n includeAllFields?: boolean;\n /**\n * If set to `true`, the position of values in array values are tracked and\n * need to be specified in queries. Otherwise all values in an array are\n * treated as equivalent. This option only applies when using the index in a\n * SearchAlias View.\n *\n * Default: `false`\n */\n trackListPositions?: boolean;\n /**\n * The number of threads to use for indexing the fields.\n *\n * Default: `2`\n */\n parallelism?: number;\n /**\n * Wait at least this many commits between removing unused files in the\n * ArangoSearch data directory.\n *\n * Default: `2`\n */\n cleanupIntervalStep?: number;\n /**\n * Wait at least this many milliseconds between committing View data store\n * changes and making documents visible to queries.\n *\n * Default: `1000`\n */\n commitIntervalMsec?: number;\n /**\n * Wait at least this many milliseconds between applying\n * `consolidationPolicy` to consolidate View data store and possibly release\n * space on the filesystem.\n *\n * Default: `1000`\n */\n consolidationIntervalMsec?: number;\n /**\n * The consolidation policy to apply for selecting which segments should be\n * merged.\n *\n * Default: `{ type: \"tier\" }`\n */\n consolidationPolicy?: TierConsolidationPolicy;\n /**\n * Maximum number of writers (segments) cached in the pool.\n *\n * Default: `64`\n */\n writeBufferIdle?: number;\n /**\n * Maximum number of concurrent active writers (segments) that perform a\n * transaction.\n *\n * Default: `0` (disabled)\n */\n writeBufferActive?: number;\n /**\n * Maximum memory byte size per writer (segment) before a writer (segment)\n * flush is triggered.\n *\n * Default: `33554432` (32 MiB)\n */\n writeBufferSizeMax?: number;\n /**\n * If set to `true`, the index will be created in the background to reduce\n * the write-lock duration for the collection during index creation.\n *\n * Default: `false`\n */\n inBackground?: boolean;\n};\n\n/**\n * Shared attributes of all index types.\n */\nexport type GenericIndex = {\n /**\n * A unique name for this index.\n */\n name: string;\n /**\n * A unique identifier for this index.\n */\n id: string;\n /**\n * Whether documents not containing at least one of the attribute paths\n * are omitted by this index.\n */\n sparse: boolean;\n /**\n * Whether this index enforces uniqueness for values of its attribute paths.\n */\n unique: boolean;\n};\n\n/**\n * An object representing a persistent index.\n */\nexport type PersistentIndex = GenericIndex & {\n type: \"persistent\";\n fields: string[];\n cacheEnabled: boolean;\n deduplicate: boolean;\n estimates: boolean;\n storedValues?: string[];\n};\n\n/**\n * An object representing a primary index.\n */\nexport type PrimaryIndex = GenericIndex & {\n type: \"primary\";\n fields: string[];\n selectivityEstimate: number;\n};\n\n/**\n * An object representing a fulltext index.\n *\n * @deprecated Fulltext indexes have been deprecated in ArangoDB 3.10 and\n * should be replaced with ArangoSearch.\n */\nexport type FulltextIndex = GenericIndex & {\n type: \"fulltext\";\n fields: [string];\n minLength: number;\n};\n\n/**\n * An object representing a geo index.\n */\nexport type GeoIndex = GenericIndex & {\n type: \"geo\";\n fields: [string] | [string, string];\n geoJson: boolean;\n legacyPolygons: boolean;\n bestIndexedLevel: number;\n worstIndexedLevel: number;\n maxNumCoverCells: number;\n};\n\n/**\n * An object representing a TTL index.\n */\nexport type TtlIndex = GenericIndex & {\n type: \"ttl\";\n fields: [string];\n expireAfter: number;\n selectivityEstimate: number;\n};\n\n/**\n * An object representing a ZKD index.\n */\nexport type ZkdIndex = GenericIndex & {\n type: \"zkd\";\n fields: string[];\n fieldValueTypes: \"double\";\n};\n\n/**\n * (Enterprise Edition only.) An object representing a nested field in an\n * inverted index.\n */\nexport type InvertedIndexNestedField = {\n name: string;\n analyzer?: string;\n features?: AnalyzerFeature[];\n searchField?: boolean;\n nested?: InvertedIndexNestedField[];\n};\n\n/**\n * An object representing an inverted index.\n */\nexport type InvertedIndex = GenericIndex & {\n type: \"inverted\";\n fields: {\n name: string;\n analyzer?: string;\n features?: AnalyzerFeature[];\n includeAllFields?: boolean;\n searchField?: boolean;\n trackListPositions?: boolean;\n nested?: InvertedIndexNestedField[];\n }[];\n searchField: boolean;\n storedValues: {\n fields: string[];\n compression: Compression;\n }[];\n primarySort: {\n fields: {\n field: string;\n direction: Direction;\n }[];\n compression: Compression;\n };\n analyzer: string;\n features: AnalyzerFeature[];\n includeAllFields: boolean;\n trackListPositions: boolean;\n parallelism: number;\n cleanupIntervalStep: number;\n commitIntervalMsec: number;\n consolidationIntervalMsec: number;\n consolidationPolicy: Required<TierConsolidationPolicy>;\n writeBufferIdle: number;\n writeBufferActive: number;\n writeBufferSizeMax: number;\n};\n\n/**\n * An object representing an index.\n */\nexport type Index =\n | GeoIndex\n | FulltextIndex\n | PersistentIndex\n | PrimaryIndex\n | TtlIndex\n | ZkdIndex\n | InvertedIndex;\n\nexport type ObjectWithId = {\n [key: string]: any;\n id: string;\n};\n\nexport type ObjectWithName = {\n [key: string]: any;\n name: string;\n};\n\n/**\n * Index name, id or object with a `name` or `id` property.\n */\nexport type IndexSelector = ObjectWithId | ObjectWithName | string;\n\n/**\n * @internal\n */\nexport function _indexHandle(\n selector: IndexSelector,\n collectionName: string\n): string {\n if (typeof selector !== \"string\") {\n if (selector.id) {\n return _indexHandle(selector.id, collectionName);\n }\n throw new Error(\n \"Index handle must be a string or an object with an id attribute\"\n );\n }\n if (selector.includes(\"/\")) {\n const [head, ...tail] = selector.split(\"/\");\n const normalizedHead = head.normalize(\"NFC\");\n if (normalizedHead !== collectionName) {\n throw new Error(\n `Index ID \"${selector}\" does not match collection name \"${collectionName}\"`\n );\n }\n return [normalizedHead, ...tail].join(\"/\");\n }\n return `${collectionName}/${selector}`;\n}\n","/**\n * ```ts\n * import type {\n * DocumentCollection,\n * EdgeCollection,\n * } from \"arangojs/collection\";\n * ```\n *\n * The \"collection\" module provides collection related types and interfaces\n * for TypeScript.\n *\n * @packageDocumentation\n */\nimport { AqlLiteral, AqlQuery, isAqlLiteral, isAqlQuery } from \"./aql\";\nimport { ArangoApiResponse, Params } from \"./connection\";\nimport { ArrayCursor, BatchedArrayCursor } from \"./cursor\";\nimport { Database } from \"./database\";\nimport {\n Document,\n DocumentData,\n DocumentMetadata,\n DocumentSelector,\n Edge,\n EdgeData,\n ObjectWithKey,\n Patch,\n _documentHandle,\n} from \"./documents\";\nimport { HttpError, isArangoError } from \"./error\";\nimport {\n EnsureFulltextIndexOptions,\n EnsureGeoIndexOptions,\n EnsureInvertedIndexOptions,\n EnsurePersistentIndexOptions,\n EnsureTtlIndexOptions,\n EnsureZkdIndexOptions,\n FulltextIndex,\n GeoIndex,\n Index,\n IndexSelector,\n InvertedIndex,\n PersistentIndex,\n TtlIndex,\n ZkdIndex,\n _indexHandle,\n} from \"./indexes\";\nimport { Blob } from \"./lib/blob\";\nimport { COLLECTION_NOT_FOUND, DOCUMENT_NOT_FOUND } from \"./lib/codes\";\n\n/**\n * Indicates whether the given value represents an {@link ArangoCollection}.\n *\n * @param collection - A value that might be a collection.\n */\nexport function isArangoCollection(\n collection: any\n): collection is ArangoCollection {\n return Boolean(collection && collection.isArangoCollection);\n}\n\n/**\n * Coerces the given collection name or {@link ArangoCollection} object to\n * a string representing the collection name.\n *\n * @param collection - Collection name or {@link ArangoCollection} object.\n */\nexport function collectionToString(\n collection: string | ArangoCollection\n): string {\n if (isArangoCollection(collection)) {\n return String(collection.name);\n } else return String(collection).normalize(\"NFC\");\n}\n\n/**\n * A marker interface identifying objects that can be used in AQL template\n * strings to create references to ArangoDB collections.\n *\n * See {@link aql!aql}.\n */\nexport interface ArangoCollection {\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB collection.\n */\n readonly isArangoCollection: true;\n /**\n * Name of the collection.\n */\n readonly name: string;\n}\n\n/**\n * Integer values indicating the collection type.\n */\nexport enum CollectionType {\n DOCUMENT_COLLECTION = 2,\n EDGE_COLLECTION = 3,\n}\n\n/**\n * Integer values indicating the collection loading status.\n */\nexport enum CollectionStatus {\n NEWBORN = 1,\n UNLOADED = 2,\n LOADED = 3,\n UNLOADING = 4,\n DELETED = 5,\n LOADING = 6,\n}\n\n/**\n * Type of key generator.\n */\nexport type KeyGenerator = \"traditional\" | \"autoincrement\" | \"uuid\" | \"padded\";\n\n/**\n * Strategy for sharding a collection.\n */\nexport type ShardingStrategy =\n | \"hash\"\n | \"enterprise-hash-smart-edge\"\n | \"enterprise-hash-smart-vertex\"\n | \"community-compat\"\n | \"enterprise-compat\"\n | \"enterprise-smart-edge-compat\";\n\n/**\n * Type of document reference.\n *\n * See {@link DocumentCollection#list} and {@link EdgeCollection#list}.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryListType = \"id\" | \"key\" | \"path\";\n\n/**\n * When a validation should be applied.\n *\n * * `\"none\"`: No validation.\n * * `\"new\"`: Newly inserted documents are validated.\n * * `\"moderate\"`: New and modified documents are validated unless the modified\n * document was already invalid.\n * * `\"strict\"`: New and modified documents are always validated.\n */\nexport type ValidationLevel = \"none\" | \"new\" | \"moderate\" | \"strict\";\n\n/**\n * Write operation that can result in a computed value being computed.\n */\nexport type WriteOperation = \"insert\" | \"update\" | \"replace\";\n\n/**\n * Properties defining a computed value.\n */\nexport type ComputedValueProperties = {\n /**\n * Name of the target attribute of the computed value.\n */\n name: string;\n /**\n * AQL `RETURN` expression that computes the value.\n */\n expression: string;\n /**\n * If set to `false`, the computed value will not be applied if the\n * expression evaluates to `null`.\n */\n overwrite: boolean;\n /**\n * Which operations should result in the value being computed.\n */\n computeOn: WriteOperation[];\n /**\n * If set to `false`, the field will be unset if the expression evaluates to\n * `null`. Otherwise the field will be set to the value `null`. Has no effect\n * if `overwrite` is set to `false`.\n */\n keepNull: boolean;\n /**\n * Whether the write operation should fail if the expression produces a\n * warning.\n */\n failOnWarning: boolean;\n};\n\n/**\n * General information about a collection.\n */\nexport type CollectionMetadata = {\n /**\n * Collection name.\n */\n name: string;\n /**\n * A globally unique identifier for this collection.\n */\n globallyUniqueId: string;\n /**\n * An integer indicating the collection loading status.\n */\n status: CollectionStatus;\n /**\n * An integer indicating the collection type.\n */\n type: CollectionType;\n /**\n * @internal\n *\n * Whether the collection is a system collection.\n */\n isSystem: boolean;\n};\n\n/**\n * An object defining the collection's key generation.\n */\nexport type CollectionKeyProperties = {\n /**\n * Type of key generator to use.\n */\n type: KeyGenerator;\n /**\n * Whether documents can be created with a user-specified `_key` attribute.\n */\n allowUserKeys: boolean;\n /**\n * (Autoincrement only.) How many steps to increment the key each time.\n */\n increment?: number;\n /**\n * (Autoincrement only.) Initial offset for the key.\n */\n offset?: number;\n /**\n * Most recent key that has been generated.\n */\n lastValue: number;\n};\n\n/**\n * Properties for validating documents in a collection.\n */\nexport type SchemaProperties = {\n /**\n * Type of document validation.\n */\n type: \"json\";\n /**\n * JSON Schema description of the validation schema for documents.\n */\n rule: any;\n /**\n * When validation should be applied.\n */\n level: ValidationLevel;\n /**\n * Message to be used if validation fails.\n */\n message: string;\n};\n\n/**\n * An object defining the properties of a collection.\n */\nexport type CollectionProperties = {\n /**\n * A human-readable representation of the collection loading status.\n */\n statusString: string;\n /**\n * Whether data should be synchronized to disk before returning from\n * a document create, update, replace or removal operation.\n */\n waitForSync: boolean;\n /**\n * An object defining the collection's key generation.\n */\n keyOptions: CollectionKeyProperties;\n /**\n * Properties for validating documents in the collection.\n */\n schema: SchemaProperties | null;\n /**\n * (Cluster only.) Write concern for this collection.\n */\n writeConcern: number;\n /**\n * (Cluster only.) Number of shards of this collection.\n */\n numberOfShards?: number;\n /**\n * (Cluster only.) Keys of this collection that will be used for\n * sharding.\n */\n shardKeys?: string[];\n /**\n * (Cluster only.) Replication factor of the collection.\n */\n replicationFactor?: number | \"satellite\";\n /**\n * (Cluster only.) Sharding strategy of the collection.\n */\n shardingStrategy?: ShardingStrategy;\n /**\n * (Enterprise Edition cluster only.) If set to a collection name, sharding\n * of the new collection will follow the rules for that collection. As long\n * as the new collection exists, the indicated collection can not be dropped.\n */\n distributeShardsLike?: string;\n /**\n * (Enterprise Edition cluster only.) Attribute containing the shard key\n * value of the referred-to smart join collection.\n */\n smartJoinAttribute?: string;\n /**\n * (Enterprise Edition cluster only.) Attribute used for sharding.\n */\n smartGraphAttribute?: string;\n /**\n * Computed values applied to documents in this collection.\n */\n computedValues: ComputedValueProperties[];\n /**\n * Whether the in-memory hash cache is enabled for this collection.\n */\n cacheEnabled: boolean;\n /**\n * Whether the newer revision-based replication protocol is enabled for\n * this collection.\n */\n syncByRevision: boolean;\n /**\n * (Enterprise Edition only.) Whether the collection is used in a SmartGraph or EnterpriseGraph.\n */\n isSmart?: boolean;\n /**\n * (Enterprise Edition only.) Whether the SmartGraph this collection belongs to is disjoint.\n */\n isDisjoint?: string;\n};\n\n// Options\n\n/**\n * Options for creating a computed value.\n */\nexport type ComputedValueOptions = {\n /**\n * Name of the target attribute of the computed value.\n */\n name: string;\n /**\n * AQL `RETURN` expression that computes the value.\n *\n * Note that when passing an AQL query object, the `bindVars` will be ignored.\n */\n expression: string | AqlLiteral | AqlQuery;\n /**\n * If set to `false`, the computed value will not be applied if the\n * expression evaluates to `null`.\n *\n * Default: `true`\n */\n overwrite?: boolean;\n /**\n * Which operations should result in the value being computed.\n *\n * Default: `[\"insert\", \"update\", \"replace\"]`\n */\n computeOn?: WriteOperation[];\n /**\n * If set to `false`, the field will be unset if the expression evaluates to\n * `null`. Otherwise the field will be set to the value `null`. Has no effect\n * if `overwrite` is set to `false`.\n *\n * Default: `true`\n */\n keepNull?: boolean;\n /**\n * Whether the write operation should fail if the expression produces a\n * warning.\n *\n * Default: `false`\n */\n failOnWarning?: boolean;\n};\n\n/**\n * Options for validating collection documents.\n */\nexport type SchemaOptions = {\n /**\n * JSON Schema description of the validation schema for documents.\n */\n rule: any;\n /**\n * When validation should be applied.\n *\n * Default: `\"strict\"`\n */\n level?: ValidationLevel;\n /**\n * Message to be used if validation fails.\n */\n message?: string;\n};\n\n/**\n * Options for setting a collection's properties.\n *\n * See {@link DocumentCollection#properties} and {@link EdgeCollection#properties}.\n */\nexport type CollectionPropertiesOptions = {\n /**\n * Whether data should be synchronized to disk before returning from\n * a document create, update, replace or removal operation.\n */\n waitForSync?: boolean;\n /**\n * (Cluster only.) How many copies of each document should be kept in the\n * cluster.\n *\n * Default: `1`\n */\n replicationFactor?: number | \"satellite\";\n /**\n * (Cluster only.) Write concern for this collection.\n */\n writeConcern?: number;\n /**\n * Options for validating documents in this collection.\n */\n schema?: SchemaOptions;\n /**\n * Computed values to apply to documents in this collection.\n */\n computedValues?: ComputedValueOptions[];\n /**\n * Whether the in-memory hash cache is enabled for this collection.\n *\n * Default: `false`\n */\n cacheEnabled?: boolean;\n};\n\n/**\n * Options for retrieving a collection checksum.\n */\nexport type CollectionChecksumOptions = {\n /**\n * If set to `true`, revision IDs will be included in the calculation\n * of the checksum.\n *\n * Default: `false`\n */\n withRevisions?: boolean;\n /**\n * If set to `true`, document data will be included in the calculation\n * of the checksum.\n *\n * Default: `false`\n */\n withData?: boolean;\n};\n\n/**\n * Options for dropping collections.\n */\nexport type CollectionDropOptions = {\n /**\n * Whether the collection is a system collection. If the collection is a\n * system collection, this option must be set to `true` or ArangoDB will\n * refuse to drop the collection.\n *\n * Default: `false`\n */\n isSystem?: boolean;\n};\n\n/**\n * An object defining the collection's key generation.\n */\nexport type CollectionKeyOptions = {\n /**\n * Type of key generator to use.\n */\n type?: KeyGenerator;\n /**\n * Unless set to `false`, documents can be created with a user-specified\n * `_key` attribute.\n *\n * Default: `true`\n */\n allowUserKeys?: boolean;\n /**\n * (Autoincrement only.) How many steps to increment the key each time.\n */\n increment?: number;\n /**\n * (Autoincrement only.) Initial offset for the key.\n */\n offset?: number;\n};\n\n/**\n * Options for creating a collection.\n *\n * See {@link database.Database#createCollection}, {@link database.Database#createEdgeCollection}\n * and {@link DocumentCollection#create} or {@link EdgeCollection#create}.\n */\nexport type CreateCollectionOptions = {\n /**\n * If set to `true`, data will be synchronized to disk before returning from\n * a document create, update, replace or removal operation.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * @internal\n *\n * Whether the collection should be created as a system collection.\n *\n * Default: `false`\n */\n isSystem?: boolean;\n /**\n * An object defining the collection's key generation.\n */\n keyOptions?: CollectionKeyOptions;\n /**\n * Options for validating documents in the collection.\n */\n schema?: SchemaOptions;\n /**\n * (Cluster only.) Unless set to `false`, the server will wait for all\n * replicas to create the collection before returning.\n *\n * Default: `true`\n */\n waitForSyncReplication?: boolean;\n /**\n * (Cluster only.) Unless set to `false`, the server will check whether\n * enough replicas are available at creation time and bail out otherwise.\n *\n * Default: `true`\n */\n enforceReplicationFactor?: boolean;\n /**\n * (Cluster only.) Number of shards to distribute the collection across.\n *\n * Default: `1`\n */\n numberOfShards?: number;\n /**\n * (Cluster only.) Document attributes to use to determine the target shard\n * for each document.\n *\n * Default: `[\"_key\"]`\n */\n shardKeys?: string[];\n /**\n * (Cluster only.) How many copies of each document should be kept in the\n * cluster.\n *\n * Default: `1`\n */\n replicationFactor?: number;\n /**\n * (Cluster only.) Write concern for this collection.\n */\n writeConcern?: number;\n /**\n * (Cluster only.) Sharding strategy to use.\n */\n shardingStrategy?: ShardingStrategy;\n /**\n * (Enterprise Edition cluster only.) If set to a collection name, sharding\n * of the new collection will follow the rules for that collection. As long\n * as the new collection exists, the indicated collection can not be dropped.\n */\n distributeShardsLike?: string;\n /**\n * (Enterprise Edition cluster only.) Attribute containing the shard key\n * value of the referred-to smart join collection.\n */\n smartJoinAttribute?: string;\n /**\n * (Enterprise Edition cluster only.) Attribute used for sharding.\n */\n smartGraphAttribute?: string;\n /**\n * Computed values to apply to documents in this collection.\n */\n computedValues?: ComputedValueOptions[];\n /**\n * Whether the in-memory hash cache is enabled for this collection.\n */\n cacheEnabled?: boolean;\n};\n\n/**\n * Options for checking whether a document exists in a collection.\n */\nexport type DocumentExistsOptions = {\n /**\n * If set to a document revision, the document will only match if its `_rev`\n * matches the given revision.\n */\n ifMatch?: string;\n /**\n * If set to a document revision, the document will only match if its `_rev`\n * does not match the given revision.\n */\n ifNoneMatch?: string;\n};\n\n/**\n * Options for retrieving a document from a collection.\n */\nexport type CollectionReadOptions = {\n /**\n * If set to `true`, `null` is returned instead of an exception being thrown\n * if the document does not exist.\n */\n graceful?: boolean;\n /**\n * If set to `true`, the request will explicitly permit ArangoDB to return a\n * potentially dirty or stale result and arangojs will load balance the\n * request without distinguishing between leaders and followers.\n */\n allowDirtyRead?: boolean;\n /**\n * If set to a document revision, the request will fail with an error if the\n * document exists but its `_rev` does not match the given revision.\n */\n ifMatch?: string;\n /**\n * If set to a document revision, the request will fail with an error if the\n * document exists and its `_rev` matches the given revision. Note that an\n * `HttpError` with code 304 will be thrown instead of an `ArangoError`.\n */\n ifNoneMatch?: string;\n};\n\n/**\n * Options for retrieving multiple documents from a collection.\n */\nexport type CollectionBatchReadOptions = {\n /**\n * If set to `true`, the request will explicitly permit ArangoDB to return a\n * potentially dirty or stale result and arangojs will load balance the\n * request without distinguishing between leaders and followers.\n */\n allowDirtyRead?: boolean;\n};\n\n/**\n * Options for inserting a new document into a collection.\n */\nexport type CollectionInsertOptions = {\n /**\n * If set to `true`, data will be synchronized to disk before returning.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * If set to `true`, no data will be returned by the server. This option can\n * be used to reduce network traffic.\n *\n * Default: `false`\n */\n silent?: boolean;\n /**\n * If set to `true`, the complete new document will be returned as the `new`\n * property on the result object. Has no effect if `silent` is set to `true`.\n *\n * Default: `false`\n */\n returnNew?: boolean;\n /**\n * Defines what should happen if a document with the same `_key` or `_id`\n * already exists, instead of throwing an exception.\n *\n * Default: `\"conflict\"\n */\n overwriteMode?: \"ignore\" | \"update\" | \"replace\" | \"conflict\";\n};\n\n/**\n * Options for replacing an existing document in a collection.\n */\nexport type CollectionReplaceOptions = {\n /**\n * If set to `true`, data will be synchronized to disk before returning.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * If set to `true`, no data will be returned by the server. This option can\n * be used to reduce network traffic.\n *\n * Default: `false`\n */\n silent?: boolean;\n /**\n * If set to `true`, the complete new document will be returned as the `new`\n * property on the result object. Has no effect if `silent` is set to `true`.\n *\n * Default: `false`\n */\n returnNew?: boolean;\n /**\n * If set to `false`, the existing document will only be modified if its\n * `_rev` property matches the same property on the new data.\n *\n * Default: `true`\n */\n ignoreRevs?: boolean;\n /**\n * If set to `true`, the complete old document will be returned as the `old`\n * property on the result object. Has no effect if `silent` is set to `true`.\n *\n * Default: `false`\n */\n returnOld?: boolean;\n /**\n * If set to a document revision, the document will only be replaced if its\n * `_rev` matches the given revision.\n */\n ifMatch?: string;\n};\n\n/**\n * Options for updating a document in a collection.\n */\nexport type CollectionUpdateOptions = {\n /**\n * If set to `true`, data will be synchronized to disk before returning.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * If set to `true`, no data will be returned by the server. This option can\n * be used to reduce network traffic.\n *\n * Default: `false`\n */\n silent?: boolean;\n /**\n * If set to `true`, the complete new document will be returned as the `new`\n * property on the result object. Has no effect if `silent` is set to `true`.\n *\n * Default: `false`\n */\n returnNew?: boolean;\n /**\n * If set to `false`, the existing document will only be modified if its\n * `_rev` property matches the same property on the new data.\n *\n * Default: `true`\n */\n ignoreRevs?: boolean;\n /**\n * If set to `true`, the complete old document will be returned as the `old`\n * property on the result object. Has no effect if `silent` is set to `true`.\n *\n * Default: `false`\n */\n returnOld?: boolean;\n /**\n * If set to `false`, properties with a value of `null` will be removed from\n * the new document.\n *\n * Default: `true`\n */\n keepNull?: boolean;\n /**\n * If set to `false`, object properties that already exist in the old\n * document will be overwritten rather than merged. This does not affect\n * arrays.\n *\n * Default: `true`\n */\n mergeObjects?: boolean;\n /**\n * If set to a document revision, the document will only be updated if its\n * `_rev` matches the given revision.\n */\n ifMatch?: string;\n};\n\n/**\n * Options for removing a document from a collection.\n */\nexport type CollectionRemoveOptions = {\n /**\n * If set to `true`, changes will be synchronized to disk before returning.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * If set to `true`, the complete old document will be returned as the `old`\n * property on the result object. Has no effect if `silent` is set to `true`.\n *\n * Default: `false`\n */\n returnOld?: boolean;\n /**\n * If set to `true`, no data will be returned by the server. This option can\n * be used to reduce network traffic.\n *\n * Default: `false`\n */\n silent?: boolean;\n /**\n * If set to a document revision, the document will only be removed if its\n * `_rev` matches the given revision.\n */\n ifMatch?: string;\n};\n\n/**\n * Options for bulk importing documents into a collection.\n */\nexport type CollectionImportOptions = {\n /**\n * (Edge collections only.) Prefix to prepend to `_from` attribute values.\n */\n fromPrefix?: string;\n /**\n * (Edge collections only.) Prefix to prepend to `_to` attribute values.\n */\n toPrefix?: string;\n /**\n * If set to `true`, the collection is truncated before the data is imported.\n *\n * Default: `false`\n */\n overwrite?: boolean;\n /**\n * Whether to wait for the documents to have been synced to disk.\n */\n waitForSync?: boolean;\n /**\n * Controls behavior when a unique constraint is violated on the document key.\n *\n * * `\"error\"`: the document will not be imported.\n * * `\"update`: the document will be merged into the existing document.\n * * `\"replace\"`: the document will replace the existing document.\n * * `\"ignore\"`: the document will not be imported and the unique constraint\n * error will be ignored.\n *\n * Default: `\"error\"`\n */\n onDuplicate?: \"error\" | \"update\" | \"replace\" | \"ignore\";\n /**\n * If set to `true`, the import will abort if any error occurs.\n */\n complete?: boolean;\n /**\n * Whether the response should contain additional details about documents\n * that could not be imported.\n */\n details?: boolean;\n};\n\n/**\n * Options for retrieving a document's edges from a collection.\n */\nexport type CollectionEdgesOptions = {\n /**\n * If set to `true`, the request will explicitly permit ArangoDB to return a\n * potentially dirty or stale result and arangojs will load balance the\n * request without distinguishing between leaders and followers.\n */\n allowDirtyRead?: boolean;\n};\n\n/**\n * Options for retrieving documents by example.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryByExampleOptions = {\n /**\n * Number of documents to skip in the query.\n */\n skip?: number;\n /**\n * Maximum number of documents to return.\n */\n limit?: number;\n /**\n * Number of result values to be transferred by the server in each\n * network roundtrip (or \"batch\").\n *\n * Must be greater than zero.\n *\n * See also {@link database.QueryOptions}.\n */\n batchSize?: number;\n /**\n * Time-to-live for the cursor in seconds. The cursor results may be\n * garbage collected by ArangoDB after this much time has passed.\n *\n * See also {@link database.QueryOptions}.\n */\n ttl?: number;\n};\n\n/**\n * Options for retrieving all documents in a collection.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryAllOptions = {\n /**\n * Number of documents to skip in the query.\n */\n skip?: number;\n /**\n * Maximum number of documents to return.\n */\n limit?: number;\n /**\n * Number of result values to be transferred by the server in each\n * network roundtrip (or \"batch\").\n *\n * Must be greater than zero.\n *\n * See also {@link database.QueryOptions}.\n */\n batchSize?: number;\n /**\n * Time-to-live for the cursor in seconds. The cursor results may be\n * garbage collected by ArangoDB after this much time has passed.\n *\n * See also {@link database.QueryOptions}.\n */\n ttl?: number;\n /**\n * If set to `true`, the query will be executed as a streaming query.\n *\n * See also {@link database.QueryOptions}.\n */\n stream?: boolean;\n};\n\n/**\n * Options for updating documents by example.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryUpdateByExampleOptions = {\n /**\n * If set to `false`, properties with a value of `null` will be removed from\n * the new document.\n *\n * Default: `true`\n */\n keepNull?: boolean;\n /**\n * If set to `true`, the request will wait until all modifications have been\n * synchronized to disk before returning successfully.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * Maximum number of documents to return.\n */\n limit?: number;\n /**\n * If set to `false`, object properties that already exist in the old\n * document will be overwritten rather than merged. This does not affect\n * arrays.\n *\n * Default: `true`\n */\n mergeObjects?: boolean;\n};\n\n/**\n * Options for removing documents by example.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryRemoveByExampleOptions = {\n /**\n * If set to `true`, the request will wait until all modifications have been\n * synchronized to disk before returning successfully.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * Maximum number of documents to return.\n */\n limit?: number;\n};\n\n/**\n * Options for replacing documents by example.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryReplaceByExampleOptions =\n SimpleQueryRemoveByExampleOptions;\n\n/**\n * Options for removing documents by keys.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryRemoveByKeysOptions = {\n /**\n * If set to `true`, the complete old document will be returned as the `old`\n * property on the result object. Has no effect if `silent` is set to `true`.\n *\n * Default: `false`\n */\n returnOld?: boolean;\n /**\n * If set to `true`, no data will be returned by the server. This option can\n * be used to reduce network traffic.\n *\n * Default: `false`\n */\n silent?: boolean;\n /**\n * If set to `true`, the request will wait until all modifications have been\n * synchronized to disk before returning successfully.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n};\n\n/**\n * Options for performing a fulltext query.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryFulltextOptions = {\n /**\n * Unique identifier of the fulltext index to use to perform the query.\n */\n index?: string;\n /**\n * Maximum number of documents to return.\n */\n limit?: number;\n /**\n * Number of documents to skip in the query.\n */\n skip?: number;\n};\n\n/**\n * Options for performing a graph traversal.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type TraversalOptions = {\n /**\n * A string evaluating to the body of a JavaScript function to be executed\n * on the server to initialize the traversal result object.\n *\n * The code has access to two variables: `config`, `result`.\n * The code may modify the `result` object.\n *\n * **Note**: This code will be evaluated and executed on the\n * server inside ArangoDB's embedded JavaScript environment and can not\n * access any other variables.\n *\n * See the official ArangoDB documentation for\n * [the JavaScript `@arangodb` module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html)\n * for information about accessing the database from within ArangoDB's\n * server-side JavaScript environment.\n */\n init?: string;\n /**\n * A string evaluating to the body of a JavaScript function to be executed\n * on the server to filter nodes.\n *\n * The code has access to three variables: `config`, `vertex`, `path`.\n * The code may include a return statement for the following values:\n *\n * * `\"exclude\"`: The vertex will not be visited.\n * * `\"prune\"`: The edges of the vertex will not be followed.\n * * `\"\"` or `undefined`: The vertex will be visited and its edges followed.\n * * an array including any of the above values.\n *\n * **Note**: This code will be evaluated and executed on the\n * server inside ArangoDB's embedded JavaScript environment and can not\n * access any other variables.\n *\n * See the official ArangoDB documentation for\n * [the JavaScript `@arangodb` module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html)\n * for information about accessing the database from within ArangoDB's\n * server-side JavaScript environment.\n */\n filter?: string;\n /**\n * A string evaluating to the body of a JavaScript function to be executed\n * on the server to sort edges if `expander` is not set.\n *\n * The code has access to two variables representing edges: `l`, `r`.\n * The code must return `-1` if `l < r`, `1` if `l > r` or `0` if both\n * values are equal.\n *\n * **Note**: This code will be evaluated and executed on the\n * server inside ArangoDB's embedded JavaScript environment and can not\n * access any other variables.\n *\n * See the official ArangoDB documentation for\n * [the JavaScript `@arangodb` module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html)\n * for information about accessing the database from within ArangoDB's\n * server-side JavaScript environment.\n */\n sort?: string;\n /**\n * A string evaluating to the body of a JavaScript function to be executed\n * on the server when a node is visited.\n *\n * The code has access to five variables: `config`, `result`, `vertex`,\n * `path`, `connected`.\n * The code may modify the `result` object.\n *\n * **Note**: This code will be evaluated and executed on the\n * server inside ArangoDB's embedded JavaScript environment and can not\n * access any other variables.\n *\n * See the official ArangoDB documentation for\n * [the JavaScript `@arangodb` module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html)\n * for information about accessing the database from within ArangoDB's\n * server-side JavaScript environment.\n */\n visitor?: string;\n /**\n * A string evaluating to the body of a JavaScript function to be executed\n * on the server to use when `direction` is not set.\n *\n * The code has access to three variables: `config`, `vertex`, `path`.\n * The code must return an array of objects with `edge` and `vertex`\n * attributes representing the connections for the vertex.\n *\n * **Note**: This code will be evaluated and executed on the\n * server inside ArangoDB's embedded JavaScript environment and can not\n * access any other variables.\n *\n * See the official ArangoDB documentation for\n * [the JavaScript `@arangodb` module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html)\n * for information about accessing the database from within ArangoDB's\n * server-side JavaScript environment.\n */\n expander?: string;\n /**\n * Direction of the traversal, relative to the starting vertex if `expander`\n * is not set.\n */\n direction?: \"inbound\" | \"outbound\" | \"any\";\n /**\n * Item iteration order.\n */\n itemOrder?: \"forward\" | \"backward\";\n /**\n * Traversal strategy.\n */\n strategy?: \"depthfirst\" | \"breadthfirst\";\n /**\n * Traversal order.\n */\n order?: \"preorder\" | \"postorder\" | \"preorder-expander\";\n /**\n * Specifies uniqueness for vertices and edges.\n */\n uniqueness?: {\n /**\n * Uniqueness for vertices.\n */\n vertices?: \"none\" | \"global\" | \"path\";\n /**\n * Uniqueness for edges.\n */\n edges?: \"none\" | \"global\" | \"path\";\n };\n /**\n * If specified, only nodes in at least this depth will be visited.\n */\n minDepth?: number;\n /**\n * If specified, only nodes in at most this depth will be visited.\n */\n maxDepth?: number;\n /**\n * Maximum number of iterations before a traversal is aborted because of a\n * potential endless loop.\n */\n maxIterations?: number;\n};\n\n// Results\n\n/**\n * Result of a collection bulk import.\n */\nexport type CollectionImportResult = {\n /**\n * Whether the import failed.\n */\n error: false;\n /**\n * Number of new documents imported.\n */\n created: number;\n /**\n * Number of documents that failed with an error.\n */\n errors: number;\n /**\n * Number of empty documents.\n */\n empty: number;\n /**\n * Number of documents updated.\n */\n updated: number;\n /**\n * Number of documents that failed with an error that is ignored.\n */\n ignored: number;\n /**\n * Additional details about any errors encountered during the import.\n */\n details?: string[];\n};\n\n/**\n * Result of retrieving edges in a collection.\n */\nexport type CollectionEdgesResult<T extends Record<string, any> = any> = {\n edges: Edge<T>[];\n stats: {\n scannedIndex: number;\n filtered: number;\n };\n};\n\n/**\n * Result of removing documents by an example.\n *\n * See {@link DocumentCollection#removeByExample} and {@link EdgeCollection#removeByExample}.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryRemoveByExampleResult = {\n /**\n * Number of documents removed.\n */\n deleted: number;\n};\n\n/**\n * Result of replacing documents by an example.\n *\n * See {@link DocumentCollection#replaceByExample} and {@link EdgeCollection#replaceByExample}.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryReplaceByExampleResult = {\n /**\n * Number of documents replaced.\n */\n replaced: number;\n};\n\n/**\n * Result of updating documents by an example.\n *\n * See {@link DocumentCollection#updateByExample} and {@link EdgeCollection#updateByExample}.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryUpdateByExampleResult = {\n /**\n * Number of documents updated.\n */\n updated: number;\n};\n\n/**\n * Result of removing documents by keys.\n *\n * See {@link DocumentCollection#removeByKeys} and {@link EdgeCollection#removeByKeys}.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n */\nexport type SimpleQueryRemoveByKeysResult<T extends Record<string, any> = any> =\n {\n /**\n * Number of documents removed.\n */\n removed: number;\n /**\n * Number of documents not removed.\n */\n ignored: number;\n /**\n * Documents that have been removed.\n */\n old?: DocumentMetadata[] | Document<T>[];\n };\n\n// Collections\n\n/**\n * Represents an document collection in a {@link database.Database}.\n *\n * See {@link EdgeCollection} for a variant of this interface more suited for\n * edge collections.\n *\n * When using TypeScript, collections can be cast to a specific document data\n * type to increase type safety.\n *\n * @param T - Type to use for document data. Defaults to `any`.\n *\n * @example\n * ```ts\n * interface Person {\n * name: string;\n * }\n * const db = new Database();\n * const documents = db.collection(\"persons\") as DocumentCollection<Person>;\n * ```\n */\nexport interface DocumentCollection<T extends Record<string, any> = any>\n extends ArangoCollection {\n /**\n * Checks whether the collection exists.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const result = await collection.exists();\n * // result indicates whether the collection exists\n * ```\n */\n exists(): Promise<boolean>;\n /**\n * Retrieves general information about the collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const data = await collection.get();\n * // data contains general information about the collection\n * ```\n */\n get(): Promise<ArangoApiResponse<CollectionMetadata>>;\n /**\n * Creates a collection with the given `options` and the instance's name.\n *\n * See also {@link database.Database#createCollection} and\n * {@link database.Database#createEdgeCollection}.\n *\n * **Note**: When called on an {@link EdgeCollection} instance in TypeScript,\n * the `type` option must still be set to the correct {@link CollectionType}.\n * Otherwise this will result in the collection being created with the\n * default type (i.e. as a document collection).\n *\n * @param options - Options for creating the collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"potatoes\");\n * await collection.create();\n * // the document collection \"potatoes\" now exists\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * await collection.create({ type: CollectionType.EDGE_COLLECTION });\n * // the edge collection \"friends\" now exists\n * ```\n *\n * @example\n * ```ts\n * interface Friend {\n * startDate: number;\n * endDate?: number;\n * }\n * const db = new Database();\n * const collection = db.collection(\"friends\") as EdgeCollection<Friend>;\n * // even in TypeScript you still need to indicate the collection type\n * // if you want to create an edge collection\n * await collection.create({ type: CollectionType.EDGE_COLLECTION });\n * // the edge collection \"friends\" now exists\n * ```\n */\n create(\n options?: CreateCollectionOptions & {\n type?: CollectionType;\n }\n ): Promise<ArangoApiResponse<CollectionMetadata & CollectionProperties>>;\n /**\n * Retrieves the collection's properties.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const data = await collection.properties();\n * // data contains the collection's properties\n * ```\n */\n properties(): Promise<\n ArangoApiResponse<CollectionMetadata & CollectionProperties>\n >;\n /**\n * Replaces the properties of the collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const result = await collection.setProperties({ waitForSync: true });\n * // the collection will now wait for data being written to disk\n * // whenever a document is changed\n * ```\n */\n properties(\n properties: CollectionPropertiesOptions\n ): Promise<ArangoApiResponse<CollectionMetadata & CollectionProperties>>;\n /**\n * Retrieves information about the number of documents in a collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const data = await collection.count();\n * // data contains the collection's count\n * ```\n */\n count(): Promise<\n ArangoApiResponse<\n CollectionMetadata & CollectionProperties & { count: number }\n >\n >;\n /**\n * (RocksDB only.) Instructs ArangoDB to recalculate the collection's\n * document count to fix any inconsistencies.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"inconsistent-collection\");\n * const badData = await collection.count();\n * // oh no, the collection count looks wrong -- fix it!\n * await collection.recalculateCount();\n * const goodData = await collection.count();\n * // goodData contains the collection's improved count\n * ```\n */\n recalculateCount(): Promise<boolean>;\n /**\n * Retrieves statistics for a collection.\n *\n * @param details - whether to return extended storage engine-specific details\n * to the figures, which may cause additional load and impact performance\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const data = await collection.figures();\n * // data contains the collection's figures\n * ```\n */\n figures(\n details?: boolean\n ): Promise<\n ArangoApiResponse<\n CollectionMetadata &\n CollectionProperties & { count: number; figures: Record<string, any> }\n >\n >;\n /**\n * Retrieves the collection revision ID.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const data = await collection.revision();\n * // data contains the collection's revision\n * ```\n */\n revision(): Promise<\n ArangoApiResponse<\n CollectionMetadata & CollectionProperties & { revision: string }\n >\n >;\n /**\n * Retrieves the collection checksum.\n *\n * @param options - Options for retrieving the checksum.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const data = await collection.checksum();\n * // data contains the collection's checksum\n * ```\n */\n checksum(\n options?: CollectionChecksumOptions\n ): Promise<\n ArangoApiResponse<\n CollectionMetadata & { revision: string; checksum: string }\n >\n >;\n /**\n * (RocksDB only.) Instructs ArangoDB to load as many indexes of the\n * collection into memory as permitted by the memory limit.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"indexed-collection\");\n * await collection.loadIndexes();\n * // the indexes are now loaded into memory\n * ```\n */\n loadIndexes(): Promise<boolean>;\n /**\n * Renames the collection and updates the instance's `name` to `newName`.\n *\n * Additionally removes the instance from the {@link database.Database}'s internal\n * cache.\n *\n * **Note**: Renaming collections may not be supported when ArangoDB is\n * running in a cluster configuration.\n *\n * @param newName - The new name of the collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection1 = db.collection(\"some-collection\");\n * await collection1.rename(\"other-collection\");\n * const collection2 = db.collection(\"some-collection\");\n * const collection3 = db.collection(\"other-collection\");\n * // Note all three collection instances are different objects but\n * // collection1 and collection3 represent the same ArangoDB collection!\n * ```\n */\n rename(newName: string): Promise<ArangoApiResponse<CollectionMetadata>>;\n /**\n * Deletes all documents in the collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.truncate();\n * // millions of documents cry out in terror and are suddenly silenced,\n * // the collection \"some-collection\" is now empty\n * ```\n */\n truncate(): Promise<ArangoApiResponse<CollectionMetadata>>;\n /**\n * Deletes the collection from the database.\n *\n * @param options - Options for dropping the collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.drop();\n * // The collection \"some-collection\" is now an ex-collection\n * ```\n */\n drop(\n options?: CollectionDropOptions\n ): Promise<ArangoApiResponse<Record<string, never>>>;\n\n //#region crud\n /**\n * Retrieves the `shardId` of the shard responsible for the given document.\n *\n * @param document - Document in the collection to look up the `shardId` of.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const responsibleShard = await collection.getResponsibleShard();\n * ```\n */\n getResponsibleShard(document: Partial<Document<T>>): Promise<string>;\n /**\n * Derives a document `_id` from the given selector for this collection.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const meta = await collection.save({ foo: \"bar\" }, { returnNew: true });\n * const doc = meta.new;\n * console.log(collection.documentId(meta)); // via meta._id\n * console.log(collection.documentId(doc)); // via doc._id\n * console.log(collection.documentId(meta._key)); // also works\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection1 = db.collection(\"some-collection\");\n * const collection2 = db.collection(\"other-collection\");\n * const meta = await collection1.save({ foo: \"bar\" });\n * // Mixing collections is usually a mistake\n * console.log(collection1.documentId(meta)); // ok: same collection\n * console.log(collection2.documentId(meta)); // throws: wrong collection\n * console.log(collection2.documentId(meta._id)); // also throws\n * console.log(collection2.documentId(meta._key)); // ok but wrong collection\n * ```\n */\n documentId(selector: DocumentSelector): string;\n /**\n * Checks whether a document matching the given key or id exists in this\n * collection.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const exists = await collection.documentExists(\"abc123\");\n * if (!exists) {\n * console.log(\"Document does not exist\");\n * }\n * ```\n */\n documentExists(\n selector: DocumentSelector,\n options?: DocumentExistsOptions\n ): Promise<boolean>;\n /**\n * Retrieves the document matching the given key or id.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param options - Options for retrieving the document.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * try {\n * const document = await collection.document(\"abc123\");\n * console.log(document);\n * } catch (e: any) {\n * console.error(\"Could not find document\");\n * }\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const document = await collection.document(\"abc123\", { graceful: true });\n * if (document) {\n * console.log(document);\n * } else {\n * console.error(\"Could not find document\");\n * }\n * ```\n */\n document(\n selector: DocumentSelector,\n options?: CollectionReadOptions\n ): Promise<Document<T>>;\n /**\n * Retrieves the document matching the given key or id.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param graceful - If set to `true`, `null` is returned instead of an\n * exception being thrown if the document does not exist.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * try {\n * const document = await collection.document(\"abc123\", false);\n * console.log(document);\n * } catch (e: any) {\n * console.error(\"Could not find document\");\n * }\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const document = await collection.document(\"abc123\", true);\n * if (document) {\n * console.log(document);\n * } else {\n * console.error(\"Could not find document\");\n * }\n * ```\n */\n document(selector: DocumentSelector, graceful: boolean): Promise<Document<T>>;\n /**\n * Retrieves the documents matching the given key or id values.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection, or if the document does not exist.\n *\n * @param selectors - Array of document `_key`, `_id` or objects with either\n * of those properties (e.g. a document from this collection).\n * @param options - Options for retrieving the documents.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * try {\n * const documents = await collection.documents([\"abc123\", \"xyz456\"]);\n * console.log(documents);\n * } catch (e: any) {\n * console.error(\"Could not find document\");\n * }\n * ```\n */\n documents(\n selectors: (string | ObjectWithKey)[],\n options?: CollectionBatchReadOptions\n ): Promise<Document<T>[]>;\n /**\n * Inserts a new document with the given `data` into the collection.\n *\n * @param data - The contents of the new document.\n * @param options - Options for inserting the document.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const result = await collection.save(\n * { _key: \"a\", color: \"blue\", count: 1 },\n * { returnNew: true }\n * );\n * console.log(result.new.color, result.new.count); // \"blue\" 1\n * ```\n */\n save(\n data: DocumentData<T>,\n options?: CollectionInsertOptions\n ): Promise<DocumentMetadata & { new?: Document<T> }>;\n /**\n * Inserts new documents with the given `data` into the collection.\n *\n * @param data - The contents of the new documents.\n * @param options - Options for inserting the documents.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const result = await collection.saveAll(\n * [\n * { _key: \"a\", color: \"blue\", count: 1 },\n * { _key: \"b\", color: \"red\", count: 2 },\n * ],\n * { returnNew: true }\n * );\n * console.log(result[0].new.color, result[0].new.count); // \"blue\" 1\n * console.log(result[1].new.color, result[1].new.count); // \"red\" 2\n * ```\n */\n saveAll(\n data: Array<DocumentData<T>>,\n options?: CollectionInsertOptions\n ): Promise<Array<DocumentMetadata & { new?: Document<T> }>>;\n /**\n * Replaces an existing document in the collection.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param newData - The contents of the new document.\n * @param options - Options for replacing the document.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.save({ _key: \"a\", color: \"blue\", count: 1 });\n * const result = await collection.replace(\n * \"a\",\n * { color: \"red\" },\n * { returnNew: true }\n * );\n * console.log(result.new.color, result.new.count); // \"red\" undefined\n * ```\n */\n replace(\n selector: DocumentSelector,\n newData: DocumentData<T>,\n options?: CollectionReplaceOptions\n ): Promise<DocumentMetadata & { new?: Document<T>; old?: Document<T> }>;\n /**\n * Replaces existing documents in the collection, identified by the `_key` or\n * `_id` of each document.\n *\n * @param newData - The documents to replace.\n * @param options - Options for replacing the documents.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.save({ _key: \"a\", color: \"blue\", count: 1 });\n * await collection.save({ _key: \"b\", color: \"green\", count: 3 });\n * const result = await collection.replaceAll(\n * [\n * { _key: \"a\", color: \"red\" },\n * { _key: \"b\", color: \"yellow\", count: 2 }\n * ],\n * { returnNew: true }\n * );\n * console.log(result[0].new.color, result[0].new.count); // \"red\" undefined\n * console.log(result[1].new.color, result[1].new.count); // \"yellow\" 2\n * ```\n */\n replaceAll(\n newData: Array<DocumentData<T> & ({ _key: string } | { _id: string })>,\n options?: Omit<CollectionReplaceOptions, \"ifMatch\">\n ): Promise<\n Array<DocumentMetadata & { new?: Document<T>; old?: Document<T> }>\n >;\n /**\n * Updates an existing document in the collection.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param newData - The data for updating the document.\n * @param options - Options for updating the document.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.save({ _key: \"a\", color: \"blue\", count: 1 });\n * const result = await collection.update(\n * \"a\",\n * { count: 2 },\n * { returnNew: true }\n * );\n * console.log(result.new.color, result.new.count); // \"blue\" 2\n * ```\n */\n update(\n selector: DocumentSelector,\n newData: Patch<DocumentData<T>>,\n options?: CollectionUpdateOptions\n ): Promise<DocumentMetadata & { new?: Document<T>; old?: Document<T> }>;\n /**\n * Updates existing documents in the collection, identified by the `_key` or\n * `_id` of each document.\n *\n * @param newData - The data for updating the documents.\n * @param options - Options for updating the documents.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.save({ _key: \"a\", color: \"blue\", count: 1 });\n * await collection.save({ _key: \"b\", color: \"green\", count: 3 });\n * const result = await collection.updateAll(\n * [\n * { _key: \"a\", count: 2 },\n * { _key: \"b\", count: 4 }\n * ],\n * { returnNew: true }\n * );\n * console.log(result[0].new.color, result[0].new.count); // \"blue\" 2\n * console.log(result[1].new.color, result[1].new.count); // \"green\" 4\n * ```\n */\n updateAll(\n newData: Array<\n Patch<DocumentData<T>> & ({ _key: string } | { _id: string })\n >,\n options?: Omit<CollectionUpdateOptions, \"ifMatch\">\n ): Promise<\n Array<DocumentMetadata & { new?: Document<T>; old?: Document<T> }>\n >;\n /**\n * Removes an existing document from the collection.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param options - Options for removing the document.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.remove(\"abc123\");\n * // document with key \"abc123\" deleted\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const doc = await collection.document(\"abc123\");\n * await collection.remove(doc);\n * // document with key \"abc123\" deleted\n * ```\n */\n remove(\n selector: DocumentSelector,\n options?: CollectionRemoveOptions\n ): Promise<DocumentMetadata & { old?: Document<T> }>;\n /**\n * Removes existing documents from the collection.\n *\n * Throws an exception when passed any document or `_id` from a different\n * collection.\n *\n * @param selectors - Documents `_key`, `_id` or objects with either of those\n * properties (e.g. documents from this collection).\n * @param options - Options for removing the documents.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.removeAll([\"abc123\", \"def456\"]);\n * // document with keys \"abc123\" and \"def456\" deleted\n * ```\n */\n removeAll(\n selectors: (string | ObjectWithKey)[],\n options?: Omit<CollectionRemoveOptions, \"ifMatch\">\n ): Promise<Array<DocumentMetadata & { old?: Document<T> }>>;\n /**\n * Bulk imports the given `data` into the collection.\n *\n * @param data - The data to import, as an array of document data.\n * @param options - Options for importing the data.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.import(\n * [\n * { _key: \"jcd\", password: \"bionicman\" },\n * { _key: \"jreyes\", password: \"amigo\" },\n * { _key: \"ghermann\", password: \"zeitgeist\" }\n * ]\n * );\n * ```\n */\n import(\n data: DocumentData<T>[],\n options?: CollectionImportOptions\n ): Promise<CollectionImportResult>;\n /**\n * Bulk imports the given `data` into the collection.\n *\n * @param data - The data to import, as an array containing a single array of\n * attribute names followed by one or more arrays of attribute values for\n * each document.\n * @param options - Options for importing the data.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.import(\n * [\n * [ \"_key\", \"password\" ],\n * [ \"jcd\", \"bionicman\" ],\n * [ \"jreyes\", \"amigo\" ],\n * [ \"ghermann\", \"zeitgeist\" ]\n * ]\n * );\n * ```\n */\n import(\n data: any[][],\n options?: CollectionImportOptions\n ): Promise<CollectionImportResult>;\n /**\n * Bulk imports the given `data` into the collection.\n *\n * If `type` is omitted, `data` must contain one JSON array per line with\n * the first array providing the attribute names and all other arrays\n * providing attribute values for each document.\n *\n * If `type` is set to `\"documents\"`, `data` must contain one JSON document\n * per line.\n *\n * If `type` is set to `\"list\"`, `data` must contain a JSON array of\n * documents.\n *\n * If `type` is set to `\"auto\"`, `data` can be in either of the formats\n * supported by `\"documents\"` or `\"list\"`.\n *\n * @param data - The data to import as a Buffer (Node), Blob (browser) or\n * string.\n * @param options - Options for importing the data.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.import(\n * '{\"_key\":\"jcd\",\"password\":\"bionicman\"}\\r\\n' +\n * '{\"_key\":\"jreyes\",\"password\":\"amigo\"}\\r\\n' +\n * '{\"_key\":\"ghermann\",\"password\":\"zeitgeist\"}\\r\\n',\n * { type: \"documents\" } // or \"auto\"\n * );\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.import(\n * '[{\"_key\":\"jcd\",\"password\":\"bionicman\"},' +\n * '{\"_key\":\"jreyes\",\"password\":\"amigo\"},' +\n * '{\"_key\":\"ghermann\",\"password\":\"zeitgeist\"}]',\n * { type: \"list\" } // or \"auto\"\n * );\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.import(\n * '[\"_key\",\"password\"]\\r\\n' +\n * '[\"jcd\",\"bionicman\"]\\r\\n' +\n * '[\"jreyes\",\"amigo\"]\\r\\n' +\n * '[\"ghermann\",\"zeitgeist\"]\\r\\n'\n * );\n * ```\n */\n import(\n data: Buffer | Blob | string,\n options?: CollectionImportOptions & {\n type?: \"documents\" | \"list\" | \"auto\";\n }\n ): Promise<CollectionImportResult>;\n //#endregion\n\n //#region simple queries\n\n /**\n * Retrieves a list of references for all documents in the collection.\n *\n * @param type - The type of document reference to retrieve.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const ids = await collection.list(\"id\");\n * const ids = await db.query(aql`\n * FOR doc IN ${collection}\n * RETURN doc._id\n * `);\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const keys = await collection.list(\"key\");\n * const keys = await db.query(aql`\n * FOR doc IN ${collection}\n * RETURN doc._key\n * `);\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const paths = await collection.list(\"path\");\n * const paths = await db.query(aql`\n * FOR doc IN ${collection}\n * RETURN CONCAT(\"/_db/\", CURRENT_DATABASE(), \"/_api/document/\", doc._id)\n * `);\n * ```\n */\n list(type?: SimpleQueryListType): Promise<ArrayCursor<string>>;\n\n /**\n * Retrieves all documents in the collection.\n *\n * @param options - Options for retrieving the documents.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const cursor = await collection.all();\n * const cursor = await db.query(aql`\n * FOR doc IN ${collection}\n * RETURN doc\n * `);\n * ```\n */\n all(options?: SimpleQueryAllOptions): Promise<ArrayCursor<Document<T>>>;\n\n /**\n * Retrieves a random document from the collection.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const doc = await collection.any();\n * const cursor = await db.query(aql`\n * FOR doc IN ${collection}\n * SORT RAND()\n * LIMIT 1\n * RETURN doc\n * `);\n * const doc = await cursor.next();\n * ```\n */\n any(): Promise<Document<T>>;\n\n /**\n * Retrieves all documents in the collection matching the given example.\n *\n * @param example - An object representing an example for documents.\n * @param options - Options for retrieving the documents.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const cursor = await collection.byExample({ flavor: \"strawberry\" });\n * const cursor = await db.query(aql`\n * FOR doc IN ${collection}\n * FILTER doc.flavor == \"strawberry\"\n * RETURN doc\n * `);\n * ```\n */\n byExample(\n example: Partial<DocumentData<T>>,\n options?: SimpleQueryByExampleOptions\n ): Promise<ArrayCursor<Document<T>>>;\n\n /**\n * Retrieves a single document in the collection matching the given example.\n *\n * @param example - An object representing an example for the document.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const doc = await collection.firstExample({ flavor: \"strawberry\" });\n * const cursor = await db.query(aql`\n * FOR doc IN ${collection}\n * FILTER doc.flavor == \"strawberry\"\n * LIMIT 1\n * RETURN doc\n * `);\n * const doc = await cursor.next();\n * ```\n */\n firstExample(example: Partial<DocumentData<T>>): Promise<Document<T>>;\n\n /**\n * Removes all documents in the collection matching the given example.\n *\n * @param example - An object representing an example for the document.\n * @param options - Options for removing the documents.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const { deleted } = await collection.removeByExample({\n * // flavor: \"strawberry\"\n * // });\n * const cursor = await db.query(aql`\n * RETURN LENGTH(\n * FOR doc IN ${collection}\n * FILTER doc.flavor == \"strawberry\"\n * REMOVE doc IN ${collection}\n * RETURN 1\n * )\n * `);\n * const deleted = await cursor.next();\n * ```\n */\n removeByExample(\n example: Partial<DocumentData<T>>,\n options?: SimpleQueryRemoveByExampleOptions\n ): Promise<ArangoApiResponse<SimpleQueryRemoveByExampleResult>>;\n\n /**\n * Replaces all documents in the collection matching the given example.\n *\n * @param example - An object representing an example for the documents.\n * @param newValue - Document data to replace the matching documents with.\n * @param options - Options for replacing the documents.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const newValue = { flavor: \"chocolate\" };\n * // const { replaced } = await collection.replaceByExample(\n * // { flavor: \"strawberry\" },\n * // newValue\n * // );\n * const cursor = await db.query(aql`\n * RETURN LENGTH(\n * FOR doc IN ${collection}\n * FILTER doc.flavor == \"strawberry\"\n * REPLACE doc WITH ${newValue} IN ${collection}\n * RETURN 1\n * )\n * `);\n * const replaced = await cursor.next();\n * ```\n */\n replaceByExample(\n example: Partial<DocumentData<T>>,\n newValue: DocumentData<T>,\n options?: SimpleQueryReplaceByExampleOptions\n ): Promise<ArangoApiResponse<SimpleQueryReplaceByExampleResult>>;\n\n /**\n * Updates all documents in the collection matching the given example.\n *\n * @param example - An object representing an example for the documents.\n * @param newValue - Document data to update the matching documents with.\n * @param options - Options for updating the documents.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const newData = { color: \"red\" };\n * // const { updated } = await collection.updateByExample(\n * // { flavor: \"strawberry\" },\n * // newValue\n * // );\n * const cursor = await db.query(aql`\n * RETURN LENGTH(\n * FOR doc IN ${collection}\n * FILTER doc.flavor == \"strawberry\"\n * UPDATE doc WITH ${newValue} IN ${collection}\n * RETURN 1\n * )\n * `);\n * const updated = await cursor.next();\n * ```\n */\n updateByExample(\n example: Partial<DocumentData<T>>,\n newValue: Patch<DocumentData<T>>,\n options?: SimpleQueryUpdateByExampleOptions\n ): Promise<ArangoApiResponse<SimpleQueryUpdateByExampleResult>>;\n\n /**\n * Retrieves all documents matching the given document keys.\n *\n * @param keys - An array of document keys to look up.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const keys = [\"a\", \"b\", \"c\"];\n * // const docs = await collection.byKeys(keys);\n * const cursor = await db.query(aql`\n * FOR key IN ${keys}\n * LET doc = DOCUMENT(${collection}, key)\n * RETURN doc\n * `);\n * const docs = await cursor.all();\n * ```\n */\n lookupByKeys(keys: string[]): Promise<Document<T>[]>;\n\n /**\n * Removes all documents matching the given document keys.\n *\n * @param keys - An array of document keys to remove.\n * @param options - Options for removing the documents.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const keys = [\"a\", \"b\", \"c\"];\n * // const { removed, ignored } = await collection.removeByKeys(keys);\n * const cursor = await db.query(aql`\n * FOR key IN ${keys}\n * LET doc = DOCUMENT(${collection}, key)\n * FILTER doc\n * REMOVE doc IN ${collection}\n * RETURN key\n * `);\n * const removed = await cursor.all();\n * const ignored = keys.filter((key) => !removed.includes(key));\n * ```\n */\n removeByKeys(\n keys: string[],\n options?: SimpleQueryRemoveByKeysOptions\n ): Promise<ArangoApiResponse<SimpleQueryRemoveByKeysResult<T>>>;\n\n /**\n * Performs a fulltext query in the given `attribute` on the collection.\n *\n * @param attribute - Name of the field to search.\n * @param query - Fulltext query string to search for.\n * @param options - Options for performing the fulltext query.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const cursor = await collection.fulltext(\"article\", \"needle\");\n * const cursor = await db.query(aql`\n * FOR doc IN FULLTEXT(${collection}, \"article\", \"needle\")\n * RETURN doc\n * `);\n * ```\n */\n fulltext(\n attribute: string,\n query: string,\n options?: SimpleQueryFulltextOptions\n ): Promise<ArrayCursor<Document<T>>>;\n //#endregion\n\n //#region indexes\n /**\n * Returns a list of all index descriptions for the collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const indexes = await collection.indexes();\n * ```\n */\n indexes(): Promise<Index[]>;\n /**\n * Returns an index description by name or `id` if it exists.\n *\n * @param selector - Index name, id or object with either property.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const index = await collection.index(\"some-index\");\n * ```\n */\n index(selector: IndexSelector): Promise<Index>;\n /**\n * Creates a persistent index on the collection if it does not already exist.\n *\n * @param details - Options for creating the persistent index.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // Create a unique index for looking up documents by username\n * await collection.ensureIndex({\n * type: \"persistent\",\n * fields: [\"username\"],\n * name: \"unique-usernames\",\n * unique: true\n * });\n * ```\n */\n ensureIndex(\n details: EnsurePersistentIndexOptions\n ): Promise<ArangoApiResponse<PersistentIndex & { isNewlyCreated: boolean }>>;\n /**\n * Creates a TTL index on the collection if it does not already exist.\n *\n * @param details - Options for creating the TTL index.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // Expire documents with \"createdAt\" timestamp one day after creation\n * await collection.ensureIndex({\n * type: \"ttl\",\n * fields: [\"createdAt\"],\n * expireAfter: 60 * 60 * 24 // 24 hours\n * });\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // Expire documents with \"expiresAt\" timestamp according to their value\n * await collection.ensureIndex({\n * type: \"ttl\",\n * fields: [\"expiresAt\"],\n * expireAfter: 0 // when attribute value is exceeded\n * });\n * ```\n */\n ensureIndex(\n details: EnsureTtlIndexOptions\n ): Promise<ArangoApiResponse<TtlIndex & { isNewlyCreated: boolean }>>;\n /**\n * Creates a multi-dimensional index on the collection if it does not already exist.\n *\n * @param details - Options for creating the multi-dimensional index.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-points\");\n * // Create a multi-dimensional index for the attributes x, y and z\n * await collection.ensureIndex({\n * type: \"zkd\",\n * fields: [\"x\", \"y\", \"z\"],\n * fieldValueTypes: \"double\"\n * });\n * ```\n * ```\n */\n ensureIndex(\n details: EnsureZkdIndexOptions\n ): Promise<ArangoApiResponse<ZkdIndex & { isNewlyCreated: boolean }>>;\n /**\n * Creates a fulltext index on the collection if it does not already exist.\n *\n * @param details - Options for creating the fulltext index.\n *\n * @deprecated Fulltext indexes have been deprecated in ArangoDB 3.10 and\n * should be replaced with ArangoSearch.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // Create a fulltext index for tokens longer than or equal to 3 characters\n * await collection.ensureIndex({\n * type: \"fulltext\",\n * fields: [\"description\"],\n * minLength: 3\n * });\n * ```\n */\n ensureIndex(\n details: EnsureFulltextIndexOptions\n ): Promise<ArangoApiResponse<FulltextIndex & { isNewlyCreated: boolean }>>;\n /**\n * Creates a geo index on the collection if it does not already exist.\n *\n * @param details - Options for creating the geo index.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // Create an index for GeoJSON data\n * await collection.ensureIndex({\n * type: \"geo\",\n * fields: [\"lngLat\"],\n * geoJson: true\n * });\n * ```\n */\n ensureIndex(\n details: EnsureGeoIndexOptions\n ): Promise<ArangoApiResponse<GeoIndex & { isNewlyCreated: boolean }>>;\n /**\n * Creates a inverted index on the collection if it does not already exist.\n *\n * @param details - Options for creating the inverted index.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // Create an inverted index\n * await collection.ensureIndex({\n * type: \"inverted\",\n * fields: [\"a\", { name: \"b\", analyzer: \"text_en\" }]\n * });\n * ```\n */\n ensureIndex(\n details: EnsureInvertedIndexOptions\n ): Promise<ArangoApiResponse<InvertedIndex & { isNewlyCreated: boolean }>>;\n /**\n * Deletes the index with the given name or `id` from the database.\n *\n * @param selector - Index name, id or object with either property.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.dropIndex(\"some-index\");\n * // The index \"some-index\" no longer exists\n * ```\n */\n dropIndex(\n selector: IndexSelector\n ): Promise<ArangoApiResponse<{ id: string }>>;\n /**\n * Triggers compaction for a collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.compact();\n * // Background compaction is triggered on the collection\n * ```\n */\n compact(): Promise<ArangoApiResponse<Record<string, never>>>;\n //#endregion\n}\n\n/**\n * Represents an edge collection in a {@link database.Database}.\n *\n * See {@link DocumentCollection} for a more generic variant of this interface\n * more suited for regular document collections.\n *\n * See also {@link graph.GraphEdgeCollection} for the type representing an edge\n * collection in a {@link graph.Graph}.\n *\n * When using TypeScript, collections can be cast to a specific edge document\n * data type to increase type safety.\n *\n * @param T - Type to use for edge document data. Defaults to `any`.\n *\n * @example\n * ```ts\n * interface Friend {\n * startDate: number;\n * endDate?: number;\n * }\n * const db = new Database();\n * const edges = db.collection(\"friends\") as EdgeCollection<Friend>;\n * ```\n */\nexport interface EdgeCollection<T extends Record<string, any> = any>\n extends DocumentCollection<T> {\n /**\n * Retrieves the document matching the given key or id.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection, or if the document does not exist.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param options - Options for retrieving the document.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * try {\n * const document = await collection.document(\"abc123\");\n * console.log(document);\n * } catch (e: any) {\n * console.error(\"Could not find document\");\n * }\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const document = await collection.document(\"abc123\", { graceful: true });\n * if (document) {\n * console.log(document);\n * } else {\n * console.error(\"Document does not exist\");\n * }\n * ```\n */\n document(\n selector: DocumentSelector,\n options?: CollectionReadOptions\n ): Promise<Edge<T>>;\n /**\n * Retrieves the document matching the given key or id.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection, or if the document does not exist.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param graceful - If set to `true`, `null` is returned instead of an\n * exception being thrown if the document does not exist.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * try {\n * const document = await collection.document(\"abc123\", false);\n * console.log(document);\n * } catch (e: any) {\n * console.error(\"Could not find document\");\n * }\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const document = await collection.document(\"abc123\", true);\n * if (document) {\n * console.log(document);\n * } else {\n * console.error(\"Document does not exist\");\n * }\n * ```\n */\n document(selector: DocumentSelector, graceful: boolean): Promise<Edge<T>>;\n /**\n * Retrieves the documents matching the given key or id values.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection, or if the document does not exist.\n *\n * @param selectors - Array of document `_key`, `_id` or objects with either\n * of those properties (e.g. a document from this collection).\n * @param options - Options for retrieving the documents.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * try {\n * const documents = await collection.documents([\"abc123\", \"xyz456\"]);\n * console.log(documents);\n * } catch (e: any) {\n * console.error(\"Could not find document\");\n * }\n * ```\n */\n documents(\n selectors: (string | ObjectWithKey)[],\n options?: CollectionBatchReadOptions\n ): Promise<Edge<T>[]>;\n /**\n * Inserts a new document with the given `data` into the collection.\n *\n * @param data - The contents of the new document.\n * @param options - Options for inserting the document.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * const result = await collection.save(\n * { _from: \"users/rana\", _to: \"users/mudasir\", active: false },\n * { returnNew: true }\n * );\n * ```\n */\n save(\n data: EdgeData<T>,\n options?: CollectionInsertOptions\n ): Promise<DocumentMetadata & { new?: Edge<T> }>;\n /**\n * Inserts new documents with the given `data` into the collection.\n *\n * @param data - The contents of the new documents.\n * @param options - Options for inserting the documents.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * const result = await collection.saveAll(\n * [\n * { _from: \"users/rana\", _to: \"users/mudasir\", active: false },\n * { _from: \"users/rana\", _to: \"users/salman\", active: true }\n * ],\n * { returnNew: true }\n * );\n * ```\n */\n saveAll(\n data: Array<EdgeData<T>>,\n options?: CollectionInsertOptions\n ): Promise<Array<DocumentMetadata & { new?: Edge<T> }>>;\n /**\n * Replaces an existing document in the collection.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param newData - The contents of the new document.\n * @param options - Options for replacing the document.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * await collection.save(\n * {\n * _key: \"musadir\",\n * _from: \"users/rana\",\n * _to: \"users/mudasir\",\n * active: true,\n * best: true\n * }\n * );\n * const result = await collection.replace(\n * \"musadir\",\n * { active: false },\n * { returnNew: true }\n * );\n * console.log(result.new.active, result.new.best); // false undefined\n * ```\n */\n replace(\n selector: DocumentSelector,\n newData: DocumentData<T>,\n options?: CollectionReplaceOptions\n ): Promise<DocumentMetadata & { new?: Edge<T>; old?: Edge<T> }>;\n /**\n * Replaces existing documents in the collection, identified by the `_key` or\n * `_id` of each document.\n *\n * @param newData - The documents to replace.\n * @param options - Options for replacing the documents.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * await collection.save(\n * {\n * _key: \"musadir\",\n * _from: \"users/rana\",\n * _to: \"users/mudasir\",\n * active: true,\n * best: true\n * }\n * );\n * await collection.save(\n * {\n * _key: \"salman\",\n * _from: \"users/rana\",\n * _to: \"users/salman\",\n * active: false,\n * best: false\n * }\n * );\n * const result = await collection.replaceAll(\n * [\n * { _key: \"musadir\", active: false },\n * { _key: \"salman\", active: true, best: true }\n * ],\n * { returnNew: true }\n * );\n * console.log(result[0].new.active, result[0].new.best); // false undefined\n * console.log(result[1].new.active, result[1].new.best); // true true\n * ```\n */\n replaceAll(\n newData: Array<DocumentData<T> & ({ _key: string } | { _id: string })>,\n options?: CollectionReplaceOptions\n ): Promise<Array<DocumentMetadata & { new?: Edge<T>; old?: Edge<T> }>>;\n /**\n * Updates an existing document in the collection.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param newData - The data for updating the document.\n * @param options - Options for updating the document.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * await collection.save(\n * {\n * _key: \"musadir\",\n * _from: \"users/rana\",\n * _to: \"users/mudasir\",\n * active: true,\n * best: true\n * }\n * );\n * const result = await collection.update(\n * \"musadir\",\n * { active: false },\n * { returnNew: true }\n * );\n * console.log(result.new.active, result.new.best); // false true\n * ```\n */\n update(\n selector: DocumentSelector,\n newData: Patch<DocumentData<T>>,\n options?: CollectionUpdateOptions\n ): Promise<DocumentMetadata & { new?: Edge<T>; old?: Edge<T> }>;\n /**\n * Updates existing documents in the collection, identified by the `_key` or\n * `_id` of each document.\n *\n * @param newData - The data for updating the documents.\n * @param options - Options for updating the documents.\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * await collection.save(\n * {\n * _key: \"musadir\",\n * _from: \"users/rana\",\n * _to: \"users/mudasir\",\n * active: true,\n * best: true\n * }\n * );\n * await collection.save(\n * {\n * _key: \"salman\",\n * _from: \"users/rana\",\n * _to: \"users/salman\",\n * active: false,\n * best: false\n * }\n * );\n * const result = await collection.updateAll(\n * [\n * { _key: \"musadir\", active: false },\n * { _key: \"salman\", active: true, best: true }\n * ],\n * { returnNew: true }\n * );\n * console.log(result[0].new.active, result[0].new.best); // false true\n * console.log(result[1].new.active, result[1].new.best); // true true\n * ```\n */\n updateAll(\n newData: Array<\n Patch<DocumentData<T>> & ({ _key: string } | { _id: string })\n >,\n options?: CollectionUpdateOptions\n ): Promise<Array<DocumentMetadata & { new?: Edge<T>; old?: Edge<T> }>>;\n /**\n * Removes an existing document from the collection.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param options - Options for removing the document.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * const doc = await collection.document(\"musadir\");\n * await collection.remove(doc);\n * // document with key \"musadir\" deleted\n * ```\n */\n remove(\n selector: DocumentSelector,\n options?: CollectionRemoveOptions\n ): Promise<DocumentMetadata & { old?: Edge<T> }>;\n /**\n * Removes existing documents from the collection.\n *\n * Throws an exception when passed any document or `_id` from a different\n * collection.\n *\n * @param selectors - Documents `_key`, `_id` or objects with either of those\n * properties (e.g. documents from this collection).\n * @param options - Options for removing the documents.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * await collection.removeAll([\"musadir\", \"salman\"]);\n * // document with keys \"musadir\" and \"salman\" deleted\n * ```\n */\n removeAll(\n selectors: DocumentSelector[],\n options?: CollectionRemoveOptions\n ): Promise<Array<DocumentMetadata & { old?: Edge<T> }>>;\n /**\n * Bulk imports the given `data` into the collection.\n *\n * @param data - The data to import, as an array of edge data.\n * @param options - Options for importing the data.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.import(\n * [\n * { _key: \"x\", _from: \"vertices/a\", _to: \"vertices/b\", weight: 1 },\n * { _key: \"y\", _from: \"vertices/a\", _to: \"vertices/c\", weight: 2 }\n * ]\n * );\n * ```\n */\n import(\n data: EdgeData<T>[],\n options?: CollectionImportOptions\n ): Promise<CollectionImportResult>;\n /**\n * Bulk imports the given `data` into the collection.\n *\n * @param data - The data to import, as an array containing a single array of\n * attribute names followed by one or more arrays of attribute values for\n * each edge document.\n * @param options - Options for importing the data.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.import(\n * [\n * [ \"_key\", \"_from\", \"_to\", \"weight\" ],\n * [ \"x\", \"vertices/a\", \"vertices/b\", 1 ],\n * [ \"y\", \"vertices/a\", \"vertices/c\", 2 ]\n * ]\n * );\n * ```\n */\n import(\n data: any[][],\n options?: CollectionImportOptions\n ): Promise<CollectionImportResult>;\n /**\n * Bulk imports the given `data` into the collection.\n *\n * If `type` is omitted, `data` must contain one JSON array per line with\n * the first array providing the attribute names and all other arrays\n * providing attribute values for each edge document.\n *\n * If `type` is set to `\"documents\"`, `data` must contain one JSON document\n * per line.\n *\n * If `type` is set to `\"list\"`, `data` must contain a JSON array of\n * edge documents.\n *\n * If `type` is set to `\"auto\"`, `data` can be in either of the formats\n * supported by `\"documents\"` or `\"list\"`.\n *\n * @param data - The data to import as a Buffer (Node), Blob (browser) or\n * string.\n * @param options - Options for importing the data.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.import(\n * '{\"_key\":\"x\",\"_from\":\"vertices/a\",\"_to\":\"vertices/b\",\"weight\":1}\\r\\n' +\n * '{\"_key\":\"y\",\"_from\":\"vertices/a\",\"_to\":\"vertices/c\",\"weight\":2}\\r\\n',\n * { type: \"documents\" } // or \"auto\"\n * );\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.import(\n * '[{\"_key\":\"x\",\"_from\":\"vertices/a\",\"_to\":\"vertices/b\",\"weight\":1},' +\n * '{\"_key\":\"y\",\"_from\":\"vertices/a\",\"_to\":\"vertices/c\",\"weight\":2}]',\n * { type: \"list\" } // or \"auto\"\n * );\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * await collection.import(\n * '[\"_key\",\"_from\",\"_to\",\"weight\"]\\r\\n' +\n * '[\"x\",\"vertices/a\",\"vertices/b\",1]\\r\\n' +\n * '[\"y\",\"vertices/a\",\"vertices/c\",2]\\r\\n'\n * );\n * ```\n */\n import(\n data: Buffer | Blob | string,\n options?: CollectionImportOptions & {\n type?: \"documents\" | \"list\" | \"auto\";\n }\n ): Promise<CollectionImportResult>;\n //#endregion\n\n //#region simple queries\n\n /**\n * Retrieves all documents in the collection.\n *\n * @param options - Options for retrieving the documents.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const cursor = await collection.all();\n * const cursor = await db.query(aql`\n * FOR doc IN ${collection}\n * RETURN doc\n * `);\n * ```\n */\n all(options?: SimpleQueryAllOptions): Promise<ArrayCursor<Edge<T>>>;\n\n /**\n * Retrieves a random document from the collection.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const doc = await collection.any();\n * const cursor = await db.query(aql`\n * FOR doc IN ${collection}\n * SORT RAND()\n * LIMIT 1\n * RETURN doc\n * `);\n * const doc = await cursor.next();\n * ```\n */\n any(): Promise<Edge<T>>;\n\n /**\n * Retrieves all documents in the collection matching the given example.\n *\n * @param example - An object representing an example for documents.\n * @param options - Options for retrieving the documents.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const cursor = await collection.byExample({ flavor: \"strawberry\" });\n * const cursor = await db.query(aql`\n * FOR doc IN ${collection}\n * FILTER doc.flavor == \"strawberry\"\n * RETURN doc\n * `);\n * ```\n */\n byExample(\n example: Partial<DocumentData<T>>,\n options?: SimpleQueryByExampleOptions\n ): Promise<ArrayCursor<Edge<T>>>;\n\n /**\n * Retrieves a single document in the collection matching the given example.\n *\n * @param example - An object representing an example for the document.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const doc = await collection.firstExample({ flavor: \"strawberry\" });\n * const cursor = await db.query(aql`\n * FOR doc IN ${collection}\n * FILTER doc.flavor == \"strawberry\"\n * LIMIT 1\n * RETURN doc\n * `);\n * const doc = await cursor.next();\n * ```\n */\n firstExample(example: Partial<DocumentData<T>>): Promise<Edge<T>>;\n\n /**\n * Retrieves all documents matching the given document keys.\n *\n * @param keys - An array of document keys to look up.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const keys = [\"a\", \"b\", \"c\"];\n * // const docs = await collection.byKeys(keys);\n * const cursor = await db.query(aql`\n * FOR key IN ${keys}\n * LET doc = DOCUMENT(${collection}, key)\n * RETURN doc\n * `);\n * const docs = await cursor.all();\n * ```\n */\n lookupByKeys(keys: string[]): Promise<Edge<T>[]>;\n\n /**\n * Performs a fulltext query in the given `attribute` on the collection.\n *\n * @param attribute - Name of the field to search.\n * @param query - Fulltext query string to search for.\n * @param options - Options for performing the fulltext query.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * // const cursor = await collection.fulltext(\"article\", \"needle\");\n * const cursor = await db.query(aql`\n * FOR doc IN FULLTEXT(${collection}, \"article\", \"needle\")\n * RETURN doc\n * `);\n * ```\n */\n fulltext(\n attribute: string,\n query: string,\n options?: SimpleQueryFulltextOptions\n ): Promise<ArrayCursor<Edge<T>>>;\n //#endregion\n\n //#region edges\n /**\n * Retrieves a list of all edges of the document matching the given\n * `selector`.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param options - Options for retrieving the edges.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"edges\");\n * await collection.import([\n * [\"_key\", \"_from\", \"_to\"],\n * [\"x\", \"vertices/a\", \"vertices/b\"],\n * [\"y\", \"vertices/a\", \"vertices/c\"],\n * [\"z\", \"vertices/d\", \"vertices/a\"],\n * ]);\n * const edges = await collection.edges(\"vertices/a\");\n * console.log(edges.map((edge) => edge._key)); // [\"x\", \"y\", \"z\"]\n * ```\n */\n edges(\n selector: DocumentSelector,\n options: CollectionEdgesOptions\n ): Promise<ArangoApiResponse<CollectionEdgesResult<T>>>;\n /**\n * Retrieves a list of all incoming edges of the document matching the given\n * `selector`.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param options - Options for retrieving the edges.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"edges\");\n * await collection.import([\n * [\"_key\", \"_from\", \"_to\"],\n * [\"x\", \"vertices/a\", \"vertices/b\"],\n * [\"y\", \"vertices/a\", \"vertices/c\"],\n * [\"z\", \"vertices/d\", \"vertices/a\"],\n * ]);\n * const edges = await collection.inEdges(\"vertices/a\");\n * console.log(edges.map((edge) => edge._key)); // [\"z\"]\n * ```\n */\n inEdges(\n selector: DocumentSelector,\n options: CollectionEdgesOptions\n ): Promise<ArangoApiResponse<CollectionEdgesResult<T>>>;\n /**\n * Retrieves a list of all outgoing edges of the document matching the given\n * `selector`.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param options - Options for retrieving the edges.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"edges\");\n * await collection.import([\n * [\"_key\", \"_from\", \"_to\"],\n * [\"x\", \"vertices/a\", \"vertices/b\"],\n * [\"y\", \"vertices/a\", \"vertices/c\"],\n * [\"z\", \"vertices/d\", \"vertices/a\"],\n * ]);\n * const edges = await collection.outEdges(\"vertices/a\");\n * console.log(edges.map((edge) => edge._key)); // [\"x\", \"y\"]\n * ```\n */\n outEdges(\n selector: DocumentSelector,\n options: CollectionEdgesOptions\n ): Promise<ArangoApiResponse<CollectionEdgesResult<T>>>;\n\n /**\n * Performs a traversal starting from the given `startVertex` and following\n * edges contained in this edge collection.\n *\n * Throws an exception when passed a document or `_id` from a different\n * collection.\n *\n * See also {@link graph.Graph#traversal}.\n *\n * @param startVertex - Document `_key`, `_id` or object with either of those\n * properties (e.g. a document from this collection).\n * @param options - Options for performing the traversal.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"edges\");\n * await collection.import([\n * [\"_key\", \"_from\", \"_to\"],\n * [\"x\", \"vertices/a\", \"vertices/b\"],\n * [\"y\", \"vertices/b\", \"vertices/c\"],\n * [\"z\", \"vertices/c\", \"vertices/d\"],\n * ]);\n * const startVertex = \"vertices/a\";\n * const cursor = await db.query(aql`\n * FOR vertex IN OUTBOUND ${startVertex}\n * RETURN vertex._key\n * `);\n * const result = await cursor.all();\n * console.log(result); // [\"a\", \"b\", \"c\", \"d\"]\n * ```\n */\n traversal(\n startVertex: DocumentSelector,\n options?: TraversalOptions\n ): Promise<any>;\n //#endregion\n}\n\n/**\n * @internal\n */\nexport class Collection<T extends Record<string, any> = any>\n implements EdgeCollection<T>, DocumentCollection<T>\n{\n //#region attributes\n protected _name: string;\n protected _db: Database;\n //#endregion\n\n /**\n * @internal\n */\n constructor(db: Database, name: string) {\n this._name = name.normalize(\"NFC\");\n this._db = db;\n }\n\n //#region metadata\n get isArangoCollection(): true {\n return true;\n }\n\n get name() {\n return this._name;\n }\n\n get() {\n return this._db.request({\n path: `/_api/collection/${encodeURIComponent(this._name)}`,\n });\n }\n\n async exists() {\n try {\n await this.get();\n return true;\n } catch (err: any) {\n if (isArangoError(err) && err.errorNum === COLLECTION_NOT_FOUND) {\n return false;\n }\n throw err;\n }\n }\n\n create(\n options: CreateCollectionOptions & {\n type?: CollectionType;\n } = {}\n ) {\n const {\n waitForSyncReplication = undefined,\n enforceReplicationFactor = undefined,\n ...opts\n } = options;\n if (opts.computedValues) {\n opts.computedValues = opts.computedValues.map((computedValue) => {\n if (isAqlLiteral(computedValue.expression)) {\n return {\n ...computedValue,\n expression: computedValue.expression.toAQL(),\n };\n }\n if (isAqlQuery(computedValue.expression)) {\n return {\n ...computedValue,\n expression: computedValue.expression.query,\n };\n }\n return computedValue;\n });\n }\n const qs: Params = {};\n if (typeof waitForSyncReplication === \"boolean\") {\n qs.waitForSyncReplication = waitForSyncReplication ? 1 : 0;\n }\n if (typeof enforceReplicationFactor === \"boolean\") {\n qs.enforceReplicationFactor = enforceReplicationFactor ? 1 : 0;\n }\n return this._db.request({\n method: \"POST\",\n path: \"/_api/collection\",\n qs,\n body: {\n ...opts,\n name: this._name,\n },\n });\n }\n\n properties(\n properties?: CollectionPropertiesOptions\n ): Promise<ArangoApiResponse<CollectionMetadata & CollectionProperties>> {\n if (!properties) {\n return this._db.request({\n path: `/_api/collection/${encodeURIComponent(this._name)}/properties`,\n });\n }\n return this._db.request({\n method: \"PUT\",\n path: `/_api/collection/${encodeURIComponent(this._name)}/properties`,\n body: properties,\n });\n }\n\n count(): Promise<\n ArangoApiResponse<\n CollectionMetadata & CollectionProperties & { count: number }\n >\n > {\n return this._db.request({\n path: `/_api/collection/${encodeURIComponent(this._name)}/count`,\n });\n }\n\n async recalculateCount(): Promise<boolean> {\n return this._db.request(\n {\n method: \"PUT\",\n path: `/_api/collection/${encodeURIComponent(\n this._name\n )}/recalculateCount`,\n },\n (res) => res.body.result\n );\n }\n\n figures(\n details = false\n ): Promise<\n CollectionMetadata &\n ArangoApiResponse<\n CollectionProperties & { count: number; figures: Record<string, any> }\n >\n > {\n return this._db.request({\n path: `/_api/collection/${encodeURIComponent(this._name)}/figures`,\n qs: { details },\n });\n }\n\n revision(): Promise<\n ArangoApiResponse<\n CollectionMetadata & CollectionProperties & { revision: string }\n >\n > {\n return this._db.request({\n path: `/_api/collection/${encodeURIComponent(this._name)}/revision`,\n });\n }\n\n checksum(\n options?: CollectionChecksumOptions\n ): Promise<\n ArangoApiResponse<\n CollectionMetadata & { revision: string; checksum: string }\n >\n > {\n return this._db.request({\n path: `/_api/collection/${encodeURIComponent(this._name)}/checksum`,\n qs: options,\n });\n }\n\n async loadIndexes(): Promise<boolean> {\n return this._db.request(\n {\n method: \"PUT\",\n path: `/_api/collection/${encodeURIComponent(\n this._name\n )}/loadIndexesIntoMemory`,\n },\n (res) => res.body.result\n );\n }\n\n async rename(newName: string) {\n const result = await this._db.renameCollection(this._name, newName);\n this._name = newName.normalize(\"NFC\");\n return result;\n }\n\n truncate(): Promise<ArangoApiResponse<CollectionMetadata>> {\n return this._db.request({\n method: \"PUT\",\n path: `/_api/collection/${this._name}/truncate`,\n });\n }\n\n drop(options?: CollectionDropOptions) {\n return this._db.request({\n method: \"DELETE\",\n path: `/_api/collection/${encodeURIComponent(this._name)}`,\n qs: options,\n });\n }\n //#endregion\n\n //#region crud\n getResponsibleShard(document: Partial<Document<T>>): Promise<string> {\n return this._db.request(\n {\n method: \"PUT\",\n path: `/_api/collection/${encodeURIComponent(\n this._name\n )}/responsibleShard`,\n body: document,\n },\n (res) => res.body.shardId\n );\n }\n\n documentId(selector: DocumentSelector): string {\n return _documentHandle(selector, this._name);\n }\n\n async documentExists(\n selector: DocumentSelector,\n options: DocumentExistsOptions = {}\n ): Promise<boolean> {\n const { ifMatch = undefined, ifNoneMatch = undefined } = options;\n const headers = {} as Record<string, string>;\n if (ifMatch) headers[\"if-match\"] = ifMatch;\n if (ifNoneMatch) headers[\"if-none-match\"] = ifNoneMatch;\n try {\n return await this._db.request(\n {\n method: \"HEAD\",\n path: `/_api/document/${encodeURI(\n _documentHandle(selector, this._name)\n )}`,\n headers,\n },\n (res) => {\n if (ifNoneMatch && res.statusCode === 304) {\n throw new HttpError(res);\n }\n return true;\n }\n );\n } catch (err: any) {\n if (err.code === 404) {\n return false;\n }\n throw err;\n }\n }\n\n documents(\n selectors: (string | ObjectWithKey)[],\n options: CollectionBatchReadOptions = {}\n ) {\n const { allowDirtyRead = undefined } = options;\n return this._db.request({\n method: \"PUT\",\n path: `/_api/document/${encodeURIComponent(this._name)}`,\n qs: { onlyget: true },\n allowDirtyRead,\n body: selectors,\n });\n }\n\n async document(\n selector: DocumentSelector,\n options: boolean | CollectionReadOptions = {}\n ) {\n if (typeof options === \"boolean\") {\n options = { graceful: options };\n }\n const {\n allowDirtyRead = undefined,\n graceful = false,\n ifMatch = undefined,\n ifNoneMatch = undefined,\n } = options;\n const headers = {} as Record<string, string>;\n if (ifMatch) headers[\"if-match\"] = ifMatch;\n if (ifNoneMatch) headers[\"if-none-match\"] = ifNoneMatch;\n const result = this._db.request(\n {\n path: `/_api/document/${encodeURI(\n _documentHandle(selector, this._name)\n )}`,\n headers,\n allowDirtyRead,\n },\n (res) => {\n if (ifNoneMatch && res.statusCode === 304) {\n throw new HttpError(res);\n }\n return res.body;\n }\n );\n if (!graceful) return result;\n try {\n return await result;\n } catch (err: any) {\n if (isArangoError(err) && err.errorNum === DOCUMENT_NOT_FOUND) {\n return null;\n }\n throw err;\n }\n }\n\n save(data: DocumentData<T>, options?: CollectionInsertOptions) {\n return this._db.request(\n {\n method: \"POST\",\n path: `/_api/document/${encodeURIComponent(this._name)}`,\n body: data,\n qs: options,\n },\n (res) => (options?.silent ? undefined : res.body)\n );\n }\n\n saveAll(data: Array<DocumentData<T>>, options?: CollectionInsertOptions) {\n return this._db.request(\n {\n method: \"POST\",\n path: `/_api/document/${encodeURIComponent(this._name)}`,\n body: data,\n qs: options,\n },\n (res) => (options?.silent ? undefined : res.body)\n );\n }\n\n replace(\n selector: DocumentSelector,\n newData: DocumentData<T>,\n options: CollectionReplaceOptions = {}\n ) {\n const { ifMatch = undefined, ...opts } = options;\n const headers = {} as Record<string, string>;\n if (ifMatch) headers[\"if-match\"] = ifMatch;\n return this._db.request(\n {\n method: \"PUT\",\n path: `/_api/document/${encodeURI(\n _documentHandle(selector, this._name)\n )}`,\n headers,\n body: newData,\n qs: opts,\n },\n (res) => (options?.silent ? undefined : res.body)\n );\n }\n\n replaceAll(\n newData: Array<DocumentData<T> & ({ _key: string } | { _id: string })>,\n options?: CollectionReplaceOptions\n ) {\n return this._db.request(\n {\n method: \"PUT\",\n path: `/_api/document/${encodeURIComponent(this._name)}`,\n body: newData,\n qs: options,\n },\n (res) => (options?.silent ? undefined : res.body)\n );\n }\n\n update(\n selector: DocumentSelector,\n newData: Patch<DocumentData<T>>,\n options: CollectionUpdateOptions = {}\n ) {\n const { ifMatch = undefined, ...opts } = options;\n const headers = {} as Record<string, string>;\n if (ifMatch) headers[\"if-match\"] = ifMatch;\n return this._db.request(\n {\n method: \"PATCH\",\n path: `/_api/document/${encodeURI(\n _documentHandle(selector, this._name)\n )}`,\n headers,\n body: newData,\n qs: opts,\n },\n (res) => (options?.silent ? undefined : res.body)\n );\n }\n\n updateAll(\n newData: Array<\n Patch<DocumentData<T>> & ({ _key: string } | { _id: string })\n >,\n options?: CollectionUpdateOptions\n ) {\n return this._db.request(\n {\n method: \"PATCH\",\n path: `/_api/document/${encodeURIComponent(this._name)}`,\n body: newData,\n qs: options,\n },\n (res) => (options?.silent ? undefined : res.body)\n );\n }\n\n remove(selector: DocumentSelector, options: CollectionRemoveOptions = {}) {\n const { ifMatch = undefined, ...opts } = options;\n const headers = {} as Record<string, string>;\n if (ifMatch) headers[\"if-match\"] = ifMatch;\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/document/${encodeURI(\n _documentHandle(selector, this._name)\n )}`,\n headers,\n qs: opts,\n },\n (res) => (options?.silent ? undefined : res.body)\n );\n }\n\n removeAll(\n selectors: (string | ObjectWithKey)[],\n options?: CollectionRemoveOptions\n ) {\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/document/${encodeURIComponent(this._name)}`,\n body: selectors,\n qs: options,\n },\n (res) => (options?.silent ? undefined : res.body)\n );\n }\n\n import(\n data: Buffer | Blob | string | any[],\n options: CollectionImportOptions & {\n type?: \"documents\" | \"list\" | \"auto\";\n } = {}\n ): Promise<CollectionImportResult> {\n const qs = { ...options, collection: this._name };\n if (Array.isArray(data)) {\n qs.type = Array.isArray(data[0]) ? undefined : \"documents\";\n const lines = data as any[];\n data = lines.map((line) => JSON.stringify(line)).join(\"\\r\\n\") + \"\\r\\n\";\n }\n return this._db.request({\n method: \"POST\",\n path: \"/_api/import\",\n body: data,\n isBinary: true,\n qs,\n });\n }\n //#endregion\n\n //#region edges\n protected _edges(\n selector: DocumentSelector,\n options: CollectionEdgesOptions,\n direction?: \"in\" | \"out\"\n ) {\n const { allowDirtyRead = undefined } = options;\n return this._db.request({\n path: `/_api/edges/${encodeURIComponent(this._name)}`,\n allowDirtyRead,\n qs: {\n direction,\n vertex: _documentHandle(selector, this._name, false),\n },\n });\n }\n\n edges(vertex: DocumentSelector, options: CollectionEdgesOptions) {\n return this._edges(vertex, options);\n }\n\n inEdges(vertex: DocumentSelector, options: CollectionEdgesOptions) {\n return this._edges(vertex, options, \"in\");\n }\n\n outEdges(vertex: DocumentSelector, options: CollectionEdgesOptions) {\n return this._edges(vertex, options, \"out\");\n }\n\n traversal(startVertex: DocumentSelector, options?: TraversalOptions) {\n return this._db.request(\n {\n method: \"POST\",\n path: \"/_api/traversal\",\n body: {\n ...options,\n startVertex,\n edgeCollection: this._name,\n },\n },\n (res) => res.body.result\n );\n }\n //#endregion\n\n //#region simple queries\n list(type: SimpleQueryListType = \"id\") {\n return this._db.request(\n {\n method: \"PUT\",\n path: \"/_api/simple/all-keys\",\n body: { type, collection: this._name },\n },\n (res) =>\n new BatchedArrayCursor(this._db, res.body, res.arangojsHostUrl).items\n );\n }\n\n all(options?: SimpleQueryAllOptions) {\n return this._db.request(\n {\n method: \"PUT\",\n path: \"/_api/simple/all\",\n body: {\n ...options,\n collection: this._name,\n },\n },\n (res) =>\n new BatchedArrayCursor(this._db, res.body, res.arangojsHostUrl).items\n );\n }\n\n any() {\n return this._db.request(\n {\n method: \"PUT\",\n path: \"/_api/simple/any\",\n body: { collection: this._name },\n },\n (res) => res.body.document\n );\n }\n\n byExample(\n example: Partial<DocumentData<T>>,\n options?: SimpleQueryByExampleOptions\n ) {\n return this._db.request(\n {\n method: \"PUT\",\n path: \"/_api/simple/by-example\",\n body: {\n ...options,\n example,\n collection: this._name,\n },\n },\n (res) =>\n new BatchedArrayCursor(this._db, res.body, res.arangojsHostUrl).items\n );\n }\n\n firstExample(example: Partial<DocumentData<T>>) {\n return this._db.request(\n {\n method: \"PUT\",\n path: \"/_api/simple/first-example\",\n body: {\n example,\n collection: this._name,\n },\n },\n (res) => res.body.document\n );\n }\n\n removeByExample(\n example: Partial<DocumentData<T>>,\n options?: SimpleQueryRemoveByExampleOptions\n ) {\n return this._db.request({\n method: \"PUT\",\n path: \"/_api/simple/remove-by-example\",\n body: {\n ...options,\n example,\n collection: this._name,\n },\n });\n }\n\n replaceByExample(\n example: Partial<DocumentData<T>>,\n newValue: DocumentData<T>,\n options?: SimpleQueryReplaceByExampleOptions\n ) {\n return this._db.request({\n method: \"PUT\",\n path: \"/_api/simple/replace-by-example\",\n body: {\n ...options,\n example,\n newValue,\n collection: this._name,\n },\n });\n }\n\n updateByExample(\n example: Partial<DocumentData<T>>,\n newValue: Patch<DocumentData<T>>,\n options?: SimpleQueryUpdateByExampleOptions\n ) {\n return this._db.request({\n method: \"PUT\",\n path: \"/_api/simple/update-by-example\",\n body: {\n ...options,\n example,\n newValue,\n collection: this._name,\n },\n });\n }\n\n lookupByKeys(keys: string[]) {\n return this._db.request(\n {\n method: \"PUT\",\n path: \"/_api/simple/lookup-by-keys\",\n body: {\n keys,\n collection: this._name,\n },\n },\n (res) => res.body.documents\n );\n }\n\n removeByKeys(keys: string[], options?: SimpleQueryRemoveByKeysOptions) {\n return this._db.request({\n method: \"PUT\",\n path: \"/_api/simple/remove-by-keys\",\n body: {\n options: options,\n keys,\n collection: this._name,\n },\n });\n }\n //#endregion\n\n //#region indexes\n indexes() {\n return this._db.request(\n {\n path: \"/_api/index\",\n qs: { collection: this._name },\n },\n (res) => res.body.indexes\n );\n }\n\n index(selector: IndexSelector) {\n return this._db.request({\n path: `/_api/index/${encodeURI(_indexHandle(selector, this._name))}`,\n });\n }\n\n ensureIndex(\n options:\n | EnsurePersistentIndexOptions\n | EnsureGeoIndexOptions\n | EnsureFulltextIndexOptions\n | EnsureTtlIndexOptions\n | EnsureZkdIndexOptions\n | EnsureInvertedIndexOptions\n ) {\n return this._db.request({\n method: \"POST\",\n path: \"/_api/index\",\n body: options,\n qs: { collection: this._name },\n });\n }\n\n dropIndex(selector: IndexSelector) {\n return this._db.request({\n method: \"DELETE\",\n path: `/_api/index/${encodeURI(_indexHandle(selector, this._name))}`,\n });\n }\n\n fulltext(\n attribute: string,\n query: string,\n { index, ...options }: SimpleQueryFulltextOptions = {}\n ) {\n return this._db.request(\n {\n method: \"PUT\",\n path: \"/_api/simple/fulltext\",\n body: {\n ...options,\n index: index ? _indexHandle(index, this._name) : undefined,\n attribute,\n query,\n collection: this._name,\n },\n },\n (res) =>\n new BatchedArrayCursor(this._db, res.body, res.arangojsHostUrl).items\n );\n }\n\n compact() {\n return this._db.request(\n {\n method: \"PUT\",\n path: `/_api/collection/${this._name}/compact`,\n },\n (res) => res.body\n );\n }\n //#endregion\n}\n","/**\n * ```ts\n * import type { ArrayCursor, BatchedArrayCursor } from \"arangojs/cursor\";\n * ```\n *\n * The \"cursor\" module provides cursor-related interfaces for TypeScript.\n *\n * @packageDocumentation\n */\nimport { LinkedList } from \"x3-linkedlist\";\nimport { Database } from \"./database\";\n\n/**\n * Additional information about the cursor.\n */\nexport interface CursorExtras {\n /**\n * Warnings encountered while executing the query.\n */\n warnings: {\n code: number;\n message: string;\n }[];\n /**\n * Query execution plan for the executed query.\n */\n plan?: Record<string, any>;\n /**\n * Additional profiling information for the executed query.\n */\n profile?: Record<string, number>;\n /**\n * Additional statistics about the query execution.\n */\n stats?: CursorStats;\n}\n\n/**\n * Additional statics about the query execution of the cursor.\n */\nexport interface CursorStats {\n /**\n * Total number of index entries read from in-memory caches for indexes of\n * type edge or persistent.\n */\n cacheHits: number;\n /**\n * Total number of cache read attempts for index entries that could not be\n * served from in-memory caches for indexes of type edge or persistent.\n */\n cacheMisses: number;\n /**\n * Total number of cursor objects created during query execution.\n */\n cursorsCreated: number;\n /**\n * Total number of times an existing cursor object was repurposed.\n */\n cursorsRearmed: number;\n /**\n * Total number of data-modification operations successfully executed.\n */\n writesExecuted: number;\n /**\n * Total number of data-modification operations that were unsuccessful, but have been ignored because of query option ignoreErrors.\n */\n writesIgnored: number;\n /**\n * Total number of documents iterated over when scanning a collection without an index.\n */\n scannedFull: number;\n /**\n * Total number of documents iterated over when scanning a collection using an index.\n */\n scannedIndex: number;\n /**\n * Total number of documents that were removed after executing a filter condition in a FilterNode.\n */\n filtered: number;\n /**\n * Maximum memory usage of the query while it was running.\n */\n peakMemoryUsage: number;\n /**\n * Execution time of the query in seconds.\n */\n executionTime: number;\n /**\n * Total number of documents that matched the search condition if the query’s final top-level LIMIT statement were not present.\n */\n fullCount?: number;\n /**\n * Total number of cluster-internal HTTP requests performed.\n */\n httpRequests: number;\n /**\n * Runtime statistics per query execution node if `profile` was set to `2` or greater.\n */\n nodes?: {\n /**\n * Execution node ID to correlate this node with nodes in the `extra.plan`.\n */\n id: number;\n /**\n * Number of calls in this node.\n */\n calls: number;\n /**\n * Number of temporary result items returned by this node.\n */\n items: number;\n filter: number;\n /**\n * Execution time of this node in seconds.\n */\n runtime: number;\n }[];\n}\n\ninterface BatchView<T = any> {\n isEmpty: boolean;\n more(): Promise<void>;\n shift(): T | undefined;\n}\n\n/**\n * The `BatchedArrayCursor` provides a batch-wise API to an {@link ArrayCursor}.\n *\n * When using TypeScript, cursors can be cast to a specific item type in order\n * to increase type safety.\n *\n * @param T - Type to use for each item. Defaults to `any`.\n *\n * @example\n * ```ts\n * const db = new Database();\n * const query = aql`FOR x IN 1..5 RETURN x`;\n * const cursor = await db.query(query) as ArrayCursor<number>;\n * const batches = cursor.batches;\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const query = aql`FOR x IN 1..10000 RETURN x`;\n * const cursor = await db.query(query, { batchSize: 10 });\n * for await (const batch of cursor.batches) {\n * // Process all values in a batch in parallel\n * await Promise.all(batch.map(\n * value => asyncProcessValue(value)\n * ));\n * }\n * ```\n */\nexport class BatchedArrayCursor<T = any> {\n protected _db: Database;\n protected _batches: LinkedList<LinkedList<any>>;\n protected _count?: number;\n protected _extra: CursorExtras;\n protected _hasMore: boolean;\n protected _id: string | undefined;\n protected _hostUrl?: string;\n protected _allowDirtyRead?: boolean;\n protected _itemsCursor: ArrayCursor<T>;\n\n /**\n * @internal\n */\n constructor(\n db: Database,\n body: {\n extra: any;\n result: T[];\n hasMore: boolean;\n id: string;\n count: number;\n },\n hostUrl?: string,\n allowDirtyRead?: boolean\n ) {\n const batches = new LinkedList(\n body.result.length ? [new LinkedList(body.result)] : []\n );\n this._db = db;\n this._batches = batches;\n this._id = body.id;\n this._hasMore = Boolean(body.id && body.hasMore);\n this._hostUrl = hostUrl;\n this._count = body.count;\n this._extra = body.extra;\n this._allowDirtyRead = allowDirtyRead;\n this._itemsCursor = new ArrayCursor(this, {\n get isEmpty() {\n return !batches.length;\n },\n more: () => this._more(),\n shift: () => {\n let batch = batches.first?.value;\n while (batch && !batch.length) {\n batches.shift();\n batch = batches.first?.value;\n }\n if (!batch) return undefined;\n const value = batch.shift();\n if (!batch.length) batches.shift();\n return value;\n },\n });\n }\n\n protected async _more(): Promise<void> {\n if (!this.hasMore) return;\n const body = await this._db.request({\n method: \"PUT\",\n path: `/_api/cursor/${encodeURIComponent(this._id!)}`,\n hostUrl: this._hostUrl,\n allowDirtyRead: this._allowDirtyRead,\n });\n this._batches.push(new LinkedList(body.result));\n this._hasMore = body.hasMore;\n }\n\n /**\n * An {@link ArrayCursor} providing item-wise access to the cursor result set.\n *\n * See also {@link ArrayCursor#batches}.\n */\n get items() {\n return this._itemsCursor;\n }\n\n /**\n * Additional information about the cursor.\n */\n get extra(): Readonly<CursorExtras> {\n return this._extra;\n }\n\n /**\n * Total number of documents in the query result. Only available if the\n * `count` option was used.\n */\n get count(): number | undefined {\n return this._count;\n }\n\n /**\n * Whether the cursor has any remaining batches that haven't yet been\n * fetched. If set to `false`, all batches have been fetched and no\n * additional requests to the server will be made when consuming any\n * remaining batches from this cursor.\n */\n get hasMore(): boolean {\n return this._hasMore;\n }\n\n /**\n * Whether the cursor has more batches. If set to `false`, the cursor has\n * already been depleted and contains no more batches.\n */\n get hasNext(): boolean {\n return this.hasMore || Boolean(this._batches.length);\n }\n\n /**\n * Enables use with `for await` to deplete the cursor by asynchronously\n * yielding every batch in the cursor's remaining result set.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`\n * FOR user IN users\n * FILTER user.isActive\n * RETURN user\n * `);\n * for await (const users of cursor.batches) {\n * for (const user of users) {\n * console.log(user.email, user.isAdmin);\n * }\n * }\n * ```\n */\n async *[Symbol.asyncIterator](): AsyncGenerator<T[], undefined, undefined> {\n while (this.hasNext) {\n yield this.next() as Promise<T[]>;\n }\n return undefined;\n }\n\n /**\n * Loads all remaining batches from the server.\n *\n * **Warning**: This may impact memory use when working with very large\n * query result sets.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 1 }\n * );\n * console.log(cursor.hasMore); // true\n * await cursor.batches.loadAll();\n * console.log(cursor.hasMore); // false\n * console.log(cursor.hasNext); // true\n * for await (const item of cursor) {\n * console.log(item);\n * // No server roundtrips necessary any more\n * }\n * ```\n */\n async loadAll(): Promise<void> {\n while (this._hasMore) {\n await this._more();\n }\n }\n\n /**\n * Depletes the cursor, then returns an array containing all batches in the\n * cursor's remaining result list.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * const result = await cursor.batches.all(); // [[1, 2], [3, 4], [5]]\n * console.log(cursor.hasNext); // false\n * ```\n */\n async all(): Promise<T[][]> {\n return this.map((batch) => batch);\n }\n\n /**\n * Advances the cursor and returns all remaining values in the cursor's\n * current batch. If the current batch has already been exhausted, fetches\n * the next batch from the server and returns it, or `undefined` if the\n * cursor has been depleted.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR i IN 1..10 RETURN i`,\n * { batchSize: 5 }\n * );\n * const firstBatch = await cursor.batches.next(); // [1, 2, 3, 4, 5]\n * await cursor.next(); // 6\n * const lastBatch = await cursor.batches.next(); // [7, 8, 9, 10]\n * console.log(cursor.hasNext); // false\n * ```\n */\n async next(): Promise<T[] | undefined> {\n while (!this._batches.length && this.hasNext) {\n await this._more();\n }\n if (!this._batches.length) {\n return undefined;\n }\n const batch = this._batches.shift();\n if (!batch) return undefined;\n const values = [...batch.values()];\n batch.clear(true);\n return values;\n }\n\n /**\n * Advances the cursor by applying the `callback` function to each item in\n * the cursor's remaining result list until the cursor is depleted or\n * `callback` returns the exact value `false`. Returns a promise that\n * evalues to `true` unless the function returned `false`.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * [`Array.prototype.forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach).\n *\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * const result = await cursor.batches.forEach((currentBatch) => {\n * for (const value of currentBatch) {\n * console.log(value);\n * }\n * });\n * console.log(result) // true\n * console.log(cursor.hasNext); // false\n * ```\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * const result = await cursor.batches.forEach((currentBatch) => {\n * for (const value of currentBatch) {\n * console.log(value);\n * }\n * return false; // stop after the first batch\n * });\n * console.log(result); // false\n * console.log(cursor.hasNext); // true\n * ```\n */\n async forEach(\n callback: (currentBatch: T[], index: number, self: this) => false | void\n ): Promise<boolean> {\n let index = 0;\n while (this.hasNext) {\n const currentBatch = await this.next();\n const result = callback(currentBatch!, index, this);\n index++;\n if (result === false) return result;\n if (this.hasNext) await this._more();\n }\n return true;\n }\n\n /**\n * Depletes the cursor by applying the `callback` function to each batch in\n * the cursor's remaining result list. Returns an array containing the\n * return values of `callback` for each batch.\n *\n * **Note**: This creates an array of all return values, which may impact\n * memory use when working with very large query result sets. Consider using\n * {@link BatchedArrayCursor#forEach}, {@link BatchedArrayCursor#reduce} or\n * {@link BatchedArrayCursor#flatMap} instead.\n *\n * See also:\n * [`Array.prototype.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map).\n *\n * @param R - Return type of the `callback` function.\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * const squares = await cursor.batches.map((currentBatch) => {\n * return currentBatch.map((value) => value ** 2);\n * });\n * console.log(squares); // [[1, 4], [9, 16], [25]]\n * console.log(cursor.hasNext); // false\n * ```\n */\n async map<R>(\n callback: (currentBatch: T[], index: number, self: this) => R\n ): Promise<R[]> {\n let index = 0;\n const result: any[] = [];\n while (this.hasNext) {\n const currentBatch = await this.next();\n result.push(callback(currentBatch!, index, this));\n index++;\n }\n return result;\n }\n\n /**\n * Depletes the cursor by applying the `callback` function to each batch in\n * the cursor's remaining result list. Returns an array containing the\n * return values of `callback` for each batch, flattened to a depth of 1.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * [`Array.prototype.flatMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap).\n *\n * @param R - Return type of the `callback` function.\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * const squares = await cursor.batches.flatMap((currentBatch) => {\n * return currentBatch.map((value) => value ** 2);\n * });\n * console.log(squares); // [1, 1, 2, 4, 3, 9, 4, 16, 5, 25]\n * console.log(cursor.hasNext); // false\n * ```\n *\n * @example\n * ```js\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 1 }\n * );\n * const odds = await cursor.batches.flatMap((currentBatch) => {\n * if (currentBatch[0] % 2 === 0) {\n * return []; // empty array flattens into nothing\n * }\n * return currentBatch;\n * });\n * console.logs(odds); // [1, 3, 5]\n * ```\n */\n async flatMap<R>(\n callback: (currentBatch: T[], index: number, self: this) => R | R[]\n ): Promise<R[]> {\n let index = 0;\n const result: any[] = [];\n while (this.hasNext) {\n const currentBatch = await this.next();\n const value = callback(currentBatch!, index, this);\n if (Array.isArray(value)) {\n result.push(...value);\n } else {\n result.push(value);\n }\n index++;\n }\n return result;\n }\n\n /**\n * Depletes the cursor by applying the `reducer` function to each batch in\n * the cursor's remaining result list. Returns the return value of `reducer`\n * for the last batch.\n *\n * **Note**: Most complex uses of the `reduce` method can be replaced with\n * simpler code using {@link BatchedArrayCursor#forEach} or the `for await`\n * syntax.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * [`Array.prototype.reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce).\n *\n * @param R - Return type of the `reducer` function.\n * @param reducer - Function to execute on each element.\n * @param initialValue - Initial value of the `accumulator` value passed to\n * the `reducer` function.\n *\n * @example\n * ```js\n * function largestValue(baseline, values) {\n * return Math.max(baseline, ...values);\n * }\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 3 }\n * );\n * const result = await cursor.batches.reduce(largestValue, 0);\n * console.log(result); // 5\n * console.log(cursor.hasNext); // false\n * const emptyResult = await cursor.batches.reduce(largestValue, 0);\n * console.log(emptyResult); // 0\n * ```\n *\n * @example\n * ```js\n * // BAD! NEEDLESSLY COMPLEX!\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 1 }\n * );\n * const result = await cursor.reduce((accumulator, currentBatch) => {\n * if (currentBatch[0] % 2 === 0) {\n * accumulator.even.push(...currentBatch);\n * } else {\n * accumulator.odd.push(...currentBatch);\n * }\n * return accumulator;\n * }, { odd: [], even: [] });\n * console.log(result); // { odd: [1, 3, 5], even: [2, 4] }\n *\n * // GOOD! MUCH SIMPLER!\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const odd = [];\n * const even = [];\n * for await (const currentBatch of cursor) {\n * if (currentBatch[0] % 2 === 0) {\n * even.push(...currentBatch);\n * } else {\n * odd.push(...currentBatch);\n * }\n * }\n * console.log({ odd, even }); // { odd: [1, 3, 5], even: [2, 4] }\n * ```\n */\n async reduce<R>(\n reducer: (\n accumulator: R,\n currentBatch: T[],\n index: number,\n self: this\n ) => R,\n initialValue: R\n ): Promise<R>;\n\n /**\n * Depletes the cursor by applying the `reducer` function to each batch in\n * the cursor's remaining result list. Returns the return value of `reducer`\n * for the last batch.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * [`Array.prototype.reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce).\n *\n * @param R - Return type of the `reducer` function.\n * @param reducer - Function to execute on each element.\n *\n * @example\n * ```js\n * function largestValue(values1, values2) {\n * return [Math.max(...values1, ...values2)];\n * }\n * const cursor = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 3 }\n * );\n * const result = await cursor.batches.reduce(largestValue);\n * console.log(result); // [5]\n * console.log(cursor.hasNext); // false\n * ```\n *\n */\n async reduce<R>(\n reducer: (\n accumulator: T[] | R,\n currentBatch: T[],\n index: number,\n self: this\n ) => R\n ): Promise<R | undefined>;\n async reduce<R>(\n reducer: (\n accumulator: R,\n currentBatch: T[],\n index: number,\n self: this\n ) => R,\n initialValue?: R\n ): Promise<R | undefined> {\n let index = 0;\n if (!this.hasNext) return initialValue;\n if (initialValue === undefined) {\n initialValue = (await this.next()) as any;\n index += 1;\n }\n let value = initialValue as R;\n while (this.hasNext) {\n const currentBatch = await this.next();\n value = reducer(value, currentBatch!, index, this);\n index++;\n }\n return value;\n }\n\n /**\n * Drains the cursor and frees up associated database resources.\n *\n * This method has no effect if all batches have already been consumed.\n *\n * @example\n * ```js\n * const cursor1 = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * console.log(cursor1.hasMore); // false\n * await cursor1.kill(); // no effect\n *\n * const cursor2 = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * console.log(cursor2.hasMore); // true\n * await cursor2.kill(); // cursor is depleted\n * ```\n */\n async kill(): Promise<void> {\n if (this._batches.length) {\n for (const batch of this._batches.values()) {\n batch.clear();\n }\n this._batches.clear();\n }\n if (!this.hasNext) return undefined;\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/cursor/${encodeURIComponent(this._id!)}`,\n },\n () => {\n this._hasMore = false;\n return undefined;\n }\n );\n }\n}\n\n/**\n * The `ArrayCursor` type represents a cursor returned from a\n * {@link database.Database#query}.\n *\n * When using TypeScript, cursors can be cast to a specific item type in order\n * to increase type safety.\n *\n * See also {@link BatchedArrayCursor}.\n *\n * @param T - Type to use for each item. Defaults to `any`.\n *\n * @example\n * ```ts\n * const db = new Database();\n * const query = aql`FOR x IN 1..5 RETURN x`;\n * const result = await db.query(query) as ArrayCursor<number>;\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const query = aql`FOR x IN 1..10 RETURN x`;\n * const cursor = await db.query(query);\n * for await (const value of cursor) {\n * // Process each value asynchronously\n * await processValue(value);\n * }\n * ```\n */\nexport class ArrayCursor<T = any> {\n protected _batches: BatchedArrayCursor<T>;\n protected _view: BatchView<T>;\n\n /**\n * @internal\n */\n constructor(batchedCursor: BatchedArrayCursor, view: BatchView<T>) {\n this._batches = batchedCursor;\n this._view = view;\n }\n\n /**\n * A {@link BatchedArrayCursor} providing batch-wise access to the cursor\n * result set.\n *\n * See also {@link BatchedArrayCursor#items}.\n */\n get batches() {\n return this._batches;\n }\n\n /**\n * Additional information about the cursor.\n */\n get extra(): CursorExtras {\n return this.batches.extra;\n }\n\n /**\n * Total number of documents in the query result. Only available if the\n * `count` option was used.\n */\n get count(): number | undefined {\n return this.batches.count;\n }\n\n /**\n * Whether the cursor has more values. If set to `false`, the cursor has\n * already been depleted and contains no more items.\n */\n get hasNext(): boolean {\n return this.batches.hasNext;\n }\n\n /**\n * Enables use with `for await` to deplete the cursor by asynchronously\n * yielding every value in the cursor's remaining result set.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`\n * FOR user IN users\n * FILTER user.isActive\n * RETURN user\n * `);\n * for await (const user of cursor) {\n * console.log(user.email, user.isAdmin);\n * }\n * ```\n */\n async *[Symbol.asyncIterator](): AsyncGenerator<T, undefined, undefined> {\n while (this.hasNext) {\n yield this.next() as Promise<T>;\n }\n return undefined;\n }\n\n /**\n * Depletes the cursor, then returns an array containing all values in the\n * cursor's remaining result list.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.all(); // [1, 2, 3, 4, 5]\n * console.log(cursor.hasNext); // false\n * ```\n */\n async all(): Promise<T[]> {\n return this.batches.flatMap((v) => v);\n }\n\n /**\n * Advances the cursor and returns the next value in the cursor's remaining\n * result list, or `undefined` if the cursor has been depleted.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..3 RETURN x`);\n * const one = await cursor.next(); // 1\n * const two = await cursor.next(); // 2\n * const three = await cursor.next(); // 3\n * const empty = await cursor.next(); // undefined\n * ```\n */\n async next(): Promise<T | undefined> {\n while (this._view.isEmpty && this.batches.hasMore) {\n await this._view.more();\n }\n if (this._view.isEmpty) {\n return undefined;\n }\n return this._view.shift();\n }\n\n /**\n * Advances the cursor by applying the `callback` function to each item in\n * the cursor's remaining result list until the cursor is depleted or\n * `callback` returns the exact value `false`. Returns a promise that\n * evalues to `true` unless the function returned `false`.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * [`Array.prototype.forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach).\n *\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.forEach((currentValue) => {\n * console.log(currentValue);\n * });\n * console.log(result) // true\n * console.log(cursor.hasNext); // false\n * ```\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.forEach((currentValue) => {\n * console.log(currentValue);\n * return false; // stop after the first item\n * });\n * console.log(result); // false\n * console.log(cursor.hasNext); // true\n * ```\n */\n async forEach(\n callback: (currentValue: T, index: number, self: this) => false | void\n ): Promise<boolean> {\n let index = 0;\n while (this.hasNext) {\n const value = await this.next();\n const result = callback(value!, index, this);\n index++;\n if (result === false) return result;\n }\n return true;\n }\n\n /**\n * Depletes the cursor by applying the `callback` function to each item in\n * the cursor's remaining result list. Returns an array containing the\n * return values of `callback` for each item.\n *\n * **Note**: This creates an array of all return values, which may impact\n * memory use when working with very large query result sets. Consider using\n * {@link ArrayCursor#forEach}, {@link ArrayCursor#reduce} or\n * {@link ArrayCursor#flatMap} instead.\n *\n * See also:\n * [`Array.prototype.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map).\n *\n * @param R - Return type of the `callback` function.\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const squares = await cursor.map((currentValue) => {\n * return currentValue ** 2;\n * });\n * console.log(squares); // [1, 4, 9, 16, 25]\n * console.log(cursor.hasNext); // false\n * ```\n */\n async map<R>(\n callback: (currentValue: T, index: number, self: this) => R\n ): Promise<R[]> {\n let index = 0;\n const result: any[] = [];\n while (this.hasNext) {\n const value = await this.next();\n result.push(callback(value!, index, this));\n index++;\n }\n return result;\n }\n\n /**\n * Depletes the cursor by applying the `callback` function to each item in\n * the cursor's remaining result list. Returns an array containing the\n * return values of `callback` for each item, flattened to a depth of 1.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * [`Array.prototype.flatMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap).\n *\n * @param R - Return type of the `callback` function.\n * @param callback - Function to execute on each element.\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const squares = await cursor.flatMap((currentValue) => {\n * return [currentValue, currentValue ** 2];\n * });\n * console.log(squares); // [1, 1, 2, 4, 3, 9, 4, 16, 5, 25]\n * console.log(cursor.hasNext); // false\n * ```\n *\n * @example\n * ```js\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const odds = await cursor.flatMap((currentValue) => {\n * if (currentValue % 2 === 0) {\n * return []; // empty array flattens into nothing\n * }\n * return currentValue; // or [currentValue]\n * });\n * console.logs(odds); // [1, 3, 5]\n * ```\n */\n async flatMap<R>(\n callback: (currentValue: T, index: number, self: this) => R | R[]\n ): Promise<R[]> {\n let index = 0;\n const result: any[] = [];\n while (this.hasNext) {\n const value = await this.next();\n const item = callback(value!, index, this);\n if (Array.isArray(item)) {\n result.push(...item);\n } else {\n result.push(item);\n }\n index++;\n }\n return result;\n }\n\n /**\n * Depletes the cursor by applying the `reducer` function to each item in\n * the cursor's remaining result list. Returns the return value of `reducer`\n * for the last item.\n *\n * **Note**: Most complex uses of the `reduce` method can be replaced with\n * simpler code using {@link ArrayCursor#forEach} or the `for await` syntax.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * [`Array.prototype.reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce).\n *\n * @param R - Return type of the `reducer` function.\n * @param reducer - Function to execute on each element.\n * @param initialValue - Initial value of the `accumulator` value passed to\n * the `reducer` function.\n *\n * @example\n * ```js\n * function largestOfTwo(one, two) {\n * return Math.max(one, two);\n * }\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.reduce(largestOfTwo, 0);\n * console.log(result); // 5\n * console.log(cursor.hasNext); // false\n * const emptyResult = await cursor.reduce(largestOfTwo, 0);\n * console.log(emptyResult); // 0\n * ```\n *\n * @example\n * ```js\n * // BAD! NEEDLESSLY COMPLEX!\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.reduce((accumulator, currentValue) => {\n * if (currentValue % 2 === 0) {\n * accumulator.even.push(...currentValue);\n * } else {\n * accumulator.odd.push(...currentValue);\n * }\n * return accumulator;\n * }, { odd: [], even: [] });\n * console.log(result); // { odd: [1, 3, 5], even: [2, 4] }\n *\n * // GOOD! MUCH SIMPLER!\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const odd = [];\n * const even = [];\n * for await (const currentValue of cursor) {\n * if (currentValue % 2 === 0) {\n * even.push(currentValue);\n * } else {\n * odd.push(currentValue);\n * }\n * }\n * console.log({ odd, even }); // { odd: [1, 3, 5], even: [2, 4] }\n * ```\n */\n async reduce<R>(\n reducer: (accumulator: R, currentValue: T, index: number, self: this) => R,\n initialValue: R\n ): Promise<R>;\n /**\n * Depletes the cursor by applying the `reducer` function to each item in\n * the cursor's remaining result list. Returns the return value of `reducer`\n * for the last item.\n *\n * **Note**: If the result set spans multiple batches, any remaining batches\n * will only be fetched on demand. Depending on the cursor's TTL and the\n * processing speed, this may result in the server discarding the cursor\n * before it is fully depleted.\n *\n * See also:\n * [`Array.prototype.reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce).\n *\n * @param R - Return type of the `reducer` function.\n * @param reducer - Function to execute on each element.\n *\n * @example\n * ```js\n * function largestOfTwo(one, two) {\n * return Math.max(one, two);\n * }\n * const cursor = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * const result = await cursor.reduce(largestOfTwo);\n * console.log(result); // 5\n * console.log(cursor.hasNext); // false\n * const emptyResult = await cursor.reduce(largestOfTwo);\n * console.log(emptyResult); // undefined\n * ```\n */\n async reduce<R>(\n reducer: (\n accumulator: T | R,\n currentValue: T,\n index: number,\n self: this\n ) => R\n ): Promise<R | undefined>;\n async reduce<R>(\n reducer: (accumulator: R, currentValue: T, index: number, self: this) => R,\n initialValue?: R\n ): Promise<R | undefined> {\n let index = 0;\n if (!this.hasNext) return initialValue;\n if (initialValue === undefined) {\n const value = (await this.next()) as any;\n initialValue = value as R;\n index += 1;\n }\n let value = initialValue;\n while (this.hasNext) {\n const item = await this.next();\n value = reducer(value, item!, index, this);\n index++;\n }\n return value;\n }\n\n /**\n * Kills the cursor and frees up associated database resources.\n *\n * This method has no effect if all batches have already been fetched.\n *\n * @example\n * ```js\n * const cursor1 = await db.query(aql`FOR x IN 1..5 RETURN x`);\n * console.log(cursor1.hasMore); // false\n * await cursor1.kill(); // no effect\n *\n * const cursor2 = await db.query(\n * aql`FOR x IN 1..5 RETURN x`,\n * { batchSize: 2 }\n * );\n * console.log(cursor2.hasMore); // true\n * await cursor2.kill(); // cursor is depleted\n * ```\n */\n async kill(): Promise<void> {\n return this.batches.kill();\n }\n}\n","/**\n * Wrapper around browser `btoa` function to allow substituting a\n * Node.js-specific implementation.\n *\n * @packageDocumentation\n * @internal\n */\n\n/**\n * @internal\n */\nexport function base64Encode(str: string): string {\n return btoa(str);\n}\n","/**\n * Utility function for normalizing URLs.\n *\n * @packageDocumentation\n * @internal\n */\n\n/**\n * @internal\n */\nexport function normalizeUrl(url: string): string {\n const raw = url.match(/^(tcp|ssl|tls)((?::|\\+).+)/);\n if (raw) url = (raw[1] === \"tcp\" ? \"http\" : \"https\") + raw[2];\n const unix = url.match(/^(?:(http|https)\\+)?unix:\\/\\/(\\/.+)/);\n if (unix) url = `${unix[1] || \"http\"}://unix:${unix[2]}`;\n return url;\n}\n","/**\n * Wrapper around the `xhr` module for HTTP(S) requests in the browser.\n *\n * @packageDocumentation\n * @internal\n */\n\nimport { ClientRequest } from \"http\";\nimport { Errback } from \"./errback\";\n\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nexport default require(\"xhr\") as (\n options: any,\n cb: Errback<any>\n) => ClientRequest;\n","/// <reference lib=\"dom\" />\n\n/**\n * Node.js implementation of the HTTP(S) request function.\n *\n * @packageDocumentation\n * @internal\n */\n\nimport { RequestInterceptors, XhrOptions } from \"../connection\";\nimport { base64Encode } from \"./btoa\";\nimport { Errback } from \"./errback\";\nimport { omit } from \"./omit\";\nimport {\n ArangojsError,\n ArangojsResponse,\n RequestOptions,\n} from \"./request.node\";\nimport xhr from \"./xhr\";\n\nexport const isBrowser = true;\n\n/**\n * @internal\n */\nfunction errorToJSON(this: Error) {\n return {\n error: true,\n message: this.message,\n };\n}\n\n/**\n * Create a function for performing requests against a given host.\n *\n * @param baseUrl - Base URL of the host, i.e. protocol, port and domain name.\n * @param agentOptions - Options to use for performing requests.\n *\n * @param baseUrl\n * @param agentOptions\n *\n * @internal\n */\nexport function createRequest(\n baseUrl: string,\n agentOptions: XhrOptions & RequestInterceptors\n) {\n const base = new URL(baseUrl);\n const auth = base64Encode(`${base.username || \"root\"}:${base.password}`);\n base.username = \"\";\n base.password = \"\";\n const options = omit(agentOptions, [\"maxSockets\"]);\n return function request(\n {\n method,\n url: reqUrl,\n headers,\n body,\n timeout,\n expectBinary,\n }: RequestOptions,\n cb: Errback<ArangojsResponse>\n ) {\n const url = new URL(reqUrl.pathname, base);\n if (base.search || reqUrl.search) {\n url.search = reqUrl.search\n ? `${base.search}&${reqUrl.search.slice(1)}`\n : base.search;\n }\n if (!headers[\"authorization\"]) {\n headers[\"authorization\"] = `Basic ${auth}`;\n }\n\n let callback: Errback<ArangojsResponse> = (err, res) => {\n callback = () => undefined;\n cb(err, res);\n };\n const req = xhr(\n {\n useXDR: true,\n withCredentials: true,\n ...options,\n responseType: expectBinary ? \"blob\" : \"text\",\n url: String(url),\n body,\n method,\n headers,\n timeout,\n },\n (err: Error | null, res?: any) => {\n if (!err) {\n const response = res as ArangojsResponse;\n response.request = req;\n if (!response.body) response.body = \"\";\n if (options.after) {\n options.after(null, response);\n }\n callback(null, response as ArangojsResponse);\n } else {\n const error = err as ArangojsError;\n error.request = req;\n error.toJSON = errorToJSON;\n if (options.after) {\n options.after(error);\n }\n callback(error);\n }\n }\n );\n if (options.before) {\n options.before(req);\n }\n };\n}\n","/**\n * Utility function for omitting properties by key.\n *\n * @packageDocumentation\n * @internal\n */\n\n/**\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nexport function omit<T extends {}>(obj: T, keys: (keyof T)[]): T {\n const result = {} as T;\n for (const key of Object.keys(obj)) {\n if (keys.includes(key as keyof T)) continue;\n result[key as keyof T] = obj[key as keyof T];\n }\n return result;\n}\n","/**\n * ```ts\n * import type { Config } from \"arangojs/connection\";\n * ```\n *\n * The \"connection\" module provides connection and configuration related types\n * for TypeScript.\n *\n * @packageDocumentation\n */\nimport { ClientRequest } from \"http\";\nimport { AgentOptions as NodeAgentOptions } from \"https\";\nimport { LinkedList } from \"x3-linkedlist\";\nimport { Database } from \"./database\";\nimport {\n ArangoError,\n HttpError,\n isArangoError,\n isArangoErrorResponse,\n isSystemError,\n} from \"./error\";\nimport { base64Encode } from \"./lib/btoa\";\nimport {\n ERROR_ARANGO_CONFLICT,\n ERROR_ARANGO_MAINTENANCE_MODE,\n} from \"./lib/codes\";\nimport { Errback } from \"./lib/errback\";\nimport { normalizeUrl } from \"./lib/normalizeUrl\";\nimport { querystringify } from \"./lib/querystringify\";\nimport {\n ArangojsError,\n ArangojsResponse,\n createRequest,\n isBrowser,\n RequestFunction,\n} from \"./lib/request\";\n\nconst MIME_JSON = /\\/(json|javascript)(\\W|$)/;\nconst LEADER_ENDPOINT_HEADER = \"x-arango-endpoint\";\n\n/**\n * Determines the behavior when multiple URLs are used:\n *\n * - `\"NONE\"`: No load balancing. All requests will be handled by the first\n * URL in the list until a network error is encountered. On network error,\n * arangojs will advance to using the next URL in the list.\n *\n * - `\"ONE_RANDOM\"`: Randomly picks one URL from the list initially, then\n * behaves like `\"NONE\"`.\n *\n * - `\"ROUND_ROBIN\"`: Every sequential request uses the next URL in the list.\n */\nexport type LoadBalancingStrategy = \"NONE\" | \"ROUND_ROBIN\" | \"ONE_RANDOM\";\n\n/**\n * An arbitrary object with string values representing HTTP headers and their\n * values.\n *\n * Header names should always be lowercase.\n */\nexport type Headers = Record<string, string>;\n\n/**\n * An arbitrary object with scalar values representing query string parameters\n * and their values.\n */\nexport type Params = Record<string, any>;\n\n/**\n * Generic properties shared by all ArangoDB HTTP API responses.\n */\nexport type ArangoResponseMetadata = {\n /**\n * Indicates that the request was successful.\n */\n error: false;\n /**\n * Response status code, typically `200`.\n */\n code: number;\n};\n\n/**\n * Extends the given base type `T` with the generic HTTP API response properties.\n */\nexport type ArangoApiResponse<T> = T & ArangoResponseMetadata;\n\n/**\n * Credentials for HTTP Basic authentication.\n */\nexport type BasicAuthCredentials = {\n /**\n * Username to use for authentication, e.g. `\"root\"`.\n */\n username: string;\n /**\n * Password to use for authentication. Defaults to an empty string.\n */\n password?: string;\n};\n\n/**\n * Credentials for HTTP Bearer token authentication.\n */\nexport type BearerAuthCredentials = {\n /**\n * Bearer token to use for authentication.\n */\n token: string;\n};\n\nfunction isBearerAuth(auth: any): auth is BearerAuthCredentials {\n return auth.hasOwnProperty(\"token\");\n}\n\n/**\n * @internal\n */\nfunction generateStackTrace() {\n let err = new Error();\n if (!err.stack) {\n try {\n throw err;\n } catch (e: any) {\n err = e;\n }\n }\n return err;\n}\n\n/**\n * @internal\n */\ntype UrlInfo = {\n absolutePath?: boolean;\n basePath?: string;\n path?: string;\n qs?: string | Params;\n};\n\n/**\n * Options of the `xhr` module that can be set using `agentOptions` when using\n * arangojs in the browser. Additionally `maxSockets` can be used to control\n * the maximum number of parallel requests.\n *\n * See also: [`xhr` on npm](https://www.npmjs.com/package/xhr).\n */\nexport type XhrOptions = {\n /**\n * Maximum number of parallel requests arangojs will perform. If any\n * additional requests are attempted, they will be enqueued until one of the\n * active requests has completed.\n */\n maxSockets?: number;\n /**\n * Number of milliseconds to wait for a response.\n *\n * Default: `0` (disabled)\n */\n timeout?: number;\n /**\n * Callback that will be invoked immediately before the `send` method of the\n * request is called.\n *\n * See also {@link RequestInterceptors}.\n */\n beforeSend?: (xhrObject: any) => void;\n /**\n * `XMLHttpRequest` object to use instead of the native implementation.\n */\n xhr?: any;\n /**\n * (Internet Explorer 10 and lower only.) Whether `XDomainRequest` should be\n * used instead of `XMLHttpRequest`. Only required for performing\n * cross-domain requests in older versions of Internet Explorer.\n */\n useXdr?: boolean;\n /**\n * Specifies whether browser credentials (e.g. cookies) should be sent if\n * performing a cross-domain request.\n *\n * See [`XMLHttpRequest.withCredentials`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials).\n */\n withCredentials?: boolean;\n};\n\n/**\n * Additional options for intercepting the request/response. These methods\n * are primarily intended for tracking network related metrics.\n */\nexport type RequestInterceptors = {\n /**\n * Callback that will be invoked with the finished request object before it\n * is finalized. In the browser the request may already have been sent.\n *\n * @param req - Request object or XHR instance used for this request.\n */\n before?: (req: ClientRequest) => void;\n /**\n * Callback that will be invoked when the server response has been received\n * and processed or when the request has been failed without a response.\n *\n * The originating request will be available as the `request` property\n * on either the error or response object.\n *\n * @param err - Error encountered when handling this request or `null`.\n * @param res - Response object for this request, if no error occurred.\n */\n after?: (err: ArangojsError | null, res?: ArangojsResponse) => void;\n};\n\n/**\n * Options for performing a request with arangojs.\n */\nexport type RequestOptions = {\n /**\n * @internal\n *\n * Identifier of a specific ArangoDB host to use when more than one is known.\n */\n hostUrl?: string;\n /**\n * HTTP method to use in order to perform the request.\n *\n * Default: `\"GET\"`\n */\n method?: string;\n /**\n * Request body data.\n */\n body?: any;\n /**\n * If set to `true`, the response body will not be interpreted as JSON and\n * instead passed as-is.\n */\n expectBinary?: boolean;\n /**\n * If set to `true`, the request body will not be converted to JSON and\n * instead passed as-is.\n */\n isBinary?: boolean;\n /**\n * Whether ArangoDB is allowed to perform a dirty read to respond to this\n * request. If set to `true`, the response may reflect a dirty state from\n * a non-authoritative server.\n */\n allowDirtyRead?: boolean;\n /**\n * If set to a positive number, the request will automatically be retried at\n * most this many times if it results in a write-write conflict.\n *\n * Default: `config.retryOnConflict`\n */\n retryOnConflict?: number;\n /**\n * HTTP headers to pass along with this request in addition to the default\n * headers generated by arangojs.\n */\n headers?: Headers;\n /**\n * Time in milliseconds after which arangojs will abort the request if the\n * socket has not already timed out.\n *\n * See also `agentOptions.timeout` in {@link Config}.\n */\n timeout?: number;\n /**\n * Optional prefix path to prepend to the `path`.\n */\n basePath?: string;\n /**\n * URL path, relative to the `basePath` and server domain.\n */\n path?: string;\n /**\n * URL parameters to pass as part of the query string.\n */\n qs?: string | Params;\n};\n\n/**\n * @internal\n */\ntype Task = {\n hostUrl?: string;\n stack?: () => string;\n allowDirtyRead: boolean;\n retryOnConflict: number;\n resolve: (result: any) => void;\n reject: (error: Error) => void;\n transform?: (res: ArangojsResponse) => any;\n retries: number;\n options: {\n method: string;\n expectBinary: boolean;\n timeout?: number;\n url: { pathname: string; search?: string };\n headers: Headers;\n body: any;\n };\n};\n\n/**\n * Options for creating the Node.js `http.Agent` or `https.Agent`.\n *\n * In browser environments this option can be used to pass additional options\n * to the underlying calls of the\n * [xhr module](https://www.npmjs.com/package/xhr).\n *\n * See also [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options)\n * and [`https.Agent`](https://nodejs.org/api/https.html#https_new_agent_options)\n * (when using TLS).\n */\nexport type AgentOptions = NodeAgentOptions | XhrOptions;\n\n/**\n * Options for configuring arangojs.\n */\nexport type Config = {\n /**\n * Name of the database to use.\n *\n * Default: `\"_system\"`\n */\n databaseName?: string;\n /**\n * Base URL of the ArangoDB server or list of server URLs.\n *\n * When working with a cluster or a single server with leader/follower\n * failover, the method {@link database.Database#acquireHostList} can be used to\n * automatically pick up additional coordinators/followers at any point.\n *\n * When running ArangoDB on a unix socket, e.g. `/tmp/arangodb.sock`, the\n * following URL formats are supported for unix sockets:\n *\n * - `unix:///tmp/arangodb.sock` (no SSL)\n * - `http+unix:///tmp/arangodb.sock` (or `https+unix://` for SSL)\n * - `http://unix:/tmp/arangodb.sock` (or `https://unix:` for SSL)\n *\n * Additionally `ssl` and `tls` are treated as synonymous with `https` and\n * `tcp` is treated as synonymous with `http`, so the following URLs are\n * considered identical:\n *\n * - `tcp://127.0.0.1:8529` and `http://127.0.0.1:8529`\n * - `ssl://127.0.0.1:8529` and `https://127.0.0.1:8529`\n * - `tcp+unix:///tmp/arangodb.sock` and `http+unix:///tmp/arangodb.sock`\n * - `ssl+unix:///tmp/arangodb.sock` and `https+unix:///tmp/arangodb.sock`\n * - `tcp://unix:/tmp/arangodb.sock` and `http://unix:/tmp/arangodb.sock`\n * - `ssl://unix:/tmp/arangodb.sock` and `https://unix:/tmp/arangodb.sock`\n *\n * See also `auth` for passing authentication credentials.\n *\n * Default: `\"http://127.0.0.1:8529\"`\n */\n url?: string | string[];\n /**\n * Credentials to use for authentication.\n *\n * See also {@link database.Database#useBasicAuth} and\n * {@link database.Database#useBearerAuth}.\n *\n * Default: `{ username: \"root\", password: \"\" }`\n */\n auth?: BasicAuthCredentials | BearerAuthCredentials;\n /**\n * Numeric representation of the ArangoDB version the driver should expect.\n * The format is defined as `XYYZZ` where `X` is the major version, `Y` is\n * the zero-filled two-digit minor version and `Z` is the zero-filled two-digit\n * bugfix version, e.g. `30102` for 3.1.2, `20811` for 2.8.11.\n *\n * Depending on this value certain methods may become unavailable or change\n * their behavior to remain compatible with different versions of ArangoDB.\n *\n * Default: `30900`\n */\n arangoVersion?: number;\n /**\n * Determines the behavior when multiple URLs are provided:\n *\n * - `\"NONE\"`: No load balancing. All requests will be handled by the first\n * URL in the list until a network error is encountered. On network error,\n * arangojs will advance to using the next URL in the list.\n *\n * - `\"ONE_RANDOM\"`: Randomly picks one URL from the list initially, then\n * behaves like `\"NONE\"`.\n *\n * - `\"ROUND_ROBIN\"`: Every sequential request uses the next URL in the list.\n *\n * Default: `\"NONE\"`\n */\n loadBalancingStrategy?: LoadBalancingStrategy;\n /**\n * Determines the behavior when a request fails because the underlying\n * connection to the server could not be opened\n * (i.e. [`ECONNREFUSED` in Node.js](https://nodejs.org/api/errors.html#errors_common_system_errors)):\n *\n * - `false`: the request fails immediately.\n *\n * - `0`: the request is retried until a server can be reached but only a\n * total number of times matching the number of known servers (including\n * the initial failed request).\n *\n * - any other number: the request is retried until a server can be reached\n * or the request has been retried a total of `maxRetries` number of times\n * (not including the initial failed request).\n *\n * When working with a single server without leader/follower failover, the\n * retries (if any) will be made to the same server.\n *\n * This setting currently has no effect when using arangojs in a browser.\n *\n * **Note**: Requests bound to a specific server (e.g. fetching query results)\n * will never be retried automatically and ignore this setting.\n *\n * **Note**: To set the number of retries when a write-write conflict is\n * encountered, see `retryOnConflict` instead.\n *\n * Default: `0`\n */\n maxRetries?: false | number;\n /**\n * If set to a positive number, requests will automatically be retried at\n * most this many times if they result in a write-write conflict.\n *\n * Default: `0`\n */\n retryOnConflict?: number;\n /**\n * An http `Agent` instance to use for connections.\n *\n * By default a new `Agent` instance will be created using the `agentOptions`.\n *\n * This option has no effect when using the browser version of arangojs.\n *\n * See also [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options)\n * and [`https.Agent`](https://nodejs.org/api/https.html#https_new_agent_options)\n * (when using TLS).\n */\n agent?: any;\n /**\n * Options used to create that underlying HTTP/HTTPS `Agent` (or the `xhr`\n * module when using arangojs in the browser). This will be ignored if\n * `agent` is also provided.\n *\n * The option `maxSockets` is also used to limit how many requests\n * arangojs will perform concurrently. The maximum number of requests is\n * equal to `maxSockets`.\n *\n * **Note:** arangojs will limit the number of concurrent requests based on\n * this value even if an `agent` is provided.\n *\n * **Note:** when using `ROUND_ROBIN` load balancing and passing an array of\n * URLs in the `url` option, the default value of `maxSockets` will be set\n * to `3 * url.length` instead of `3`.\n *\n * Default (Node.js): `{ maxSockets: 3, keepAlive: true, keepAliveMsecs: 1000 }`\n *\n * Default (browser): `{ maxSockets: 3, useXDR: true, withCredentials: true }`\n */\n agentOptions?: AgentOptions & RequestInterceptors;\n /**\n * An object with additional headers to send with every request.\n *\n * If an `\"authorization\"` header is provided, it will be overridden when\n * using {@link database.Database#useBasicAuth}, {@link database.Database#useBearerAuth} or\n * the `auth` configuration option.\n */\n headers?: Headers;\n /**\n * If set to `true`, arangojs will generate stack traces every time a request\n * is initiated and augment the stack traces of any errors it generates.\n *\n * **Warning**: This will cause arangojs to generate stack traces in advance\n * even if the request does not result in an error. Generating stack traces\n * may negatively impact performance.\n */\n precaptureStackTraces?: boolean;\n /**\n * Limits the number of values of server-reported response queue times that\n * will be stored and accessible using {@link database.Database#queueTime}. If set to\n * a finite value, older values will be discarded to make room for new values\n * when that limit is reached.\n *\n * Default: `10`\n */\n responseQueueTimeSamples?: number;\n};\n\n/**\n * Indicates whether the given value represents a {@link Connection}.\n *\n * @param connection - A value that might be a connection.\n *\n * @internal\n */\nexport function isArangoConnection(connection: any): connection is Connection {\n return Boolean(connection && connection.isArangoConnection);\n}\n\n/**\n * Represents a connection pool shared by one or more databases.\n *\n * @internal\n */\nexport class Connection {\n protected _activeTasks: number = 0;\n protected _agent?: any;\n protected _agentOptions: { [key: string]: any };\n protected _arangoVersion: number = 30900;\n protected _headers: Headers;\n protected _loadBalancingStrategy: LoadBalancingStrategy;\n protected _maxRetries: number | false;\n protected _retryOnConflict: number;\n protected _maxTasks: number;\n protected _queue = new LinkedList<Task>();\n protected _databases = new Map<string, Database>();\n protected _hosts: RequestFunction[] = [];\n protected _hostUrls: string[] = [];\n protected _activeHostUrl: string;\n protected _activeDirtyHostUrl: string;\n protected _transactionId: string | null = null;\n protected _precaptureStackTraces: boolean;\n protected _queueTimes = new LinkedList<[number, number]>();\n protected _responseQueueTimeSamples: number;\n\n /**\n * @internal\n *\n * Creates a new `Connection` instance.\n *\n * @param config - An object with configuration options.\n *\n */\n constructor(config: Omit<Config, \"databaseName\"> = {}) {\n const URLS = config.url\n ? Array.isArray(config.url)\n ? config.url\n : [config.url]\n : [\"http://127.0.0.1:8529\"];\n const MAX_SOCKETS =\n 3 * (config.loadBalancingStrategy === \"ROUND_ROBIN\" ? URLS.length : 1);\n\n if (config.arangoVersion !== undefined) {\n this._arangoVersion = config.arangoVersion;\n }\n this._agent = config.agent;\n this._agentOptions = isBrowser\n ? { maxSockets: MAX_SOCKETS, ...config.agentOptions }\n : {\n maxSockets: MAX_SOCKETS,\n keepAlive: true,\n keepAliveMsecs: 1000,\n scheduling: \"lifo\",\n ...config.agentOptions,\n };\n this._maxTasks = this._agentOptions.maxSockets;\n this._headers = { ...config.headers };\n this._loadBalancingStrategy = config.loadBalancingStrategy ?? \"NONE\";\n this._precaptureStackTraces = Boolean(config.precaptureStackTraces);\n this._responseQueueTimeSamples = config.responseQueueTimeSamples ?? 10;\n this._retryOnConflict = config.retryOnConflict ?? 0;\n if (this._responseQueueTimeSamples < 0) {\n this._responseQueueTimeSamples = Infinity;\n }\n if (config.maxRetries === false) {\n this._maxRetries = false;\n } else {\n this._maxRetries = Number(config.maxRetries ?? 0);\n }\n\n this.addToHostList(URLS);\n\n if (config.auth) {\n if (isBearerAuth(config.auth)) {\n this.setBearerAuth(config.auth);\n } else {\n this.setBasicAuth(config.auth);\n }\n }\n\n if (this._loadBalancingStrategy === \"ONE_RANDOM\") {\n this._activeHostUrl =\n this._hostUrls[Math.floor(Math.random() * this._hostUrls.length)];\n this._activeDirtyHostUrl =\n this._hostUrls[Math.floor(Math.random() * this._hostUrls.length)];\n } else {\n this._activeHostUrl = this._hostUrls[0];\n this._activeDirtyHostUrl = this._hostUrls[0];\n }\n }\n\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB connection.\n */\n get isArangoConnection(): true {\n return true;\n }\n\n get queueTime() {\n return {\n getLatest: () => this._queueTimes.last?.value[1],\n getValues: () => Array.from(this._queueTimes.values()),\n getAvg: () => {\n let avg = 0;\n for (const [, [, value]] of this._queueTimes) {\n avg += value / this._queueTimes.length;\n }\n return avg;\n },\n };\n }\n\n protected _runQueue() {\n if (!this._queue.length || this._activeTasks >= this._maxTasks) return;\n const task = this._queue.shift()!;\n let hostUrl = this._activeHostUrl;\n if (task.hostUrl !== undefined) {\n hostUrl = task.hostUrl;\n } else if (task.allowDirtyRead) {\n hostUrl = this._activeDirtyHostUrl;\n this._activeDirtyHostUrl =\n this._hostUrls[\n (this._hostUrls.indexOf(this._activeDirtyHostUrl) + 1) %\n this._hostUrls.length\n ];\n task.options.headers[\"x-arango-allow-dirty-read\"] = \"true\";\n } else if (this._loadBalancingStrategy === \"ROUND_ROBIN\") {\n this._activeHostUrl =\n this._hostUrls[\n (this._hostUrls.indexOf(this._activeHostUrl) + 1) %\n this._hostUrls.length\n ];\n }\n this._activeTasks += 1;\n const callback: Errback<ArangojsResponse> = (err, res) => {\n this._activeTasks -= 1;\n if (!err && res) {\n if (res.statusCode === 503 && res.headers[LEADER_ENDPOINT_HEADER]) {\n const url = res.headers[LEADER_ENDPOINT_HEADER]!;\n const [cleanUrl] = this.addToHostList(url);\n task.hostUrl = cleanUrl;\n if (this._activeHostUrl === hostUrl) {\n this._activeHostUrl = cleanUrl;\n }\n this._queue.push(task);\n } else {\n res.arangojsHostUrl = hostUrl;\n const contentType = res.headers[\"content-type\"];\n const queueTime = res.headers[\"x-arango-queue-time-seconds\"];\n if (queueTime) {\n this._queueTimes.push([Date.now(), Number(queueTime)]);\n while (this._responseQueueTimeSamples < this._queueTimes.length) {\n this._queueTimes.shift();\n }\n }\n let parsedBody: any = undefined;\n if (res.body.length && contentType && contentType.match(MIME_JSON)) {\n try {\n parsedBody = res.body;\n parsedBody = JSON.parse(parsedBody);\n } catch (e: any) {\n if (!task.options.expectBinary) {\n if (typeof parsedBody !== \"string\") {\n parsedBody = res.body.toString(\"utf-8\");\n }\n e.res = res;\n if (task.stack) {\n e.stack += task.stack();\n }\n callback(e);\n return;\n }\n }\n } else if (res.body && !task.options.expectBinary) {\n parsedBody = res.body.toString(\"utf-8\");\n } else {\n parsedBody = res.body;\n }\n if (isArangoErrorResponse(parsedBody)) {\n res.body = parsedBody;\n err = new ArangoError(res);\n } else if (res.statusCode && res.statusCode >= 400) {\n res.body = parsedBody;\n err = new HttpError(res);\n } else {\n if (!task.options.expectBinary) res.body = parsedBody;\n task.resolve(task.transform ? task.transform(res) : (res as any));\n }\n }\n }\n if (err) {\n if (\n !task.allowDirtyRead &&\n this._hosts.length > 1 &&\n this._activeHostUrl === hostUrl &&\n this._loadBalancingStrategy !== \"ROUND_ROBIN\"\n ) {\n this._activeHostUrl =\n this._hostUrls[\n (this._hostUrls.indexOf(this._activeHostUrl) + 1) %\n this._hostUrls.length\n ];\n }\n if (\n isArangoError(err) &&\n err.errorNum === ERROR_ARANGO_CONFLICT &&\n task.retryOnConflict > 0\n ) {\n task.retryOnConflict -= 1;\n this._queue.push(task);\n } else if (\n ((isSystemError(err) &&\n err.syscall === \"connect\" &&\n err.code === \"ECONNREFUSED\") ||\n (isArangoError(err) &&\n err.errorNum === ERROR_ARANGO_MAINTENANCE_MODE)) &&\n task.hostUrl === undefined &&\n this._maxRetries !== false &&\n task.retries < (this._maxRetries || this._hosts.length - 1)\n ) {\n task.retries += 1;\n this._queue.push(task);\n } else {\n if (task.stack) {\n err.stack += task.stack();\n }\n task.reject(err);\n }\n }\n this._runQueue();\n };\n try {\n this._hosts[this._hostUrls.indexOf(hostUrl)](task.options, callback);\n } catch (e: any) {\n callback(e);\n }\n }\n\n protected _buildUrl({ basePath, path, qs }: UrlInfo) {\n const pathname = `${basePath || \"\"}${path || \"\"}`;\n let search;\n if (qs) {\n if (typeof qs === \"string\") search = `?${qs}`;\n else search = `?${querystringify(qs)}`;\n }\n return search ? { pathname, search } : { pathname };\n }\n\n setBearerAuth(auth: BearerAuthCredentials) {\n this.setHeader(\"authorization\", `Bearer ${auth.token}`);\n }\n\n setBasicAuth(auth: BasicAuthCredentials) {\n this.setHeader(\n \"authorization\",\n `Basic ${base64Encode(`${auth.username}:${auth.password}`)}`\n );\n }\n\n setResponseQueueTimeSamples(responseQueueTimeSamples: number) {\n if (responseQueueTimeSamples < 0) {\n responseQueueTimeSamples = Infinity;\n }\n this._responseQueueTimeSamples = responseQueueTimeSamples;\n while (this._responseQueueTimeSamples < this._queueTimes.length) {\n this._queueTimes.shift();\n }\n }\n\n /**\n * @internal\n *\n * Fetches a {@link database.Database} instance for the given database name from the\n * internal cache, if available.\n *\n * @param databaseName - Name of the database.\n */\n database(databaseName: string): Database | undefined;\n /**\n * @internal\n *\n * Adds a {@link database.Database} instance for the given database name to the\n * internal cache.\n *\n * @param databaseName - Name of the database.\n * @param database - Database instance to add to the cache.\n */\n database(databaseName: string, database: Database): Database;\n /**\n * @internal\n *\n * Clears any {@link database.Database} instance stored for the given database name\n * from the internal cache, if present.\n *\n * @param databaseName - Name of the database.\n * @param database - Must be `null`.\n */\n database(databaseName: string, database: null): undefined;\n database(\n databaseName: string,\n database?: Database | null\n ): Database | undefined {\n if (database === null) {\n this._databases.delete(databaseName);\n return undefined;\n }\n if (!database) {\n return this._databases.get(databaseName);\n }\n this._databases.set(databaseName, database);\n return database;\n }\n\n /**\n * @internal\n *\n * Replaces the host list with the given URLs.\n *\n * See {@link Connection#acquireHostList}.\n *\n * @param urls - URLs to use as host list.\n */\n setHostList(urls: string[]): void {\n const cleanUrls = urls.map((url) => normalizeUrl(url));\n this._hosts.splice(\n 0,\n this._hosts.length,\n ...cleanUrls.map((url) => {\n const i = this._hostUrls.indexOf(url);\n if (i !== -1) return this._hosts[i];\n return createRequest(url, this._agentOptions, this._agent);\n })\n );\n this._hostUrls.splice(0, this._hostUrls.length, ...cleanUrls);\n }\n\n /**\n * @internal\n *\n * Adds the given URL or URLs to the host list.\n *\n * See {@link Connection#acquireHostList}.\n *\n * @param urls - URL or URLs to add.\n */\n addToHostList(urls: string | string[]): string[] {\n const cleanUrls = (Array.isArray(urls) ? urls : [urls]).map((url) =>\n normalizeUrl(url)\n );\n const newUrls = cleanUrls.filter(\n (url) => this._hostUrls.indexOf(url) === -1\n );\n this._hostUrls.push(...newUrls);\n this._hosts.push(\n ...newUrls.map((url: string) =>\n createRequest(url, this._agentOptions, this._agent)\n )\n );\n return cleanUrls;\n }\n\n /**\n * @internal\n *\n * Sets the connection's active `transactionId`.\n *\n * While set, all requests will use this ID, ensuring the requests are executed\n * within the transaction if possible. Setting the ID manually may cause\n * unexpected behavior.\n *\n * See also {@link Connection#clearTransactionId}.\n *\n * @param transactionId - ID of the active transaction.\n */\n setTransactionId(transactionId: string) {\n this._transactionId = transactionId;\n }\n\n /**\n * @internal\n *\n * Clears the connection's active `transactionId`.\n */\n clearTransactionId() {\n this._transactionId = null;\n }\n\n /**\n * @internal\n *\n * Sets the header `headerName` with the given `value` or clears the header if\n * `value` is `null`.\n *\n * @param headerName - Name of the header to set.\n * @param value - Value of the header.\n */\n setHeader(headerName: string, value: string | null) {\n if (value === null) {\n delete this._headers[headerName];\n } else {\n this._headers[headerName] = value;\n }\n }\n\n /**\n * @internal\n *\n * Closes all open connections.\n *\n * See {@link database.Database#close}.\n */\n close() {\n for (const host of this._hosts) {\n if (host.close) host.close();\n }\n }\n\n /**\n * @internal\n *\n * Waits for propagation.\n *\n * See {@link database.Database#waitForPropagation}.\n *\n * @param request - Request to perform against each coordinator.\n * @param timeout - Maximum number of milliseconds to wait for propagation.\n */\n async waitForPropagation(request: RequestOptions, timeout = Infinity) {\n const numHosts = this._hosts.length;\n const propagated = [] as string[];\n const started = Date.now();\n let index = 0;\n while (true) {\n if (propagated.length === numHosts) {\n return;\n }\n while (propagated.includes(this._hostUrls[index])) {\n index = (index + 1) % numHosts;\n }\n const hostUrl = this._hostUrls[index];\n try {\n await this.request({ ...request, hostUrl });\n } catch (e: any) {\n if (started + timeout < Date.now()) {\n throw e;\n }\n await new Promise((resolve) => setTimeout(resolve, 1000));\n continue;\n }\n if (!propagated.includes(hostUrl)) {\n propagated.push(hostUrl);\n }\n }\n }\n\n /**\n * @internal\n *\n * Performs a request using the arangojs connection pool.\n */\n request<T = ArangojsResponse>(\n {\n hostUrl,\n method = \"GET\",\n body,\n expectBinary = false,\n isBinary = false,\n allowDirtyRead = false,\n retryOnConflict = this._retryOnConflict,\n timeout = 0,\n headers,\n ...urlInfo\n }: RequestOptions,\n transform?: (res: ArangojsResponse) => T\n ): Promise<T> {\n return new Promise((resolve, reject) => {\n let contentType = \"text/plain\";\n if (isBinary) {\n contentType = \"application/octet-stream\";\n } else if (body) {\n if (typeof body === \"object\") {\n body = JSON.stringify(body);\n contentType = \"application/json\";\n } else {\n body = String(body);\n }\n }\n\n const extraHeaders: Headers = {\n ...this._headers,\n \"content-type\": contentType,\n \"x-arango-version\": String(this._arangoVersion),\n };\n\n if (this._transactionId) {\n extraHeaders[\"x-arango-trx-id\"] = this._transactionId;\n }\n\n const task: Task = {\n retries: 0,\n hostUrl,\n allowDirtyRead,\n retryOnConflict,\n options: {\n url: this._buildUrl(urlInfo),\n headers: { ...extraHeaders, ...headers },\n timeout,\n method,\n expectBinary,\n body,\n },\n reject,\n resolve,\n transform,\n };\n\n if (this._precaptureStackTraces) {\n if (typeof Error.captureStackTrace === \"function\") {\n const capture = {} as { readonly stack: string };\n Error.captureStackTrace(capture);\n task.stack = () =>\n `\\n${capture.stack.split(\"\\n\").slice(3).join(\"\\n\")}`;\n } else {\n const capture = generateStackTrace() as { readonly stack: string };\n if (Object.prototype.hasOwnProperty.call(capture, \"stack\")) {\n task.stack = () =>\n `\\n${capture.stack.split(\"\\n\").slice(4).join(\"\\n\")}`;\n }\n }\n }\n\n this._queue.push(task);\n this._runQueue();\n });\n }\n}\n","export function querystringify(\n obj: Record<\n string,\n | string\n | number\n | boolean\n | null\n | undefined\n | readonly (string | number | boolean | null | undefined)[]\n >\n) {\n let result = \"\";\n for (let [key, value] of Object.entries(obj)) {\n if (value === undefined) continue;\n key = encodeURIComponent(key);\n if (!Array.isArray(value)) {\n if (value === null) value = \"\";\n else value = encodeURIComponent(String(value));\n result += `&${key}=${value}`;\n } else {\n for (let item of value) {\n if (item == null) item = \"\";\n else item = encodeURIComponent(String(item));\n result += `&${key}=${item}`;\n }\n }\n }\n return result.slice(1);\n}\n","/**\n * Utility function for constructing a multipart form in the browser.\n *\n * @packageDocumentation\n * @internal\n */\n\nimport { Errback } from \"./errback\";\nimport { Fields, MultipartRequest } from \"./multipart\";\n\ndeclare const FormData: any;\ndeclare const Blob: any;\n\n/**\n * @internal\n */\nexport function toForm(fields: Fields, callback: Errback<MultipartRequest>) {\n let form;\n try {\n form = new FormData();\n for (const key of Object.keys(fields)) {\n let value = fields[key];\n if (value === undefined) continue;\n if (\n !(value instanceof Blob) &&\n (typeof value === \"object\" || typeof value === \"function\")\n ) {\n value = JSON.stringify(value);\n }\n form.append(key, value);\n }\n } catch (e: any) {\n callback(e);\n return;\n }\n callback(null, { body: form });\n}\n","/**\n * ```ts\n * import type { Route } from \"arangojs/route\";\n * ```\n *\n * The \"route\" module provides route related types and interfaces for TypeScript.\n *\n * @packageDocumentation\n */\nimport { Headers, Params, RequestOptions } from \"./connection\";\nimport { Database } from \"./database\";\nimport { ArangojsResponse } from \"./lib/request\";\n\n/**\n * Represents an arbitrary route relative to an ArangoDB database.\n */\nexport class Route {\n protected _db: Database;\n protected _path: string;\n protected _headers: Headers;\n\n /**\n * @internal\n */\n constructor(db: Database, path: string = \"\", headers: Headers = {}) {\n if (!path) path = \"\";\n else if (path.charAt(0) !== \"/\") path = `/${path}`;\n this._db = db;\n this._path = path;\n this._headers = headers;\n }\n\n /**\n * Creates a new route relative to this route that inherits any of its default\n * HTTP headers.\n *\n * @param path - Path relative to this route.\n * @param headers - Additional headers that will be sent with each request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const users = foxx.route(\"/users\");\n * ```\n */\n route(path: string, headers?: Headers) {\n if (!path) path = \"\";\n else if (path.charAt(0) !== \"/\") path = `/${path}`;\n return new Route(this._db, this._path + path, {\n ...this._headers,\n ...headers,\n });\n }\n\n /**\n * Performs an arbitrary HTTP request relative to this route and returns the\n * server response.\n *\n * @param options - Options for performing the request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const res = await foxx.request({\n * method: \"POST\",\n * path: \"/users\",\n * body: {\n * username: \"admin\",\n * password: \"hunter2\"\n * }\n * });\n * ```\n */\n request(options?: RequestOptions) {\n const opts = { ...options };\n if (!opts.path || opts.path === \"/\") opts.path = \"\";\n else if (!this._path || opts.path.charAt(0) === \"/\") opts.path = opts.path;\n else opts.path = `/${opts.path}`;\n opts.basePath = this._path;\n opts.headers = { ...this._headers, ...opts.headers };\n opts.method = opts.method ? opts.method.toUpperCase() : \"GET\";\n return this._db.request(opts, false);\n }\n\n /**\n * Performs a DELETE request against the given path relative to this route\n * and returns the server response.\n *\n * @param path - Path relative to this route.\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const res = await foxx.delete(\"/users/admin\");\n * ```\n */\n delete(\n path: string,\n qs?: string | Params,\n headers?: Headers\n ): Promise<ArangojsResponse>;\n /**\n * Performs a DELETE request against the given path relative to this route\n * and returns the server response.\n *\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const user = foxx.roue(\"/users/admin\");\n * const res = await user.delete();\n * ```\n */\n delete(qs?: Params, headers?: Headers): Promise<ArangojsResponse>;\n delete(...args: any[]): Promise<ArangojsResponse> {\n const path = typeof args[0] === \"string\" ? args.shift() : undefined;\n const [qs, headers] = args;\n return this.request({ method: \"DELETE\", path, qs, headers });\n }\n\n /**\n * Performs a GET request against the given path relative to this route\n * and returns the server response.\n *\n * @param path - Path relative to this route.\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const res = await foxx.get(\"/users\", { offset: 10, limit: 5 });\n * ```\n */\n get(\n path: string,\n qs?: string | Params,\n headers?: Headers\n ): Promise<ArangojsResponse>;\n /**\n * Performs a GET request against the given path relative to this route\n * and returns the server response.\n *\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const users = foxx.route(\"/users\");\n * const res = await users.get({ offset: 10, limit: 5 });\n * ```\n */\n get(qs?: Params, headers?: Headers): Promise<ArangojsResponse>;\n get(...args: any[]): Promise<ArangojsResponse> {\n const path = typeof args[0] === \"string\" ? args.shift() : undefined;\n const [qs, headers] = args;\n return this.request({ method: \"GET\", path, qs, headers });\n }\n\n /**\n * Performs a HEAD request against the given path relative to this route\n * and returns the server response.\n *\n * @param path - Path relative to this route.\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const res = await foxx.head(\"/users\", { offset: 10, limit: 5 });\n * ```\n */\n head(\n path: string,\n qs?: string | Params,\n headers?: Headers\n ): Promise<ArangojsResponse>;\n /**\n * Performs a HEAD request against the given path relative to this route\n * and returns the server response.\n *\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const users = foxx.route(\"/users\");\n * const res = await users.head({ offset: 10, limit: 5 });\n * ```\n */\n head(qs?: Params, headers?: Headers): Promise<ArangojsResponse>;\n head(...args: any[]): Promise<ArangojsResponse> {\n const path = typeof args[0] === \"string\" ? args.shift() : undefined;\n const [qs, headers] = args;\n return this.request({ method: \"HEAD\", path, qs, headers });\n }\n\n /**\n * Performs a PATCH request against the given path relative to this route\n * and returns the server response.\n *\n * @param path - Path relative to this route.\n * @param body - Body of the request object.\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const res = await foxx.patch(\"/users/admin\", { password: \"admin\" });\n * ```\n */\n patch(\n path: string,\n body?: any,\n qs?: string | Params,\n headers?: Headers\n ): Promise<ArangojsResponse>;\n /**\n * Performs a PATCH request against the given path relative to this route\n * and returns the server response.\n *\n * **Note**: `body` must not be a `string`.\n *\n * @param body - Body of the request object. Must not be a string.\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const user = foxx.route(\"/users/admin\")\n * const res = await user.patch({ password: \"admin\" });\n * ```\n */\n patch(\n body?: any,\n qs?: string | Params,\n headers?: Headers\n ): Promise<ArangojsResponse>;\n patch(...args: any[]): Promise<ArangojsResponse> {\n const path = typeof args[0] === \"string\" ? args.shift() : undefined;\n const [body, qs, headers] = args;\n return this.request({ method: \"PATCH\", path, body, qs, headers });\n }\n\n /**\n * Performs a POST request against the given path relative to this route\n * and returns the server response.\n *\n * @param path - Path relative to this route.\n * @param body - Body of the request object.\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const res = await foxx.post(\"/users\", {\n * username: \"admin\",\n * password: \"hunter2\"\n * });\n * ```\n */\n post(\n path: string,\n body?: any,\n qs?: string | Params,\n headers?: Headers\n ): Promise<ArangojsResponse>;\n /**\n * Performs a POST request against the given path relative to this route\n * and returns the server response.\n *\n * **Note**: `body` must not be a `string`.\n *\n * @param body - Body of the request object. Must not be a string.\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const users = foxx.route(\"/users\");\n * const res = await users.post({\n * username: \"admin\",\n * password: \"hunter2\"\n * });\n * ```\n */\n post(\n body?: any,\n qs?: string | Params,\n headers?: Headers\n ): Promise<ArangojsResponse>;\n post(...args: any[]): Promise<ArangojsResponse> {\n const path = typeof args[0] === \"string\" ? args.shift() : undefined;\n const [body, qs, headers] = args;\n return this.request({ method: \"POST\", path, body, qs, headers });\n }\n\n /**\n * Performs a PUT request against the given path relative to this route\n * and returns the server response.\n *\n * @param path - Path relative to this route.\n * @param body - Body of the request object.\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const res = await foxx.put(\"/users/admin/password\", { password: \"admin\" });\n * ```\n */\n put(\n path: string,\n body?: any,\n qs?: string | Params,\n headers?: Headers\n ): Promise<ArangojsResponse>;\n /**\n * Performs a PUT request against the given path relative to this route\n * and returns the server response.\n *\n * **Note**: `body` must not be a `string`.\n *\n * @param body - Body of the request object. Must not be a string.\n * @param qs - Query string parameters for this request.\n * @param headers - Additional headers to send with this request.\n *\n * @example\n * ```js\n * const db = new Database();\n * const foxx = db.route(\"/my-foxx-service\");\n * const password = foxx.route(\"/users/admin/password\");\n * const res = await password.put({ password: \"admin\" });\n * ```\n */\n put(\n body?: any,\n qs?: string | Params,\n headers?: Headers\n ): Promise<ArangojsResponse>;\n put(...args: any[]): Promise<ArangojsResponse> {\n const path = typeof args[0] === \"string\" ? args.shift() : undefined;\n const [body, qs, headers] = args;\n return this.request({ method: \"PUT\", path, body, qs, headers });\n }\n}\n","/**\n * ```ts\n * import type { Transaction } from \"arangojs/transaction\";\n * ```\n *\n * The \"transaction\" module provides transaction related types and interfaces\n * for TypeScript.\n *\n * @packageDocumentation\n */\nimport { Connection } from \"./connection\";\nimport { Database } from \"./database\";\nimport { isArangoError } from \"./error\";\nimport { TRANSACTION_NOT_FOUND } from \"./lib/codes\";\n\n/**\n * Indicates whether the given value represents a {@link Transaction}.\n *\n * @param transaction - A value that might be a transaction.\n */\nexport function isArangoTransaction(\n transaction: any\n): transaction is Transaction {\n return Boolean(transaction && transaction.isArangoTransaction);\n}\n\n/**\n * Options for how the transaction should be committed.\n */\nexport type TransactionCommitOptions = {\n /**\n * If set to `true`, the request will explicitly permit ArangoDB to return a\n * potentially dirty or stale result and arangojs will load balance the\n * request without distinguishing between leaders and followers.\n */\n allowDirtyRead?: boolean;\n};\n\n/**\n * Options for how the transaction should be aborted.\n */\nexport type TransactionAbortOptions = {\n /**\n * If set to `true`, the request will explicitly permit ArangoDB to return a\n * potentially dirty or stale result and arangojs will load balance the\n * request without distinguishing between leaders and followers.\n */\n allowDirtyRead?: boolean;\n};\n\n/**\n * Status of a given transaction.\n *\n * See also {@link database.TransactionDetails}.\n */\nexport type TransactionStatus = {\n /**\n * Unique identifier of the transaction.\n */\n id: string;\n /**\n * Status of the transaction.\n */\n status: \"running\" | \"committed\" | \"aborted\";\n};\n\n/**\n * Represents a streaming transaction in a {@link database.Database}.\n */\nexport class Transaction {\n protected _db: Database;\n protected _id: string;\n\n /**\n * @internal\n */\n constructor(db: Database, id: string) {\n this._db = db;\n this._id = id;\n }\n\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB transaction.\n */\n get isArangoTransaction(): true {\n return true;\n }\n\n /**\n * Unique identifier of this transaction.\n *\n * See {@link database.Database#transaction}.\n */\n get id() {\n return this._id;\n }\n\n /**\n * Checks whether the transaction exists.\n *\n * @example\n * ```js\n * const db = new Database();\n * const trx = db.transaction(\"some-transaction\");\n * const result = await trx.exists();\n * // result indicates whether the transaction exists\n * ```\n */\n async exists(): Promise<boolean> {\n try {\n await this.get();\n return true;\n } catch (err: any) {\n if (isArangoError(err) && err.errorNum === TRANSACTION_NOT_FOUND) {\n return false;\n }\n throw err;\n }\n }\n\n /**\n * Retrieves general information about the transaction.\n *\n * @example\n * ```js\n * const db = new Database();\n * const col = db.collection(\"some-collection\");\n * const trx = db.beginTransaction(col);\n * await trx.step(() => col.save({ hello: \"world\" }));\n * const info = await trx.get();\n * // the transaction exists\n * ```\n */\n get(): Promise<TransactionStatus> {\n return this._db.request(\n {\n path: `/_api/transaction/${encodeURIComponent(this.id)}`,\n },\n (res) => res.body.result\n );\n }\n\n /**\n * Attempts to commit the transaction to the databases.\n *\n * @param options - Options for comitting the transaction.\n *\n * @example\n * ```js\n * const db = new Database();\n * const col = db.collection(\"some-collection\");\n * const trx = db.beginTransaction(col);\n * await trx.step(() => col.save({ hello: \"world\" }));\n * const result = await trx.commit();\n * // result indicates the updated transaction status\n * ```\n */\n commit(options: TransactionCommitOptions = {}): Promise<TransactionStatus> {\n const { allowDirtyRead = undefined } = options;\n return this._db.request(\n {\n method: \"PUT\",\n path: `/_api/transaction/${encodeURIComponent(this.id)}`,\n allowDirtyRead,\n },\n (res) => res.body.result\n );\n }\n\n /**\n * Attempts to abort the transaction to the databases.\n *\n * @param options - Options for aborting the transaction.\n *\n * @example\n * ```js\n * const db = new Database();\n * const col = db.collection(\"some-collection\");\n * const trx = db.beginTransaction(col);\n * await trx.step(() => col.save({ hello: \"world\" }));\n * const result = await trx.abort();\n * // result indicates the updated transaction status\n * ```\n */\n abort(options: TransactionAbortOptions = {}): Promise<TransactionStatus> {\n const { allowDirtyRead = undefined } = options;\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/transaction/${encodeURIComponent(this.id)}`,\n allowDirtyRead,\n },\n (res) => res.body.result\n );\n }\n\n /**\n * Executes the given function locally as a single step of the transaction.\n *\n * @param T - Type of the callback's returned promise.\n * @param callback - Callback function returning a promise.\n *\n * **Warning**: The callback function should wrap a single call of an async\n * arangojs method (e.g. a method on a `Collection` object of a collection\n * that is involved in the transaction or the `db.query` method).\n * If the callback function is async, only the first promise-returning (or\n * async) method call will be executed as part of the transaction. See the\n * examples below for how to avoid common mistakes when using this method.\n *\n * **Note**: Avoid defining the callback as an async function if possible\n * as arangojs will throw an error if the callback did not return a promise.\n * Async functions will return an empty promise by default, making it harder\n * to notice if you forgot to return something from the callback.\n *\n * **Note**: Although almost anything can be wrapped in a callback and passed\n * to this method, that does not guarantee ArangoDB can actually do it in a\n * transaction. Refer to the ArangoDB documentation if you are unsure whether\n * a given operation can be executed as part of a transaction. Generally any\n * modification or retrieval of data is eligible but modifications of\n * collections or databases are not.\n *\n * @example\n * ```js\n * const db = new Database();\n * const vertices = db.collection(\"vertices\");\n * const edges = db.collection(\"edges\");\n * const trx = await db.beginTransaction({ write: [vertices, edges] });\n *\n * // The following code will be part of the transaction\n * const left = await trx.step(() => vertices.save({ label: \"left\" }));\n * const right = await trx.step(() => vertices.save({ label: \"right\" }));\n *\n * // Results from preceding actions can be used normally\n * await trx.step(() => edges.save({\n * _from: left._id,\n * _to: right._id,\n * data: \"potato\"\n * }));\n *\n * // Transaction must be committed for changes to take effected\n * // Always call either trx.commit or trx.abort to end a transaction\n * await trx.commit();\n * ```\n *\n * @example\n * ```js\n * // BAD! If the callback is an async function it must only use await once!\n * await trx.step(async () => {\n * await collection.save(data);\n * await collection.save(moreData); // WRONG\n * });\n *\n * // BAD! Callback function must use only one arangojs call!\n * await trx.step(() => {\n * return collection.save(data)\n * .then(() => collection.save(moreData)); // WRONG\n * });\n *\n * // BETTER: Wrap every arangojs method call that should be part of the\n * // transaction in a separate `trx.step` call\n * await trx.step(() => collection.save(data));\n * await trx.step(() => collection.save(moreData));\n * ```\n *\n * @example\n * ```js\n * // BAD! If the callback is an async function it must not await before\n * // calling an arangojs method!\n * await trx.step(async () => {\n * await doSomethingElse();\n * return collection.save(data); // WRONG\n * });\n *\n * // BAD! Any arangojs inside the callback must not happen inside a promise\n * // method!\n * await trx.step(() => {\n * return doSomethingElse()\n * .then(() => collection.save(data)); // WRONG\n * });\n *\n * // BETTER: Perform any async logic needed outside the `trx.step` call\n * await doSomethingElse();\n * await trx.step(() => collection.save(data));\n *\n * // OKAY: You can perform async logic in the callback after the arangojs\n * // method call as long as it does not involve additional arangojs method\n * // calls, but this makes it easy to make mistakes later\n * await trx.step(async () => {\n * await collection.save(data);\n * await doSomethingDifferent(); // no arangojs method calls allowed\n * });\n * ```\n *\n * @example\n * ```js\n * // BAD! The callback should not use any functions that themselves use any\n * // arangojs methods!\n * async function saveSomeData() {\n * await collection.save(data);\n * await collection.save(moreData);\n * }\n * await trx.step(() => saveSomeData()); // WRONG\n *\n * // BETTER: Pass the transaction to functions that need to call arangojs\n * // methods inside a transaction\n * async function saveSomeData(trx) {\n * await trx.step(() => collection.save(data));\n * await trx.step(() => collection.save(moreData));\n * }\n * await saveSomeData(); // no `trx.step` call needed\n * ```\n *\n * @example\n * ```js\n * // BAD! You must wait for the promise to resolve (or await on the\n * // `trx.step` call) before calling `trx.step` again!\n * trx.step(() => collection.save(data)); // WRONG\n * await trx.step(() => collection.save(moreData));\n *\n * // BAD! The trx.step callback can not make multiple calls to async arangojs\n * // methods, not even using Promise.all!\n * await trx.step(() => Promise.all([ // WRONG\n * collection.save(data),\n * collection.save(moreData),\n * ]));\n *\n * // BAD! Multiple `trx.step` calls can not run in parallel!\n * await Promise.all([ // WRONG\n * trx.step(() => collection.save(data)),\n * trx.step(() => collection.save(moreData)),\n * ]));\n *\n * // BETTER: Always call `trx.step` sequentially, one after the other\n * await trx.step(() => collection.save(data));\n * await trx.step(() => collection.save(moreData));\n *\n * // OKAY: The then callback can be used if async/await is not available\n * trx.step(() => collection.save(data))\n * .then(() => trx.step(() => collection.save(moreData)));\n * ```\n *\n * @example\n * ```js\n * // BAD! The callback will return an empty promise that resolves before\n * // the inner arangojs method call has even talked to ArangoDB!\n * await trx.step(async () => {\n * collection.save(data); // WRONG\n * });\n *\n * // BETTER: Use an arrow function so you don't forget to return\n * await trx.step(() => collection.save(data));\n *\n * // OKAY: Remember to always return when using a function body\n * await trx.step(() => {\n * return collection.save(data); // easy to forget!\n * });\n *\n * // OKAY: You do not have to use arrow functions but it helps\n * await trx.step(function () {\n * return collection.save(data);\n * });\n * ```\n *\n * @example\n * ```js\n * // BAD! You can not pass promises instead of a callback!\n * await trx.step(collection.save(data)); // WRONG\n *\n * // BETTER: Wrap the code in a function and pass the function instead\n * await trx.step(() => collection.save(data));\n * ```\n *\n * @example\n * ```js\n * // WORSE: Calls to non-async arangojs methods don't need to be performed\n * // as part of a transaction\n * const collection = await trx.step(() => db.collection(\"my-documents\"));\n *\n * // BETTER: If an arangojs method is not async and doesn't return promises,\n * // call it without `trx.step`\n * const collection = db.collection(\"my-documents\");\n * ```\n */\n step<T>(callback: () => Promise<T>): Promise<T> {\n const conn = (this._db as any)._connection as Connection;\n conn.setTransactionId(this.id);\n try {\n const promise = callback();\n if (!promise) {\n throw new Error(\n \"Transaction callback was not an async function or did not return a promise!\"\n );\n }\n return Promise.resolve(promise);\n } finally {\n conn.clearTransactionId();\n }\n }\n}\n","/**\n * ```js\n * import { Database } from \"arangojs/database\";\n * ```\n *\n * The \"database\" module provides the {@link Database} class and associated\n * types and interfaces for TypeScript.\n *\n * The Database class is also re-exported by the \"index\" module.\n *\n * @packageDocumentation\n */\nimport { Readable } from \"stream\";\nimport {\n Analyzer,\n AnalyzerDescription,\n CreateAnalyzerOptions,\n} from \"./analyzer\";\nimport { AqlLiteral, AqlQuery, isAqlLiteral, isAqlQuery } from \"./aql\";\nimport {\n ArangoCollection,\n Collection,\n CollectionMetadata,\n collectionToString,\n CollectionType,\n CreateCollectionOptions,\n DocumentCollection,\n EdgeCollection,\n isArangoCollection,\n} from \"./collection\";\nimport {\n ArangoApiResponse,\n Config,\n Connection,\n Headers,\n RequestOptions,\n} from \"./connection\";\nimport { ArrayCursor, BatchedArrayCursor } from \"./cursor\";\nimport { isArangoError } from \"./error\";\nimport { FoxxManifest } from \"./foxx-manifest\";\nimport {\n CreateGraphOptions,\n EdgeDefinitionOptions,\n Graph,\n GraphInfo,\n} from \"./graph\";\nimport { Blob } from \"./lib/blob\";\nimport { DATABASE_NOT_FOUND } from \"./lib/codes\";\nimport { toForm } from \"./lib/multipart\";\nimport { ArangojsResponse } from \"./lib/request\";\nimport { Route } from \"./route\";\nimport { Transaction } from \"./transaction\";\nimport { CreateViewOptions, View, ViewDescription } from \"./view\";\n\n/**\n * Indicates whether the given value represents a {@link Database}.\n *\n * @param database - A value that might be a database.\n */\nexport function isArangoDatabase(database: any): database is Database {\n return Boolean(database && database.isArangoDatabase);\n}\n\n/**\n * @internal\n */\nfunction coerceTransactionCollections(\n collections:\n | (TransactionCollections & { allowImplicit?: boolean })\n | (string | ArangoCollection)[]\n | string\n | ArangoCollection\n): CoercedTransactionCollections {\n if (typeof collections === \"string\") {\n return { write: [collections] };\n }\n if (Array.isArray(collections)) {\n return { write: collections.map(collectionToString) };\n }\n if (isArangoCollection(collections)) {\n return { write: collectionToString(collections) };\n }\n const cols: CoercedTransactionCollections = {};\n if (collections) {\n if (collections.allowImplicit !== undefined) {\n cols.allowImplicit = collections.allowImplicit;\n }\n if (collections.read) {\n cols.read = Array.isArray(collections.read)\n ? collections.read.map(collectionToString)\n : collectionToString(collections.read);\n }\n if (collections.write) {\n cols.write = Array.isArray(collections.write)\n ? collections.write.map(collectionToString)\n : collectionToString(collections.write);\n }\n if (collections.exclusive) {\n cols.exclusive = Array.isArray(collections.exclusive)\n ? collections.exclusive.map(collectionToString)\n : collectionToString(collections.exclusive);\n }\n }\n return cols;\n}\n\n/**\n * @internal\n */\ntype CoercedTransactionCollections = {\n allowImplicit?: boolean;\n exclusive?: string | string[];\n write?: string | string[];\n read?: string | string[];\n};\n\n/**\n * Collections involved in a transaction.\n */\nexport type TransactionCollections = {\n /**\n * An array of collections or a single collection that will be read from or\n * written to during the transaction with no other writes being able to run\n * in parallel.\n */\n exclusive?: (string | ArangoCollection)[] | string | ArangoCollection;\n /**\n * An array of collections or a single collection that will be read from or\n * written to during the transaction.\n */\n write?: (string | ArangoCollection)[] | string | ArangoCollection;\n /**\n * An array of collections or a single collection that will be read from\n * during the transaction.\n */\n read?: (string | ArangoCollection)[] | string | ArangoCollection;\n};\n\n/**\n * Options for how the transaction should be performed.\n */\nexport type TransactionOptions = {\n /**\n * Whether the transaction may read from collections not specified for this\n * transaction. If set to `false`, accessing any collections not specified\n * will result in the transaction being aborted to avoid potential deadlocks.\n *\n * Default: `true`.\n */\n allowImplicit?: boolean;\n /**\n * If set to `true`, the request will explicitly permit ArangoDB to return a\n * potentially dirty or stale result and arangojs will load balance the\n * request without distinguishing between leaders and followers.\n */\n allowDirtyRead?: boolean;\n /**\n * Determines whether to force the transaction to write all data to disk\n * before returning.\n */\n waitForSync?: boolean;\n /**\n * Determines how long the database will wait while attempting to gain locks\n * on collections used by the transaction before timing out.\n */\n lockTimeout?: number;\n /**\n * (RocksDB only.) Determines the transaction size limit in bytes.\n */\n maxTransactionSize?: number;\n};\n\n/**\n * Options for executing a query.\n *\n * See {@link Database#query}.\n */\nexport type QueryOptions = {\n /**\n * If set to `true`, the query will be executed with support for dirty reads\n * enabled, permitting ArangoDB to return a potentially dirty or stale result\n * and arangojs will load balance the request without distinguishing between\n * leaders and followers.\n *\n * Note that dirty reads are only supported for read-only queries, not data\n * modification queries (e.g. using `INSERT`, `UPDATE`, `REPLACE` or\n * `REMOVE`) and only when using ArangoDB 3.4 or later.\n *\n * Default: `false`\n */\n allowDirtyRead?: boolean;\n /**\n * Maximum time in milliseconds arangojs will wait for a server response.\n * Exceeding this value will result in the request being cancelled.\n *\n * **Note**: Setting a timeout for the client does not guarantee the query\n * will be killed by ArangoDB if it is already being executed. See the\n * `maxRuntime` option for limiting the execution time within ArangoDB.\n */\n timeout?: number;\n /**\n * If set to a positive number, the query will automatically be retried at\n * most this many times if it results in a write-write conflict.\n *\n * Default: `0`\n */\n retryOnConflict?: number;\n /**\n * Unless set to `false`, the number of result values in the result set will\n * be returned in the `count` attribute. This may be disabled by default in\n * a future version of ArangoDB if calculating this value has a performance\n * impact for some queries.\n *\n * Default: `true`.\n */\n count?: boolean;\n /**\n * Number of result values to be transferred by the server in each\n * network roundtrip (or \"batch\").\n *\n * Must be greater than zero.\n */\n batchSize?: number;\n /**\n * If set to `false`, the AQL query results cache lookup will be skipped for\n * this query.\n *\n * Default: `true`\n */\n cache?: boolean;\n /**\n * Maximum memory size in bytes that the query is allowed to use.\n * Exceeding this value will result in the query failing with an error.\n *\n * If set to `0`, the memory limit is disabled.\n *\n * Default: `0`\n */\n memoryLimit?: number;\n /**\n * Maximum allowed execution time before the query will be killed in seconds.\n *\n * If set to `0`, the query will be allowed to run indefinitely.\n *\n * Default: `0`\n */\n maxRuntime?: number;\n /**\n * Time-to-live for the cursor in seconds. The cursor results may be\n * garbage collected by ArangoDB after this much time has passed.\n *\n * Default: `30`\n */\n ttl?: number;\n /**\n * If set to `true`, the query will throw an exception and abort if it would\n otherwise produce a warning.\n */\n failOnWarning?: boolean;\n /**\n * If set to `1` or `true`, additional query profiling information will be\n * returned in the `extra.profile` attribute if the query is not served from\n * the result cache.\n *\n * If set to `2`, the query will return execution stats per query plan node\n * in the `extra.stats.nodes` attribute. Additionally the query plan is\n * returned in `extra.plan`.\n */\n profile?: boolean | number;\n /**\n * If set to `true`, the query will be executed as a streaming query.\n */\n stream?: boolean;\n /**\n * Limits the maximum number of warnings a query will return.\n */\n maxWarningsCount?: number;\n /**\n * If set to `true` and the query has a `LIMIT` clause, the total number of\n * values matched before the last top-level `LIMIT` in the query was applied\n * will be returned in the `extra.stats.fullCount` attribute.\n */\n fullCount?: boolean;\n /**\n * If set to `false`, the query data will not be stored in the RocksDB block\n * cache. This can be used to avoid thrashing he block cache when reading a\n * lot of data.\n */\n fillBlockCache?: boolean;\n /**\n * An object with a `rules` property specifying a list of optimizer rules to\n * be included or excluded by the optimizer for this query. Prefix a rule\n * name with `+` to include it, or `-` to exclude it. The name `all` acts as\n * an alias matching all optimizer rules.\n */\n optimizer?: { rules: string[] };\n /**\n * Limits the maximum number of plans that will be created by the AQL query\n * optimizer.\n */\n maxPlans?: number;\n /**\n * Controls after how many execution nodes in a query a stack split should be\n * performed.\n *\n * Default: `250` (`200` on macOS)\n */\n maxNodesPerCallstack?: number;\n /**\n * (RocksDB only.) Maximum size of transactions in bytes.\n */\n maxTransactionSize?: number;\n /**\n * (RocksDB only.) Maximum number of operations after which an intermediate\n * commit is automatically performed.\n */\n intermediateCommitCount?: number;\n /**\n * (RocksDB only.) Maximum total size of operations in bytes after which an\n * intermediate commit is automatically performed.\n */\n intermediateCommitSize?: number;\n /**\n * (Enterprise Edition cluster only.) If set to `true`, collections\n * inaccessible to current user will result in an access error instead\n * of being treated as empty.\n */\n skipInaccessibleCollections?: boolean;\n /**\n * (Enterprise Edition cluster only.) Limits the maximum time in seconds a\n * DBServer will wait to bring satellite collections involved in the query\n * into sync. Exceeding this value will result in the query being stopped.\n *\n * Default: `60`\n */\n satelliteSyncWait?: number;\n};\n\n/**\n * Options for explaining a query.\n *\n * See {@link Database#explain}.\n */\nexport type ExplainOptions = {\n /**\n * An object with a `rules` property specifying a list of optimizer rules to\n * be included or excluded by the optimizer for this query. Prefix a rule\n * name with `+` to include it, or `-` to exclude it. The name `all` acts as\n * an alias matching all optimizer rules.\n */\n optimizer?: { rules: string[] };\n /**\n * Maximum number of plans that the optimizer is allowed to generate.\n * Setting this to a low value limits the amount of work the optimizer does.\n */\n maxNumberOfPlans?: number;\n /**\n * If set to true, all possible execution plans will be returned as the\n * `plans` property. Otherwise only the optimal execution plan will be\n * returned as the `plan` property.\n *\n * Default: `false`\n */\n allPlans?: boolean;\n};\n\n/**\n * Details for a transaction.\n *\n * See also {@link transaction.TransactionStatus}.\n */\nexport type TransactionDetails = {\n /**\n * Unique identifier of the transaction.\n */\n id: string;\n /**\n * Status (or \"state\") of the transaction.\n */\n state: \"running\" | \"committed\" | \"aborted\";\n};\n\n/**\n * Plan explaining query execution.\n */\nexport type ExplainPlan = {\n /**\n * Execution nodes in this plan.\n */\n nodes: {\n [key: string]: any;\n type: string;\n id: number;\n dependencies: number[];\n estimatedCost: number;\n estimatedNrItems: number;\n }[];\n /**\n * Rules applied by the optimizer.\n */\n rules: string[];\n /**\n * Information about collections involved in the query.\n */\n collections: {\n name: string;\n type: \"read\" | \"write\";\n }[];\n /**\n * Variables used in the query.\n */\n variables: {\n id: number;\n name: string;\n }[];\n /**\n * Total estimated cost of the plan.\n */\n estimatedCost: number;\n /**\n * Estimated number of items returned by the query.\n */\n estimatedNrItems: number;\n /**\n * Whether the query is a data modification query.\n */\n isModificationQuery: boolean;\n};\n\n/**\n * Result of explaining a query with a single plan.\n */\nexport type SingleExplainResult = {\n /**\n * Query plan.\n */\n plan: ExplainPlan;\n /**\n * Whether it would be possible to cache the query.\n */\n cacheable: boolean;\n /**\n * Warnings encountered while planning the query execution.\n */\n warnings: { code: number; message: string }[];\n /**\n * Statistical information about the query plan generation.\n */\n stats: {\n /**\n * Total number of rules executed for this query.\n */\n rulesExecuted: number;\n /**\n * Number of rules skipped for this query.\n */\n rulesSkipped: number;\n /**\n * Total number of plans created.\n */\n plansCreated: number;\n };\n};\n\n/**\n * Result of explaining a query with multiple plans.\n */\nexport type MultiExplainResult = {\n /**\n * Query plans.\n */\n plans: ExplainPlan[];\n /**\n * Whether it would be possible to cache the query.\n */\n cacheable: boolean;\n /**\n * Warnings encountered while planning the query execution.\n */\n warnings: { code: number; message: string }[];\n /**\n * Statistical information about the query plan generation.\n */\n stats: {\n /**\n * Total number of rules executed for this query.\n */\n rulesExecuted: number;\n /**\n * Number of rules skipped for this query.\n */\n rulesSkipped: number;\n /**\n * Total number of plans created.\n */\n plansCreated: number;\n };\n};\n\n/**\n * Node in an AQL abstract syntax tree (AST).\n */\nexport type AstNode = {\n [key: string]: any;\n type: string;\n subNodes: AstNode[];\n};\n\n/**\n * Result of parsing a query.\n */\nexport type ParseResult = {\n /**\n * Whether the query was parsed.\n */\n parsed: boolean;\n /**\n * Names of all collections involved in the query.\n */\n collections: string[];\n /**\n * Names of all bind parameters used in the query.\n */\n bindVars: string[];\n /**\n * Abstract syntax tree (AST) of the query.\n */\n ast: AstNode[];\n};\n\n/**\n * Optimizer rule for AQL queries.\n */\nexport type QueryOptimizerRule = {\n name: string;\n flags: {\n hidden: boolean;\n clusterOnly: boolean;\n canBeDisabled: boolean;\n canCreateAdditionalPlans: boolean;\n disabledByDefault: boolean;\n enterpriseOnly: boolean;\n };\n};\n\n/**\n * Information about query tracking.\n */\nexport type QueryTracking = {\n /**\n * Whether query tracking is enabled.\n */\n enabled: boolean;\n /**\n * Maximum query string length in bytes that is kept in the list.\n */\n maxQueryStringLength: number;\n /**\n * Maximum number of slow queries that is kept in the list.\n */\n maxSlowQueries: number;\n /**\n * Threshold execution time in seconds for when a query is\n * considered slow.\n */\n slowQueryThreshold: number;\n /**\n * Whether bind parameters are being tracked along with queries.\n */\n trackBindVars: boolean;\n /**\n * Whether slow queries are being tracked.\n */\n trackSlowQueries: boolean;\n};\n\n/**\n * Options for query tracking.\n *\n * See {@link Database#queryTracking}.\n */\nexport type QueryTrackingOptions = {\n /**\n * If set to `false`, neither queries nor slow queries will be tracked.\n */\n enabled?: boolean;\n /**\n * Maximum query string length in bytes that will be kept in the list.\n */\n maxQueryStringLength?: number;\n /**\n * Maximum number of slow queries to be kept in the list.\n */\n maxSlowQueries?: number;\n /**\n * Threshold execution time in seconds for when a query will be\n * considered slow.\n */\n slowQueryThreshold?: number;\n /**\n * If set to `true`, bind parameters will be tracked along with queries.\n */\n trackBindVars?: boolean;\n /**\n * If set to `true` and `enabled` is also set to `true`, slow queries will be\n * tracked if their execution time exceeds `slowQueryThreshold`.\n */\n trackSlowQueries?: boolean;\n};\n\n/**\n * Object describing a query.\n */\nexport type QueryInfo = {\n /**\n * Unique identifier for this query.\n */\n id: string;\n /**\n * Query string (potentially truncated).\n */\n query: string;\n /**\n * Bind parameters used in the query.\n */\n bindVars: Record<string, any>;\n /**\n * Query's running time in seconds.\n */\n runTime: number;\n /**\n * Date and time the query was started.\n */\n started: string;\n /**\n * Query's current execution state.\n */\n state: \"executing\" | \"finished\" | \"killed\";\n /**\n * Whether the query uses a streaming cursor.\n */\n stream: boolean;\n};\n\n/**\n * Database user to create with a database.\n */\nexport type CreateDatabaseUser = {\n /**\n * Username of the user to create.\n */\n username: string;\n /**\n * Password of the user to create.\n *\n * Default: `\"\"`\n */\n passwd?: string;\n /**\n * Whether the user is active.\n *\n * Default: `true`\n */\n active?: boolean;\n /**\n * Additional data to store with the user object.\n */\n extra?: Record<string, any>;\n};\n\n/**\n * Options for creating a database.\n *\n * See {@link Database#createDatabase}.\n */\nexport type CreateDatabaseOptions = {\n /**\n * Database users to create with the database.\n */\n users?: CreateDatabaseUser[];\n /**\n * (Cluster only.) The sharding method to use for new collections in the\n * database.\n */\n sharding?: \"\" | \"flexible\" | \"single\";\n /**\n * (Cluster only.) Default replication factor for new collections in this\n * database.\n *\n * Setting this to `1` disables replication. Setting this to `\"satellite\"`\n * will replicate to every DBServer.\n */\n replicationFactor?: \"satellite\" | number;\n /**\n * (Cluster only.) Default write concern for new collections created in this\n * database.\n */\n writeConcern?: number;\n};\n\n/**\n * Object describing a database.\n *\n * See {@link Database#get}.\n */\nexport type DatabaseInfo = {\n /**\n * Name of the database.\n */\n name: string;\n /**\n * Unique identifier of the database.\n */\n id: string;\n /**\n * File system path of the database.\n */\n path: string;\n /**\n * Whether the database is the system database.\n */\n isSystem: boolean;\n /**\n * (Cluster only.) The sharding method to use for new collections in the\n * database.\n */\n sharding?: \"\" | \"flexible\" | \"single\";\n /**\n * (Cluster only.) Default replication factor for new collections in this\n * database.\n */\n replicationFactor?: \"satellite\" | number;\n /**\n * (Cluster only.) Default write concern for new collections created in this\n * database.\n */\n writeConcern?: number;\n};\n\n/**\n * Result of retrieving database version information.\n */\nexport type VersionInfo = {\n /**\n * Value identifying the server type, i.e. `\"arango\"`.\n */\n server: string;\n /**\n * ArangoDB license type or \"edition\".\n */\n license: \"community\" | \"enterprise\";\n /**\n * ArangoDB server version.\n */\n version: string;\n /**\n * Additional information about the ArangoDB server.\n */\n details?: { [key: string]: string };\n};\n\n/**\n * Definition of an AQL User Function.\n */\nexport type AqlUserFunction = {\n /**\n * Name of the AQL User Function.\n */\n name: string;\n /**\n * Implementation of the AQL User Function.\n */\n code: string;\n /**\n * Whether the function is deterministic.\n *\n * See {@link Database#createFunction}.\n */\n isDeterministic: boolean;\n};\n\n/**\n * Options for installing the service.\n *\n * See {@link Database#installService}.\n */\nexport type InstallServiceOptions = {\n /**\n * An object mapping configuration option names to values.\n *\n * See also {@link Database#getServiceConfiguration}.\n */\n configuration?: Record<string, any>;\n /**\n * An object mapping dependency aliases to mount points.\n *\n * See also {@link Database#getServiceDependencies}.\n */\n dependencies?: Record<string, string>;\n /**\n * Whether the service should be installed in development mode.\n *\n * See also {@link Database#setServiceDevelopmentMode}.\n *\n * Default: `false`\n */\n development?: boolean;\n /**\n * Whether the service should be installed in legacy compatibility mode\n *\n * This overrides the `engines` option in the service manifest (if any).\n *\n * Default: `false`\n */\n legacy?: boolean;\n /**\n * Whether the \"setup\" script should be executed.\n *\n * Default: `true`\n */\n setup?: boolean;\n};\n\n/**\n * Options for replacing a service.\n *\n * See {@link Database#replaceService}.\n */\nexport type ReplaceServiceOptions = {\n /**\n * An object mapping configuration option names to values.\n *\n * See also {@link Database#getServiceConfiguration}.\n */\n configuration?: Record<string, any>;\n /**\n * An object mapping dependency aliases to mount points.\n *\n * See also {@link Database#getServiceDependencies}.\n */\n dependencies?: Record<string, string>;\n /**\n * Whether the service should be installed in development mode.\n *\n * See also {@link Database#setServiceDevelopmentMode}.\n *\n * Default: `false`\n */\n development?: boolean;\n /**\n * Whether the service should be installed in legacy compatibility mode\n *\n * This overrides the `engines` option in the service manifest (if any).\n *\n * Default: `false`\n */\n legacy?: boolean;\n /**\n * Whether the \"setup\" script should be executed.\n *\n * Default: `true`\n */\n setup?: boolean;\n /**\n * Whether the existing service's \"teardown\" script should be executed\n * prior to removing that service.\n *\n * Default: `true`\n */\n teardown?: boolean;\n /**\n * If set to `true`, replacing a service that does not already exist will\n * fall back to installing the new service.\n *\n * Default: `false`\n */\n force?: boolean;\n};\n\n/**\n * Options for upgrading a service.\n *\n * See {@link Database#upgradeService}.\n */\nexport type UpgradeServiceOptions = {\n /**\n * An object mapping configuration option names to values.\n *\n * See also {@link Database#getServiceConfiguration}.\n */\n configuration?: Record<string, any>;\n /**\n * An object mapping dependency aliases to mount points.\n *\n * See also {@link Database#getServiceDependencies}.\n */\n dependencies?: Record<string, string>;\n /**\n * Whether the service should be installed in development mode.\n *\n * See also {@link Database#setServiceDevelopmentMode}.\n *\n * Default: `false`\n */\n development?: boolean;\n /**\n * Whether the service should be installed in legacy compatibility mode\n *\n * This overrides the `engines` option in the service manifest (if any).\n *\n * Default: `false`\n */\n legacy?: boolean;\n /**\n * Whether the \"setup\" script should be executed.\n *\n * Default: `true`\n */\n setup?: boolean;\n /**\n * Whether the existing service's \"teardown\" script should be executed\n * prior to upgrading that service.\n *\n * Default: `false`\n */\n teardown?: boolean;\n /**\n * Unless set to `true`, upgrading a service that does not already exist will\n * fall back to installing the new service.\n *\n * Default: `false`\n */\n force?: boolean;\n};\n\n/**\n * Options for uninstalling a service.\n *\n * See {@link Database#uninstallService}.\n */\nexport type UninstallServiceOptions = {\n /**\n * Whether the service's \"teardown\" script should be executed\n * prior to removing that service.\n *\n * Default: `true`\n */\n teardown?: boolean;\n /**\n * If set to `true`, uninstalling a service that does not already exist\n * will be considered successful.\n *\n * Default: `false`\n */\n force?: boolean;\n};\n\n/**\n * Object briefly describing a Foxx service.\n */\nexport type ServiceSummary = {\n /**\n * Service mount point, relative to the database.\n */\n mount: string;\n /**\n * Name defined in the service manifest.\n */\n name?: string;\n /**\n * Version defined in the service manifest.\n */\n version?: string;\n /**\n * Service dependencies the service expects to be able to match as a mapping\n * from dependency names to versions the service is compatible with.\n */\n provides: Record<string, string>;\n /**\n * Whether development mode is enabled for this service.\n */\n development: boolean;\n /**\n * Whether the service is running in legacy compatibility mode.\n */\n legacy: boolean;\n};\n\n/**\n * Object describing a Foxx service in detail.\n */\nexport type ServiceInfo = {\n /**\n * Service mount point, relative to the database.\n */\n mount: string;\n /**\n * File system path of the service.\n */\n path: string;\n /**\n * Name defined in the service manifest.\n */\n name?: string;\n /**\n * Version defined in the service manifest.\n */\n version?: string;\n /**\n * Whether development mode is enabled for this service.\n */\n development: boolean;\n /**\n * Whether the service is running in legacy compatibility mode.\n */\n legacy: boolean;\n /**\n * Content of the service manifest of this service.\n */\n manifest: FoxxManifest;\n /**\n * Internal checksum of the service's initial source bundle.\n */\n checksum: string;\n /**\n * Options for this service.\n */\n options: {\n /**\n * Configuration values set for this service.\n */\n configuration: Record<string, any>;\n /**\n * Service dependency configuration of this service.\n */\n dependencies: Record<string, string>;\n };\n};\n\n/**\n * Object describing a configuration option of a Foxx service.\n */\nexport type ServiceConfiguration = {\n /**\n * Data type of the configuration value.\n *\n * **Note**: `\"int\"` and `\"bool\"` are historical synonyms for `\"integer\"` and\n * `\"boolean\"`. The `\"password\"` type is synonymous with `\"string\"` but can\n * be used to distinguish values which should not be displayed in plain text\n * by software when managing the service.\n */\n type:\n | \"integer\"\n | \"boolean\"\n | \"string\"\n | \"number\"\n | \"json\"\n | \"password\"\n | \"int\"\n | \"bool\";\n /**\n * Current value of the configuration option as stored internally.\n */\n currentRaw: any;\n /**\n * Processed current value of the configuration option as exposed in the\n * service code.\n */\n current: any;\n /**\n * Formatted name of the configuration option.\n */\n title: string;\n /**\n * Human-readable description of the configuration option.\n */\n description?: string;\n /**\n * Whether the configuration option must be set in order for the service\n * to be operational.\n */\n required: boolean;\n /**\n * Default value of the configuration option.\n */\n default?: any;\n};\n\n/**\n * Object describing a single-service dependency defined by a Foxx service.\n */\nexport type SingleServiceDependency = {\n /**\n * Whether this is a multi-service dependency.\n */\n multiple: false;\n /**\n * Current mount point the dependency is resolved to.\n */\n current?: string;\n /**\n * Formatted name of the dependency.\n */\n title: string;\n /**\n * Name of the service the dependency expects to match.\n */\n name: string;\n /**\n * Version of the service the dependency expects to match.\n */\n version: string;\n /**\n * Human-readable description of the dependency.\n */\n description?: string;\n /**\n * Whether the dependency must be matched in order for the service\n * to be operational.\n */\n required: boolean;\n};\n\n/**\n * Object describing a multi-service dependency defined by a Foxx service.\n */\nexport type MultiServiceDependency = {\n /**\n * Whether this is a multi-service dependency.\n */\n multiple: true;\n /**\n * Current mount points the dependency is resolved to.\n */\n current?: string[];\n /**\n * Formatted name of the dependency.\n */\n title: string;\n /**\n * Name of the service the dependency expects to match.\n */\n name: string;\n /**\n * Version of the service the dependency expects to match.\n */\n version: string;\n /**\n * Human-readable description of the dependency.\n */\n description?: string;\n /**\n * Whether the dependency must be matched in order for the service\n * to be operational.\n */\n required: boolean;\n};\n\n/**\n * Test stats for a Foxx service's tests.\n */\nexport type ServiceTestStats = {\n /**\n * Total number of tests found.\n */\n tests: number;\n /**\n * Number of tests that ran successfully.\n */\n passes: number;\n /**\n * Number of tests that failed.\n */\n failures: number;\n /**\n * Number of tests skipped or not executed.\n */\n pending: number;\n /**\n * Total test duration in milliseconds.\n */\n duration: number;\n};\n\n/**\n * Test results for a single test case using the stream reporter.\n */\nexport type ServiceTestStreamTest = {\n title: string;\n fullTitle: string;\n duration: number;\n err?: string;\n};\n\n/**\n * Test results for a Foxx service's tests using the stream reporter.\n */\nexport type ServiceTestStreamReport = (\n | [\"start\", { total: number }]\n | [\"pass\", ServiceTestStreamTest]\n | [\"fail\", ServiceTestStreamTest]\n | [\"end\", ServiceTestStats]\n)[];\n\n/**\n * Test results for a single test case using the suite reporter.\n */\nexport type ServiceTestSuiteTest = {\n result: \"pending\" | \"pass\" | \"fail\";\n title: string;\n duration: number;\n err?: any;\n};\n\n/**\n * Test results for a single test suite using the suite reporter.\n */\nexport type ServiceTestSuite = {\n title: string;\n suites: ServiceTestSuite[];\n tests: ServiceTestSuiteTest[];\n};\n\n/**\n * Test results for a Foxx service's tests using the suite reporter.\n */\nexport type ServiceTestSuiteReport = {\n stats: ServiceTestStats;\n suites: ServiceTestSuite[];\n tests: ServiceTestSuiteTest[];\n};\n\n/**\n * Test results for a single test case in XUnit format using the JSONML\n * representation.\n */\nexport type ServiceTestXunitTest =\n | [\"testcase\", { classname: string; name: string; time: number }]\n | [\n \"testcase\",\n { classname: string; name: string; time: number },\n [\"failure\", { message: string; type: string }, string]\n ];\n\n/**\n * Test results for a Foxx service's tests in XUnit format using the JSONML\n * representation.\n */\nexport type ServiceTestXunitReport = [\n \"testsuite\",\n {\n timestamp: number;\n tests: number;\n errors: number;\n failures: number;\n skip: number;\n time: number;\n },\n ...ServiceTestXunitTest[]\n];\n\n/**\n * Test results for a Foxx service's tests in TAP format.\n */\nexport type ServiceTestTapReport = string[];\n\n/**\n * Test results for a single test case using the default reporter.\n */\nexport type ServiceTestDefaultTest = {\n title: string;\n fullTitle: string;\n duration: number;\n err?: string;\n};\n\n/**\n * Test results for a Foxx service's tests using the default reporter.\n */\nexport type ServiceTestDefaultReport = {\n stats: ServiceTestStats;\n tests: ServiceTestDefaultTest[];\n pending: ServiceTestDefaultTest[];\n failures: ServiceTestDefaultTest[];\n passes: ServiceTestDefaultTest[];\n};\n\n/**\n * OpenAPI 2.0 description of a Foxx service.\n */\nexport type SwaggerJson = {\n [key: string]: any;\n info: {\n title: string;\n description: string;\n version: string;\n license: string;\n };\n path: {\n [key: string]: any;\n };\n};\n\n/**\n * Access level for an ArangoDB user's access to a collection or database.\n */\nexport type AccessLevel = \"rw\" | \"ro\" | \"none\";\n\n/**\n * Properties of an ArangoDB user object.\n */\nexport type ArangoUser = {\n /**\n * ArangoDB username of the user.\n */\n user: string;\n /**\n * Whether the ArangoDB user account is enabled and can authenticate.\n */\n active: boolean;\n /**\n * Additional information to store about this user.\n */\n extra: Record<string, any>;\n};\n\n/**\n * Options for creating an ArangoDB user.\n */\nexport type CreateUserOptions = {\n /**\n * ArangoDB username of the user.\n */\n user: string;\n /**\n * Password the ArangoDB user will use for authentication.\n */\n passwd: string;\n /**\n * Whether the ArangoDB user account is enabled and can authenticate.\n *\n * Default: `true`\n */\n active?: boolean;\n /**\n * Additional information to store about this user.\n *\n * Default: `{}`\n */\n extra?: Record<string, any>;\n};\n\n/**\n * Options for modifying an ArangoDB user.\n */\nexport type UserOptions = {\n /**\n * Password the ArangoDB user will use for authentication.\n */\n passwd: string;\n /**\n * Whether the ArangoDB user account is enabled and can authenticate.\n *\n * Default: `true`\n */\n active?: boolean;\n /**\n * Additional information to store about this user.\n *\n * Default: `{}`\n */\n extra?: Record<string, any>;\n};\n\n/**\n * Options for accessing or manipulating access levels.\n */\nexport type UserAccessLevelOptions = {\n /**\n * The database to access or manipulate the access level of.\n *\n * If `collection` is an `ArangoCollection`, this option defaults to the\n * database the collection is contained in. Otherwise this option defaults to\n * the current database.\n */\n database?: Database | string;\n /**\n * The collection to access or manipulate the access level of.\n */\n collection?: ArangoCollection | string;\n};\n\n/**\n * An object providing methods for accessing queue time metrics of the most\n * recently received server responses if the server supports this feature.\n */\nexport type QueueTimeMetrics = {\n /**\n * Returns the queue time of the most recently received response in seconds.\n */\n getLatest: () => number | undefined;\n /**\n * Returns a list of the most recently received queue time values as tuples\n * of the timestamp of the response being processed in milliseconds and the\n * queue time in seconds.\n */\n getValues: () => [number, number][];\n /**\n * Returns the average queue time of the most recently received responses\n * in seconds.\n */\n getAvg: () => number;\n};\n\n/**\n * An object representing a single ArangoDB database. All arangojs collections,\n * cursors, analyzers and so on are linked to a `Database` object.\n */\nexport class Database {\n protected _connection: Connection;\n protected _name: string;\n protected _analyzers = new Map<string, Analyzer>();\n protected _collections = new Map<string, Collection>();\n protected _graphs = new Map<string, Graph>();\n protected _views = new Map<string, View>();\n\n /**\n * Creates a new `Database` instance with its own connection pool.\n *\n * See also {@link Database#database}.\n *\n * @param config - An object with configuration options.\n *\n * @example\n * ```js\n * const db = new Database({\n * url: \"http://127.0.0.1:8529\",\n * databaseName: \"my_database\",\n * auth: { username: \"admin\", password: \"hunter2\" },\n * });\n * ```\n */\n constructor(config?: Config);\n /**\n * Creates a new `Database` instance with its own connection pool.\n *\n * See also {@link Database#database}.\n *\n * @param url - Base URL of the ArangoDB server or list of server URLs.\n * Equivalent to the `url` option in {@link connection.Config}.\n *\n * @example\n * ```js\n * const db = new Database(\"http://127.0.0.1:8529\", \"my_database\");\n * db.useBasicAuth(\"admin\", \"hunter2\");\n * ```\n */\n constructor(url: string | string[], name?: string);\n /**\n * @internal\n */\n constructor(database: Database, name?: string);\n constructor(\n configOrDatabase: string | string[] | Config | Database = {},\n name?: string\n ) {\n if (isArangoDatabase(configOrDatabase)) {\n const connection = configOrDatabase._connection;\n const databaseName = (name || configOrDatabase.name).normalize(\"NFC\");\n this._connection = connection;\n this._name = databaseName;\n const database = connection.database(databaseName);\n if (database) return database;\n } else {\n const config = configOrDatabase;\n const { databaseName, ...options } =\n typeof config === \"string\" || Array.isArray(config)\n ? { databaseName: name, url: config }\n : config;\n this._connection = new Connection(options);\n this._name = databaseName?.normalize(\"NFC\") || \"_system\";\n }\n }\n\n //#region misc\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB database.\n */\n get isArangoDatabase(): true {\n return true;\n }\n\n /**\n * Name of the ArangoDB database this instance represents.\n */\n get name() {\n return this._name;\n }\n\n /**\n * Fetches version information from the ArangoDB server.\n *\n * @param details - If set to `true`, additional information about the\n * ArangoDB server will be available as the `details` property.\n *\n * @example\n * ```js\n * const db = new Database();\n * const version = await db.version();\n * // the version object contains the ArangoDB version information.\n * // license: \"community\" or \"enterprise\"\n * // version: ArangoDB version number\n * // server: description of the server\n * ```\n */\n version(details?: boolean): Promise<VersionInfo> {\n return this.request({\n method: \"GET\",\n path: \"/_api/version\",\n qs: { details },\n });\n }\n\n /**\n * Returns a new {@link route.Route} instance for the given path (relative to the\n * database) that can be used to perform arbitrary HTTP requests.\n *\n * @param path - The database-relative URL of the route. Defaults to the\n * database API root.\n * @param headers - Default headers that should be sent with each request to\n * the route.\n *\n * @example\n * ```js\n * const db = new Database();\n * const myFoxxService = db.route(\"my-foxx-service\");\n * const response = await myFoxxService.post(\"users\", {\n * username: \"admin\",\n * password: \"hunter2\"\n * });\n * // response.body is the result of\n * // POST /_db/_system/my-foxx-service/users\n * // with JSON request body '{\"username\": \"admin\", \"password\": \"hunter2\"}'\n * ```\n */\n route(path?: string, headers?: Headers): Route {\n return new Route(this, path, headers);\n }\n\n /**\n * @internal\n *\n * Performs an arbitrary HTTP request against the database.\n *\n * If `absolutePath` is set to `true`, the database path will not be\n * automatically prepended to the `basePath`.\n *\n * @param T - Return type to use. Defaults to the response object type.\n * @param options - Options for this request.\n * @param transform - An optional function to transform the low-level\n * response object to a more useful return value.\n */\n request<T = any>(\n options: RequestOptions & { absolutePath?: boolean },\n transform?: false | ((res: ArangojsResponse) => T)\n ): Promise<T>;\n request<T = any>(\n {\n absolutePath = false,\n basePath,\n ...opts\n }: RequestOptions & { absolutePath?: boolean },\n transform: false | ((res: ArangojsResponse) => T) = (res) => res.body\n ): Promise<T> {\n if (!absolutePath) {\n basePath = `/_db/${encodeURIComponent(this._name)}${basePath || \"\"}`;\n }\n return this._connection.request(\n { basePath, ...opts },\n transform || undefined\n );\n }\n\n /**\n * Updates the URL list by requesting a list of all coordinators in the\n * cluster and adding any endpoints not initially specified in the\n * {@link connection.Config}.\n *\n * For long-running processes communicating with an ArangoDB cluster it is\n * recommended to run this method periodically (e.g. once per hour) to make\n * sure new coordinators are picked up correctly and can be used for\n * fail-over or load balancing.\n *\n * @param overwrite - If set to `true`, the existing host list will be\n * replaced instead of extended.\n *\n * @example\n * ```js\n * const db = new Database();\n * const interval = setInterval(\n * () => db.acquireHostList(),\n * 5 * 60 * 1000 // every 5 minutes\n * );\n *\n * // later\n * clearInterval(interval);\n * system.close();\n * ```\n */\n async acquireHostList(overwrite = false): Promise<void> {\n const urls: string[] = await this.request(\n { path: \"/_api/cluster/endpoints\" },\n (res) => res.body.endpoints.map((endpoint: any) => endpoint.endpoint)\n );\n if (urls.length > 0) {\n if (overwrite) this._connection.setHostList(urls);\n else this._connection.addToHostList(urls);\n }\n }\n\n /**\n * Closes all active connections of this database instance.\n *\n * Can be used to clean up idling connections during longer periods of\n * inactivity.\n *\n * **Note**: This method currently has no effect in the browser version of\n * arangojs.\n *\n * @example\n * ```js\n * const db = new Database();\n * const sessions = db.collection(\"sessions\");\n * // Clean up expired sessions once per hour\n * setInterval(async () => {\n * await db.query(aql`\n * FOR session IN ${sessions}\n * FILTER session.expires < DATE_NOW()\n * REMOVE session IN ${sessions}\n * `);\n * // Making sure to close the connections because they're no longer used\n * system.close();\n * }, 1000 * 60 * 60);\n * ```\n */\n close(): void {\n this._connection.close();\n }\n\n /**\n * Performs a request against every known coordinator and returns when the\n * request has succeeded against every coordinator or the timeout is reached.\n *\n * **Note**: This method is primarily intended to make database setup easier\n * in cluster scenarios and requires all coordinators to be known to arangojs\n * before the method is invoked. The method is not useful in single-server or\n * leader-follower replication scenarios.\n *\n * @example\n * ```js\n * const db = new Database({ loadBalancingStrategy: \"ROUND_ROBIN\" });\n * await system.acquireHostList();\n * const analyzer = db.analyzer(\"my-analyzer\");\n * await analyzer.create();\n * await db.waitForPropagation(\n * { path: `/_api/analyzer/${encodeURIComponent(analyzer.name)}` },\n * 30000\n * );\n * // Analyzer has been propagated to all coordinators and can safely be used\n * ```\n *\n * @param request - Request to perform against each known coordinator.\n * @param timeout - Maximum number of milliseconds to wait for propagation.\n */\n async waitForPropagation(\n request: RequestOptions,\n timeout?: number\n ): Promise<void>;\n async waitForPropagation(\n { basePath, ...request }: RequestOptions,\n timeout?: number\n ): Promise<void> {\n await this._connection.waitForPropagation(\n {\n ...request,\n basePath: `/_db/${encodeURIComponent(this._name)}${basePath || \"\"}`,\n },\n timeout\n );\n }\n\n /**\n * Methods for accessing the server-reported queue times of the mostly\n * recently received responses.\n */\n get queueTime(): QueueTimeMetrics {\n return this._connection.queueTime;\n }\n\n /**\n * Sets the limit for the number of values of the most recently received\n * server-reported queue times that can be accessed using\n * {@link Database#queueTime}.\n *\n * @param responseQueueTimeSamples - Number of values to maintain.\n */\n setResponseQueueTimeSamples(responseQueueTimeSamples: number) {\n this._connection.setResponseQueueTimeSamples(responseQueueTimeSamples);\n }\n //#endregion\n\n //#region auth\n /**\n * Updates the underlying connection's `authorization` header to use Basic\n * authentication with the given `username` and `password`, then returns\n * itself.\n *\n * @param username - The username to authenticate with.\n * @param password - The password to authenticate with.\n *\n * @example\n * ```js\n * const db = new Database();\n * db.useBasicAuth(\"admin\", \"hunter2\");\n * // with the username \"admin\" and password \"hunter2\".\n * ```\n */\n useBasicAuth(username: string = \"root\", password: string = \"\"): this {\n this._connection.setBasicAuth({ username, password });\n return this;\n }\n\n /**\n * Updates the underlying connection's `authorization` header to use Bearer\n * authentication with the given authentication `token`, then returns itself.\n *\n * @param token - The token to authenticate with.\n *\n * @example\n * ```js\n * const db = new Database();\n * db.useBearerAuth(\"keyboardcat\");\n * // The database instance now uses Bearer authentication.\n * ```\n */\n useBearerAuth(token: string): this {\n this._connection.setBearerAuth({ token });\n return this;\n }\n\n /**\n * Validates the given database credentials and exchanges them for an\n * authentication token, then uses the authentication token for future\n * requests and returns it.\n *\n * @param username - The username to authenticate with.\n * @param password - The password to authenticate with.\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.login(\"admin\", \"hunter2\");\n * // with an authentication token for the \"admin\" user.\n * ```\n */\n login(username: string = \"root\", password: string = \"\"): Promise<string> {\n return this.request(\n {\n method: \"POST\",\n path: \"/_open/auth\",\n body: { username, password },\n },\n (res) => {\n this.useBearerAuth(res.body.jwt);\n return res.body.jwt;\n }\n );\n }\n //#endregion\n\n //#region databases\n /**\n * Creates a new `Database` instance for the given `databaseName` that\n * shares this database's connection pool.\n *\n * See also {@link Database:constructor}.\n *\n * @param databaseName - Name of the database.\n *\n * @example\n * ```js\n * const systemDb = new Database();\n * const myDb = system.database(\"my_database\");\n * ```\n */\n database(databaseName: string) {\n return new Database(this as any, databaseName);\n }\n\n /**\n * Fetches the database description for the active database from the server.\n *\n * @example\n * ```js\n * const db = new Database();\n * const info = await db.get();\n * // the database exists\n * ```\n */\n get(): Promise<DatabaseInfo> {\n return this.request(\n { path: \"/_api/database/current\" },\n (res) => res.body.result\n );\n }\n\n /**\n * Checks whether the database exists.\n *\n * @example\n * ```js\n * const db = new Database();\n * const result = await db.exists();\n * // result indicates whether the database exists\n * ```\n */\n async exists(): Promise<boolean> {\n try {\n await this.get();\n return true;\n } catch (err: any) {\n if (isArangoError(err) && err.errorNum === DATABASE_NOT_FOUND) {\n return false;\n }\n throw err;\n }\n }\n\n /**\n * Creates a new database with the given `databaseName` with the given\n * `options` and returns a `Database` instance for that database.\n *\n * @param databaseName - Name of the database to create.\n * @param options - Options for creating the database.\n *\n * @example\n * ```js\n * const db = new Database();\n * const info = await db.createDatabase(\"mydb\", {\n * users: [{ username: \"root\" }]\n * });\n * // the database has been created\n * ```\n */\n createDatabase(\n databaseName: string,\n options?: CreateDatabaseOptions\n ): Promise<Database>;\n /**\n * Creates a new database with the given `databaseName` with the given\n * `users` and returns a `Database` instance for that database.\n *\n * @param databaseName - Name of the database to create.\n * @param users - Database users to create with the database.\n *\n * @example\n * ```js\n * const db = new Database();\n * const info = await db.createDatabase(\"mydb\", [{ username: \"root\" }]);\n * // the database has been created\n * ```\n */\n createDatabase(\n databaseName: string,\n users: CreateDatabaseUser[]\n ): Promise<Database>;\n createDatabase(\n databaseName: string,\n usersOrOptions: CreateDatabaseUser[] | CreateDatabaseOptions = {}\n ): Promise<Database> {\n const { users, ...options } = Array.isArray(usersOrOptions)\n ? { users: usersOrOptions }\n : usersOrOptions;\n return this.request(\n {\n method: \"POST\",\n path: \"/_api/database\",\n body: { name: databaseName.normalize(\"NFC\"), users, options },\n },\n () => this.database(databaseName)\n );\n }\n\n /**\n * Fetches all databases from the server and returns an array of their names.\n *\n * See also {@link Database#databases} and\n * {@link Database#listUserDatabases}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const names = await db.listDatabases();\n * // databases is an array of database names\n * ```\n */\n listDatabases(): Promise<string[]> {\n return this.request({ path: \"/_api/database\" }, (res) => res.body.result);\n }\n\n /**\n * Fetches all databases accessible to the active user from the server and\n * returns an array of their names.\n *\n * See also {@link Database#userDatabases} and\n * {@link Database#listDatabases}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const names = await db.listUserDatabases();\n * // databases is an array of database names\n * ```\n */\n listUserDatabases(): Promise<string[]> {\n return this.request(\n { path: \"/_api/database/user\" },\n (res) => res.body.result\n );\n }\n\n /**\n * Fetches all databases from the server and returns an array of `Database`\n * instances for those databases.\n *\n * See also {@link Database#listDatabases} and\n * {@link Database#userDatabases}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const names = await db.databases();\n * // databases is an array of databases\n * ```\n */\n databases(): Promise<Database[]> {\n return this.request({ path: \"/_api/database\" }, (res) =>\n (res.body.result as string[]).map((databaseName) =>\n this.database(databaseName)\n )\n );\n }\n\n /**\n * Fetches all databases accessible to the active user from the server and\n * returns an array of `Database` instances for those databases.\n *\n * See also {@link Database#listUserDatabases} and\n * {@link Database#databases}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const names = await db.userDatabases();\n * // databases is an array of databases\n * ```\n */\n userDatabases(): Promise<Database[]> {\n return this.request({ path: \"/_api/database/user\" }, (res) =>\n (res.body.result as string[]).map((databaseName) =>\n this.database(databaseName)\n )\n );\n }\n\n /**\n * Deletes the database with the given `databaseName` from the server.\n *\n * @param databaseName - Name of the database to delete.\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.dropDatabase(\"mydb\");\n * // database \"mydb\" no longer exists\n * ```\n */\n dropDatabase(databaseName: string): Promise<boolean> {\n databaseName = databaseName.normalize(\"NFC\");\n return this.request(\n {\n method: \"DELETE\",\n path: `/_api/database/${encodeURIComponent(databaseName)}`,\n },\n (res) => res.body.result\n );\n }\n //#endregion\n\n //#region collections\n /**\n * Returns a `Collection` instance for the given collection name.\n *\n * In TypeScript the collection implements both the\n * {@link collection.DocumentCollection} and {@link collection.EdgeCollection}\n * interfaces and can be cast to either type to enforce a stricter API.\n *\n * @param T - Type to use for document data. Defaults to `any`.\n * @param collectionName - Name of the edge collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"potatoes\");\n * ```\n *\n * @example\n * ```ts\n * interface Person {\n * name: string;\n * }\n * const db = new Database();\n * const persons = db.collection<Person>(\"persons\");\n * ```\n *\n * @example\n * ```ts\n * interface Person {\n * name: string;\n * }\n * interface Friend {\n * startDate: number;\n * endDate?: number;\n * }\n * const db = new Database();\n * const documents = db.collection(\"persons\") as DocumentCollection<Person>;\n * const edges = db.collection(\"friends\") as EdgeCollection<Friend>;\n * ```\n */\n collection<T extends Record<string, any> = any>(\n collectionName: string\n ): DocumentCollection<T> & EdgeCollection<T> {\n collectionName = collectionName.normalize(\"NFC\");\n if (!this._collections.has(collectionName)) {\n this._collections.set(\n collectionName,\n new Collection(this, collectionName)\n );\n }\n return this._collections.get(collectionName)!;\n }\n\n /**\n * Creates a new collection with the given `collectionName` and `options`,\n * then returns a {@link collection.DocumentCollection} instance for the new collection.\n *\n * @param T - Type to use for document data. Defaults to `any`.\n * @param collectionName - Name of the new collection.\n * @param options - Options for creating the collection.\n *\n * @example\n * ```ts\n * const db = new Database();\n * const documents = db.createCollection(\"persons\");\n * ```\n *\n * @example\n * ```ts\n * interface Person {\n * name: string;\n * }\n * const db = new Database();\n * const documents = db.createCollection<Person>(\"persons\");\n * ```\n */\n async createCollection<T extends Record<string, any> = any>(\n collectionName: string,\n options?: CreateCollectionOptions & {\n type?: CollectionType.DOCUMENT_COLLECTION;\n }\n ): Promise<DocumentCollection<T>>;\n /**\n * Creates a new edge collection with the given `collectionName` and\n * `options`, then returns an {@link collection.EdgeCollection} instance for the new\n * edge collection.\n *\n * @param T - Type to use for edge document data. Defaults to `any`.\n * @param collectionName - Name of the new collection.\n * @param options - Options for creating the collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const edges = db.createCollection(\"friends\", {\n * type: CollectionType.EDGE_COLLECTION\n * });\n * ```\n *\n * @example\n * ```ts\n * interface Friend {\n * startDate: number;\n * endDate?: number;\n * }\n * const db = new Database();\n * const edges = db.createCollection<Friend>(\"friends\", {\n * type: CollectionType.EDGE_COLLECTION\n * });\n * ```\n */\n async createCollection<T extends Record<string, any> = any>(\n collectionName: string,\n options: CreateCollectionOptions & {\n type: CollectionType.EDGE_COLLECTION;\n }\n ): Promise<EdgeCollection<T>>;\n async createCollection<T extends Record<string, any> = any>(\n collectionName: string,\n options?: CreateCollectionOptions & { type?: CollectionType }\n ): Promise<DocumentCollection<T> & EdgeCollection<T>> {\n const collection = this.collection(collectionName);\n await collection.create(options);\n return collection;\n }\n\n /**\n * Creates a new edge collection with the given `collectionName` and\n * `options`, then returns an {@link collection.EdgeCollection} instance for the new\n * edge collection.\n *\n * This is a convenience method for calling {@link Database#createCollection}\n * with `options.type` set to `EDGE_COLLECTION`.\n *\n * @param T - Type to use for edge document data. Defaults to `any`.\n * @param collectionName - Name of the new collection.\n * @param options - Options for creating the collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const edges = db.createEdgeCollection(\"friends\");\n * ```\n *\n * @example\n * ```ts\n * interface Friend {\n * startDate: number;\n * endDate?: number;\n * }\n * const db = new Database();\n * const edges = db.createEdgeCollection<Friend>(\"friends\");\n * ```\n */\n async createEdgeCollection<T extends Record<string, any> = any>(\n collectionName: string,\n options?: CreateCollectionOptions\n ): Promise<EdgeCollection<T>> {\n return this.createCollection(collectionName, {\n ...options,\n type: CollectionType.EDGE_COLLECTION,\n });\n }\n\n /**\n * Renames the collection `collectionName` to `newName`.\n *\n * Additionally removes any stored `Collection` instance for\n * `collectionName` from the `Database` instance's internal cache.\n *\n * **Note**: Renaming collections may not be supported when ArangoDB is\n * running in a cluster configuration.\n *\n * @param collectionName - Current name of the collection.\n * @param newName - The new name of the collection.\n */\n async renameCollection(\n collectionName: string,\n newName: string\n ): Promise<ArangoApiResponse<CollectionMetadata>> {\n collectionName = collectionName.normalize(\"NFC\");\n const result = await this.request({\n method: \"PUT\",\n path: `/_api/collection/${encodeURIComponent(collectionName)}/rename`,\n body: { name: newName.normalize(\"NFC\") },\n });\n this._collections.delete(collectionName);\n return result;\n }\n\n /**\n * Fetches all collections from the database and returns an array of\n * collection descriptions.\n *\n * See also {@link Database#collections}.\n *\n * @param excludeSystem - Whether system collections should be excluded.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collections = await db.listCollections();\n * // collections is an array of collection descriptions\n * // not including system collections\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collections = await db.listCollections(false);\n * // collections is an array of collection descriptions\n * // including system collections\n * ```\n */\n listCollections(\n excludeSystem: boolean = true\n ): Promise<CollectionMetadata[]> {\n return this.request(\n {\n path: \"/_api/collection\",\n qs: { excludeSystem },\n },\n (res) => res.body.result\n );\n }\n\n /**\n * Fetches all collections from the database and returns an array of\n * `Collection` instances.\n *\n * In TypeScript these instances implement both the\n * {@link collection.DocumentCollection} and {@link collection.EdgeCollection}\n * interfaces and can be cast to either type to enforce a stricter API.\n *\n * See also {@link Database#listCollections}.\n *\n * @param excludeSystem - Whether system collections should be excluded.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collections = await db.collections();\n * // collections is an array of DocumentCollection and EdgeCollection\n * // instances not including system collections\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const collections = await db.collections(false);\n * // collections is an array of DocumentCollection and EdgeCollection\n * // instances including system collections\n * ```\n */\n async collections(\n excludeSystem: boolean = true\n ): Promise<Array<DocumentCollection & EdgeCollection>> {\n const collections = await this.listCollections(excludeSystem);\n return collections.map((data) => this.collection(data.name));\n }\n //#endregion\n\n //#region graphs\n /**\n * Returns a {@link graph.Graph} instance representing the graph with the given\n * `graphName`.\n *\n * @param graphName - Name of the graph.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * ```\n */\n graph(graphName: string): Graph {\n graphName = graphName.normalize(\"NFC\");\n if (!this._graphs.has(graphName)) {\n this._graphs.set(graphName, new Graph(this, graphName));\n }\n return this._graphs.get(graphName)!;\n }\n\n /**\n * Creates a graph with the given `graphName` and `edgeDefinitions`, then\n * returns a {@link graph.Graph} instance for the new graph.\n *\n * @param graphName - Name of the graph to be created.\n * @param edgeDefinitions - An array of edge definitions.\n * @param options - An object defining the properties of the graph.\n */\n async createGraph(\n graphName: string,\n edgeDefinitions: EdgeDefinitionOptions[],\n options?: CreateGraphOptions\n ): Promise<Graph> {\n const graph = this.graph(graphName.normalize(\"NFC\"));\n await graph.create(edgeDefinitions, options);\n return graph;\n }\n\n /**\n * Fetches all graphs from the database and returns an array of graph\n * descriptions.\n *\n * See also {@link Database#graphs}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graphs = await db.listGraphs();\n * // graphs is an array of graph descriptions\n * ```\n */\n listGraphs(): Promise<GraphInfo[]> {\n return this.request({ path: \"/_api/gharial\" }, (res) => res.body.graphs);\n }\n\n /**\n * Fetches all graphs from the database and returns an array of {@link graph.Graph}\n * instances for those graphs.\n *\n * See also {@link Database#listGraphs}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graphs = await db.graphs();\n * // graphs is an array of Graph instances\n * ```\n */\n async graphs(): Promise<Graph[]> {\n const graphs = await this.listGraphs();\n return graphs.map((data: any) => this.graph(data._key));\n }\n //#endregion\n\n //#region views\n /**\n * Returns a {@link view.View} instance for the given `viewName`.\n *\n * @param viewName - Name of the ArangoSearch or SearchAlias View.\n *\n * @example\n * ```js\n * const db = new Database();\n * const view = db.view(\"potatoes\");\n * ```\n */\n view(viewName: string): View {\n viewName = viewName.normalize(\"NFC\");\n if (!this._views.has(viewName)) {\n this._views.set(viewName, new View(this, viewName));\n }\n return this._views.get(viewName)!;\n }\n\n /**\n * Creates a new View with the given `viewName` and `options`, then returns a\n * {@link view.View} instance for the new View.\n *\n * @param viewName - Name of the View.\n * @param options - An object defining the properties of the View.\n *\n * @example\n * ```js\n * const db = new Database();\n * const view = await db.createView(\"potatoes\", { type: \"arangosearch\" });\n * // the ArangoSearch View \"potatoes\" now exists\n * ```\n */\n async createView(\n viewName: string,\n options: CreateViewOptions\n ): Promise<View> {\n const view = this.view(viewName.normalize(\"NFC\"));\n await view.create(options);\n return view;\n }\n\n /**\n * Renames the view `viewName` to `newName`.\n *\n * Additionally removes any stored {@link view.View} instance for `viewName` from\n * the `Database` instance's internal cache.\n *\n * **Note**: Renaming views may not be supported when ArangoDB is running in\n * a cluster configuration.\n *\n * @param viewName - Current name of the view.\n * @param newName - The new name of the view.\n */\n async renameView(\n viewName: string,\n newName: string\n ): Promise<ArangoApiResponse<ViewDescription>> {\n viewName = viewName.normalize(\"NFC\");\n const result = await this.request({\n method: \"PUT\",\n path: `/_api/view/${encodeURIComponent(viewName)}/rename`,\n body: { name: newName.normalize(\"NFC\") },\n });\n this._views.delete(viewName);\n return result;\n }\n\n /**\n * Fetches all Views from the database and returns an array of View\n * descriptions.\n *\n * See also {@link Database#views}.\n *\n * @example\n * ```js\n * const db = new Database();\n *\n * const views = await db.listViews();\n * // views is an array of View descriptions\n * ```\n */\n listViews(): Promise<ViewDescription[]> {\n return this.request({ path: \"/_api/view\" }, (res) => res.body.result);\n }\n\n /**\n * Fetches all Views from the database and returns an array of\n * {@link view.View} instances\n * for the Views.\n *\n * See also {@link Database#listViews}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const views = await db.views();\n * // views is an array of ArangoSearch View instances\n * ```\n */\n async views(): Promise<View[]> {\n const views = await this.listViews();\n return views.map((data) => this.view(data.name));\n }\n //#endregion\n\n //#region analyzers\n /**\n * Returns an {@link analyzer.Analyzer} instance representing the Analyzer with the\n * given `analyzerName`.\n *\n * @example\n * ```js\n * const db = new Database();\n * const analyzer = db.analyzer(\"some-analyzer\");\n * const info = await analyzer.get();\n * ```\n */\n analyzer(analyzerName: string): Analyzer {\n analyzerName = analyzerName.normalize(\"NFC\");\n if (!this._analyzers.has(analyzerName)) {\n this._analyzers.set(analyzerName, new Analyzer(this, analyzerName));\n }\n return this._analyzers.get(analyzerName)!;\n }\n\n /**\n * Creates a new Analyzer with the given `analyzerName` and `options`, then\n * returns an {@link analyzer.Analyzer} instance for the new Analyzer.\n *\n * @param analyzerName - Name of the Analyzer.\n * @param options - An object defining the properties of the Analyzer.\n *\n * @example\n * ```js\n * const db = new Database();\n * const analyzer = await db.createAnalyzer(\"potatoes\", { type: \"identity\" });\n * // the identity Analyzer \"potatoes\" now exists\n * ```\n */\n async createAnalyzer(\n analyzerName: string,\n options: CreateAnalyzerOptions\n ): Promise<Analyzer> {\n const analyzer = this.analyzer(analyzerName);\n await analyzer.create(options);\n return analyzer;\n }\n\n /**\n * Fetches all Analyzers visible in the database and returns an array of\n * Analyzer descriptions.\n *\n * See also {@link Database#analyzers}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const analyzers = await db.listAnalyzers();\n * // analyzers is an array of Analyzer descriptions\n * ```\n */\n listAnalyzers(): Promise<AnalyzerDescription[]> {\n return this.request({ path: \"/_api/analyzer\" }, (res) => res.body.result);\n }\n\n /**\n * Fetches all Analyzers visible in the database and returns an array of\n * {@link analyzer.Analyzer} instances for those Analyzers.\n *\n * See also {@link Database#listAnalyzers}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const analyzers = await db.analyzers();\n * // analyzers is an array of Analyzer instances\n * ```\n */\n async analyzers(): Promise<Analyzer[]> {\n const analyzers = await this.listAnalyzers();\n return analyzers.map((data) => this.analyzer(data.name));\n }\n //#endregion\n\n //#region users\n /**\n * Fetches all ArangoDB users visible to the authenticated user and returns\n * an array of user objects.\n *\n * @example\n * ```js\n * const db = new Database();\n * const users = await db.listUsers();\n * // users is an array of user objects\n * ```\n */\n listUsers(): Promise<ArangoUser[]> {\n return this.request({\n absolutePath: true,\n path: \"/_api/user\",\n });\n }\n\n /**\n * Fetches the user data of a single ArangoDB user.\n *\n * @param username - Name of the ArangoDB user to fetch.\n *\n * @example\n * ```js\n * const db = new Database();\n * const user = await db.getUser(\"steve\");\n * // user is the user object for the user named \"steve\"\n * ```\n */\n getUser(username: string): Promise<ArangoApiResponse<ArangoUser>> {\n return this.request({\n absolutePath: true,\n path: `/_api/user/${encodeURIComponent(username)}`,\n });\n }\n\n /**\n * Creates a new ArangoDB user with the given password.\n *\n * @param username - Name of the ArangoDB user to create.\n * @param passwd - Password of the new ArangoDB user.\n *\n * @example\n * ```js\n * const db = new Database();\n * const user = await db.createUser(\"steve\", \"hunter2\");\n * // The user \"steve\" has been created\n * ```\n */\n createUser(\n username: string,\n passwd: string\n ): Promise<ArangoApiResponse<ArangoUser>>;\n /**\n * Creates a new ArangoDB user with the given options.\n *\n * @param username - Name of the ArangoDB user to create.\n * @param options - Additional options for creating the ArangoDB user.\n *\n * @example\n * ```js\n * const db = new Database();\n * const user = await db.createUser(\"steve\", { passwd: \"hunter2\" });\n * // The user \"steve\" has been created\n * ```\n */\n createUser(\n username: string,\n options: UserOptions\n ): Promise<ArangoApiResponse<ArangoUser>>;\n createUser(\n username: string,\n options: string | UserOptions\n ): Promise<ArangoApiResponse<ArangoUser>> {\n if (typeof options === \"string\") {\n options = { passwd: options };\n }\n return this.request(\n {\n absolutePath: true,\n method: \"POST\",\n path: \"/_api/user\",\n body: { user: username, ...options },\n },\n (res) => res.body\n );\n }\n\n /**\n * Sets the password of a given ArangoDB user to the new value.\n *\n * @param username - Name of the ArangoDB user to change the password for.\n * @param passwd - New password for the ArangoDB user.\n *\n * @example\n * ```js\n * const db = new Database();\n * const user = await db.updateUser(\"steve\", \"hunter2\");\n * // The user \"steve\" has received a new password\n * ```\n */\n updateUser(\n username: string,\n passwd: string\n ): Promise<ArangoApiResponse<ArangoUser>>;\n /**\n * Updates the ArangoDB user with the new options.\n *\n * @param username - Name of the ArangoDB user to modify.\n * @param options - Options of the ArangoDB user to modify.\n *\n * @example\n * ```js\n * const db = new Database();\n * const user = await db.updateUser(\"steve\", { active: false });\n * // The user \"steve\" has been set to inactive\n * ```\n */\n updateUser(\n username: string,\n options: Partial<UserOptions>\n ): Promise<ArangoApiResponse<ArangoUser>>;\n updateUser(\n username: string,\n options: string | Partial<UserOptions>\n ): Promise<ArangoApiResponse<ArangoUser>> {\n if (typeof options === \"string\") {\n options = { passwd: options };\n }\n return this.request(\n {\n absolutePath: true,\n method: \"PATCH\",\n path: `/api/user/${encodeURIComponent(username)}`,\n body: options,\n },\n (res) => res.body\n );\n }\n\n /**\n * Replaces the ArangoDB user's option with the new options.\n *\n * @param username - Name of the ArangoDB user to modify.\n * @param options - New options to replace the user's existing options.\n *\n * @example\n * ```js\n * const db = new Database();\n * const user = await db.replaceUser(\"steve\", { passwd: \"\", active: false });\n * // The user \"steve\" has been set to inactive with an empty password\n * ```\n */\n replaceUser(\n username: string,\n options: UserOptions\n ): Promise<ArangoApiResponse<ArangoUser>> {\n if (typeof options === \"string\") {\n options = { passwd: options };\n }\n return this.request(\n {\n absolutePath: true,\n method: \"PUT\",\n path: `/api/user/${encodeURIComponent(username)}`,\n body: options,\n },\n (res) => res.body\n );\n }\n\n /**\n * Removes the ArangoDB user with the given username from the server.\n *\n * @param username - Name of the ArangoDB user to remove.\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.removeUser(\"steve\");\n * // The user \"steve\" has been removed\n * ```\n */\n removeUser(\n username: string\n ): Promise<ArangoApiResponse<Record<string, never>>> {\n return this.request(\n {\n absolutePath: true,\n method: \"DELETE\",\n path: `/_api/user/${encodeURIComponent(username)}`,\n },\n (res) => res.body\n );\n }\n\n /**\n * Fetches the given ArangoDB user's access level for the database, or the\n * given collection in the given database.\n *\n * @param username - Name of the ArangoDB user to fetch the access level for.\n * @param database - Database to fetch the access level for.\n * @param collection - Collection to fetch the access level for.\n *\n * @example\n * ```js\n * const db = new Database();\n * const accessLevel = await db.getUserAccessLevel(\"steve\");\n * // The access level of the user \"steve\" has been fetched for the current\n * // database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const accessLevel = await db.getUserAccessLevel(\"steve\", {\n * database: \"staging\"\n * });\n * // The access level of the user \"steve\" has been fetched for the \"staging\"\n * // database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const accessLevel = await db.getUserAccessLevel(\"steve\", {\n * collection: \"pokemons\"\n * });\n * // The access level of the user \"steve\" has been fetched for the\n * // \"pokemons\" collection in the current database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const accessLevel = await db.getUserAccessLevel(\"steve\", {\n * database: \"staging\",\n * collection: \"pokemons\"\n * });\n * // The access level of the user \"steve\" has been fetched for the\n * // \"pokemons\" collection in the \"staging\" database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const staging = db.database(\"staging\");\n * const accessLevel = await db.getUserAccessLevel(\"steve\", {\n * database: staging\n * });\n * // The access level of the user \"steve\" has been fetched for the \"staging\"\n * // database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const staging = db.database(\"staging\");\n * const accessLevel = await db.getUserAccessLevel(\"steve\", {\n * collection: staging.collection(\"pokemons\")\n * });\n * // The access level of the user \"steve\" has been fetched for the\n * // \"pokemons\" collection in database \"staging\".\n * ```\n */\n getUserAccessLevel(\n username: string,\n { database, collection }: UserAccessLevelOptions\n ): Promise<AccessLevel> {\n const databaseName = isArangoDatabase(database)\n ? database.name\n : database?.normalize(\"NFC\") ??\n (isArangoCollection(collection)\n ? ((collection as any)._db as Database).name\n : this._name);\n const suffix = collection\n ? `/${encodeURIComponent(\n isArangoCollection(collection)\n ? collection.name\n : collection.normalize(\"NFC\")\n )}`\n : \"\";\n return this.request(\n {\n absolutePath: true,\n path: `/_api/user/${encodeURIComponent(\n username\n )}/database/${encodeURIComponent(databaseName)}${suffix}`,\n },\n (res) => res.body.result\n );\n }\n\n /**\n * Sets the given ArangoDB user's access level for the database, or the\n * given collection in the given database.\n *\n * @param username - Name of the ArangoDB user to set the access level for.\n * @param database - Database to set the access level for.\n * @param collection - Collection to set the access level for.\n * @param grant - Access level to set for the given user.\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.setUserAccessLevel(\"steve\", { grant: \"rw\" });\n * // The user \"steve\" now has read-write access to the current database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.setUserAccessLevel(\"steve\", {\n * database: \"staging\",\n * grant: \"rw\"\n * });\n * // The user \"steve\" now has read-write access to the \"staging\" database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.setUserAccessLevel(\"steve\", {\n * collection: \"pokemons\",\n * grant: \"rw\"\n * });\n * // The user \"steve\" now has read-write access to the \"pokemons\" collection\n * // in the current database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.setUserAccessLevel(\"steve\", {\n * database: \"staging\",\n * collection: \"pokemons\",\n * grant: \"rw\"\n * });\n * // The user \"steve\" now has read-write access to the \"pokemons\" collection\n * // in the \"staging\" database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const staging = db.database(\"staging\");\n * await db.setUserAccessLevel(\"steve\", {\n * database: staging,\n * grant: \"rw\"\n * });\n * // The user \"steve\" now has read-write access to the \"staging\" database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const staging = db.database(\"staging\");\n * await db.setUserAccessLevel(\"steve\", {\n * collection: staging.collection(\"pokemons\"),\n * grant: \"rw\"\n * });\n * // The user \"steve\" now has read-write access to the \"pokemons\" collection\n * // in database \"staging\".\n * ```\n */\n setUserAccessLevel(\n username: string,\n {\n database,\n collection,\n grant,\n }: UserAccessLevelOptions & { grant: AccessLevel }\n ): Promise<ArangoApiResponse<Record<string, AccessLevel>>> {\n const databaseName = isArangoDatabase(database)\n ? database.name\n : database?.normalize(\"NFC\") ??\n (isArangoCollection(collection)\n ? ((collection as any)._db as Database).name\n : this._name);\n const suffix = collection\n ? `/${encodeURIComponent(\n isArangoCollection(collection)\n ? collection.name\n : collection.normalize(\"NFC\")\n )}`\n : \"\";\n return this.request(\n {\n absolutePath: true,\n method: \"PUT\",\n path: `/_api/user/${encodeURIComponent(\n username\n )}/database/${encodeURIComponent(databaseName)}${suffix}`,\n body: { grant },\n },\n (res) => res.body\n );\n }\n\n /**\n * Clears the given ArangoDB user's access level for the database, or the\n * given collection in the given database.\n *\n * @param username - Name of the ArangoDB user to clear the access level for.\n * @param database - Database to clear the access level for.\n * @param collection - Collection to clear the access level for.\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.clearUserAccessLevel(\"steve\");\n * // The access level of the user \"steve\" has been cleared for the current\n * // database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.clearUserAccessLevel(\"steve\", { database: \"staging\" });\n * // The access level of the user \"steve\" has been cleared for the \"staging\"\n * // database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.clearUserAccessLevel(\"steve\", { collection: \"pokemons\" });\n * // The access level of the user \"steve\" has been cleared for the\n * // \"pokemons\" collection in the current database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.clearUserAccessLevel(\"steve\", {\n * database: \"staging\",\n * collection: \"pokemons\"\n * });\n * // The access level of the user \"steve\" has been cleared for the\n * // \"pokemons\" collection in the \"staging\" database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const staging = db.database(\"staging\");\n * await db.clearUserAccessLevel(\"steve\", { database: staging });\n * // The access level of the user \"steve\" has been cleared for the \"staging\"\n * // database.\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const staging = db.database(\"staging\");\n * await db.clearUserAccessLevel(\"steve\", {\n * collection: staging.collection(\"pokemons\")\n * });\n * // The access level of the user \"steve\" has been cleared for the\n * // \"pokemons\" collection in database \"staging\".\n * ```\n */\n clearUserAccessLevel(\n username: string,\n { database, collection }: UserAccessLevelOptions\n ): Promise<ArangoApiResponse<Record<string, AccessLevel>>> {\n const databaseName = isArangoDatabase(database)\n ? database.name\n : database?.normalize(\"NFC\") ??\n (isArangoCollection(collection)\n ? ((collection as any)._db as Database).name\n : this._name);\n const suffix = collection\n ? `/${encodeURIComponent(\n isArangoCollection(collection)\n ? collection.name\n : collection.normalize(\"NFC\")\n )}`\n : \"\";\n return this.request(\n {\n absolutePath: true,\n method: \"DELETE\",\n path: `/_api/user/${encodeURIComponent(\n username\n )}/database/${encodeURIComponent(databaseName)}${suffix}`,\n },\n (res) => res.body\n );\n }\n\n /**\n * Fetches an object mapping names of databases to the access level of the\n * given ArangoDB user for those databases.\n *\n * @param username - Name of the ArangoDB user to fetch the access levels for.\n * @param full - Whether access levels for collections should be included.\n *\n * @example\n * ```js\n * const db = new Database();\n * const accessLevels = await db.getUserDatabases(\"steve\");\n * for (const [databaseName, accessLevel] of Object.entries(accessLevels)) {\n * console.log(`${databaseName}: ${accessLevel}`);\n * }\n * ```\n */\n getUserDatabases(\n username: string,\n full?: false\n ): Promise<Record<string, AccessLevel>>;\n /**\n * Fetches an object mapping names of databases to the access level of the\n * given ArangoDB user for those databases and the collections within each\n * database.\n *\n * @param username - Name of the ArangoDB user to fetch the access levels for.\n * @param full - Whether access levels for collections should be included.\n *\n * @example\n * ```js\n * const db = new Database();\n * const accessLevels = await db.getUserDatabases(\"steve\", true);\n * for (const [databaseName, obj] of Object.entries(accessLevels)) {\n * console.log(`${databaseName}: ${obj.permission}`);\n * for (const [collectionName, accessLevel] of Object.entries(obj.collections)) {\n * console.log(`${databaseName}/${collectionName}: ${accessLevel}`);\n * }\n * }\n * ```\n */\n getUserDatabases(\n username: string,\n full: true\n ): Promise<\n Record<\n string,\n {\n permission: AccessLevel;\n collections: Record<string, AccessLevel | \"undefined\">;\n }\n >\n >;\n getUserDatabases(username: string, full?: boolean) {\n return this.request(\n {\n absolutePath: true,\n path: `/_api/user/${encodeURIComponent(username)}/database`,\n qs: { full },\n },\n (res) => res.body.result\n );\n }\n //#endregion\n\n //#region transactions\n /**\n * Performs a server-side JavaScript transaction and returns its return\n * value.\n *\n * Collections can be specified as collection names (strings) or objects\n * implementing the {@link collection.ArangoCollection} interface: `Collection`,\n * {@link graph.GraphVertexCollection}, {@link graph.GraphEdgeCollection} as well as\n * (in TypeScript) {@link collection.DocumentCollection} and {@link collection.EdgeCollection}.\n *\n * **Note**: The `action` function will be evaluated and executed on the\n * server inside ArangoDB's embedded JavaScript environment and can not\n * access any values other than those passed via the `params` option.\n *\n * See the official ArangoDB documentation for\n * [the JavaScript `@arangodb` module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html)\n * for information about accessing the database from within ArangoDB's\n * server-side JavaScript environment.\n *\n * @param collections - Collections involved in the transaction.\n * @param action - A string evaluating to a JavaScript function to be\n * executed on the server.\n * @param options - Options for the transaction. If `options.allowImplicit`\n * is specified, it will be used if `collections.allowImplicit` was not\n * specified.\n *\n * @example\n * ```js\n * const db = new Database();\n *\n * const action = `\n * function(params) {\n * // This code will be executed inside ArangoDB!\n * const { query } = require(\"@arangodb\");\n * return query\\`\n * FOR user IN _users\n * FILTER user.age > ${params.age}\n * RETURN u.user\n * \\`.toArray();\n * }\n * `);\n *\n * const result = await db.executeTransaction({\n * read: [\"_users\"]\n * }, action, {\n * params: { age: 12 }\n * });\n * // result contains the return value of the action\n * ```\n */\n executeTransaction(\n collections: TransactionCollections & { allowImplicit?: boolean },\n action: string,\n options?: TransactionOptions & { params?: any }\n ): Promise<any>;\n /**\n * Performs a server-side transaction and returns its return value.\n *\n * Collections can be specified as collection names (strings) or objects\n * implementing the {@link collection.ArangoCollection} interface: `Collection`,\n * {@link graph.GraphVertexCollection}, {@link graph.GraphEdgeCollection} as well as\n * (in TypeScript) {@link collection.DocumentCollection} and {@link collection.EdgeCollection}.\n *\n * **Note**: The `action` function will be evaluated and executed on the\n * server inside ArangoDB's embedded JavaScript environment and can not\n * access any values other than those passed via the `params` option.\n * See the official ArangoDB documentation for\n * [the JavaScript `@arangodb` module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html)\n * for information about accessing the database from within ArangoDB's\n * server-side JavaScript environment.\n *\n * @param collections - Collections that can be read from and written to\n * during the transaction.\n * @param action - A string evaluating to a JavaScript function to be\n * executed on the server.\n * @param options - Options for the transaction.\n *\n * @example\n * ```js\n * const db = new Database();\n *\n * const action = `\n * function(params) {\n * // This code will be executed inside ArangoDB!\n * const { query } = require(\"@arangodb\");\n * return query\\`\n * FOR user IN _users\n * FILTER user.age > ${params.age}\n * RETURN u.user\n * \\`.toArray();\n * }\n * `);\n *\n * const result = await db.executeTransaction([\"_users\"], action, {\n * params: { age: 12 }\n * });\n * // result contains the return value of the action\n * ```\n */\n executeTransaction(\n collections: (string | ArangoCollection)[],\n action: string,\n options?: TransactionOptions & { params?: any }\n ): Promise<any>;\n /**\n * Performs a server-side transaction and returns its return value.\n *\n * The Collection can be specified as a collection name (string) or an object\n * implementing the {@link collection.ArangoCollection} interface: `Collection`,\n * {@link graph.GraphVertexCollection}, {@link graph.GraphEdgeCollection} as well as\n * (in TypeScript) {@link collection.DocumentCollection} and {@link collection.EdgeCollection}.\n *\n * **Note**: The `action` function will be evaluated and executed on the\n * server inside ArangoDB's embedded JavaScript environment and can not\n * access any values other than those passed via the `params` option.\n * See the official ArangoDB documentation for\n * [the JavaScript `@arangodb` module](https://www.arangodb.com/docs/stable/appendix-java-script-modules-arango-db.html)\n * for information about accessing the database from within ArangoDB's\n * server-side JavaScript environment.\n *\n * @param collection - A collection that can be read from and written to\n * during the transaction.\n * @param action - A string evaluating to a JavaScript function to be\n * executed on the server.\n * @param options - Options for the transaction.\n *\n * @example\n * ```js\n * const db = new Database();\n *\n * const action = `\n * function(params) {\n * // This code will be executed inside ArangoDB!\n * const { query } = require(\"@arangodb\");\n * return query\\`\n * FOR user IN _users\n * FILTER user.age > ${params.age}\n * RETURN u.user\n * \\`.toArray();\n * }\n * `);\n *\n * const result = await db.executeTransaction(\"_users\", action, {\n * params: { age: 12 }\n * });\n * // result contains the return value of the action\n * ```\n */\n executeTransaction(\n collection: string | ArangoCollection,\n action: string,\n options?: TransactionOptions & { params?: any }\n ): Promise<any>;\n executeTransaction(\n collections:\n | (TransactionCollections & { allowImplicit?: boolean })\n | (string | ArangoCollection)[]\n | string\n | ArangoCollection,\n action: string,\n options: TransactionOptions & { params?: any } = {}\n ): Promise<any> {\n const { allowDirtyRead = undefined, ...opts } = options;\n return this.request(\n {\n method: \"POST\",\n path: \"/_api/transaction\",\n allowDirtyRead,\n body: {\n collections: coerceTransactionCollections(collections),\n action,\n ...opts,\n },\n },\n (res) => res.body.result\n );\n }\n\n /**\n * Returns a {@link transaction.Transaction} instance for an existing streaming\n * transaction with the given `id`.\n *\n * See also {@link Database#beginTransaction}.\n *\n * @param id - The `id` of an existing stream transaction.\n *\n * @example\n * ```js\n * const trx1 = await db.beginTransaction(collections);\n * const id = trx1.id;\n * // later\n * const trx2 = db.transaction(id);\n * await trx2.commit();\n * ```\n */\n transaction(transactionId: string): Transaction {\n return new Transaction(this, transactionId);\n }\n\n /**\n * Begins a new streaming transaction for the given collections, then returns\n * a {@link transaction.Transaction} instance for the transaction.\n *\n * Collections can be specified as collection names (strings) or objects\n * implementing the {@link collection.ArangoCollection} interface: `Collection`,\n * {@link graph.GraphVertexCollection}, {@link graph.GraphEdgeCollection} as\n * well as (in TypeScript) {@link collection.DocumentCollection} and\n * {@link collection.EdgeCollection}.\n *\n * @param collections - Collections involved in the transaction.\n * @param options - Options for the transaction.\n *\n * @example\n * ```js\n * const vertices = db.collection(\"vertices\");\n * const edges = db.collection(\"edges\");\n * const trx = await db.beginTransaction({\n * read: [\"vertices\"],\n * write: [edges] // collection instances can be passed directly\n * });\n * const start = await trx.step(() => vertices.document(\"a\"));\n * const end = await trx.step(() => vertices.document(\"b\"));\n * await trx.step(() => edges.save({ _from: start._id, _to: end._id }));\n * await trx.commit();\n * ```\n */\n beginTransaction(\n collections: TransactionCollections,\n options?: TransactionOptions\n ): Promise<Transaction>;\n /**\n * Begins a new streaming transaction for the given collections, then returns\n * a {@link transaction.Transaction} instance for the transaction.\n *\n * Collections can be specified as collection names (strings) or objects\n * implementing the {@link collection.ArangoCollection} interface: `Collection`,\n * {@link graph.GraphVertexCollection}, {@link graph.GraphEdgeCollection} as well as\n * (in TypeScript) {@link collection.DocumentCollection} and {@link collection.EdgeCollection}.\n *\n * @param collections - Collections that can be read from and written to\n * during the transaction.\n * @param options - Options for the transaction.\n *\n * @example\n * ```js\n * const vertices = db.collection(\"vertices\");\n * const edges = db.collection(\"edges\");\n * const trx = await db.beginTransaction([\n * \"vertices\",\n * edges // collection instances can be passed directly\n * ]);\n * const start = await trx.step(() => vertices.document(\"a\"));\n * const end = await trx.step(() => vertices.document(\"b\"));\n * await trx.step(() => edges.save({ _from: start._id, _to: end._id }));\n * await trx.commit();\n * ```\n */\n beginTransaction(\n collections: (string | ArangoCollection)[],\n options?: TransactionOptions\n ): Promise<Transaction>;\n /**\n * Begins a new streaming transaction for the given collections, then returns\n * a {@link transaction.Transaction} instance for the transaction.\n *\n * The Collection can be specified as a collection name (string) or an object\n * implementing the {@link collection.ArangoCollection} interface: `Collection`,\n * {@link graph.GraphVertexCollection}, {@link graph.GraphEdgeCollection} as well as\n * (in TypeScript) {@link collection.DocumentCollection} and {@link collection.EdgeCollection}.\n *\n * @param collections - A collection that can be read from and written to\n * during the transaction.\n * @param options - Options for the transaction.\n *\n * @example\n * ```js\n * const vertices = db.collection(\"vertices\");\n * const start = vertices.document(\"a\");\n * const end = vertices.document(\"b\");\n * const edges = db.collection(\"edges\");\n * const trx = await db.beginTransaction(\n * edges // collection instances can be passed directly\n * );\n * await trx.step(() => edges.save({ _from: start._id, _to: end._id }));\n * await trx.commit();\n * ```\n */\n beginTransaction(\n collection: string | ArangoCollection,\n options?: TransactionOptions\n ): Promise<Transaction>;\n beginTransaction(\n collections:\n | TransactionCollections\n | (string | ArangoCollection)[]\n | string\n | ArangoCollection,\n options: TransactionOptions = {}\n ): Promise<Transaction> {\n const { allowDirtyRead = undefined, ...opts } = options;\n return this.request(\n {\n method: \"POST\",\n path: \"/_api/transaction/begin\",\n allowDirtyRead,\n body: {\n collections: coerceTransactionCollections(collections),\n ...opts,\n },\n },\n (res) => new Transaction(this, res.body.result.id)\n );\n }\n\n /**\n * Fetches all active transactions from the database and returns an array of\n * transaction descriptions.\n *\n * See also {@link Database#transactions}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const transactions = await db.listTransactions();\n * // transactions is an array of transaction descriptions\n * ```\n */\n listTransactions(): Promise<TransactionDetails[]> {\n return this._connection.request(\n { path: \"/_api/transaction\" },\n (res) => res.body.transactions\n );\n }\n\n /**\n * Fetches all active transactions from the database and returns an array of\n * {@link transaction.Transaction} instances for those transactions.\n *\n * See also {@link Database#listTransactions}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const transactions = await db.transactions();\n * // transactions is an array of transactions\n * ```\n */\n async transactions(): Promise<Transaction[]> {\n const transactions = await this.listTransactions();\n return transactions.map((data) => this.transaction(data.id));\n }\n //#endregion\n\n //#region queries\n /**\n * Performs a database query using the given `query`, then returns a new\n * {@link cursor.ArrayCursor} instance for the result set.\n *\n * See the {@link aql!aql} template string handler for information about how\n * to create a query string without manually defining bind parameters nor\n * having to worry about escaping variables.\n *\n * @param query - An object containing an AQL query string and bind\n * parameters, e.g. the object returned from an {@link aql!aql} template string.\n * @param options - Options for the query execution.\n *\n * @example\n * ```js\n * const db = new Database();\n * const active = true;\n * const Users = db.collection(\"_users\");\n *\n * // Using an aql template string:\n * // Bind parameters are automatically extracted and arangojs collections\n * // are automatically passed as collection bind parameters.\n * const cursor = await db.query(aql`\n * FOR u IN ${Users}\n * FILTER u.authData.active == ${active}\n * RETURN u.user\n * `);\n * // cursor is a cursor for the query result\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const active = true;\n * const Users = db.collection(\"_users\");\n *\n * // Using an object with a regular multi-line string\n * const cursor = await db.query({\n * query: `\n * FOR u IN @@users\n * FILTER u.authData.active == @active\n * RETURN u.user\n * `,\n * bindVars: { active: active, \"@users\": Users.name }\n * });\n * ```\n */\n query<T = any>(\n query: AqlQuery,\n options?: QueryOptions\n ): Promise<ArrayCursor<T>>;\n /**\n * Performs a database query using the given `query` and `bindVars`, then\n * returns a new {@link cursor.ArrayCursor} instance for the result set.\n *\n * See the {@link aql!aql} template string handler for a safer and easier\n * alternative to passing strings directly.\n *\n * @param query - An AQL query string.\n * @param bindVars - An object defining bind parameters for the query.\n * @param options - Options for the query execution.\n *\n * @example\n * ```js\n * const db = new Database();\n * const active = true;\n * const Users = db.collection(\"_users\");\n *\n * const cursor = await db.query(\n * // A normal multi-line string\n * `\n * FOR u IN @@users\n * FILTER u.authData.active == @active\n * RETURN u.user\n * `,\n * { active: active, \"@users\": Users.name }\n * );\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const active = true;\n * const Users = db.collection(\"_users\");\n *\n * const cursor = await db.query(\n * // An AQL literal created from a normal multi-line string\n * aql.literal(`\n * FOR u IN @@users\n * FILTER u.authData.active == @active\n * RETURN u.user\n * `),\n * { active: active, \"@users\": Users.name }\n * );\n * ```\n */\n query<T = any>(\n query: string | AqlLiteral,\n bindVars?: Record<string, any>,\n options?: QueryOptions\n ): Promise<ArrayCursor<T>>;\n query<T = any>(\n query: string | AqlQuery | AqlLiteral,\n bindVars?: Record<string, any>,\n options: QueryOptions = {}\n ): Promise<ArrayCursor<T>> {\n if (isAqlQuery(query)) {\n options = bindVars ?? {};\n bindVars = query.bindVars;\n query = query.query;\n } else if (isAqlLiteral(query)) {\n query = query.toAQL();\n }\n const {\n allowDirtyRead,\n retryOnConflict,\n count,\n batchSize,\n cache,\n memoryLimit,\n ttl,\n timeout,\n ...opts\n } = options;\n return this.request(\n {\n method: \"POST\",\n path: \"/_api/cursor\",\n body: {\n query,\n bindVars,\n count,\n batchSize,\n cache,\n memoryLimit,\n ttl,\n options: opts,\n },\n allowDirtyRead,\n retryOnConflict,\n timeout,\n },\n (res) =>\n new BatchedArrayCursor<T>(\n this,\n res.body,\n res.arangojsHostUrl,\n allowDirtyRead\n ).items\n );\n }\n\n /**\n * Explains a database query using the given `query`.\n *\n * See the {@link aql!aql} template string handler for information about how\n * to create a query string without manually defining bind parameters nor\n * having to worry about escaping variables.\n *\n * @param query - An object containing an AQL query string and bind\n * parameters, e.g. the object returned from an {@link aql!aql} template string.\n * @param options - Options for explaining the query.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const explanation = await db.explain(aql`\n * FOR doc IN ${collection}\n * FILTER doc.flavor == \"strawberry\"\n * RETURN doc._key\n * `);\n * ```\n */\n explain(\n query: AqlQuery,\n options?: ExplainOptions & { allPlans?: false }\n ): Promise<ArangoApiResponse<SingleExplainResult>>;\n /**\n * Explains a database query using the given `query`.\n *\n * See the {@link aql!aql} template string handler for information about how\n * to create a query string without manually defining bind parameters nor\n * having to worry about escaping variables.\n *\n * @param query - An object containing an AQL query string and bind\n * parameters, e.g. the object returned from an {@link aql!aql} template string.\n * @param options - Options for explaining the query.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const explanation = await db.explain(\n * aql`\n * FOR doc IN ${collection}\n * FILTER doc.flavor == \"strawberry\"\n * RETURN doc._key\n * `,\n * { allPlans: true }\n * );\n * ```\n */\n explain(\n query: AqlQuery,\n options?: ExplainOptions & { allPlans: true }\n ): Promise<ArangoApiResponse<MultiExplainResult>>;\n /**\n * Explains a database query using the given `query` and `bindVars`.\n *\n * See the {@link aql!aql} template string handler for a safer and easier\n * alternative to passing strings directly.\n *\n * @param query - An AQL query string.\n * @param bindVars - An object defining bind parameters for the query.\n * @param options - Options for explaining the query.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const explanation = await db.explain(\n * `\n * FOR doc IN @@collection\n * FILTER doc.flavor == \"strawberry\"\n * RETURN doc._key\n * `,\n * { \"@collection\": collection.name }\n * );\n * ```\n */\n explain(\n query: string | AqlLiteral,\n bindVars?: Record<string, any>,\n options?: ExplainOptions & { allPlans?: false }\n ): Promise<ArangoApiResponse<SingleExplainResult>>;\n /**\n * Explains a database query using the given `query` and `bindVars`.\n *\n * See the {@link aql!aql} template string handler for a safer and easier\n * alternative to passing strings directly.\n *\n * @param query - An AQL query string.\n * @param bindVars - An object defining bind parameters for the query.\n * @param options - Options for explaining the query.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const explanation = await db.explain(\n * `\n * FOR doc IN @@collection\n * FILTER doc.flavor == \"strawberry\"\n * RETURN doc._key\n * `,\n * { \"@collection\": collection.name },\n * { allPlans: true }\n * );\n * ```\n */\n explain(\n query: string | AqlLiteral,\n bindVars?: Record<string, any>,\n options?: ExplainOptions & { allPlans: true }\n ): Promise<ArangoApiResponse<MultiExplainResult>>;\n explain(\n query: string | AqlQuery | AqlLiteral,\n bindVars?: Record<string, any>,\n options?: ExplainOptions\n ): Promise<ArangoApiResponse<SingleExplainResult | MultiExplainResult>> {\n if (isAqlQuery(query)) {\n options = bindVars;\n bindVars = query.bindVars;\n query = query.query;\n } else if (isAqlLiteral(query)) {\n query = query.toAQL();\n }\n return this.request({\n method: \"POST\",\n path: \"/_api/explain\",\n body: { query, bindVars, options },\n });\n }\n\n /**\n * Parses the given query and returns the result.\n *\n * See the {@link aql!aql} template string handler for information about how\n * to create a query string without manually defining bind parameters nor\n * having to worry about escaping variables.\n *\n * @param query - An AQL query string or an object containing an AQL query\n * string and bind parameters, e.g. the object returned from an {@link aql!aql}\n * template string.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"some-collection\");\n * const ast = await db.parse(aql`\n * FOR doc IN ${collection}\n * FILTER doc.flavor == \"strawberry\"\n * RETURN doc._key\n * `);\n * ```\n */\n parse(query: string | AqlQuery | AqlLiteral): Promise<ParseResult> {\n if (isAqlQuery(query)) {\n query = query.query;\n } else if (isAqlLiteral(query)) {\n query = query.toAQL();\n }\n return this.request({\n method: \"POST\",\n path: \"/_api/query\",\n body: { query },\n });\n }\n\n /**\n * Fetches the available optimizer rules.\n *\n * @example\n * ```js\n * const db = new Database();\n * const rules = await db.queryRules();\n * for (const rule of rules) {\n * console.log(rule.name);\n * }\n * ```\n */\n queryRules(): Promise<QueryOptimizerRule[]> {\n return this.request({\n path: \"/_api/query/rules\",\n });\n }\n\n /**\n * Fetches the query tracking properties.\n *\n * @example\n * ```js\n * const db = new Database();\n * const tracking = await db.queryTracking();\n * console.log(tracking.enabled);\n * ```\n */\n queryTracking(): Promise<QueryTracking>;\n /**\n * Modifies the query tracking properties.\n *\n * @param options - Options for query tracking.\n *\n * @example\n * ```js\n * const db = new Database();\n * // track up to 5 slow queries exceeding 5 seconds execution time\n * await db.setQueryTracking({\n * enabled: true,\n * trackSlowQueries: true,\n * maxSlowQueries: 5,\n * slowQueryThreshold: 5\n * });\n * ```\n */\n queryTracking(options: QueryTrackingOptions): Promise<QueryTracking>;\n queryTracking(options?: QueryTrackingOptions): Promise<QueryTracking> {\n return this.request(\n options\n ? {\n method: \"PUT\",\n path: \"/_api/query/properties\",\n body: options,\n }\n : {\n method: \"GET\",\n path: \"/_api/query/properties\",\n }\n );\n }\n\n /**\n * Fetches a list of information for all currently running queries.\n *\n * See also {@link Database#listSlowQueries} and {@link Database#killQuery}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const queries = await db.listRunningQueries();\n * ```\n */\n listRunningQueries(): Promise<QueryInfo[]> {\n return this.request({\n method: \"GET\",\n path: \"/_api/query/current\",\n });\n }\n\n /**\n * Fetches a list of information for all recent slow queries.\n *\n * See also {@link Database#listRunningQueries} and\n * {@link Database#clearSlowQueries}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const queries = await db.listSlowQueries();\n * // Only works if slow query tracking is enabled\n * ```\n */\n listSlowQueries(): Promise<QueryInfo[]> {\n return this.request({\n method: \"GET\",\n path: \"/_api/query/slow\",\n });\n }\n\n /**\n * Clears the list of recent slow queries.\n *\n * See also {@link Database#listSlowQueries}.\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.clearSlowQueries();\n * // Slow query list is now cleared\n * ```\n */\n clearSlowQueries(): Promise<void> {\n return this.request(\n {\n method: \"DELETE\",\n path: \"/_api/query/slow\",\n },\n () => undefined\n );\n }\n\n /**\n * Kills a running query with the given `queryId`.\n *\n * See also {@link Database#listRunningQueries}.\n *\n * @param queryId - The ID of a currently running query.\n *\n * @example\n * ```js\n * const db = new Database();\n * const queries = await db.listRunningQueries();\n * await Promise.all(queries.map(\n * async (query) => {\n * if (query.state === \"executing\") {\n * await db.killQuery(query.id);\n * }\n * }\n * ));\n * ```\n */\n killQuery(queryId: string): Promise<void> {\n return this.request(\n {\n method: \"DELETE\",\n path: `/_api/query/${encodeURIComponent(queryId)}`,\n },\n () => undefined\n );\n }\n //#endregion\n\n //#region functions\n /**\n * Fetches a list of all AQL user functions registered with the database.\n *\n * @example\n * ```js\n * const db = new Database();\n * const functions = await db.listFunctions();\n * const names = functions.map(fn => fn.name);\n * ```\n */\n listFunctions(): Promise<AqlUserFunction[]> {\n return this.request(\n { path: \"/_api/aqlfunction\" },\n (res) => res.body.result\n );\n }\n\n /**\n * Creates an AQL user function with the given _name_ and _code_ if it does\n * not already exist or replaces it if a function with the same name already\n * existed.\n *\n * @param name - A valid AQL function name. The function name must consist\n * of at least two alphanumeric identifiers separated with double colons.\n * @param code - A string evaluating to a JavaScript function (not a\n * JavaScript function object).\n * @param isDeterministic - If set to `true`, the function is expected to\n * always return the same result for equivalent inputs. This option currently\n * has no effect but may allow for optimizations in the future.\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.createFunction(\n * \"ACME::ACCOUNTING::CALCULATE_VAT\",\n * \"(price) => price * 0.19\"\n * );\n * // Use the new function in an AQL query with template handler:\n * const cursor = await db.query(aql`\n * FOR product IN products\n * RETURN MERGE(\n * { vat: ACME::ACCOUNTING::CALCULATE_VAT(product.price) },\n * product\n * )\n * `);\n * // cursor is a cursor for the query result\n * ```\n */\n createFunction(\n name: string,\n code: string,\n isDeterministic: boolean = false\n ): Promise<ArangoApiResponse<{ isNewlyCreated: boolean }>> {\n return this.request({\n method: \"POST\",\n path: \"/_api/aqlfunction\",\n body: { name, code, isDeterministic },\n });\n }\n\n /**\n * Deletes the AQL user function with the given name from the database.\n *\n * @param name - The name of the user function to drop.\n * @param group - If set to `true`, all functions with a name starting with\n * `name` will be deleted, otherwise only the function with the exact name\n * will be deleted.\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.dropFunction(\"ACME::ACCOUNTING::CALCULATE_VAT\");\n * // the function no longer exists\n * ```\n */\n dropFunction(\n name: string,\n group: boolean = false\n ): Promise<ArangoApiResponse<{ deletedCount: number }>> {\n return this.request({\n method: \"DELETE\",\n path: `/_api/aqlfunction/${encodeURIComponent(name)}`,\n qs: { group },\n });\n }\n //#endregion\n\n //#region services\n /**\n * Fetches a list of all installed service.\n *\n * @param excludeSystem - Whether system services should be excluded.\n *\n * @example\n * ```js\n * const db = new Database();\n * const services = await db.listServices();\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * const services = await db.listServices(false); // all services\n * ```\n */\n listServices(excludeSystem: boolean = true): Promise<ServiceSummary[]> {\n return this.request({\n path: \"/_api/foxx\",\n qs: { excludeSystem },\n });\n }\n\n /**\n * Installs a new service.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param source - The service bundle to install.\n * @param options - Options for installing the service.\n *\n * @example\n * ```js\n * const db = new Database();\n * // Using a node.js file stream as source\n * const source = fs.createReadStream(\"./my-foxx-service.zip\");\n * const info = await db.installService(\"/hello\", source);\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * // Using a node.js Buffer as source\n * const source = fs.readFileSync(\"./my-foxx-service.zip\");\n * const info = await db.installService(\"/hello\", source);\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * // Using a File (Blob) from a browser file input\n * const element = document.getElementById(\"my-file-input\");\n * const source = element.files[0];\n * const info = await db.installService(\"/hello\", source);\n * ```\n */\n async installService(\n mount: string,\n source: Readable | Buffer | Blob | string,\n options: InstallServiceOptions = {}\n ): Promise<ServiceInfo> {\n const { configuration, dependencies, ...qs } = options;\n const req = await toForm({\n configuration,\n dependencies,\n source,\n });\n return await this.request({\n ...req,\n method: \"POST\",\n path: \"/_api/foxx\",\n isBinary: true,\n qs: { ...qs, mount },\n });\n }\n\n /**\n * Replaces an existing service with a new service by completely removing the\n * old service and installing a new service at the same mount point.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param source - The service bundle to install.\n * @param options - Options for replacing the service.\n *\n * @example\n * ```js\n * const db = new Database();\n * // Using a node.js file stream as source\n * const source = fs.createReadStream(\"./my-foxx-service.zip\");\n * const info = await db.replaceService(\"/hello\", source);\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * // Using a node.js Buffer as source\n * const source = fs.readFileSync(\"./my-foxx-service.zip\");\n * const info = await db.replaceService(\"/hello\", source);\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * // Using a File (Blob) from a browser file input\n * const element = document.getElementById(\"my-file-input\");\n * const source = element.files[0];\n * const info = await db.replaceService(\"/hello\", source);\n * ```\n */\n async replaceService(\n mount: string,\n source: Readable | Buffer | Blob | string,\n options: ReplaceServiceOptions = {}\n ): Promise<ServiceInfo> {\n const { configuration, dependencies, ...qs } = options;\n const req = await toForm({\n configuration,\n dependencies,\n source,\n });\n return await this.request({\n ...req,\n method: \"PUT\",\n path: \"/_api/foxx/service\",\n isBinary: true,\n qs: { ...qs, mount },\n });\n }\n\n /**\n * Replaces an existing service with a new service while retaining the old\n * service's configuration and dependencies.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param source - The service bundle to install.\n * @param options - Options for upgrading the service.\n *\n * @example\n * ```js\n * const db = new Database();\n * // Using a node.js file stream as source\n * const source = fs.createReadStream(\"./my-foxx-service.zip\");\n * const info = await db.upgradeService(\"/hello\", source);\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * // Using a node.js Buffer as source\n * const source = fs.readFileSync(\"./my-foxx-service.zip\");\n * const info = await db.upgradeService(\"/hello\", source);\n * ```\n *\n * @example\n * ```js\n * const db = new Database();\n * // Using a File (Blob) from a browser file input\n * const element = document.getElementById(\"my-file-input\");\n * const source = element.files[0];\n * const info = await db.upgradeService(\"/hello\", source);\n * ```\n */\n async upgradeService(\n mount: string,\n source: Readable | Buffer | Blob | string,\n options: UpgradeServiceOptions = {}\n ): Promise<ServiceInfo> {\n const { configuration, dependencies, ...qs } = options;\n const req = await toForm({\n configuration,\n dependencies,\n source,\n });\n return await this.request({\n ...req,\n method: \"PATCH\",\n path: \"/_api/foxx/service\",\n isBinary: true,\n qs: { ...qs, mount },\n });\n }\n\n /**\n * Completely removes a service from the database.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param options - Options for uninstalling the service.\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.uninstallService(\"/my-foxx\");\n * ```\n */\n uninstallService(\n mount: string,\n options?: UninstallServiceOptions\n ): Promise<void> {\n return this.request(\n {\n method: \"DELETE\",\n path: \"/_api/foxx/service\",\n qs: { ...options, mount },\n },\n () => undefined\n );\n }\n\n /**\n * Retrieves information about a mounted service.\n *\n * @param mount - The service's mount point, relative to the database.\n *\n * @example\n * ```js\n * const db = new Database();\n * const info = await db.getService(\"/my-service\");\n * // info contains detailed information about the service\n * ```\n */\n getService(mount: string): Promise<ServiceInfo> {\n return this.request({\n path: \"/_api/foxx/service\",\n qs: { mount },\n });\n }\n\n /**\n * Retrieves information about the service's configuration options and their\n * current values.\n *\n * See also {@link Database#replaceServiceConfiguration} and\n * {@link Database#updateServiceConfiguration}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param minimal - If set to `true`, the result will only include each\n * configuration option's current value. Otherwise it will include the full\n * definition for each option.\n *\n * @example\n * ```js\n * const db = new Database();\n * const config = await db.getServiceConfiguration(\"/my-service\");\n * for (const [key, option] of Object.entries(config)) {\n * console.log(`${option.title} (${key}): ${option.current}`);\n * }\n * ```\n */\n getServiceConfiguration(\n mount: string,\n minimal?: false\n ): Promise<Record<string, ServiceConfiguration>>;\n /**\n * Retrieves information about the service's configuration options and their\n * current values.\n *\n * See also {@link Database#replaceServiceConfiguration} and\n * {@link Database#updateServiceConfiguration}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param minimal - If set to `true`, the result will only include each\n * configuration option's current value. Otherwise it will include the full\n * definition for each option.\n *\n * @example\n * ```js\n * const db = new Database();\n * const config = await db.getServiceConfiguration(\"/my-service\", true);\n * for (const [key, value] of Object.entries(config)) {\n * console.log(`${key}: ${value}`);\n * }\n * ```\n */\n getServiceConfiguration(\n mount: string,\n minimal: true\n ): Promise<Record<string, any>>;\n getServiceConfiguration(mount: string, minimal: boolean = false) {\n return this.request({\n path: \"/_api/foxx/configuration\",\n qs: { mount, minimal },\n });\n }\n\n /**\n * Replaces the configuration of the given service, discarding any existing\n * values for options not specified.\n *\n * See also {@link Database#updateServiceConfiguration} and\n * {@link Database#getServiceConfiguration}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param cfg - An object mapping configuration option names to values.\n * @param minimal - If set to `true`, the result will only include each\n * configuration option's current value and warning (if any).\n * Otherwise it will include the full definition for each option.\n *\n * @example\n * ```js\n * const db = new Database();\n * const config = { currency: \"USD\", locale: \"en-US\" };\n * const info = await db.replaceServiceConfiguration(\"/my-service\", config);\n * for (const [key, option] of Object.entries(info)) {\n * console.log(`${option.title} (${key}): ${option.value}`);\n * if (option.warning) console.warn(`Warning: ${option.warning}`);\n * }\n * ```\n */\n replaceServiceConfiguration(\n mount: string,\n cfg: Record<string, any>,\n minimal?: false\n ): Promise<Record<string, ServiceConfiguration & { warning?: string }>>;\n /**\n * Replaces the configuration of the given service, discarding any existing\n * values for options not specified.\n *\n * See also {@link Database#updateServiceConfiguration} and\n * {@link Database#getServiceConfiguration}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param cfg - An object mapping configuration option names to values.\n * @param minimal - If set to `true`, the result will only include each\n * configuration option's current value and warning (if any).\n * Otherwise it will include the full definition for each option.\n *\n * @example\n * ```js\n * const db = new Database();\n * const config = { currency: \"USD\", locale: \"en-US\" };\n * const info = await db.replaceServiceConfiguration(\"/my-service\", config);\n * for (const [key, value] of Object.entries(info.values)) {\n * console.log(`${key}: ${value}`);\n * if (info.warnings[key]) console.warn(`Warning: ${info.warnings[key]}`);\n * }\n * ```\n */\n replaceServiceConfiguration(\n mount: string,\n cfg: Record<string, any>,\n minimal: true\n ): Promise<{\n values: Record<string, any>;\n warnings: Record<string, string>;\n }>;\n replaceServiceConfiguration(\n mount: string,\n cfg: Record<string, any>,\n minimal: boolean = false\n ) {\n return this.request({\n method: \"PUT\",\n path: \"/_api/foxx/configuration\",\n body: cfg,\n qs: { mount, minimal },\n });\n }\n\n /**\n * Updates the configuration of the given service while maintaining any\n * existing values for options not specified.\n *\n * See also {@link Database#replaceServiceConfiguration} and\n * {@link Database#getServiceConfiguration}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param cfg - An object mapping configuration option names to values.\n * @param minimal - If set to `true`, the result will only include each\n * configuration option's current value and warning (if any).\n * Otherwise it will include the full definition for each option.\n *\n * @example\n * ```js\n * const db = new Database();\n * const config = { currency: \"USD\", locale: \"en-US\" };\n * const info = await db.updateServiceConfiguration(\"/my-service\", config);\n * for (const [key, option] of Object.entries(info)) {\n * console.log(`${option.title} (${key}): ${option.value}`);\n * if (option.warning) console.warn(`Warning: ${option.warning}`);\n * }\n * ```\n */\n updateServiceConfiguration(\n mount: string,\n cfg: Record<string, any>,\n minimal?: false\n ): Promise<Record<string, ServiceConfiguration & { warning?: string }>>;\n /**\n * Updates the configuration of the given service while maintaining any\n * existing values for options not specified.\n *\n * See also {@link Database#replaceServiceConfiguration} and\n * {@link Database#getServiceConfiguration}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param cfg - An object mapping configuration option names to values.\n * @param minimal - If set to `true`, the result will only include each\n * configuration option's current value and warning (if any).\n * Otherwise it will include the full definition for each option.\n *\n * @example\n * ```js\n * const db = new Database();\n * const config = { currency: \"USD\", locale: \"en-US\" };\n * const info = await db.updateServiceConfiguration(\"/my-service\", config);\n * for (const [key, value] of Object.entries(info.values)) {\n * console.log(`${key}: ${value}`);\n * if (info.warnings[key]) console.warn(`Warning: ${info.warnings[key]}`);\n * }\n * ```\n */\n updateServiceConfiguration(\n mount: string,\n cfg: Record<string, any>,\n minimal: true\n ): Promise<{\n values: Record<string, any>;\n warnings: Record<string, string>;\n }>;\n updateServiceConfiguration(\n mount: string,\n cfg: Record<string, any>,\n minimal: boolean = false\n ) {\n return this.request({\n method: \"PATCH\",\n path: \"/_api/foxx/configuration\",\n body: cfg,\n qs: { mount, minimal },\n });\n }\n\n /**\n * Retrieves information about the service's dependencies and their current\n * mount points.\n *\n * See also {@link Database#replaceServiceDependencies} and\n * {@link Database#updateServiceDependencies}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param minimal - If set to `true`, the result will only include each\n * dependency's current mount point. Otherwise it will include the full\n * definition for each dependency.\n *\n * @example\n * ```js\n * const db = new Database();\n * const deps = await db.getServiceDependencies(\"/my-service\");\n * for (const [key, dep] of Object.entries(deps)) {\n * console.log(`${dep.title} (${key}): ${dep.current}`);\n * }\n * ```\n */\n getServiceDependencies(\n mount: string,\n minimal?: false\n ): Promise<Record<string, SingleServiceDependency | MultiServiceDependency>>;\n /**\n * Retrieves information about the service's dependencies and their current\n * mount points.\n *\n * See also {@link Database#replaceServiceDependencies} and\n * {@link Database#updateServiceDependencies}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param minimal - If set to `true`, the result will only include each\n * dependency's current mount point. Otherwise it will include the full\n * definition for each dependency.\n *\n * @example\n * ```js\n * const db = new Database();\n * const deps = await db.getServiceDependencies(\"/my-service\", true);\n * for (const [key, value] of Object.entries(deps)) {\n * console.log(`${key}: ${value}`);\n * }\n * ```\n */\n getServiceDependencies(\n mount: string,\n minimal: true\n ): Promise<Record<string, string | string[]>>;\n getServiceDependencies(mount: string, minimal: boolean = false) {\n return this.request({\n path: \"/_api/foxx/dependencies\",\n qs: { mount, minimal },\n });\n }\n\n /**\n * Replaces the dependencies of the given service, discarding any existing\n * mount points for dependencies not specified.\n *\n * See also {@link Database#updateServiceDependencies} and\n * {@link Database#getServiceDependencies}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param cfg - An object mapping dependency aliases to mount points.\n * @param minimal - If set to `true`, the result will only include each\n * dependency's current mount point. Otherwise it will include the full\n * definition for each dependency.\n *\n * @example\n * ```js\n * const db = new Database();\n * const deps = { mailer: \"/mailer-api\", auth: \"/remote-auth\" };\n * const info = await db.replaceServiceDependencies(\"/my-service\", deps);\n * for (const [key, dep] of Object.entries(info)) {\n * console.log(`${dep.title} (${key}): ${dep.current}`);\n * if (dep.warning) console.warn(`Warning: ${dep.warning}`);\n * }\n * ```\n */\n replaceServiceDependencies(\n mount: string,\n deps: Record<string, string>,\n minimal?: false\n ): Promise<\n Record<\n string,\n (SingleServiceDependency | MultiServiceDependency) & { warning?: string }\n >\n >;\n /**\n * Replaces the dependencies of the given service, discarding any existing\n * mount points for dependencies not specified.\n *\n * See also {@link Database#updateServiceDependencies} and\n * {@link Database#getServiceDependencies}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param cfg - An object mapping dependency aliases to mount points.\n * @param minimal - If set to `true`, the result will only include each\n * dependency's current mount point. Otherwise it will include the full\n * definition for each dependency.\n *\n * @example\n * ```js\n * const db = new Database();\n * const deps = { mailer: \"/mailer-api\", auth: \"/remote-auth\" };\n * const info = await db.replaceServiceDependencies(\n * \"/my-service\",\n * deps,\n * true\n * );\n * for (const [key, value] of Object.entries(info)) {\n * console.log(`${key}: ${value}`);\n * if (info.warnings[key]) console.warn(`Warning: ${info.warnings[key]}`);\n * }\n * ```\n */\n replaceServiceDependencies(\n mount: string,\n deps: Record<string, string>,\n minimal: true\n ): Promise<{\n values: Record<string, string>;\n warnings: Record<string, string>;\n }>;\n replaceServiceDependencies(\n mount: string,\n deps: Record<string, string>,\n minimal: boolean = false\n ) {\n return this.request({\n method: \"PUT\",\n path: \"/_api/foxx/dependencies\",\n body: deps,\n qs: { mount, minimal },\n });\n }\n\n /**\n * Updates the dependencies of the given service while maintaining any\n * existing mount points for dependencies not specified.\n *\n * See also {@link Database#replaceServiceDependencies} and\n * {@link Database#getServiceDependencies}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param cfg - An object mapping dependency aliases to mount points.\n * @param minimal - If set to `true`, the result will only include each\n * dependency's current mount point. Otherwise it will include the full\n * definition for each dependency.\n *\n * @example\n * ```js\n * const db = new Database();\n * const deps = { mailer: \"/mailer-api\", auth: \"/remote-auth\" };\n * const info = await db.updateServiceDependencies(\"/my-service\", deps);\n * for (const [key, dep] of Object.entries(info)) {\n * console.log(`${dep.title} (${key}): ${dep.current}`);\n * if (dep.warning) console.warn(`Warning: ${dep.warning}`);\n * }\n * ```\n */\n updateServiceDependencies(\n mount: string,\n deps: Record<string, string>,\n minimal?: false\n ): Promise<\n Record<\n string,\n (SingleServiceDependency | MultiServiceDependency) & { warning?: string }\n >\n >;\n /**\n * Updates the dependencies of the given service while maintaining any\n * existing mount points for dependencies not specified.\n *\n * See also {@link Database#replaceServiceDependencies} and\n * {@link Database#getServiceDependencies}.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param cfg - An object mapping dependency aliases to mount points.\n * @param minimal - If set to `true`, the result will only include each\n * dependency's current mount point. Otherwise it will include the full\n * definition for each dependency.\n *\n * @example\n * ```js\n * const db = new Database();\n * const deps = { mailer: \"/mailer-api\", auth: \"/remote-auth\" };\n * const info = await db.updateServiceDependencies(\n * \"/my-service\",\n * deps,\n * true\n * );\n * for (const [key, value] of Object.entries(info)) {\n * console.log(`${key}: ${value}`);\n * if (info.warnings[key]) console.warn(`Warning: ${info.warnings[key]}`);\n * }\n * ```\n */\n updateServiceDependencies(\n mount: string,\n deps: Record<string, string>,\n minimal: true\n ): Promise<{\n values: Record<string, string>;\n warnings: Record<string, string>;\n }>;\n updateServiceDependencies(\n mount: string,\n deps: Record<string, string>,\n minimal: boolean = false\n ) {\n return this.request({\n method: \"PATCH\",\n path: \"/_api/foxx/dependencies\",\n body: deps,\n qs: { mount, minimal },\n });\n }\n\n /**\n * Enables or disables development mode for the given service.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param enabled - Whether development mode should be enabled or disabled.\n *\n * @example\n * ```js\n * const db = new Database();\n * await db.setServiceDevelopmentMode(\"/my-service\", true);\n * // the service is now in development mode\n * await db.setServiceDevelopmentMode(\"/my-service\", false);\n * // the service is now in production mode\n * ```\n */\n setServiceDevelopmentMode(\n mount: string,\n enabled: boolean = true\n ): Promise<ServiceInfo> {\n return this.request({\n method: enabled ? \"POST\" : \"DELETE\",\n path: \"/_api/foxx/development\",\n qs: { mount },\n });\n }\n\n /**\n * Retrieves a list of scripts defined in the service manifest's \"scripts\"\n * section mapped to their human readable representations.\n *\n * @param mount - The service's mount point, relative to the database.\n *\n * @example\n * ```js\n * const db = new Database();\n * const scripts = await db.listServiceScripts(\"/my-service\");\n * for (const [name, title] of Object.entries(scripts)) {\n * console.log(`${name}: ${title}`);\n * }\n * ```\n */\n listServiceScripts(mount: string): Promise<Record<string, string>> {\n return this.request({\n path: \"/_api/foxx/scripts\",\n qs: { mount },\n });\n }\n\n /**\n * Executes a service script and retrieves its result exposed as\n * `module.exports` (if any).\n *\n * @param mount - The service's mount point, relative to the database.\n * @param name - Name of the service script to execute as defined in the\n * service manifest.\n * @param params - Arbitrary value that will be exposed to the script as\n * `argv[0]` in the service context (e.g. `module.context.argv[0]`).\n * Must be serializable to JSON.\n *\n * @example\n * ```js\n * const db = new Database();\n * const result = await db.runServiceScript(\n * \"/my-service\",\n * \"create-user\",\n * {\n * username: \"service_admin\",\n * password: \"hunter2\"\n * }\n * );\n * ```\n */\n runServiceScript(mount: string, name: string, params?: any): Promise<any> {\n return this.request({\n method: \"POST\",\n path: `/_api/foxx/scripts/${encodeURIComponent(name)}`,\n body: params,\n qs: { mount },\n });\n }\n\n /**\n * Runs the tests of a given service and returns the results using the\n * \"default\" reporter.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param options - Options for running the tests.\n *\n * @example\n * ```js\n * const db = new Database();\n * const testReport = await db.runServiceTests(\"/my-foxx\");\n * ```\n */\n runServiceTests(\n mount: string,\n options?: {\n reporter?: \"default\";\n /**\n * Whether the reporter should use \"idiomatic\" mode. Has no effect when\n * using the \"default\" or \"suite\" reporters.\n */\n idiomatic?: false;\n /**\n * If set, only tests with full names including this exact string will be\n * executed.\n */\n filter?: string;\n }\n ): Promise<ServiceTestDefaultReport>;\n /**\n * Runs the tests of a given service and returns the results using the\n * \"suite\" reporter, which groups the test result by test suite.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param options - Options for running the tests.\n *\n * @example\n * ```js\n * const db = new Database();\n * const suiteReport = await db.runServiceTests(\n * \"/my-foxx\",\n * { reporter: \"suite\" }\n * );\n * ```\n */\n runServiceTests(\n mount: string,\n options: {\n reporter: \"suite\";\n /**\n * Whether the reporter should use \"idiomatic\" mode. Has no effect when\n * using the \"default\" or \"suite\" reporters.\n */\n idiomatic?: false;\n /**\n * If set, only tests with full names including this exact string will be\n * executed.\n */\n filter?: string;\n }\n ): Promise<ServiceTestSuiteReport>;\n /**\n * Runs the tests of a given service and returns the results using the\n * \"stream\" reporter, which represents the results as a sequence of tuples\n * representing events.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param options - Options for running the tests.\n *\n * @example\n * ```js\n * const db = new Database();\n * const streamEvents = await db.runServiceTests(\n * \"/my-foxx\",\n * { reporter: \"stream\" }\n * );\n * ```\n */\n runServiceTests(\n mount: string,\n options: {\n reporter: \"stream\";\n /**\n * Whether the reporter should use \"idiomatic\" mode. If set to `true`,\n * the results will be returned as a formatted string.\n */\n idiomatic?: false;\n /**\n * If set, only tests with full names including this exact string will be\n * executed.\n */\n filter?: string;\n }\n ): Promise<ServiceTestStreamReport>;\n /**\n * Runs the tests of a given service and returns the results using the\n * \"tap\" reporter, which represents the results as an array of strings using\n * the \"tap\" format.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param options - Options for running the tests.\n *\n * @example\n * ```js\n * const db = new Database();\n * const tapLines = await db.runServiceTests(\n * \"/my-foxx\",\n * { reporter: \"tap\" }\n * );\n * ```\n */\n runServiceTests(\n mount: string,\n options: {\n reporter: \"tap\";\n /**\n * Whether the reporter should use \"idiomatic\" mode. If set to `true`,\n * the results will be returned as a formatted string.\n */\n idiomatic?: false;\n /**\n * If set, only tests with full names including this exact string will be\n * executed.\n */\n filter?: string;\n }\n ): Promise<ServiceTestTapReport>;\n /**\n * Runs the tests of a given service and returns the results using the\n * \"xunit\" reporter, which represents the results as an XML document using\n * the JSONML exchange format.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param options - Options for running the tests.\n *\n * @example\n * ```js\n * const db = new Database();\n * const jsonML = await db.runServiceTests(\n * \"/my-foxx\",\n * { reporter: \"xunit\" }\n * );\n * ```\n */\n runServiceTests(\n mount: string,\n options: {\n reporter: \"xunit\";\n /**\n * Whether the reporter should use \"idiomatic\" mode. If set to `true`,\n * the results will be returned as a formatted string.\n */\n idiomatic?: false;\n /**\n * If set, only tests with full names including this exact string will be\n * executed.\n */\n filter?: string;\n }\n ): Promise<ServiceTestXunitReport>;\n /**\n * Runs the tests of a given service and returns the results as a string\n * using the \"stream\" reporter in \"idiomatic\" mode, which represents the\n * results as a line-delimited JSON stream of tuples representing events.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param options - Options for running the tests.\n *\n * @example\n * ```js\n * const db = new Database();\n * const streamReport = await db.runServiceTests(\n * \"/my-foxx\",\n * { reporter: \"stream\", idiomatic: true }\n * );\n * ```\n */\n runServiceTests(\n mount: string,\n options: {\n reporter: \"stream\";\n /**\n * Whether the reporter should use \"idiomatic\" mode. If set to `false`,\n * the results will be returned as an array of tuples instead of a\n * string.\n */\n idiomatic: true;\n /**\n * If set, only tests with full names including this exact string will be\n * executed.\n */\n filter?: string;\n }\n ): Promise<string>;\n /**\n * Runs the tests of a given service and returns the results as a string\n * using the \"tap\" reporter in \"idiomatic\" mode, which represents the\n * results using the \"tap\" format.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param options - Options for running the tests.\n *\n * @example\n * ```js\n * const db = new Database();\n * const tapReport = await db.runServiceTests(\n * \"/my-foxx\",\n * { reporter: \"tap\", idiomatic: true }\n * );\n * ```\n */\n runServiceTests(\n mount: string,\n options: {\n reporter: \"tap\";\n /**\n * Whether the reporter should use \"idiomatic\" mode. If set to `false`,\n * the results will be returned as an array of strings instead of a\n * single string.\n */\n idiomatic: true;\n /**\n * If set, only tests with full names including this exact string will be\n * executed.\n */\n filter?: string;\n }\n ): Promise<string>;\n /**\n * Runs the tests of a given service and returns the results as a string\n * using the \"xunit\" reporter in \"idiomatic\" mode, which represents the\n * results as an XML document.\n *\n * @param mount - The service's mount point, relative to the database.\n * @param options - Options for running the tests.\n *\n * @example\n * ```js\n * const db = new Database();\n * const xml = await db.runServiceTests(\n * \"/my-foxx\",\n * { reporter: \"xunit\", idiomatic: true }\n * );\n * ```\n */\n runServiceTests(\n mount: string,\n options: {\n reporter: \"xunit\";\n /**\n * Whether the reporter should use \"idiomatic\" mode. If set to `false`,\n * the results will be returned using the JSONML exchange format\n * instead of a string.\n */\n idiomatic: true;\n /**\n * If set, only tests with full names including this exact string will be\n * executed.\n */\n filter?: string;\n }\n ): Promise<string>;\n runServiceTests(\n mount: string,\n options?: {\n reporter?: string;\n idiomatic?: boolean;\n filter?: string;\n }\n ) {\n return this.request({\n method: \"POST\",\n path: \"/_api/foxx/tests\",\n qs: {\n ...options,\n mount,\n },\n });\n }\n\n /**\n * Retrieves the text content of the service's `README` or `README.md` file.\n *\n * Returns `undefined` if no such file could be found.\n *\n * @param mount - The service's mount point, relative to the database.\n *\n * @example\n * ```js\n * const db = new Database();\n * const readme = await db.getServiceReadme(\"/my-service\");\n * if (readme !== undefined) console.log(readme);\n * else console.warn(`No README found.`)\n * ```\n */\n getServiceReadme(mount: string): Promise<string | undefined> {\n return this.request({\n path: \"/_api/foxx/readme\",\n qs: { mount },\n });\n }\n\n /**\n * Retrieves an Open API compatible Swagger API description object for the\n * service installed at the given mount point.\n *\n * @param mount - The service's mount point, relative to the database.\n *\n * @example\n * ```js\n * const db = new Database();\n * const spec = await db.getServiceDocumentation(\"/my-service\");\n * // spec is a Swagger API description of the service\n * ```\n */\n getServiceDocumentation(mount: string): Promise<SwaggerJson> {\n return this.request({\n path: \"/_api/foxx/swagger\",\n qs: { mount },\n });\n }\n\n /**\n * Retrieves a zip bundle containing the service files.\n *\n * Returns a `Buffer` in node.js or `Blob` in the browser.\n *\n * @param mount - The service's mount point, relative to the database.\n *\n * @example\n * ```js\n * const db = new Database();\n * const serviceBundle = await db.downloadService(\"/my-foxx\");\n * ```\n */\n downloadService(mount: string): Promise<Buffer | Blob> {\n return this.request({\n method: \"POST\",\n path: \"/_api/foxx/download\",\n qs: { mount },\n expectBinary: true,\n });\n }\n\n /**\n * Writes all locally available services to the database and updates any\n * service bundles missing in the database.\n *\n * @param replace - If set to `true`, outdated services will also be\n * committed. This can be used to solve some consistency problems when\n * service bundles are missing in the database or were deleted manually.\n *\n * @example\n * ```js\n * await db.commitLocalServiceState();\n * // all services available on the coordinator have been written to the db\n * ```\n *\n * @example\n * ```js\n * await db.commitLocalServiceState(true);\n * // all service conflicts have been resolved in favor of this coordinator\n * ```\n */\n commitLocalServiceState(replace: boolean = false): Promise<void> {\n return this.request(\n {\n method: \"POST\",\n path: \"/_api/foxx/commit\",\n qs: { replace },\n },\n () => undefined\n );\n }\n //#endregion\n}\n","/**\n * ```ts\n * import type { Document, Edge } from \"arangojs/documents\";\n * ```\n *\n * The \"documents\" module provides document/edge related types for TypeScript.\n *\n * @packageDocumentation\n */\n\n/**\n * Common ArangoDB metadata properties of a document.\n */\nexport type DocumentMetadata = {\n /**\n * Key of the document, which uniquely identifies the document within its\n * collection.\n */\n _key: string;\n /**\n * Unique ID of the document, which is composed of the collection name\n * and the document `_key`.\n */\n _id: string;\n /**\n * Revision of the document data.\n */\n _rev: string;\n};\n\n/**\n * ArangoDB metadata defining the relations of an edge document.\n */\nexport type EdgeMetadata = {\n /**\n * Unique ID of the document that acts as the edge's start vertex.\n */\n _from: string;\n /**\n * Unique ID of the document that acts as the edge's end vertex.\n */\n _to: string;\n};\n\n/**\n * Type representing an object that can be stored in a collection.\n */\nexport type DocumentData<T extends Record<string, any> = any> = T &\n Partial<DocumentMetadata> &\n Partial<EdgeMetadata>;\n\n/**\n * Type representing an object that can be stored in an edge collection.\n */\nexport type EdgeData<T extends Record<string, any> = any> = T &\n Partial<DocumentMetadata> &\n EdgeMetadata;\n\n/**\n * Type representing a document stored in a collection.\n */\nexport type Document<T extends Record<string, any> = any> = T &\n DocumentMetadata &\n Partial<EdgeMetadata>;\n\n/**\n * Type representing an edge document stored in an edge collection.\n */\nexport type Edge<T extends Record<string, any> = any> = T &\n DocumentMetadata &\n EdgeMetadata;\n\n/**\n * Type representing patch data for a given object type to represent a payload\n * ArangoDB can apply in a document PATCH request (i.e. a partial update).\n *\n * This differs from `Partial` in that it also applies itself to any nested\n * objects recursively.\n */\nexport type Patch<T = Record<string, any>> = {\n [K in keyof T]?: T[K] | Patch<T[K]>;\n};\n\n/**\n * An object with an ArangoDB document `_id` property.\n *\n * See {@link documents.DocumentMetadata}.\n */\nexport type ObjectWithId = {\n [key: string]: any;\n _id: string;\n};\n\n/**\n * An object with an ArangoDB document `_key` property.\n *\n * See {@link documents.DocumentMetadata}.\n */\nexport type ObjectWithKey = {\n [key: string]: any;\n _key: string;\n};\n\n/**\n * A value that can be used to identify a document within a collection in\n * arangojs methods, i.e. a partial ArangoDB document or the value of a\n * document's `_key` or `_id`.\n *\n * See {@link documents.DocumentMetadata}.\n */\nexport type DocumentSelector = ObjectWithId | ObjectWithKey | string;\n\n/**\n * @internal\n */\nexport function _documentHandle(\n selector: DocumentSelector,\n collectionName: string,\n strict: boolean = true\n): string {\n if (typeof selector !== \"string\") {\n if (selector._id) {\n return _documentHandle(selector._id, collectionName);\n }\n if (selector._key) {\n return _documentHandle(selector._key, collectionName);\n }\n throw new Error(\n \"Document handle must be a string or an object with a _key or _id attribute\"\n );\n }\n if (selector.includes(\"/\")) {\n const [head, ...tail] = selector.split(\"/\");\n const normalizedHead = head.normalize(\"NFC\");\n if (strict && normalizedHead !== collectionName) {\n throw new Error(\n `Document ID \"${selector}\" does not match collection name \"${collectionName}\"`\n );\n }\n return [normalizedHead, ...tail].join(\"/\");\n }\n return `${collectionName}/${selector}`;\n}\n","/**\n * ```ts\n * import type { ArangoError, HttpError } from \"arangojs/error\";\n * ```\n *\n * The \"error\" module provides types and interfaces for TypeScript related\n * to arangojs error handling.\n *\n * @packageDocumentation\n */\n\nconst messages: { [key: number]: string } = {\n 0: \"Network Error\",\n 304: \"Not Modified\",\n 400: \"Bad Request\",\n 401: \"Unauthorized\",\n 402: \"Payment Required\",\n 403: \"Forbidden\",\n 404: \"Not Found\",\n 405: \"Method Not Allowed\",\n 406: \"Not Acceptable\",\n 407: \"Proxy Authentication Required\",\n 408: \"Request Timeout\",\n 409: \"Conflict\",\n 410: \"Gone\",\n 411: \"Length Required\",\n 412: \"Precondition Failed\",\n 413: \"Payload Too Large\",\n 414: \"Request-URI Too Long\",\n 415: \"Unsupported Media Type\",\n 416: \"Requested Range Not Satisfiable\",\n 417: \"Expectation Failed\",\n 418: \"I'm a teapot\",\n 421: \"Misdirected Request\",\n 422: \"Unprocessable Entity\",\n 423: \"Locked\",\n 424: \"Failed Dependency\",\n 426: \"Upgrade Required\",\n 428: \"Precondition Required\",\n 429: \"Too Many Requests\",\n 431: \"Request Header Fields Too Large\",\n 444: \"Connection Closed Without Response\",\n 451: \"Unavailable For Legal Reasons\",\n 499: \"Client Closed Request\",\n 500: \"Internal Server Error\",\n 501: \"Not Implemented\",\n 502: \"Bad Gateway\",\n 503: \"Service Unavailable\",\n 504: \"Gateway Timeout\",\n 505: \"HTTP Version Not Supported\",\n 506: \"Variant Also Negotiates\",\n 507: \"Insufficient Storage\",\n 508: \"Loop Detected\",\n 510: \"Not Extended\",\n 511: \"Network Authentication Required\",\n 599: \"Network Connect Timeout Error\",\n};\n\nconst nativeErrorKeys = [\n \"fileName\",\n \"lineNumber\",\n \"columnNumber\",\n \"stack\",\n \"description\",\n \"number\",\n] as (keyof Error)[];\n\n/**\n * Indicates whether the given value represents an {@link ArangoError}.\n *\n * @param error - A value that might be an `ArangoError`.\n */\nexport function isArangoError(error: any): error is ArangoError {\n return Boolean(error && error.isArangoError);\n}\n\n/**\n * Indicates whether the given value represents an ArangoDB error response.\n *\n * @internal\n */\nexport function isArangoErrorResponse(body: any): boolean {\n return (\n body &&\n body.hasOwnProperty(\"error\") &&\n body.hasOwnProperty(\"code\") &&\n body.hasOwnProperty(\"errorMessage\") &&\n body.hasOwnProperty(\"errorNum\")\n );\n}\n\n/**\n * Indicates whether the given value represents a Node.js `SystemError`.\n */\nexport function isSystemError(err: any): err is SystemError {\n return (\n Object.getPrototypeOf(err) === Error.prototype &&\n err.hasOwnProperty(\"code\") &&\n err.hasOwnProperty(\"errno\") &&\n err.hasOwnProperty(\"syscall\")\n );\n}\n\n/**\n * Interface representing a Node.js `SystemError`.\n */\nexport interface SystemError extends Error {\n code: string;\n errno: number | string;\n syscall: string;\n}\n\n/**\n * Represents an error returned by ArangoDB.\n */\nexport class ArangoError extends Error {\n name = \"ArangoError\";\n /**\n * ArangoDB error code.\n *\n * See [ArangoDB error documentation](https://www.arangodb.com/docs/stable/appendix-error-codes.html).\n */\n errorNum: number;\n /**\n * HTTP status code included in the server error response object.\n */\n code: number;\n /**\n * Server response object.\n */\n response: any;\n\n /**\n * @internal\n */\n constructor(response: any) {\n super();\n this.response = response;\n this.message = response.body.errorMessage;\n this.errorNum = response.body.errorNum;\n this.code = response.body.code;\n const err = new Error(this.message);\n err.name = this.name;\n for (const key of nativeErrorKeys) {\n if (err[key]) this[key] = err[key]!;\n }\n }\n\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB error.\n */\n get isArangoError(): true {\n return true;\n }\n\n toJSON() {\n return {\n error: true,\n errorMessage: this.message,\n errorNum: this.errorNum,\n code: this.code,\n };\n }\n}\n\n/**\n * Represents a plain HTTP error response.\n */\nexport class HttpError extends Error {\n name = \"HttpError\";\n /**\n * Server response object.\n */\n response: any;\n /**\n * HTTP status code of the server response.\n */\n code: number;\n\n /**\n * @internal\n */\n constructor(response: any) {\n super();\n this.response = response;\n this.code = response.statusCode || 500;\n this.message = messages[this.code] || messages[500];\n const err = new Error(this.message);\n err.name = this.name;\n for (const key of nativeErrorKeys) {\n if (err[key]) this[key] = err[key]!;\n }\n }\n\n toJSON() {\n return {\n error: true,\n code: this.code,\n };\n }\n}\n","/**\n * ```ts\n * import type {\n * Graph,\n * GraphVertexCollection,\n * GraphEdgeCollection,\n * } from \"arangojs/graph\";\n * ```\n *\n * The \"graph\" module provides graph related types and interfaces\n * for TypeScript.\n *\n * @packageDocumentation\n */\nimport {\n ArangoCollection,\n collectionToString,\n DocumentCollection,\n EdgeCollection,\n TraversalOptions,\n} from \"./collection\";\nimport { Headers } from \"./connection\";\nimport { Database } from \"./database\";\nimport {\n Document,\n DocumentData,\n DocumentMetadata,\n DocumentSelector,\n Edge,\n EdgeData,\n Patch,\n _documentHandle,\n} from \"./documents\";\nimport { isArangoError } from \"./error\";\nimport { DOCUMENT_NOT_FOUND, GRAPH_NOT_FOUND } from \"./lib/codes\";\n\n/**\n * Indicates whether the given value represents a {@link graph.Graph}.\n *\n * @param graph - A value that might be a Graph.\n */\nexport function isArangoGraph(graph: any): graph is Graph {\n return Boolean(graph && graph.isArangoGraph);\n}\n\n/**\n * @internal\n */\nfunction mungeGharialResponse(body: any, prop: \"vertex\" | \"edge\" | \"removed\") {\n const { new: newDoc, old: oldDoc, [prop]: doc, ...meta } = body;\n const result = { ...meta, ...doc };\n if (typeof newDoc !== \"undefined\") result.new = newDoc;\n if (typeof oldDoc !== \"undefined\") result.old = oldDoc;\n return result;\n}\n\n/**\n * @internal\n */\nfunction coerceEdgeDefinition(options: EdgeDefinitionOptions): EdgeDefinition {\n const edgeDefinition = {} as EdgeDefinition;\n edgeDefinition.collection = collectionToString(options.collection);\n edgeDefinition.from = Array.isArray(options.from)\n ? options.from.map(collectionToString)\n : [collectionToString(options.from)];\n edgeDefinition.to = Array.isArray(options.to)\n ? options.to.map(collectionToString)\n : [collectionToString(options.to)];\n return edgeDefinition;\n}\n\n/**\n * Options for retrieving a document from a graph collection.\n */\nexport type GraphCollectionReadOptions = {\n /**\n * If set to a document revision, the document will only be returned if its\n * `_rev` property matches this value.\n *\n * See also {@link documents.DocumentMetadata}.\n */\n rev?: string;\n /**\n * If set to `true`, `null` is returned instead of an exception being thrown\n * if the document does not exist.\n *\n * Default: `false`\n */\n graceful?: boolean;\n /**\n * If set to `true`, the request will explicitly permit ArangoDB to return a\n * potentially dirty or stale result and arangojs will load balance the\n * request without distinguishing between leaders and followers.\n *\n * Default: `false`\n */\n allowDirtyRead?: boolean;\n};\n\n/**\n * Options for inserting a document into a graph collection.\n */\nexport type GraphCollectionInsertOptions = {\n /**\n * If set to `true`, data will be synchronized to disk before returning.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * If set to `true`, the complete new document will be returned as the `new`\n * property on the result object.\n *\n * Default: `false`\n */\n returnNew?: boolean;\n};\n\n/**\n * Options for replacing a document in a graph collection.\n */\nexport type GraphCollectionReplaceOptions = {\n /**\n * If set to a document revision, the document will only be modified if its\n * `_rev` property matches this value.\n *\n * See also {@link documents.DocumentMetadata}.\n */\n rev?: string;\n /**\n * If set to `true`, data will be synchronized to disk before returning.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * If set to `false`, properties with a value of `null` will be removed from\n * the new document.\n *\n * Default: `true`\n */\n keepNull?: boolean;\n /**\n * If set to `true`, the complete old document will be returned as the `old`\n * property on the result object.\n *\n * Default: `false`\n */\n returnOld?: boolean;\n /**\n * If set to `true`, the complete new document will be returned as the `new`\n * property on the result object.\n *\n * Default: `false`\n */\n returnNew?: boolean;\n};\n\n/**\n * Options for removing a document from a graph collection.\n */\nexport type GraphCollectionRemoveOptions = {\n /**\n * If set to a document revision, the document will only be removed if its\n * `_rev` property matches this value.\n *\n * See also {@link documents.DocumentMetadata}.\n */\n rev?: string;\n /**\n * If set to `true`, data will be synchronized to disk before returning.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * If set to `true`, the complete old document will be returned as the `old`\n * property on the result object.\n *\n * Default: `false`\n */\n returnOld?: boolean;\n};\n\n/**\n * Definition of a relation in a {@link graph.Graph}.\n */\nexport type EdgeDefinition = {\n /**\n * Name of the collection containing the edges.\n */\n collection: string;\n /**\n * Array of names of collections containing the start vertices.\n */\n from: string[];\n /**\n * Array of names of collections containing the end vertices.\n */\n to: string[];\n};\n\n/**\n * An edge definition used to define a collection of edges in a {@link graph.Graph}.\n */\nexport type EdgeDefinitionOptions = {\n /**\n * Collection containing the edges.\n */\n collection: string | ArangoCollection;\n /**\n * Collection or collections containing the start vertices.\n */\n from: (string | ArangoCollection)[] | string | ArangoCollection;\n /**\n * Collection or collections containing the end vertices.\n */\n to: (string | ArangoCollection)[] | string | ArangoCollection;\n};\n\n/**\n * General information about a graph.\n */\nexport type GraphInfo = {\n /**\n * Key of the document internally representing this graph.\n *\n * See {@link documents.DocumentMetadata}.\n *\n * @internal\n */\n _key: string;\n /**\n * Unique identifier of the document internally representing this graph.\n *\n * See {@link documents.DocumentMetadata}.\n *\n * @internal\n */\n _id: string;\n /**\n * Revision of the document internally representing this graph.\n *\n * See {@link documents.DocumentMetadata}.\n *\n * @internal\n */\n _rev: string;\n /**\n * Name of the graph.\n */\n name: string;\n /**\n * Definitions for the relations of the graph.\n */\n edgeDefinitions: EdgeDefinition[];\n /**\n * Additional vertex collections. Documents within these collections do not\n * have edges within this graph.\n */\n orphanCollections: string[];\n\n /**\n * (Cluster only.) Number of shards that is used for every collection\n * within this graph.\n */\n numberOfShards?: number;\n /**\n * (Cluster only.) Replication factor used when initially creating\n * collections for this graph.\n */\n replicationFactor?: number;\n /**\n * (Cluster only.) Write concern for new collections in the graph.\n */\n writeConcern?: number;\n /**\n * (Enterprise Edition cluster only.) If set to `true`, the graph is a\n * SatelliteGraph.\n */\n isSatellite?: boolean;\n /**\n * (Enterprise Edition cluster only.) If set to `true`, the graph has been\n * created as a SmartGraph.\n */\n isSmart?: boolean;\n /**\n * (Enterprise Edition cluster only.) Attribute containing the shard key\n * value to use for smart sharding.\n */\n smartGraphAttribute?: string;\n /**\n * (Enterprise Edition cluster only.) If set to `true`, the graph has been\n * created as a Disjoint SmartGraph.\n */\n isDisjoint?: boolean;\n};\n\n/**\n * Option for creating a graph.\n */\nexport type CreateGraphOptions = {\n /**\n * If set to `true`, the request will wait until all modifications have been\n * synchronized to disk before returning successfully.\n *\n * Default: `false`\n */\n waitForSync?: boolean;\n /**\n * Additional vertex collections. Documents within these collections do not\n * have edges within this graph.\n */\n orphanCollections?: (string | ArangoCollection)[] | string | ArangoCollection;\n\n /**\n * (Cluster only.) Number of shards that is used for every collection\n * within this graph.\n *\n * Has no effect when `replicationFactor` is set to `\"satellite\"`.\n */\n numberOfShards?: number;\n /**\n * (Cluster only.) Replication factor used when initially creating\n * collections for this graph.\n *\n * Default: `1`\n */\n replicationFactor?: number | \"satellite\";\n /**\n * (Cluster only.) Write concern for new collections in the graph.\n *\n * Has no effect when `replicationFactor` is set to `\"satellite\"`.\n */\n writeConcern?: number;\n\n // Extra options\n /**\n * (Enterprise Edition cluster only.) If set to `true`, the graph will be\n * created as a SmartGraph.\n *\n * Default: `false`\n */\n isSmart?: boolean;\n /**\n * (Enterprise Edition cluster only.) Attribute containing the shard key\n * value to use for smart sharding.\n */\n smartGraphAttribute?: string;\n /**\n * (Enterprise Edition cluster only.) If set to `true`, the graph will be\n * created as a Disjoint SmartGraph.\n *\n * Default: `false`\n */\n isDisjoint?: boolean;\n /**\n * (Enterprise Edition cluster only.) Collections to be included in a Hybrid\n * SmartGraph.\n */\n satellites?: (string | ArangoCollection)[];\n};\n\nexport type AddVertexCollectionOptions = {\n /**\n * (Enterprise Edition cluster only.) Collections to be included in a Hybrid\n * SmartGraph.\n */\n satellites?: (string | ArangoCollection)[];\n};\n\nexport type AddEdgeDefinitionOptions = {\n /**\n * (Enterprise Edition cluster only.) Collections to be included in a Hybrid\n * SmartGraph.\n */\n satellites?: (string | ArangoCollection)[];\n};\n\nexport type ReplaceEdgeDefinitionOptions = {\n /**\n * (Enterprise Edition cluster only.) Collections to be included in a Hybrid\n * SmartGraph.\n */\n satellites?: string[];\n};\n\n/**\n * Represents a {@link collection.DocumentCollection} of vertices in a {@link graph.Graph}.\n *\n * @param T - Type to use for document data. Defaults to `any`.\n */\nexport class GraphVertexCollection<T extends Record<string, any> = any>\n implements ArangoCollection\n{\n protected _db: Database;\n protected _name: string;\n protected _graph: Graph;\n protected _collection: DocumentCollection<T>;\n\n /**\n * @internal\n */\n constructor(db: Database, name: string, graph: Graph) {\n this._db = db;\n this._collection = db.collection(name);\n this._name = this._collection.name;\n this._graph = graph;\n }\n\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB collection.\n */\n get isArangoCollection(): true {\n return true;\n }\n\n /**\n * Name of the collection.\n */\n get name() {\n return this._name;\n }\n\n /**\n * A {@link collection.DocumentCollection} instance for this vertex collection.\n */\n get collection() {\n return this._collection;\n }\n\n /**\n * The {@link graph.Graph} instance this vertex collection is bound to.\n */\n get graph() {\n return this._graph;\n }\n\n /**\n * Checks whether a vertex matching the given key or id exists in this\n * collection.\n *\n * Throws an exception when passed a vertex or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a vertex from this collection).\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.vertexCollection(\"vertices\");\n * const exists = await collection.vertexExists(\"abc123\");\n * if (!exists) {\n * console.log(\"Vertex does not exist\");\n * }\n * ```\n */\n async vertexExists(selector: DocumentSelector): Promise<boolean> {\n try {\n return await this._db.request(\n {\n method: \"HEAD\",\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/vertex/${encodeURI(_documentHandle(selector, this._name))}`,\n },\n () => true\n );\n } catch (err: any) {\n if (err.code === 404) {\n return false;\n }\n throw err;\n }\n }\n\n /**\n * Retrieves the vertex matching the given key or id.\n *\n * Throws an exception when passed a vertex or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a vertex from this collection).\n * @param options - Options for retrieving the vertex.\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.vertexCollection(\"vertices\");\n * try {\n * const vertex = await collection.vertex(\"abc123\");\n * console.log(vertex);\n * } catch (e: any) {\n * console.error(\"Could not find vertex\");\n * }\n * ```\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.vertexCollection(\"vertices\");\n * const vertex = await collection.vertex(\"abc123\", { graceful: true });\n * if (vertex) {\n * console.log(vertex);\n * } else {\n * console.error(\"Could not find vertex\");\n * }\n * ```\n */\n async vertex(\n selector: DocumentSelector,\n options?: GraphCollectionReadOptions\n ): Promise<Document<T>>;\n /**\n * Retrieves the vertex matching the given key or id.\n *\n * Throws an exception when passed a vertex or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a vertex from this collection).\n * @param graceful - If set to `true`, `null` is returned instead of an\n * exception being thrown if the vertex does not exist.\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.vertexCollection(\"vertices\");\n * try {\n * const vertex = await collection.vertex(\"abc123\", false);\n * console.log(vertex);\n * } catch (e: any) {\n * console.error(\"Could not find vertex\");\n * }\n * ```\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.vertexCollection(\"vertices\");\n * const vertex = await collection.vertex(\"abc123\", true);\n * if (vertex) {\n * console.log(vertex);\n * } else {\n * console.error(\"Could not find vertex\");\n * }\n * ```\n */\n async vertex(\n selector: DocumentSelector,\n graceful: boolean\n ): Promise<Document<T>>;\n async vertex(\n selector: DocumentSelector,\n options: boolean | GraphCollectionReadOptions = {}\n ): Promise<Document<T> | null> {\n if (typeof options === \"boolean\") {\n options = { graceful: options };\n }\n const {\n allowDirtyRead = undefined,\n graceful = false,\n rev,\n ...qs\n } = options;\n const headers: Headers = {};\n if (rev) headers[\"if-match\"] = rev;\n const result = this._db.request(\n {\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/vertex/${encodeURI(_documentHandle(selector, this._name))}`,\n headers,\n qs,\n allowDirtyRead,\n },\n (res) => res.body.vertex\n );\n if (!graceful) return result;\n try {\n return await result;\n } catch (err: any) {\n if (isArangoError(err) && err.errorNum === DOCUMENT_NOT_FOUND) {\n return null;\n }\n throw err;\n }\n }\n\n /**\n * Inserts a new vertex with the given `data` into the collection.\n *\n * @param data - The contents of the new vertex.\n * @param options - Options for inserting the vertex.\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.vertexCollection(\"friends\");\n * const result = await collection.save(\n * { _key: \"a\", color: \"blue\", count: 1 },\n * { returnNew: true }\n * );\n * console.log(result.new.color, result.new.count); // \"blue\" 1\n * ```\n */\n save(\n data: DocumentData<T>,\n options?: GraphCollectionInsertOptions\n ): Promise<DocumentMetadata & { new?: Document<T> }>;\n save(data: DocumentData<T>, options?: GraphCollectionInsertOptions) {\n return this._db.request(\n {\n method: \"POST\",\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/vertex/${encodeURIComponent(this._name)}`,\n body: data,\n qs: options,\n },\n (res) => mungeGharialResponse(res.body, \"vertex\")\n );\n }\n\n /**\n * Replaces an existing vertex in the collection.\n *\n * Throws an exception when passed a vertex or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a vertex from this collection).\n * @param newData - The contents of the new vertex.\n * @param options - Options for replacing the vertex.\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.collection(\"vertices\");\n * await collection.save({ _key: \"a\", color: \"blue\", count: 1 });\n * const result = await collection.replace(\n * \"a\",\n * { color: \"red\" },\n * { returnNew: true }\n * );\n * console.log(result.new.color, result.new.count); // \"red\" undefined\n * ```\n */\n replace(\n selector: DocumentSelector,\n newValue: DocumentData<T>,\n options?: GraphCollectionReplaceOptions\n ): Promise<DocumentMetadata & { new?: Document<T>; old?: Document<T> }>;\n replace(\n selector: DocumentSelector,\n newValue: DocumentData<T>,\n options: GraphCollectionReplaceOptions = {}\n ) {\n if (typeof options === \"string\") {\n options = { rev: options };\n }\n const { rev, ...qs } = options;\n const headers: Headers = {};\n if (rev) headers[\"if-match\"] = rev;\n return this._db.request(\n {\n method: \"PUT\",\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/vertex/${encodeURI(_documentHandle(selector, this._name))}`,\n body: newValue,\n qs,\n headers,\n },\n (res) => mungeGharialResponse(res.body, \"vertex\")\n );\n }\n\n /**\n * Updates an existing vertex in the collection.\n *\n * Throws an exception when passed a vertex or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a vertex from this collection).\n * @param newData - The data for updating the vertex.\n * @param options - Options for updating the vertex.\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.collection(\"vertices\");\n * await collection.save({ _key: \"a\", color: \"blue\", count: 1 });\n * const result = await collection.update(\n * \"a\",\n * { count: 2 },\n * { returnNew: true }\n * );\n * console.log(result.new.color, result.new.count); // \"blue\" 2\n * ```\n */\n update(\n selector: DocumentSelector,\n newValue: Patch<DocumentData<T>>,\n options?: GraphCollectionReplaceOptions\n ): Promise<DocumentMetadata & { new?: Document<T>; old?: Document<T> }>;\n update(\n selector: DocumentSelector,\n newValue: Patch<DocumentData<T>>,\n options: GraphCollectionReplaceOptions = {}\n ) {\n if (typeof options === \"string\") {\n options = { rev: options };\n }\n const headers: Headers = {};\n const { rev, ...qs } = options;\n if (rev) headers[\"if-match\"] = rev;\n return this._db.request(\n {\n method: \"PATCH\",\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/vertex/${encodeURI(_documentHandle(selector, this._name))}`,\n body: newValue,\n qs,\n headers,\n },\n (res) => mungeGharialResponse(res.body, \"vertex\")\n );\n }\n\n /**\n * Removes an existing vertex from the collection.\n *\n * Throws an exception when passed a vertex or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a vertex from this collection).\n * @param options - Options for removing the vertex.\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.vertexCollection(\"vertices\");\n * await collection.remove(\"abc123\");\n * // document with key \"abc123\" deleted\n * ```\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.vertexCollection(\"vertices\");\n * const doc = await collection.vertex(\"abc123\");\n * await collection.remove(doc);\n * // document with key \"abc123\" deleted\n * ```\n */\n remove(\n selector: DocumentSelector,\n options?: GraphCollectionRemoveOptions\n ): Promise<DocumentMetadata & { old?: Document<T> }>;\n remove(\n selector: DocumentSelector,\n options: GraphCollectionRemoveOptions = {}\n ) {\n if (typeof options === \"string\") {\n options = { rev: options };\n }\n const headers: Headers = {};\n const { rev, ...qs } = options;\n if (rev) headers[\"if-match\"] = rev;\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/vertex/${encodeURI(_documentHandle(selector, this._name))}`,\n qs,\n headers,\n },\n (res) => mungeGharialResponse(res.body, \"removed\")\n );\n }\n}\n\n/**\n * Represents a {@link collection.EdgeCollection} of edges in a {@link graph.Graph}.\n *\n * @param T - Type to use for document data. Defaults to `any`.\n */\nexport class GraphEdgeCollection<T extends Record<string, any> = any>\n implements ArangoCollection\n{\n protected _db: Database;\n protected _name: string;\n protected _graph: Graph;\n protected _collection: EdgeCollection<T>;\n\n /**\n * @internal\n */\n constructor(db: Database, name: string, graph: Graph) {\n this._db = db;\n this._collection = db.collection(name);\n this._name = this._collection.name;\n this._graph = graph;\n }\n\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB collection.\n */\n get isArangoCollection(): true {\n return true;\n }\n\n /**\n * Name of the collection.\n */\n get name() {\n return this._name;\n }\n\n /**\n * A {@link collection.EdgeCollection} instance for this edge collection.\n */\n get collection() {\n return this._collection;\n }\n\n /**\n * The {@link graph.Graph} instance this edge collection is bound to.\n */\n get graph() {\n return this._graph;\n }\n\n /**\n * Checks whether a edge matching the given key or id exists in this\n * collection.\n *\n * Throws an exception when passed a edge or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a edge from this collection).\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.edgeCollection(\"friends\")\n * const exists = await collection.edgeExists(\"abc123\");\n * if (!exists) {\n * console.log(\"Edge does not exist\");\n * }\n * ```\n */\n async edgeExists(selector: DocumentSelector): Promise<boolean> {\n try {\n return await this._db.request(\n {\n method: \"HEAD\",\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/edge/${encodeURI(_documentHandle(selector, this._name))}`,\n },\n () => true\n );\n } catch (err: any) {\n if (err.code === 404) {\n return false;\n }\n throw err;\n }\n }\n\n /**\n * Retrieves the edge matching the given key or id.\n *\n * Throws an exception when passed a edge or `_id` from a different\n * collection, or if the edge does not exist.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a edge from this collection).\n * @param options - Options for retrieving the edge.\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.edgeCollection(\"friends\")\n * try {\n * const edge = await collection.edge(\"abc123\");\n * console.log(edge);\n * } catch (e: any) {\n * console.error(\"Could not find edge\");\n * }\n * ```\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.edgeCollection(\"friends\")\n * const edge = await collection.edge(\"abc123\", { graceful: true });\n * if (edge) {\n * console.log(edge);\n * } else {\n * console.error(\"Edge does not exist\");\n * }\n * ```\n */\n async edge(\n selector: DocumentSelector,\n options?: GraphCollectionReadOptions\n ): Promise<Edge<T>>;\n /**\n * Retrieves the edge matching the given key or id.\n *\n * Throws an exception when passed a edge or `_id` from a different\n * collection, or if the edge does not exist.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a edge from this collection).\n * @param graceful - If set to `true`, `null` is returned instead of an\n * exception being thrown if the edge does not exist.\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.edgeCollection(\"friends\")\n * try {\n * const edge = await collection.edge(\"abc123\", false);\n * console.log(edge);\n * } catch (e: any) {\n * console.error(\"Could not find edge\");\n * }\n * ```\n *\n * @example\n * ```js\n * const graph = db.graph(\"some-graph\");\n * const collection = graph.edgeCollection(\"friends\")\n * const edge = await collection.edge(\"abc123\", true);\n * if (edge) {\n * console.log(edge);\n * } else {\n * console.error(\"Edge does not exist\");\n * }\n * ```\n */\n async edge(selector: DocumentSelector, graceful: boolean): Promise<Edge<T>>;\n async edge(\n selector: DocumentSelector,\n options: boolean | GraphCollectionReadOptions = {}\n ): Promise<Edge<T> | null> {\n if (typeof options === \"boolean\") {\n options = { graceful: options };\n }\n const {\n allowDirtyRead = undefined,\n graceful = false,\n rev,\n ...qs\n } = options;\n const headers: Headers = {};\n if (rev) headers[\"if-match\"] = rev;\n const result = this._db.request(\n {\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/edge/${encodeURI(_documentHandle(selector, this._name))}`,\n qs,\n allowDirtyRead,\n },\n (res) => res.body.edge\n );\n if (!graceful) return result;\n try {\n return await result;\n } catch (err: any) {\n if (isArangoError(err) && err.errorNum === DOCUMENT_NOT_FOUND) {\n return null;\n }\n throw err;\n }\n }\n\n /**\n * Inserts a new edge with the given `data` into the collection.\n *\n * @param data - The contents of the new edge.\n * @param options - Options for inserting the edge.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * const result = await collection.save(\n * { _from: \"users/rana\", _to: \"users/mudasir\", active: false },\n * { returnNew: true }\n * );\n * ```\n */\n save(\n data: EdgeData<T>,\n options?: GraphCollectionInsertOptions\n ): Promise<DocumentMetadata & { new?: Edge<T> }>;\n save(data: EdgeData<T>, options?: GraphCollectionInsertOptions) {\n return this._db.request(\n {\n method: \"POST\",\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/edge/${encodeURIComponent(this._name)}`,\n body: data,\n qs: options,\n },\n (res) => mungeGharialResponse(res.body, \"edge\")\n );\n }\n\n /**\n * Replaces an existing edge in the collection.\n *\n * Throws an exception when passed a edge or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a edge from this collection).\n * @param newData - The contents of the new edge.\n * @param options - Options for replacing the edge.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * await collection.save(\n * {\n * _key: \"musadir\",\n * _from: \"users/rana\",\n * _to: \"users/mudasir\",\n * active: true,\n * best: true\n * }\n * );\n * const result = await collection.replace(\n * \"musadir\",\n * { active: false },\n * { returnNew: true }\n * );\n * console.log(result.new.active, result.new.best); // false undefined\n * ```\n */\n replace(\n selector: DocumentSelector,\n newValue: EdgeData<T>,\n options?: GraphCollectionReplaceOptions\n ): Promise<DocumentMetadata & { new?: Edge<T>; old?: Edge<T> }>;\n replace(\n selector: DocumentSelector,\n newValue: EdgeData<T>,\n options: GraphCollectionReplaceOptions = {}\n ) {\n if (typeof options === \"string\") {\n options = { rev: options };\n }\n const { rev, ...qs } = options;\n const headers: Headers = {};\n if (rev) headers[\"if-match\"] = rev;\n return this._db.request(\n {\n method: \"PUT\",\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/edge/${encodeURI(_documentHandle(selector, this._name))}`,\n body: newValue,\n qs,\n headers,\n },\n (res) => mungeGharialResponse(res.body, \"edge\")\n );\n }\n\n /**\n * Updates an existing edge in the collection.\n *\n * Throws an exception when passed a edge or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a edge from this collection).\n * @param newData - The data for updating the edge.\n * @param options - Options for updating the edge.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * await collection.save(\n * {\n * _key: \"musadir\",\n * _from: \"users/rana\",\n * _to: \"users/mudasir\",\n * active: true,\n * best: true\n * }\n * );\n * const result = await collection.update(\n * \"musadir\",\n * { active: false },\n * { returnNew: true }\n * );\n * console.log(result.new.active, result.new.best); // false true\n * ```\n */\n update(\n selector: DocumentSelector,\n newValue: Patch<EdgeData<T>>,\n options?: GraphCollectionReplaceOptions\n ): Promise<DocumentMetadata & { new?: Edge<T>; old?: Edge<T> }>;\n update(\n selector: DocumentSelector,\n newValue: Patch<EdgeData<T>>,\n options: GraphCollectionReplaceOptions = {}\n ) {\n if (typeof options === \"string\") {\n options = { rev: options };\n }\n const { rev, ...qs } = options;\n const headers: Headers = {};\n if (rev) headers[\"if-match\"] = rev;\n return this._db.request(\n {\n method: \"PATCH\",\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/edge/${encodeURI(_documentHandle(selector, this._name))}`,\n body: newValue,\n qs,\n headers,\n },\n (res) => mungeGharialResponse(res.body, \"edge\")\n );\n }\n\n /**\n * Removes an existing edge from the collection.\n *\n * Throws an exception when passed a edge or `_id` from a different\n * collection.\n *\n * @param selector - Document `_key`, `_id` or object with either of those\n * properties (e.g. a edge from this collection).\n * @param options - Options for removing the edge.\n *\n * @example\n * ```js\n * const db = new Database();\n * const collection = db.collection(\"friends\");\n * const doc = await collection.edge(\"musadir\");\n * await collection.remove(doc);\n * // edge with key \"musadir\" deleted\n * ```\n */\n remove(\n selector: DocumentSelector,\n options?: GraphCollectionRemoveOptions\n ): Promise<DocumentMetadata & { old?: Edge<T> }>;\n remove(\n selector: DocumentSelector,\n options: GraphCollectionRemoveOptions = {}\n ) {\n if (typeof options === \"string\") {\n options = { rev: options };\n }\n const { rev, ...qs } = options;\n const headers: Headers = {};\n if (rev) headers[\"if-match\"] = rev;\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/gharial/${encodeURIComponent(\n this.graph.name\n )}/edge/${encodeURI(_documentHandle(selector, this._name))}`,\n qs,\n headers,\n },\n (res) => mungeGharialResponse(res.body, \"removed\")\n );\n }\n}\n\n/**\n * Represents a graph in a {@link database.Database}.\n */\nexport class Graph {\n protected _name: string;\n\n protected _db: Database;\n\n /**\n * @internal\n */\n constructor(db: Database, name: string) {\n this._name = name.normalize(\"NFC\");\n this._db = db;\n }\n\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB Graph.\n */\n get isArangoGraph(): true {\n return true;\n }\n\n /**\n * Name of the graph.\n */\n get name() {\n return this._name;\n }\n\n /**\n * Checks whether the graph exists.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const result = await graph.exists();\n * // result indicates whether the graph exists\n * ```\n */\n async exists(): Promise<boolean> {\n try {\n await this.get();\n return true;\n } catch (err: any) {\n if (isArangoError(err) && err.errorNum === GRAPH_NOT_FOUND) {\n return false;\n }\n throw err;\n }\n }\n\n /**\n * Retrieves general information about the graph.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const data = await graph.get();\n * // data contains general information about the graph\n * ```\n */\n get(): Promise<GraphInfo> {\n return this._db.request(\n { path: `/_api/gharial/${encodeURIComponent(this._name)}` },\n (res) => res.body.graph\n );\n }\n\n /**\n * Creates a graph with the given `edgeDefinitions` and `options` for this\n * graph's name.\n *\n * @param edgeDefinitions - Definitions for the relations of the graph.\n * @param options - Options for creating the graph.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const info = await graph.create([\n * {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * },\n * ]);\n * // graph now exists\n * ```\n */\n create(\n edgeDefinitions: EdgeDefinitionOptions[],\n options: CreateGraphOptions = {}\n ): Promise<GraphInfo> {\n const {\n orphanCollections,\n satellites,\n waitForSync,\n isSmart,\n isDisjoint,\n ...opts\n } = options;\n return this._db.request(\n {\n method: \"POST\",\n path: \"/_api/gharial\",\n body: {\n orphanCollections:\n orphanCollections &&\n (Array.isArray(orphanCollections)\n ? orphanCollections.map(collectionToString)\n : [collectionToString(orphanCollections)]),\n edgeDefinitions: edgeDefinitions.map(coerceEdgeDefinition),\n isSmart,\n isDisjoint,\n name: this._name,\n options: { ...opts, satellites: satellites?.map(collectionToString) },\n },\n qs: { waitForSync },\n },\n (res) => res.body.graph\n );\n }\n\n /**\n * Deletes the graph from the database.\n *\n * @param dropCollections - If set to `true`, the collections associated with\n * the graph will also be deleted.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * await graph.drop();\n * // the graph \"some-graph\" no longer exists\n * ```\n */\n drop(dropCollections: boolean = false): Promise<boolean> {\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/gharial/${encodeURIComponent(this._name)}`,\n qs: { dropCollections },\n },\n (res) => res.body.removed\n );\n }\n\n /**\n * Returns a {@link graph.GraphVertexCollection} instance for the given collection\n * name representing the collection in this graph.\n *\n * @param T - Type to use for document data. Defaults to `any`.\n * @param collection - Name of the vertex collection.\n */\n vertexCollection<T extends Record<string, any> = any>(\n collection: string | ArangoCollection\n ): GraphVertexCollection<T> {\n return new GraphVertexCollection<T>(\n this._db,\n collectionToString(collection),\n this\n );\n }\n\n /**\n * Fetches all vertex collections of this graph from the database and returns\n * an array of their names.\n *\n * See also {@link graph.Graph#vertexCollections}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const info = await graph.create([\n * {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * },\n * ]);\n * const vertexCollectionNames = await graph.listVertexCollections();\n * // [\"start-vertices\", \"end-vertices\"]\n * ```\n */\n listVertexCollections(): Promise<string[]> {\n return this._db.request(\n { path: `/_api/gharial/${encodeURIComponent(this._name)}/vertex` },\n (res) => res.body.collections\n );\n }\n\n /**\n * Fetches all vertex collections of this graph from the database and returns\n * an array of {@link graph.GraphVertexCollection} instances.\n *\n * See also {@link graph.Graph#listVertexCollections}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const info = await graph.create([\n * {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * },\n * ]);\n * const vertexCollections = await graph.vertexCollections();\n * for (const vertexCollection of vertexCollections) {\n * console.log(vertexCollection.name);\n * // \"start-vertices\"\n * // \"end-vertices\"\n * }\n * ```\n */\n async vertexCollections(): Promise<GraphVertexCollection[]> {\n const names = await this.listVertexCollections();\n return names.map((name) => new GraphVertexCollection(this._db, name, this));\n }\n\n /**\n * Adds the given collection to this graph as a vertex collection.\n *\n * @param collection - Collection to add to the graph.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * await graph.addVertexCollection(\"more-vertices\");\n * // The collection \"more-vertices\" has been added to the graph\n * const extra = db.collection(\"extra-vertices\");\n * await graph.addVertexCollection(extra);\n * // The collection \"extra-vertices\" has been added to the graph\n * ```\n */\n addVertexCollection(\n collection: string | ArangoCollection,\n options: AddVertexCollectionOptions = {}\n ): Promise<GraphInfo> {\n const { satellites, ...opts } = options;\n return this._db.request(\n {\n method: \"POST\",\n path: `/_api/gharial/${encodeURIComponent(this._name)}/vertex`,\n body: {\n collection: collectionToString(collection),\n options: { ...opts, satellites: satellites?.map(collectionToString) },\n },\n },\n (res) => res.body.graph\n );\n }\n\n /**\n * Removes the given collection from this graph as a vertex collection.\n *\n * @param collection - Collection to remove from the graph.\n * @param dropCollection - If set to `true`, the collection will also be\n * deleted from the database.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const info = await graph.create([\n * {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * },\n * ]);\n * await graph.removeVertexCollection(\"start-vertices\");\n * // The collection \"start-vertices\" is no longer part of the graph.\n * ```\n */\n removeVertexCollection(\n collection: string | ArangoCollection,\n dropCollection: boolean = false\n ): Promise<GraphInfo> {\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/gharial/${encodeURIComponent(\n this._name\n )}/vertex/${encodeURIComponent(collectionToString(collection))}`,\n qs: {\n dropCollection,\n },\n },\n (res) => res.body.graph\n );\n }\n\n /**\n * Returns a {@link graph.GraphEdgeCollection} instance for the given collection\n * name representing the collection in this graph.\n *\n * @param T - Type to use for document data. Defaults to `any`.\n * @param collection - Name of the edge collection.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const info = await graph.create([\n * {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * },\n * ]);\n * const graphEdgeCollection = graph.edgeCollection(\"edges\");\n * // Access the underlying EdgeCollection API:\n * const edgeCollection = graphEdgeCollection.collection;\n * ```\n */\n edgeCollection<T extends Record<string, any> = any>(\n collection: string | ArangoCollection\n ): GraphEdgeCollection<T> {\n return new GraphEdgeCollection<T>(\n this._db,\n collectionToString(collection),\n this\n );\n }\n\n /**\n * Fetches all edge collections of this graph from the database and returns\n * an array of their names.\n *\n * See also {@link graph.Graph#edgeCollections}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const info = await graph.create([\n * {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * },\n * ]);\n * const edgeCollectionNames = await graph.listEdgeCollections();\n * // [\"edges\"]\n * ```\n */\n listEdgeCollections(): Promise<string[]> {\n return this._db.request(\n { path: `/_api/gharial/${encodeURIComponent(this._name)}/edge` },\n (res) => res.body.collections\n );\n }\n\n /**\n * Fetches all edge collections of this graph from the database and returns\n * an array of {@link graph.GraphEdgeCollection} instances.\n *\n * See also {@link graph.Graph#listEdgeCollections}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const info = await graph.create([\n * {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * },\n * ]);\n * const graphEdgeCollections = await graph.edgeCollections();\n * for (const collection of graphEdgeCollection) {\n * console.log(collection.name);\n * // \"edges\"\n * }\n * ```\n */\n async edgeCollections(): Promise<GraphEdgeCollection[]> {\n const names = await this.listEdgeCollections();\n return names.map((name) => new GraphEdgeCollection(this._db, name, this));\n }\n\n /**\n * Adds an edge definition to this graph.\n *\n * @param edgeDefinition - Definition of a relation in this graph.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * await graph.addEdgeDefinition({\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * });\n * // The edge definition has been added to the graph\n * ```\n */\n addEdgeDefinition(\n edgeDefinition: EdgeDefinitionOptions,\n options: AddEdgeDefinitionOptions = {}\n ): Promise<GraphInfo> {\n const { satellites, ...opts } = options;\n return this._db.request(\n {\n method: \"POST\",\n path: `/_api/gharial/${encodeURIComponent(this._name)}/edge`,\n body: {\n ...coerceEdgeDefinition(edgeDefinition),\n options: { ...opts, satellites: satellites?.map(collectionToString) },\n },\n },\n (res) => res.body.graph\n );\n }\n\n /**\n * Replaces an edge definition in this graph. The existing edge definition\n * for the given edge collection will be overwritten.\n *\n * @param edgeDefinition - Definition of a relation in this graph.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const info = await graph.create([\n * {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * },\n * ]);\n * await graph.replaceEdgeDefinition({\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"other-vertices\"],\n * });\n * // The edge definition for \"edges\" has been replaced\n * ```\n */\n replaceEdgeDefinition(\n edgeDefinition: EdgeDefinitionOptions,\n options?: ReplaceEdgeDefinitionOptions\n ): Promise<GraphInfo>;\n /**\n * Replaces an edge definition in this graph. The existing edge definition\n * for the given edge collection will be overwritten.\n *\n * @param collection - Edge collection for which to replace the definition.\n * @param edgeDefinition - Definition of a relation in this graph.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const info = await graph.create([\n * {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * },\n * ]);\n * await graph.replaceEdgeDefinition(\"edges\", {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"other-vertices\"],\n * });\n * // The edge definition for \"edges\" has been replaced\n * ```\n */\n replaceEdgeDefinition(\n collection: string | ArangoCollection,\n edgeDefinition: EdgeDefinitionOptions,\n options?: ReplaceEdgeDefinitionOptions\n ): Promise<GraphInfo>;\n replaceEdgeDefinition(\n collectionOrEdgeDefinitionOptions:\n | string\n | ArangoCollection\n | EdgeDefinitionOptions,\n edgeDefinitionOrOptions?:\n | EdgeDefinitionOptions\n | ReplaceEdgeDefinitionOptions,\n options: ReplaceEdgeDefinitionOptions = {}\n ) {\n let collection = collectionOrEdgeDefinitionOptions as\n | string\n | ArangoCollection;\n let edgeDefinition = edgeDefinitionOrOptions as EdgeDefinitionOptions;\n if (\n edgeDefinitionOrOptions &&\n !edgeDefinitionOrOptions.hasOwnProperty(\"collection\")\n ) {\n options = edgeDefinitionOrOptions as ReplaceEdgeDefinitionOptions;\n edgeDefinitionOrOptions = undefined;\n }\n if (!edgeDefinitionOrOptions) {\n edgeDefinition =\n collectionOrEdgeDefinitionOptions as EdgeDefinitionOptions;\n collection = edgeDefinition.collection;\n }\n const { satellites, ...opts } = options;\n return this._db.request(\n {\n method: \"PUT\",\n path: `/_api/gharial/${encodeURIComponent(\n this._name\n )}/edge/${encodeURIComponent(collectionToString(collection))}`,\n body: {\n ...coerceEdgeDefinition(edgeDefinition),\n options: { ...opts, satellites: satellites?.map(collectionToString) },\n },\n },\n (res) => res.body.graph\n );\n }\n\n /**\n * Removes the edge definition for the given edge collection from this graph.\n *\n * @param collection - Edge collection for which to remove the definition.\n * @param dropCollection - If set to `true`, the collection will also be\n * deleted from the database.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"some-graph\");\n * const info = await graph.create([\n * {\n * collection: \"edges\",\n * from: [\"start-vertices\"],\n * to: [\"end-vertices\"],\n * },\n * ]);\n * await graph.removeEdgeDefinition(\"edges\");\n * // The edge definition for \"edges\" has been replaced\n * ```\n */\n removeEdgeDefinition(\n collection: string | ArangoCollection,\n dropCollection: boolean = false\n ): Promise<GraphInfo> {\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/gharial/${encodeURIComponent(\n this._name\n )}/edge/${encodeURIComponent(collectionToString(collection))}`,\n qs: {\n dropCollection,\n },\n },\n (res) => res.body.graph\n );\n }\n\n /**\n * Performs a traversal starting from the given `startVertex` and following\n * edges contained in this graph.\n *\n * See also {@link collection.EdgeCollection#traversal}.\n *\n * @param startVertex - Document `_id` of a vertex in this graph.\n * @param options - Options for performing the traversal.\n *\n * @deprecated Simple Queries have been deprecated in ArangoDB 3.4 and can be\n * replaced with AQL queries.\n *\n * @example\n * ```js\n * const db = new Database();\n * const graph = db.graph(\"my-graph\");\n * const collection = graph.edgeCollection(\"edges\").collection;\n * await collection.import([\n * [\"_key\", \"_from\", \"_to\"],\n * [\"x\", \"vertices/a\", \"vertices/b\"],\n * [\"y\", \"vertices/b\", \"vertices/c\"],\n * [\"z\", \"vertices/c\", \"vertices/d\"],\n * ]);\n * const startVertex = \"vertices/a\";\n * const cursor = await db.query(aql`\n * FOR vertex IN OUTBOUND ${startVertex} GRAPH ${graph}\n * RETURN vertex._key\n * `);\n * const result = await cursor.all();\n * console.log(result); // [\"a\", \"b\", \"c\", \"d\"]\n * ```\n */\n traversal(startVertex: string, options?: TraversalOptions): Promise<any> {\n return this._db.request(\n {\n method: \"POST\",\n path: `/_api/traversal`,\n body: {\n ...options,\n startVertex,\n graphName: this._name,\n },\n },\n (res) => res.body.result\n );\n }\n}\n","/**\n * Error codes handled by arangojs.\n *\n * See also [ArangoDB error documentation](https://www.arangodb.com/docs/stable/appendix-error-codes.html).\n *\n * @packageDocumentation\n * @internal\n */\n\nexport const TRANSACTION_NOT_FOUND = 10;\nexport const ERROR_ARANGO_MAINTENANCE_MODE = 503;\nexport const ERROR_ARANGO_CONFLICT = 1200;\nexport const ANALYZER_NOT_FOUND = 1202;\nexport const DOCUMENT_NOT_FOUND = 1202;\nexport const COLLECTION_NOT_FOUND = 1203;\nexport const VIEW_NOT_FOUND = 1203;\nexport const DATABASE_NOT_FOUND = 1228;\nexport const GRAPH_NOT_FOUND = 1924;\n","/**\n * ```ts\n * import type { ArangoSearchView } from \"arangojs/view\";\n * ```\n *\n * The \"view\" module provides View related types and interfaces for TypeScript.\n *\n * @packageDocumentation\n */\nimport { ArangoApiResponse } from \"./connection\";\nimport { Database } from \"./database\";\nimport { isArangoError } from \"./error\";\nimport { VIEW_NOT_FOUND } from \"./lib/codes\";\n\n/**\n * Indicates whether the given value represents a {@link View}.\n *\n * @param view - A value that might be a View.\n */\nexport function isArangoView(view: any): view is View {\n return Boolean(view && view.isArangoView);\n}\n\n/**\n * Sorting direction. Descending or ascending.\n */\nexport type Direction = \"desc\" | \"asc\";\n\n/**\n * Policy to consolidate based on segment byte size and live document count as\n * dictated by the customization attributes.\n *\n * @deprecated The `bytes_accum` consolidation policy was deprecated in\n * ArangoDB 3.7 and should be replaced with the `tier` consolidation policy.\n */\nexport type BytesAccumConsolidationPolicy = {\n /**\n * Type of consolidation policy.\n */\n type: \"bytes_accum\";\n /**\n * Must be in the range of `0.0` to `1.0`.\n */\n threshold?: number;\n};\n\n/**\n * Policy to consolidate if the sum of all candidate segment byte size is less\n * than the total segment byte size multiplied by a given threshold.\n */\nexport type TierConsolidationPolicy = {\n /**\n * Type of consolidation policy.\n */\n type: \"tier\";\n /**\n * Size below which all segments are treated as equivalent.\n *\n * Default: `2097152` (2 MiB)\n */\n segmentsBytesFloor?: number;\n /**\n * Maximum allowed size of all consolidation segments.\n *\n * Default: `5368709120` (5 GiB)\n */\n segmentsBytesMax?: number;\n /**\n * Maximum number of segments that are evaluated as candidates for\n * consolidation.\n *\n * Default: `10`\n */\n segmentsMax?: number;\n /**\n * Minimum number of segments that are evaluated as candidates for\n * consolidation.\n *\n * Default: `1`\n */\n segmentsMin?: number;\n /**\n * Consolidation candidates with a score less than this value will be\n * filtered out.\n *\n * Default: `0`\n */\n minScore?: number;\n};\n\n/**\n * Compression for storing data.\n */\nexport type Compression = \"lz4\" | \"none\";\n\n/**\n * Options for creating a View.\n */\nexport type CreateViewOptions =\n | CreateArangoSearchViewOptions\n | CreateSearchAliasViewOptions;\n\n/**\n * Options for replacing a View's properties.\n */\nexport type ViewPropertiesOptions =\n | ArangoSearchViewPropertiesOptions\n | SearchAliasViewPropertiesOptions;\n\n/**\n * Options for partially modifying a View's properties.\n */\nexport type ViewPatchPropertiesOptions =\n | ArangoSearchViewPropertiesOptions\n | SearchAliasViewPatchPropertiesOptions;\n\n/**\n * A link definition for an ArangoSearch View.\n */\nexport type ArangoSearchViewLinkOptions = {\n /**\n * A list of names of Analyzers to apply to values of processed document\n * attributes.\n *\n * Default: `[\"identity\"]`\n */\n analyzers?: string[];\n /**\n * An object mapping names of attributes to process for each document to\n * {@link ArangoSearchViewLinkOptions} definitions.\n */\n fields?: Record<string, ArangoSearchViewLinkOptions>;\n /**\n * If set to `true`, all document attributes will be processed, otherwise\n * only the attributes in `fields` will be processed.\n *\n * Default: `false`\n */\n includeAllFields?: boolean;\n /**\n * (Enterprise Edition only.) An object mapping attribute names to\n * {@link ArangoSearchViewLinkOptions} definitions to index sub-objects\n * stored in an array.\n */\n nested?: Record<string, ArangoSearchViewLinkOptions>;\n /**\n * If set to `true`, the position of values in array values will be tracked,\n * otherwise all values in an array will be treated as equal alternatives.\n */\n trackListPositions?: boolean;\n /**\n * Controls how the view should keep track of the attribute values.\n *\n * Default: `\"none\"`\n */\n storeValues?: \"none\" | \"id\";\n /**\n * If set to `true`, then no exclusive lock is used on the source collection\n * during View index creation, so that it remains basically available.\n *\n * Default: `false`\n */\n inBackground?: boolean;\n /**\n * (Enterprise Edition only.) If set to `true`, then field normalization\n * values are always cached in memory.\n *\n * Default: `false`\n */\n cache?: boolean;\n};\n\n/**\n * Options for modifying the properties of an ArangoSearch View.\n */\nexport type ArangoSearchViewPropertiesOptions = {\n /**\n * How many commits to wait between removing unused files.\n *\n * Default: `2`\n */\n cleanupIntervalStep?: number;\n /**\n * How long to wait between applying the `consolidationPolicy`.\n *\n * Default: `10000`\n */\n consolidationIntervalMsec?: number;\n /**\n * How long to wait between commiting View data store changes and making\n * documents visible to queries.\n *\n * Default: `1000`\n */\n commitIntervalMsec?: number;\n /**\n * Consolidation policy to apply for selecting which segments should be\n * merged.\n *\n * Default: `{ type: \"tier\" }`\n */\n consolidationPolicy?: TierConsolidationPolicy;\n /**\n * An object mapping names of linked collections to\n * {@link ArangoSearchViewLinkOptions} definitions.\n */\n links?: Record<string, Omit<ArangoSearchViewLinkOptions, \"nested\">>;\n};\n\n/**\n * Options for partially modifying the properties of an ArangoSearch View.\n */\nexport type ArangoSearchViewPatchPropertiesOptions =\n ArangoSearchViewPropertiesOptions;\n\n/**\n * Options for creating an ArangoSearch View.\n */\nexport type CreateArangoSearchViewOptions =\n ArangoSearchViewPropertiesOptions & {\n /**\n * Type of the View.\n */\n type: \"arangosearch\";\n /**\n * Maximum number of writers cached in the pool.\n *\n * Default: `64`\n */\n writebufferIdle?: number;\n /**\n * Maximum number of concurrent active writers that perform a transaction.\n *\n * Default: `0`\n */\n writebufferActive?: number;\n /**\n * Maximum memory byte size per writer before a writer flush is triggered.\n *\n * Default: `33554432` (32 MiB)\n */\n writebufferSizeMax?: number;\n /**\n * Attribute path (`field`) for the value of each document that will be\n * used for sorting.\n *\n * If `direction` is set to `\"asc\"` or `asc` is set to `true`,\n * the primary sorting order will be ascending.\n *\n * If `direction` is set to `\"desc\"` or `asc` is set to `false`,\n * the primary sorting order will be descending.\n */\n primarySort?: (\n | {\n /**\n * Attribute path for the value of each document to use for\n * sorting.\n */\n field: string;\n /**\n * If set to `\"asc\"`, the primary sorting order will be ascending.\n * If set to `\"desc\"`, the primary sorting order will be descending.\n */\n direction: Direction;\n }\n | {\n /**\n * Attribute path for the value of each document to use for\n * sorting.\n */\n field: string;\n /**\n * If set to `true`, the primary sorting order will be ascending.\n * If set to `false`, the primary sorting order will be descending.\n */\n asc: boolean;\n }\n )[];\n /**\n * Compression to use for the primary sort data.\n *\n * Default: `\"lz4\"`\n */\n primarySortCompression?: Compression;\n /**\n * Attribute paths for which values should be stored in the view index\n * in addition to those used for sorting via `primarySort`.\n */\n storedValues?: {\n /**\n * Attribute paths for which values should be stored in the view index\n * in addition to those used for sorting via `primarySort`.\n */\n fields: string[];\n /**\n * How the attribute values should be compressed.\n *\n * Default: `\"lz4\"`\n */\n compression?: Compression;\n /**\n * (Enterprise Edition only.) If set to `true`, then stored values are\n * always cached in memory.\n *\n * Default: `false`\n */\n cache?: boolean;\n }[];\n };\n\n/**\n * Options defining an index used in a SearchAlias View.\n */\nexport type SearchAliasViewIndexOptions = {\n /**\n * Name of a collection.\n */\n collection: string;\n /**\n * Name of an inverted index in the collection.\n */\n index: string;\n};\n\n/**\n * Options for modifying the properties of a SearchAlias View.\n */\nexport type SearchAliasViewPropertiesOptions = {\n /**\n * An array of inverted indexes to add to the View.\n */\n indexes: SearchAliasViewIndexOptions[];\n};\n\n/**\n * Options defining an index to be modified in a SearchAlias View.\n */\nexport type SearchAliasViewPatchIndexOptions = SearchAliasViewIndexOptions & {\n /**\n * Whether to add or remove the index.\n *\n * Default: `\"add\"`\n */\n operation?: \"add\" | \"del\";\n};\n\n/**\n * Options for partially modifying the properties of a SearchAlias View.\n */\nexport type SearchAliasViewPatchPropertiesOptions = {\n /**\n * An array of inverted indexes to add to the View.\n */\n indexes: SearchAliasViewPatchIndexOptions[];\n};\n\n/**\n * Options for creating a SearchAlias View.\n */\nexport type CreateSearchAliasViewOptions = SearchAliasViewPropertiesOptions & {\n /**\n * Type of the View.\n */\n type: \"search-alias\";\n};\n\n/**\n * Generic description of a View.\n */\nexport type GenericViewDescription = {\n /**\n * A globally unique identifier for this View.\n */\n globallyUniqueId: string;\n /**\n * An identifier for this View.\n */\n id: string;\n /**\n * Name of the View.\n */\n name: string;\n};\n\nexport type ViewDescription =\n | ArangoSearchViewDescription\n | SearchAliasViewDescription;\n\nexport type ArangoSearchViewDescription = GenericViewDescription & {\n type: \"arangosearch\";\n};\n\nexport type SearchAliasViewDescription = GenericViewDescription & {\n type: \"search-alias\";\n};\n\nexport type ViewProperties =\n | ArangoSearchViewProperties\n | SearchAliasViewProperties;\n\n/**\n * A link definition for an ArangoSearch View.\n */\nexport type ArangoSearchViewLink = {\n analyzers: string[];\n fields: Record<string, ArangoSearchViewLink>;\n includeAllFields: boolean;\n nested?: Record<string, ArangoSearchViewLink>;\n trackListPositions: boolean;\n storeValues: \"none\" | \"id\";\n cache: boolean;\n};\n\n/**\n * Properties of an ArangoSearch View.\n */\nexport type ArangoSearchViewProperties = ArangoSearchViewDescription & {\n cleanupIntervalStep: number;\n consolidationIntervalMsec: number;\n commitIntervalMsec: number;\n writebufferIdle: number;\n writebufferActive: number;\n writebufferSizeMax: number;\n consolidationPolicy: TierConsolidationPolicy | BytesAccumConsolidationPolicy;\n primarySort: {\n field: string;\n direction: Direction;\n }[];\n primarySortCompression: Compression;\n storedValues: {\n fields: string[];\n compression: Compression;\n cache: boolean;\n }[];\n links: Record<string, Omit<ArangoSearchViewLink, \"nested\">>;\n};\n\n/**\n * Properties of a SearchAlias View.\n */\nexport type SearchAliasViewProperties = SearchAliasViewDescription & {\n indexes: { collection: string; index: string }[];\n};\n\n/**\n * Represents a View in a {@link database.Database}.\n */\nexport class View {\n protected _name: string;\n protected _db: Database;\n\n /**\n * @internal\n */\n constructor(db: Database, name: string) {\n this._db = db;\n this._name = name.normalize(\"NFC\");\n }\n\n /**\n * @internal\n *\n * Indicates that this object represents an ArangoDB View.\n */\n get isArangoView(): true {\n return true;\n }\n\n /**\n * Name of the View.\n */\n get name() {\n return this._name;\n }\n\n /**\n * Retrieves general information about the View.\n *\n * @example\n * ```js\n * const db = new Database();\n * const view = db.view(\"some-view\");\n * const data = await view.get();\n * // data contains general information about the View\n * ```\n */\n get(): Promise<ArangoApiResponse<ViewDescription>> {\n return this._db.request({\n path: `/_api/view/${encodeURIComponent(this._name)}`,\n });\n }\n\n /**\n * Checks whether the View exists.\n *\n * @example\n * ```js\n * const db = new Database();\n * const view = db.view(\"some-view\");\n * const exists = await view.exists();\n * console.log(exists); // indicates whether the View exists\n * ```\n */\n async exists(): Promise<boolean> {\n try {\n await this.get();\n return true;\n } catch (err: any) {\n if (isArangoError(err) && err.errorNum === VIEW_NOT_FOUND) {\n return false;\n }\n throw err;\n }\n }\n\n /**\n * Creates a View with the given `options` and the instance's name.\n *\n * See also {@link database.Database#createView}.\n *\n * @example\n * ```js\n * const db = new Database();\n * const view = db.view(\"potatoes\");\n * await view.create();\n * // the ArangoSearch View \"potatoes\" now exists\n * ```\n */\n create<Options extends CreateViewOptions>(\n options: CreateViewOptions\n ): Promise<\n typeof options extends CreateArangoSearchViewOptions\n ? ArangoSearchViewDescription\n : Options extends CreateSearchAliasViewOptions\n ? SearchAliasViewDescription\n : ViewDescription\n > {\n return this._db.request({\n method: \"POST\",\n path: \"/_api/view\",\n body: {\n ...options,\n name: this._name,\n },\n });\n }\n\n /**\n * Renames the View and updates the instance's `name` to `newName`.\n *\n * Additionally removes the instance from the {@link database.Database}'s internal\n * cache.\n *\n * **Note**: Renaming Views may not be supported when ArangoDB is\n * running in a cluster configuration.\n *\n * @param newName - The new name of the View.\n *\n * @example\n * ```js\n * const db = new Database();\n * const view1 = db.view(\"some-view\");\n * await view1.rename(\"other-view\");\n * const view2 = db.view(\"some-view\");\n * const view3 = db.view(\"other-view\");\n * // Note all three View instances are different objects but\n * // view1 and view3 represent the same ArangoDB view!\n * ```\n */\n async rename(newName: string): Promise<ArangoApiResponse<ViewDescription>> {\n const result = this._db.renameView(this._name, newName);\n this._name = newName.normalize(\"NFC\");\n return result;\n }\n\n /**\n * Retrieves the View's properties.\n *\n * @example\n * ```js\n * const db = new Database();\n * const view = db.view(\"some-view\");\n * const data = await view.properties();\n * // data contains the View's properties\n * ```\n */\n properties(): Promise<ArangoApiResponse<ViewProperties>> {\n return this._db.request({\n path: `/_api/view/${encodeURIComponent(this._name)}/properties`,\n });\n }\n\n /**\n * Updates the properties of the View.\n *\n * @param properties - Properties of the View to update.\n *\n * @example\n * ```js\n * const db = new Database();\n * const view = db.view(\"some-view\");\n * const result = await view.updateProperties({\n * consolidationIntervalMsec: 234\n * });\n * console.log(result.consolidationIntervalMsec); // 234\n * ```\n */\n updateProperties<Properties extends ViewPatchPropertiesOptions | undefined>(\n properties?: Properties\n ): Promise<\n Properties extends ArangoSearchViewPatchPropertiesOptions\n ? ArangoSearchViewProperties\n : Properties extends SearchAliasViewPatchPropertiesOptions\n ? SearchAliasViewProperties\n : ViewProperties\n > {\n return this._db.request({\n method: \"PATCH\",\n path: `/_api/view/${encodeURIComponent(this._name)}/properties`,\n body: properties ?? {},\n });\n }\n\n /**\n * Replaces the properties of the View.\n *\n * @param properties - New properties of the View.\n *\n * @example\n * ```js\n * const db = new Database();\n * const view = db.view(\"some-view\");\n * const result = await view.replaceProperties({\n * consolidationIntervalMsec: 234\n * });\n * console.log(result.consolidationIntervalMsec); // 234\n * ```\n */\n replaceProperties<Properties extends ViewPropertiesOptions | undefined>(\n properties?: Properties\n ): Promise<\n Properties extends ArangoSearchViewPropertiesOptions\n ? ArangoSearchViewProperties\n : Properties extends SearchAliasViewPropertiesOptions\n ? SearchAliasViewProperties\n : ViewProperties\n > {\n return this._db.request({\n method: \"PUT\",\n path: `/_api/view/${encodeURIComponent(this._name)}/properties`,\n body: properties ?? {},\n });\n }\n\n /**\n * Deletes the View from the database.\n *\n * @example\n *\n * ```js\n * const db = new Database();\n * const view = db.view(\"some-view\");\n * await view.drop();\n * // the View \"some-view\" no longer exists\n * ```\n */\n drop(): Promise<boolean> {\n return this._db.request(\n {\n method: \"DELETE\",\n path: `/_api/view/${encodeURIComponent(this._name)}`,\n },\n (res) => res.body.result\n );\n }\n}\n","/* eslint-disable @typescript-eslint/no-var-requires */\n\"use strict\";\nconst { aql } = require(\"./aql\");\nconst { CollectionStatus, CollectionType } = require(\"./collection\");\nconst { ViewType } = require(\"./view\");\nconst { Database } = require(\"./database\");\n\nmodule.exports = exports = arangojs;\n\nfunction arangojs(config) {\n if (typeof config === \"string\" || Array.isArray(config)) {\n const url = config;\n return new Database(url);\n }\n return new Database(config);\n}\n\nObject.assign(arangojs, {\n aql,\n arangojs,\n CollectionStatus,\n CollectionType,\n Database,\n ViewType,\n});\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","// getDefaultExport function for compatibility with non-harmony modules\n__webpack_require__.n = function(module) {\n\tvar getter = module && module.__esModule ?\n\t\tfunction() { return module['default']; } :\n\t\tfunction() { return module; };\n\t__webpack_require__.d(getter, { a: getter });\n\treturn getter;\n};","// define getter functions for harmony exports\n__webpack_require__.d = function(exports, definition) {\n\tfor(var key in definition) {\n\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n\t\t}\n\t}\n};","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","__webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }","// define __esModule on exports\n__webpack_require__.r = function(exports) {\n\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n\t}\n\tObject.defineProperty(exports, '__esModule', { value: true });\n};","// startup\n// Load entry module and return exports\n// This entry module is referenced by other modules so it can't be inlined\n__webpack_require__(588);\nvar __webpack_exports__ = __webpack_require__(293);\n"],"names":["root","factory","exports","module","define","amd","self","win","window","global","fn","string","toString","call","setTimeout","alert","confirm","prompt","Object","prototype","trim","replace","headers","arg","result","headersArr","split","i","length","row","index","indexOf","key","slice","toLowerCase","value","push","runtime","undefined","Op","hasOwn","hasOwnProperty","defineProperty","obj","desc","$Symbol","Symbol","iteratorSymbol","iterator","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","enumerable","configurable","writable","err","wrap","innerFn","outerFn","tryLocsList","protoGenerator","Generator","generator","create","context","Context","makeInvokeMethod","tryCatch","type","GenStateSuspendedStart","GenStateExecuting","GenStateCompleted","ContinueSentinel","GeneratorFunction","GeneratorFunctionPrototype","IteratorPrototype","this","getProto","getPrototypeOf","NativeIteratorPrototype","values","Gp","defineIteratorMethods","forEach","method","_invoke","AsyncIterator","PromiseImpl","invoke","resolve","reject","record","__await","then","unwrapped","error","previousPromise","callInvokeWithMethodAndArg","state","Error","doneResult","delegate","delegateResult","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","done","TypeError","info","resultName","next","nextLoc","pushTryEntry","locs","entry","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","resetTryEntry","completion","reset","iterable","iteratorMethod","isNaN","displayName","isGeneratorFunction","genFun","ctor","constructor","name","mark","setPrototypeOf","__proto__","awrap","async","Promise","iter","keys","val","object","reverse","pop","skipTempReset","prev","charAt","stop","rootRecord","rval","exception","handle","loc","caught","hasCatch","hasFinally","finallyEntry","complete","finish","thrown","delegateYield","regeneratorRuntime","accidentalStrictMode","globalThis","Function","LinkedList","item","first","behind","last","before","clear","unchain","unlink","every","callback","thisArg","bind","filter","newList","find","findItem","includes","fromIndex","current","getItemByIndex","itemOf","searchedValue","lastItemOf","map","reduce","initialValue","reduceRight","some","join","separator","concat","others","other","LinkedListItem_1","unlinkCleanup","insertBehind","unshift","remove","removeAllOccurrences","foundSomethingToDelete","shift","entries","insertBefore","itemChainEnd","__export","require","isFunction","parseHeaders","xtend","initParams","uri","options","params","createXHR","_createXHR","called","response","body","getBody","xhr","responseText","responseType","responseXML","firefoxBugTakenEffect","documentElement","nodeName","e","getXml","isJson","JSON","parse","errorFunc","evt","clearTimeout","timeoutTimer","statusCode","failureResponse","loadFunc","aborted","status","useXDR","url","rawRequest","getAllResponseHeaders","cors","XDomainRequest","XMLHttpRequest","data","sync","json","stringify","onreadystatechange","readyState","onload","onerror","onprogress","onabort","ontimeout","open","username","password","withCredentials","timeout","abort","code","setRequestHeader","isEmpty","beforeSend","send","array","forEachArray","toUpperCase","target","arguments","source","isArangoAnalyzer","analyzer","Boolean","Analyzer","db","_db","_name","normalize","get","isArangoError","errorNum","ANALYZER_NOT_FOUND","request","path","encodeURIComponent","drop","force","qs","isAqlQuery","query","bindVars","isGeneratedAqlQuery","_source","isAqlLiteral","literal","toAQL","aql","templateStrings","args","strings","bindValues","rawValue","src","splice","isKnown","isArangoCollection","isArangoGraph","isArangoView","String","sep","Array","fill","_indexHandle","selector","collectionName","id","head","tail","normalizedHead","collection","collectionToString","CollectionType","CollectionStatus","Collection","COLLECTION_NOT_FOUND","waitForSyncReplication","enforceReplicationFactor","opts","computedValues","computedValue","expression","properties","count","res","figures","details","revision","checksum","newName","renameCollection","truncate","getResponsibleShard","document","shardId","documentId","_documentHandle","ifMatch","ifNoneMatch","encodeURI","HttpError","documents","selectors","allowDirtyRead","onlyget","graceful","DOCUMENT_NOT_FOUND","save","silent","saveAll","newData","replaceAll","update","updateAll","removeAll","import","isArray","line","isBinary","_edges","direction","vertex","edges","inEdges","outEdges","traversal","startVertex","edgeCollection","list","BatchedArrayCursor","arangojsHostUrl","items","all","any","byExample","example","firstExample","removeByExample","replaceByExample","newValue","updateByExample","lookupByKeys","removeByKeys","indexes","ensureIndex","dropIndex","fulltext","attribute","compact","hostUrl","batches","_batches","_id","_hasMore","hasMore","_hostUrl","_count","_extra","extra","_allowDirtyRead","_itemsCursor","ArrayCursor","more","_more","batch","hasNext","currentBatch","reducer","batchedCursor","view","_view","flatMap","v","kill","base64Encode","str","btoa","normalizeUrl","raw","match","unix","errorToJSON","message","createRequest","baseUrl","agentOptions","base","URL","auth","omit","cb","reqUrl","expectBinary","pathname","search","req","toJSON","after","MIME_JSON","Connection","config","Map","URLS","MAX_SOCKETS","loadBalancingStrategy","arangoVersion","_arangoVersion","_agent","agent","_agentOptions","maxSockets","_maxTasks","_headers","_loadBalancingStrategy","_precaptureStackTraces","precaptureStackTraces","_responseQueueTimeSamples","responseQueueTimeSamples","_retryOnConflict","retryOnConflict","Infinity","maxRetries","_maxRetries","Number","addToHostList","setBearerAuth","setBasicAuth","_activeHostUrl","_hostUrls","Math","floor","random","_activeDirtyHostUrl","isArangoConnection","queueTime","getLatest","_queueTimes","getValues","from","getAvg","avg","_runQueue","_queue","_activeTasks","task","LEADER_ENDPOINT_HEADER","cleanUrl","contentType","Date","now","parsedBody","stack","isArangoErrorResponse","ArangoError","transform","_hosts","ERROR_ARANGO_CONFLICT","isSystemError","syscall","ERROR_ARANGO_MAINTENANCE_MODE","retries","_buildUrl","basePath","querystringify","setHeader","token","setResponseQueueTimeSamples","database","databaseName","_databases","set","delete","setHostList","urls","cleanUrls","newUrls","setTransactionId","transactionId","_transactionId","clearTransactionId","headerName","close","host","numHosts","propagated","started","urlInfo","extraHeaders","captureStackTrace","capture","generateStackTrace","toForm","fields","form","FormData","Blob","append","Route","_path","route","patch","post","put","Transaction","isArangoTransaction","TRANSACTION_NOT_FOUND","commit","step","conn","_connection","promise","isArangoDatabase","coerceTransactionCollections","collections","write","cols","allowImplicit","read","exclusive","Database","configOrDatabase","connection","version","absolutePath","overwrite","endpoints","endpoint","waitForPropagation","useBasicAuth","useBearerAuth","login","jwt","DATABASE_NOT_FOUND","createDatabase","usersOrOptions","users","listDatabases","listUserDatabases","databases","userDatabases","dropDatabase","_collections","has","createCollection","listCollections","excludeSystem","graph","graphName","_graphs","Graph","edgeDefinitions","listGraphs","graphs","_key","viewName","_views","View","listViews","analyzerName","_analyzers","listAnalyzers","listUsers","getUser","createUser","passwd","user","updateUser","replaceUser","removeUser","getUserAccessLevel","suffix","setUserAccessLevel","grant","clearUserAccessLevel","getUserDatabases","full","executeTransaction","action","transaction","beginTransaction","listTransactions","transactions","batchSize","cache","memoryLimit","ttl","explain","queryRules","queryTracking","listRunningQueries","listSlowQueries","clearSlowQueries","killQuery","queryId","listFunctions","createFunction","isDeterministic","dropFunction","group","listServices","mount","configuration","dependencies","uninstallService","getService","getServiceConfiguration","minimal","replaceServiceConfiguration","cfg","updateServiceConfiguration","getServiceDependencies","replaceServiceDependencies","deps","updateServiceDependencies","setServiceDevelopmentMode","enabled","listServiceScripts","runServiceScript","runServiceTests","getServiceReadme","getServiceDocumentation","downloadService","commitLocalServiceState","strict","messages","nativeErrorKeys","super","errorMessage","mungeGharialResponse","prop","new","newDoc","old","oldDoc","doc","meta","coerceEdgeDefinition","edgeDefinition","to","GraphVertexCollection","_collection","_graph","rev","GraphEdgeCollection","edge","GRAPH_NOT_FOUND","orphanCollections","satellites","waitForSync","isSmart","isDisjoint","dropCollections","removed","vertexCollection","listVertexCollections","addVertexCollection","removeVertexCollection","dropCollection","listEdgeCollections","addEdgeDefinition","replaceEdgeDefinition","collectionOrEdgeDefinitionOptions","edgeDefinitionOrOptions","removeEdgeDefinition","VIEW_NOT_FOUND","renameView","updateProperties","replaceProperties","ViewType","arangojs","assign","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","n","getter","__esModule","d","a","definition","o","g","r"],"sourceRoot":""}