/* THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ var __create = Object.create; var __defProp = Object.defineProperty; var __defProps = Object.defineProperties; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropDescs = Object.getOwnPropertyDescriptors; var __getOwnPropNames = Object.getOwnPropertyNames; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __publicField = (obj, key, value) => { __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; var __accessCheck = (obj, member, msg) => { if (!member.has(obj)) throw TypeError("Cannot " + msg); }; var __privateGet = (obj, member, getter) => { __accessCheck(obj, member, "read from private field"); return getter ? getter.call(obj) : member.get(obj); }; var __privateAdd = (obj, member, value) => { if (member.has(obj)) throw TypeError("Cannot add the same private member more than once"); member instanceof WeakSet ? member.add(obj) : member.set(obj, value); }; var __privateSet = (obj, member, value, setter) => { __accessCheck(obj, member, "write to private field"); setter ? setter.call(obj, value) : member.set(obj, value); return value; }; var __privateWrapper = (obj, member, setter, getter) => { return { set _(value) { __privateSet(obj, member, value, setter); }, get _() { return __privateGet(obj, member, getter); } }; }; var __privateMethod = (obj, member, method) => { __accessCheck(obj, member, "access private method"); return method; }; var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { step(generator.next(value)); } catch (e) { reject(e); } }; var rejected = (value) => { try { step(generator.throw(value)); } catch (e) { reject(e); } }; var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); step((generator = generator.apply(__this, __arguments)).next()); }); }; // node_modules/abstract-logging/index.js var require_abstract_logging = __commonJS({ "node_modules/abstract-logging/index.js"(exports, module2) { "use strict"; function noop() { } var proto = { fatal: noop, error: noop, warn: noop, info: noop, debug: noop, trace: noop }; Object.defineProperty(module2, "exports", { get() { return Object.create(proto); } }); } }); // node_modules/ldapjs/lib/logger.js var require_logger = __commonJS({ "node_modules/ldapjs/lib/logger.js"(exports, module2) { "use strict"; var logger = require_abstract_logging(); logger.child = function() { return logger; }; module2.exports = logger; } }); // node_modules/ldapjs/lib/client/request-queue/enqueue.js var require_enqueue = __commonJS({ "node_modules/ldapjs/lib/client/request-queue/enqueue.js"(exports, module2) { "use strict"; module2.exports = function enqueue(message, expect, emitter, cb) { if (this._queue.size >= this.size || this._frozen) { return false; } this._queue.add({ message, expect, emitter, cb }); if (this.timeout === 0) return true; if (this._timer === null) return true; this._timer = setTimeout(queueTimeout.bind(this), this.timeout); return true; function queueTimeout() { this.freeze(); this.purge(); } }; } }); // node_modules/ldapjs/lib/client/request-queue/flush.js var require_flush = __commonJS({ "node_modules/ldapjs/lib/client/request-queue/flush.js"(exports, module2) { "use strict"; module2.exports = function flush(cb) { if (this._timer) { clearTimeout(this._timer); this._timer = null; } const requests = Array.from(this._queue.values()); this._queue.clear(); for (const req of requests) { cb(req.message, req.expect, req.emitter, req.cb); } }; } }); // node_modules/assert-plus/assert.js var require_assert = __commonJS({ "node_modules/assert-plus/assert.js"(exports, module2) { var assert = require("assert"); var Stream = require("stream").Stream; var util = require("util"); var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/; function _capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); } function _toss(name, expected, oper, arg, actual) { throw new assert.AssertionError({ message: util.format("%s (%s) is required", name, expected), actual: actual === void 0 ? typeof arg : actual(arg), expected, operator: oper || "===", stackStartFunction: _toss.caller }); } function _getClass(arg) { return Object.prototype.toString.call(arg).slice(8, -1); } function noop() { } var types = { bool: { check: function(arg) { return typeof arg === "boolean"; } }, func: { check: function(arg) { return typeof arg === "function"; } }, string: { check: function(arg) { return typeof arg === "string"; } }, object: { check: function(arg) { return typeof arg === "object" && arg !== null; } }, number: { check: function(arg) { return typeof arg === "number" && !isNaN(arg); } }, finite: { check: function(arg) { return typeof arg === "number" && !isNaN(arg) && isFinite(arg); } }, buffer: { check: function(arg) { return Buffer.isBuffer(arg); }, operator: "Buffer.isBuffer" }, array: { check: function(arg) { return Array.isArray(arg); }, operator: "Array.isArray" }, stream: { check: function(arg) { return arg instanceof Stream; }, operator: "instanceof", actual: _getClass }, date: { check: function(arg) { return arg instanceof Date; }, operator: "instanceof", actual: _getClass }, regexp: { check: function(arg) { return arg instanceof RegExp; }, operator: "instanceof", actual: _getClass }, uuid: { check: function(arg) { return typeof arg === "string" && UUID_REGEXP.test(arg); }, operator: "isUUID" } }; function _setExports(ndebug) { var keys = Object.keys(types); var out; if (process.env.NODE_NDEBUG) { out = noop; } else { out = function(arg, msg) { if (!arg) { _toss(msg, "true", arg); } }; } keys.forEach(function(k) { if (ndebug) { out[k] = noop; return; } var type = types[k]; out[k] = function(arg, msg) { if (!type.check(arg)) { _toss(msg, k, type.operator, arg, type.actual); } }; }); keys.forEach(function(k) { var name = "optional" + _capitalize(k); if (ndebug) { out[name] = noop; return; } var type = types[k]; out[name] = function(arg, msg) { if (arg === void 0 || arg === null) { return; } if (!type.check(arg)) { _toss(msg, k, type.operator, arg, type.actual); } }; }); keys.forEach(function(k) { var name = "arrayOf" + _capitalize(k); if (ndebug) { out[name] = noop; return; } var type = types[k]; var expected = "[" + k + "]"; out[name] = function(arg, msg) { if (!Array.isArray(arg)) { _toss(msg, expected, type.operator, arg, type.actual); } var i; for (i = 0; i < arg.length; i++) { if (!type.check(arg[i])) { _toss(msg, expected, type.operator, arg, type.actual); } } }; }); keys.forEach(function(k) { var name = "optionalArrayOf" + _capitalize(k); if (ndebug) { out[name] = noop; return; } var type = types[k]; var expected = "[" + k + "]"; out[name] = function(arg, msg) { if (arg === void 0 || arg === null) { return; } if (!Array.isArray(arg)) { _toss(msg, expected, type.operator, arg, type.actual); } var i; for (i = 0; i < arg.length; i++) { if (!type.check(arg[i])) { _toss(msg, expected, type.operator, arg, type.actual); } } }; }); Object.keys(assert).forEach(function(k) { if (k === "AssertionError") { out[k] = assert[k]; return; } if (ndebug) { out[k] = noop; return; } out[k] = assert[k]; }); out._setExports = _setExports; return out; } module2.exports = _setExports(process.env.NODE_NDEBUG); } }); // node_modules/@ldapjs/asn1/lib/ber/types.js var require_types = __commonJS({ "node_modules/@ldapjs/asn1/lib/ber/types.js"(exports, module2) { "use strict"; module2.exports = { EOC: 0, Boolean: 1, Integer: 2, BitString: 3, OctetString: 4, Null: 5, OID: 6, ObjectDescriptor: 7, External: 8, Real: 9, Enumeration: 10, PDV: 11, Utf8String: 12, RelativeOID: 13, Sequence: 16, Set: 17, NumericString: 18, PrintableString: 19, T61String: 20, VideotexString: 21, IA5String: 22, UTCTime: 23, GeneralizedTime: 24, GraphicString: 25, VisibleString: 26, GeneralString: 28, UniversalString: 29, CharacterString: 30, BMPString: 31, Constructor: 32, LDAPSequence: 48, Context: 128 }; } }); // node_modules/@ldapjs/asn1/lib/buffer-to-hex-dump.js var require_buffer_to_hex_dump = __commonJS({ "node_modules/@ldapjs/asn1/lib/buffer-to-hex-dump.js"(exports, module2) { "use strict"; var { createWriteStream } = require("fs"); module2.exports = function bufferToHexDump({ buffer, prefix = "", separator = "", wrapCharacters = [], width = 10, destination = process.stdout, closeDestination = false }) { let closeStream = closeDestination; if (typeof destination === "string") { destination = createWriteStream(destination); closeStream = true; } if (wrapCharacters[0]) { destination.write(wrapCharacters[0]); } for (const [i, byte] of buffer.entries()) { const outByte = Number(byte).toString(16).padStart(2, "0"); destination.write(prefix + outByte); if (i !== buffer.byteLength - 1) { destination.write(separator); } if ((i + 1) % width === 0) { destination.write("\n"); } } if (wrapCharacters[1]) { destination.write(wrapCharacters[1]); } if (closeStream === true) { destination.end(); } }; } }); // node_modules/@ldapjs/asn1/lib/ber/reader.js var require_reader = __commonJS({ "node_modules/@ldapjs/asn1/lib/ber/reader.js"(exports, module2) { "use strict"; var types = require_types(); var bufferToHexDump = require_buffer_to_hex_dump(); var _buffer, _size, _currentFieldLength, _currentSequenceStart, _offset; var _BerReader = class { constructor(buffer) { __privateAdd(this, _buffer, void 0); __privateAdd(this, _size, void 0); __privateAdd(this, _currentFieldLength, 0); __privateAdd(this, _currentSequenceStart, 0); __privateAdd(this, _offset, 0); if (Buffer.isBuffer(buffer) === false) { throw TypeError("Must supply a Buffer instance to read."); } __privateSet(this, _buffer, buffer.subarray(0)); __privateSet(this, _size, __privateGet(this, _buffer).length); } get [Symbol.toStringTag]() { return "BerReader"; } get buffer() { return __privateGet(this, _buffer).subarray(0); } get length() { return __privateGet(this, _currentFieldLength); } get offset() { return __privateGet(this, _offset); } get remain() { return __privateGet(this, _size) - __privateGet(this, _offset); } peek() { return this.readByte(true); } readBoolean(tag = types.Boolean) { const intBuffer = this.readTag(tag); __privateSet(this, _offset, __privateGet(this, _offset) + intBuffer.length); const int = parseIntegerBuffer(intBuffer); return int !== 0; } readByte(peek = false) { if (__privateGet(this, _size) - __privateGet(this, _offset) < 1) { return null; } const byte = __privateGet(this, _buffer)[__privateGet(this, _offset)] & 255; if (peek !== true) { __privateSet(this, _offset, __privateGet(this, _offset) + 1); } return byte; } readEnumeration() { const intBuffer = this.readTag(types.Enumeration); __privateSet(this, _offset, __privateGet(this, _offset) + intBuffer.length); return parseIntegerBuffer(intBuffer); } readInt(tag = types.Integer) { const intBuffer = this.readTag(tag); __privateSet(this, _offset, __privateGet(this, _offset) + intBuffer.length); return parseIntegerBuffer(intBuffer); } readLength(offset) { if (offset === void 0) { offset = __privateGet(this, _offset); } if (offset >= __privateGet(this, _size)) { return null; } let lengthByte = __privateGet(this, _buffer)[offset++] & 255; if ((lengthByte & 128) === 128) { lengthByte &= 127; if (lengthByte === 0) { throw Error("Indefinite length not supported."); } if (lengthByte > 4) { throw Error("Encoding too long."); } if (__privateGet(this, _size) - offset < lengthByte) { return null; } __privateSet(this, _currentFieldLength, 0); for (let i = 0; i < lengthByte; i++) { __privateSet(this, _currentFieldLength, (__privateGet(this, _currentFieldLength) << 8) + (__privateGet(this, _buffer)[offset++] & 255)); } } else { __privateSet(this, _currentFieldLength, lengthByte); } return offset; } readOID(tag = types.OID) { const oidBuffer = this.readString(tag, true); if (oidBuffer === null) { return null; } const values = []; let value = 0; for (let i = 0; i < oidBuffer.length; i++) { const byte = oidBuffer[i] & 255; value <<= 7; value += byte & 127; if ((byte & 128) === 0) { values.push(value); value = 0; } } value = values.shift(); values.unshift(value % 40); values.unshift(value / 40 >> 0); return values.join("."); } readRawBuffer(tag, advanceOffset = true) { if (Number.isInteger(tag) === false) { throw Error("must specify an integer tag"); } const foundTag = this.peek(); if (foundTag !== tag) { const expected = tag.toString(16).padStart(2, "0"); const found = foundTag.toString(16).padStart(2, "0"); throw Error(`Expected 0x${expected}: got 0x${found}`); } const currentOffset = __privateGet(this, _offset); const valueOffset = this.readLength(currentOffset + 1); if (valueOffset === null) { return null; } const valueBytesLength = this.length; const numTagAndLengthBytes = valueOffset - currentOffset; const endPos = currentOffset + valueBytesLength + numTagAndLengthBytes; if (endPos > this.buffer.byteLength) { return null; } const buffer = this.buffer.subarray(currentOffset, endPos); if (advanceOffset === true) { this.setOffset(currentOffset + (valueBytesLength + numTagAndLengthBytes)); } return buffer; } readSequence(tag) { const foundTag = this.peek(); if (tag !== void 0 && tag !== foundTag) { const expected = tag.toString(16).padStart(2, "0"); const found = foundTag.toString(16).padStart(2, "0"); throw Error(`Expected 0x${expected}: got 0x${found}`); } __privateSet(this, _currentSequenceStart, __privateGet(this, _offset)); const valueOffset = this.readLength(__privateGet(this, _offset) + 1); if (valueOffset === null) { return null; } __privateSet(this, _offset, valueOffset); return foundTag; } readString(tag = types.OctetString, asBuffer = false) { const tagByte = this.peek(); if (tagByte !== tag) { const expected = tag.toString(16).padStart(2, "0"); const found = tagByte.toString(16).padStart(2, "0"); throw Error(`Expected 0x${expected}: got 0x${found}`); } const valueOffset = this.readLength(__privateGet(this, _offset) + 1); if (valueOffset === null) { return null; } if (this.length > __privateGet(this, _size) - valueOffset) { return null; } __privateSet(this, _offset, valueOffset); if (this.length === 0) { return asBuffer ? Buffer.alloc(0) : ""; } const str = __privateGet(this, _buffer).subarray(__privateGet(this, _offset), __privateGet(this, _offset) + this.length); __privateSet(this, _offset, __privateGet(this, _offset) + this.length); return asBuffer ? str : str.toString("utf8"); } readTag(tag) { if (tag == null) { throw Error("Must supply an ASN.1 tag to read."); } const byte = this.peek(); if (byte !== tag) { const tagString = tag.toString(16).padStart(2, "0"); const byteString = byte.toString(16).padStart(2, "0"); throw Error(`Expected 0x${tagString}: got 0x${byteString}`); } const fieldOffset = this.readLength(__privateGet(this, _offset) + 1); if (fieldOffset === null) { return null; } if (this.length > __privateGet(this, _size) - fieldOffset) { return null; } __privateSet(this, _offset, fieldOffset); return __privateGet(this, _buffer).subarray(__privateGet(this, _offset), __privateGet(this, _offset) + this.length); } sequenceToReader() { const lengthValueLength = __privateGet(this, _offset) - __privateGet(this, _currentSequenceStart); const buffer = __privateGet(this, _buffer).subarray(__privateGet(this, _currentSequenceStart), __privateGet(this, _currentSequenceStart) + (lengthValueLength + __privateGet(this, _currentFieldLength))); return new _BerReader(buffer); } setOffset(position) { if (Number.isInteger(position) === false) { throw Error("Must supply an integer position."); } __privateSet(this, _offset, position); } toHexDump(params) { bufferToHexDump(__spreadProps(__spreadValues({}, params), { buffer: this.buffer })); } }; var BerReader = _BerReader; _buffer = new WeakMap(); _size = new WeakMap(); _currentFieldLength = new WeakMap(); _currentSequenceStart = new WeakMap(); _offset = new WeakMap(); function parseIntegerBuffer(integerBuffer) { let value = 0; let i; for (i = 0; i < integerBuffer.length; i++) { value <<= 8; value |= integerBuffer[i] & 255; } if ((integerBuffer[0] & 128) === 128 && i !== 4) { value -= 1 << i * 8; } return value >> 0; } module2.exports = BerReader; } }); // node_modules/@ldapjs/asn1/lib/ber/writer.js var require_writer = __commonJS({ "node_modules/@ldapjs/asn1/lib/ber/writer.js"(exports, module2) { "use strict"; var types = require_types(); var bufferToHexDump = require_buffer_to_hex_dump(); var _buffer, _size, _offset, _sequenceOffsets, _growthFactor, _ensureBufferCapacity, ensureBufferCapacity_fn, _shift, shift_fn; var BerWriter = class { constructor({ size = 1024, growthFactor = 8 } = {}) { __privateAdd(this, _ensureBufferCapacity); __privateAdd(this, _shift); __privateAdd(this, _buffer, void 0); __privateAdd(this, _size, void 0); __privateAdd(this, _offset, 0); __privateAdd(this, _sequenceOffsets, []); __privateAdd(this, _growthFactor, void 0); __privateSet(this, _buffer, Buffer.alloc(size)); __privateSet(this, _size, __privateGet(this, _buffer).length); __privateSet(this, _offset, 0); __privateSet(this, _growthFactor, growthFactor); } get [Symbol.toStringTag]() { return "BerWriter"; } get buffer() { return __privateGet(this, _buffer).subarray(0, __privateGet(this, _offset)); } get size() { return __privateGet(this, _size); } appendBuffer(buffer) { if (Buffer.isBuffer(buffer) === false) { throw Error("buffer must be an instance of Buffer"); } __privateMethod(this, _ensureBufferCapacity, ensureBufferCapacity_fn).call(this, buffer.length); buffer.copy(__privateGet(this, _buffer), __privateGet(this, _offset), 0, buffer.length); __privateSet(this, _offset, __privateGet(this, _offset) + buffer.length); } endSequence() { const sequenceStartOffset = __privateGet(this, _sequenceOffsets).pop(); const start = sequenceStartOffset + 3; const length = __privateGet(this, _offset) - start; if (length <= 127) { __privateMethod(this, _shift, shift_fn).call(this, start, length, -2); __privateGet(this, _buffer)[sequenceStartOffset] = length; } else if (length <= 255) { __privateMethod(this, _shift, shift_fn).call(this, start, length, -1); __privateGet(this, _buffer)[sequenceStartOffset] = 129; __privateGet(this, _buffer)[sequenceStartOffset + 1] = length; } else if (length <= 65535) { __privateGet(this, _buffer)[sequenceStartOffset] = 130; __privateGet(this, _buffer)[sequenceStartOffset + 1] = length >> 8; __privateGet(this, _buffer)[sequenceStartOffset + 2] = length; } else if (length <= 16777215) { __privateMethod(this, _shift, shift_fn).call(this, start, length, 1); __privateGet(this, _buffer)[sequenceStartOffset] = 131; __privateGet(this, _buffer)[sequenceStartOffset + 1] = length >> 16; __privateGet(this, _buffer)[sequenceStartOffset + 2] = length >> 8; __privateGet(this, _buffer)[sequenceStartOffset + 3] = length; } else { throw Error("sequence too long"); } } startSequence(tag = types.Sequence | types.Constructor) { if (typeof tag !== "number") { throw TypeError("tag must be a Number"); } this.writeByte(tag); __privateGet(this, _sequenceOffsets).push(__privateGet(this, _offset)); __privateMethod(this, _ensureBufferCapacity, ensureBufferCapacity_fn).call(this, 3); __privateSet(this, _offset, __privateGet(this, _offset) + 3); } toHexDump(params) { bufferToHexDump(__spreadProps(__spreadValues({}, params), { buffer: this.buffer })); } writeBoolean(boolValue, tag = types.Boolean) { if (typeof boolValue !== "boolean") { throw TypeError("boolValue must be a Boolean"); } if (typeof tag !== "number") { throw TypeError("tag must be a Number"); } __privateMethod(this, _ensureBufferCapacity, ensureBufferCapacity_fn).call(this, 3); __privateGet(this, _buffer)[__privateWrapper(this, _offset)._++] = tag; __privateGet(this, _buffer)[__privateWrapper(this, _offset)._++] = 1; __privateGet(this, _buffer)[__privateWrapper(this, _offset)._++] = boolValue === true ? 255 : 0; } writeBuffer(buffer, tag) { if (typeof tag !== "number") { throw TypeError("tag must be a Number"); } if (Buffer.isBuffer(buffer) === false) { throw TypeError("buffer must be an instance of Buffer"); } this.writeByte(tag); this.writeLength(buffer.length); __privateMethod(this, _ensureBufferCapacity, ensureBufferCapacity_fn).call(this, buffer.length); buffer.copy(__privateGet(this, _buffer), __privateGet(this, _offset), 0, buffer.length); __privateSet(this, _offset, __privateGet(this, _offset) + buffer.length); } writeByte(byte) { if (typeof byte !== "number") { throw TypeError("argument must be a Number"); } __privateMethod(this, _ensureBufferCapacity, ensureBufferCapacity_fn).call(this, 1); __privateGet(this, _buffer)[__privateWrapper(this, _offset)._++] = byte; } writeEnumeration(value, tag = types.Enumeration) { if (typeof value !== "number") { throw TypeError("value must be a Number"); } if (typeof tag !== "number") { throw TypeError("tag must be a Number"); } this.writeInt(value, tag); } writeInt(intToWrite, tag = types.Integer) { if (typeof intToWrite !== "number") { throw TypeError("intToWrite must be a Number"); } if (typeof tag !== "number") { throw TypeError("tag must be a Number"); } let intSize = 4; while (((intToWrite & 4286578688) === 0 || (intToWrite & 4286578688) === 4286578688 >> 0) && intSize > 1) { intSize--; intToWrite <<= 8; } if (intSize > 4) { throw Error("BER ints cannot be > 0xffffffff"); } __privateMethod(this, _ensureBufferCapacity, ensureBufferCapacity_fn).call(this, 2 + intSize); __privateGet(this, _buffer)[__privateWrapper(this, _offset)._++] = tag; __privateGet(this, _buffer)[__privateWrapper(this, _offset)._++] = intSize; while (intSize-- > 0) { __privateGet(this, _buffer)[__privateWrapper(this, _offset)._++] = (intToWrite & 4278190080) >>> 24; intToWrite <<= 8; } } writeLength(len) { if (typeof len !== "number") { throw TypeError("argument must be a Number"); } __privateMethod(this, _ensureBufferCapacity, ensureBufferCapacity_fn).call(this, 4); if (len <= 127) { __privateGet(this, _buffer)[__privateWrapper(this, _offset)._++] = len; } else if (len <= 255) { __privateGet(this, _buffer)[__privateWrapper(this, _offset)._++] = 129; __privateGet(this, _buffer)[__privateWrapper(this, _offset)._++] = len; } else if (len <= 65535) { __privateGet(this, _buffer)[__privateWrapper(this, _offset)._++] = 130; __privateGet(this, _buffer)[__privateWrapper(this, _offset)._++] = len >> 8; __privateGet(this, _buffer)[__privateWrapper(this, _offset)._++] = len; } else if (len <= 16777215) { __privateGet(this, _buffer)[__privateWrapper(this, _offset)._++] = 131; __privateGet(this, _buffer)[__privateWrapper(this, _offset)._++] = len >> 16; __privateGet(this, _buffer)[__privateWrapper(this, _offset)._++] = len >> 8; __privateGet(this, _buffer)[__privateWrapper(this, _offset)._++] = len; } else { throw Error("length too long (> 4 bytes)"); } } writeNull() { this.writeByte(types.Null); this.writeByte(0); } writeOID(oidString, tag = types.OID) { if (typeof oidString !== "string") { throw TypeError("oidString must be a string"); } if (typeof tag !== "number") { throw TypeError("tag must be a Number"); } if (/^([0-9]+\.){3,}[0-9]+$/.test(oidString) === false) { throw Error("oidString is not a valid OID string"); } const parts = oidString.split("."); const bytes = []; bytes.push(parseInt(parts[0], 10) * 40 + parseInt(parts[1], 10)); for (const part of parts.slice(2)) { encodeOctet(bytes, parseInt(part, 10)); } __privateMethod(this, _ensureBufferCapacity, ensureBufferCapacity_fn).call(this, 2 + bytes.length); this.writeByte(tag); this.writeLength(bytes.length); this.appendBuffer(Buffer.from(bytes)); function encodeOctet(bytes2, octet) { if (octet < 128) { bytes2.push(octet); } else if (octet < 16384) { bytes2.push(octet >>> 7 | 128); bytes2.push(octet & 127); } else if (octet < 2097152) { bytes2.push(octet >>> 14 | 128); bytes2.push((octet >>> 7 | 128) & 255); bytes2.push(octet & 127); } else if (octet < 268435456) { bytes2.push(octet >>> 21 | 128); bytes2.push((octet >>> 14 | 128) & 255); bytes2.push((octet >>> 7 | 128) & 255); bytes2.push(octet & 127); } else { bytes2.push((octet >>> 28 | 128) & 255); bytes2.push((octet >>> 21 | 128) & 255); bytes2.push((octet >>> 14 | 128) & 255); bytes2.push((octet >>> 7 | 128) & 255); bytes2.push(octet & 127); } } } writeString(stringToWrite, tag = types.OctetString) { if (typeof stringToWrite !== "string") { throw TypeError("stringToWrite must be a string"); } if (typeof tag !== "number") { throw TypeError("tag must be a number"); } const toWriteLength = Buffer.byteLength(stringToWrite); this.writeByte(tag); this.writeLength(toWriteLength); if (toWriteLength > 0) { __privateMethod(this, _ensureBufferCapacity, ensureBufferCapacity_fn).call(this, toWriteLength); __privateGet(this, _buffer).write(stringToWrite, __privateGet(this, _offset)); __privateSet(this, _offset, __privateGet(this, _offset) + toWriteLength); } } writeStringArray(strings) { if (Array.isArray(strings) === false) { throw TypeError("strings must be an instance of Array"); } for (const string of strings) { this.writeString(string); } } }; _buffer = new WeakMap(); _size = new WeakMap(); _offset = new WeakMap(); _sequenceOffsets = new WeakMap(); _growthFactor = new WeakMap(); _ensureBufferCapacity = new WeakSet(); ensureBufferCapacity_fn = function(numberOfBytesToWrite) { if (__privateGet(this, _size) - __privateGet(this, _offset) < numberOfBytesToWrite) { let newSize = __privateGet(this, _size) * __privateGet(this, _growthFactor); if (newSize - __privateGet(this, _offset) < numberOfBytesToWrite) { newSize += numberOfBytesToWrite; } const newBuffer = Buffer.alloc(newSize); __privateGet(this, _buffer).copy(newBuffer, 0, 0, __privateGet(this, _offset)); __privateSet(this, _buffer, newBuffer); __privateSet(this, _size, newSize); } }; _shift = new WeakSet(); shift_fn = function(start, length, shiftAmount) { __privateGet(this, _buffer).copy(__privateGet(this, _buffer), start + shiftAmount, start, start + length); __privateSet(this, _offset, __privateGet(this, _offset) + shiftAmount); }; module2.exports = BerWriter; } }); // node_modules/@ldapjs/asn1/index.js var require_asn1 = __commonJS({ "node_modules/@ldapjs/asn1/index.js"(exports, module2) { "use strict"; var BerReader = require_reader(); var BerWriter = require_writer(); var BerTypes = require_types(); var bufferToHexDump = require_buffer_to_hex_dump(); module2.exports = { BerReader, BerTypes, BerWriter, bufferToHexDump }; } }); // node_modules/process-warning/index.js var require_process_warning = __commonJS({ "node_modules/process-warning/index.js"(exports, module2) { "use strict"; var { format } = require("util"); function processWarning() { const codes = {}; const emitted = /* @__PURE__ */ new Map(); const opts = /* @__PURE__ */ Object.create(null); function create(name, code, message, { unlimited = false } = {}) { if (!name) throw new Error("Warning name must not be empty"); if (!code) throw new Error("Warning code must not be empty"); if (!message) throw new Error("Warning message must not be empty"); if (typeof unlimited !== "boolean") throw new Error("Warning opts.unlimited must be a boolean"); code = code.toUpperCase(); if (codes[code] !== void 0) { throw new Error(`The code '${code}' already exist`); } function buildWarnOpts(a, b, c) { let formatted; if (a && b && c) { formatted = format(message, a, b, c); } else if (a && b) { formatted = format(message, a, b); } else if (a) { formatted = format(message, a); } else { formatted = message; } return { code, name, message: formatted }; } Object.assign(opts, { unlimited }); emitted.set(code, unlimited); codes[code] = buildWarnOpts; return codes[code]; } function emit(code, a, b, c) { if (emitted.get(code) === true && opts.unlimited === false) return; if (codes[code] === void 0) throw new Error(`The code '${code}' does not exist`); emitted.set(code, true); const warning = codes[code](a, b, c); process.emitWarning(warning.message, warning.name, warning.code); } return { create, emit, emitted }; } module2.exports = processWarning; module2.exports.default = processWarning; module2.exports.processWarning = processWarning; } }); // node_modules/@ldapjs/messages/lib/deprecations.js var require_deprecations = __commonJS({ "node_modules/@ldapjs/messages/lib/deprecations.js"(exports, module2) { "use strict"; var warning = require_process_warning()(); var clazz = "LdapjsMessageWarning"; warning.create(clazz, "LDAP_MESSAGE_DEP_001", "messageID is deprecated. Use messageId instead."); warning.create(clazz, "LDAP_MESSAGE_DEP_002", "The .json property is deprecated. Use .pojo instead."); warning.create(clazz, "LDAP_MESSAGE_DEP_003", "abandonID is deprecated. Use abandonId instead."); warning.create(clazz, "LDAP_MESSAGE_DEP_004", "errorMessage is deprecated. Use diagnosticMessage instead."); warning.create(clazz, "LDAP_ATTRIBUTE_SPEC_ERR_001", "received attempt to define attribute with an empty name: attribute skipped.", { unlimited: true }); module2.exports = warning; } }); // node_modules/@ldapjs/protocol/index.js var require_protocol = __commonJS({ "node_modules/@ldapjs/protocol/index.js"(exports, module2) { "use strict"; var core = Object.freeze({ LDAP_VERSION_3: 3, LBER_SET: 49, LDAP_CONTROLS: 160 }); var operations = Object.freeze({ LDAP_REQ_BIND: 96, LDAP_REQ_UNBIND: 66, LDAP_REQ_SEARCH: 99, LDAP_REQ_MODIFY: 102, LDAP_REQ_ADD: 104, LDAP_REQ_DELETE: 74, LDAP_REQ_MODRDN: 108, LDAP_REQ_COMPARE: 110, LDAP_REQ_ABANDON: 80, LDAP_REQ_EXTENSION: 119, LDAP_RES_BIND: 97, LDAP_RES_SEARCH_ENTRY: 100, LDAP_RES_SEARCH_DONE: 101, LDAP_RES_SEARCH_REF: 115, LDAP_RES_SEARCH: 101, LDAP_RES_MODIFY: 103, LDAP_RES_ADD: 105, LDAP_RES_DELETE: 107, LDAP_RES_MODRDN: 109, LDAP_RES_COMPARE: 111, LDAP_RES_EXTENSION: 120, LDAP_RES_INTERMEDIATE: 121, LDAP_RES_REFERRAL: 163 }); var resultCodes = Object.freeze({ SUCCESS: 0, OPERATIONS_ERROR: 1, PROTOCOL_ERROR: 2, TIME_LIMIT_EXCEEDED: 3, SIZE_LIMIT_EXCEEDED: 4, COMPARE_FALSE: 5, COMPARE_TRUE: 6, AUTH_METHOD_NOT_SUPPORTED: 7, STRONGER_AUTH_REQUIRED: 8, REFERRAL: 10, ADMIN_LIMIT_EXCEEDED: 11, UNAVAILABLE_CRITICAL_EXTENSION: 12, CONFIDENTIALITY_REQUIRED: 13, SASL_BIND_IN_PROGRESS: 14, NO_SUCH_ATTRIBUTE: 16, UNDEFINED_ATTRIBUTE_TYPE: 17, INAPPROPRIATE_MATCHING: 18, CONSTRAINT_VIOLATION: 19, ATTRIBUTE_OR_VALUE_EXISTS: 20, INVALID_ATTRIBUTE_SYNTAX: 21, NO_SUCH_OBJECT: 32, ALIAS_PROBLEM: 33, INVALID_DN_SYNTAX: 34, IS_LEAF: 35, ALIAS_DEREFERENCING_PROBLEM: 36, INAPPROPRIATE_AUTHENTICATION: 48, INVALID_CREDENTIALS: 49, INSUFFICIENT_ACCESS_RIGHTS: 50, BUSY: 51, UNAVAILABLE: 52, UNWILLING_TO_PERFORM: 53, LOOP_DETECT: 54, SORT_CONTROL_MISSING: 60, OFFSET_RANGE_ERROR: 61, NAMING_VIOLATION: 64, OBJECT_CLASS_VIOLATION: 65, NOT_ALLOWED_ON_NON_LEAF: 66, NOT_ALLOWED_ON_RDN: 67, ENTRY_ALREADY_EXISTS: 68, OBJECT_CLASS_MODS_PROHIBITED: 69, RESULTS_TOO_LARGE: 70, AFFECTS_MULTIPLE_DSAS: 71, CONTROL_ERROR: 76, OTHER: 80, SERVER_DOWN: 81, LOCAL_ERROR: 82, ENCODING_ERROR: 83, DECODING_ERROR: 84, TIMEOUT: 85, AUTH_UNKNOWN: 86, FILTER_ERROR: 87, USER_CANCELED: 88, PARAM_ERROR: 89, NO_MEMORY: 90, CONNECT_ERROR: 91, NOT_SUPPORTED: 92, CONTROL_NOT_FOUND: 93, NO_RESULTS_RETURNED: 94, MORE_RESULTS_TO_RETURN: 95, CLIENT_LOOP: 96, REFERRAL_LIMIT_EXCEEDED: 97, INVALID_RESPONSE: 100, AMBIGUOUS_RESPONSE: 101, TLS_NOT_SUPPORTED: 112, INTERMEDIATE_RESPONSE: 113, UNKNOWN_TYPE: 114, CANCELED: 118, NO_SUCH_OPERATION: 119, TOO_LATE: 120, CANNOT_CANCEL: 121, ASSERTION_FAILED: 122, AUTHORIZATION_DENIED: 123, E_SYNC_REFRESH_REQUIRED: 4096, NO_OPERATION: 16654 }); var search = Object.freeze({ SCOPE_BASE_OBJECT: 0, SCOPE_ONE_LEVEL: 1, SCOPE_SUBTREE: 2, NEVER_DEREF_ALIASES: 0, DEREF_IN_SEARCHING: 1, DEREF_BASE_OBJECT: 2, DEREF_ALWAYS: 3, FILTER_AND: 160, FILTER_OR: 161, FILTER_NOT: 162, FILTER_EQUALITY: 163, FILTER_SUBSTRINGS: 164, FILTER_GE: 165, FILTER_LE: 166, FILTER_PRESENT: 135, FILTER_APPROX: 168, FILTER_EXT: 169 }); module2.exports = Object.freeze({ core, operations, resultCodes, search, resultCodeToName }); function resultCodeToName(code) { for (const [key, value] of Object.entries(resultCodes)) { if (value === code) return key; } } } }); // node_modules/@ldapjs/controls/node_modules/@ldapjs/asn1/lib/ber/errors.js var require_errors = __commonJS({ "node_modules/@ldapjs/controls/node_modules/@ldapjs/asn1/lib/ber/errors.js"(exports, module2) { module2.exports = { newInvalidAsn1Error: function(msg) { const e = new Error(); e.name = "InvalidAsn1Error"; e.message = msg || ""; return e; } }; } }); // node_modules/@ldapjs/controls/node_modules/@ldapjs/asn1/lib/ber/types.js var require_types2 = __commonJS({ "node_modules/@ldapjs/controls/node_modules/@ldapjs/asn1/lib/ber/types.js"(exports, module2) { module2.exports = { EOC: 0, Boolean: 1, Integer: 2, BitString: 3, OctetString: 4, Null: 5, OID: 6, ObjectDescriptor: 7, External: 8, Real: 9, Enumeration: 10, PDV: 11, Utf8String: 12, RelativeOID: 13, Sequence: 16, Set: 17, NumericString: 18, PrintableString: 19, T61String: 20, VideotexString: 21, IA5String: 22, UTCTime: 23, GeneralizedTime: 24, GraphicString: 25, VisibleString: 26, GeneralString: 28, UniversalString: 29, CharacterString: 30, BMPString: 31, Constructor: 32, Context: 128 }; } }); // node_modules/@ldapjs/controls/node_modules/@ldapjs/asn1/lib/ber/reader.js var require_reader2 = __commonJS({ "node_modules/@ldapjs/controls/node_modules/@ldapjs/asn1/lib/ber/reader.js"(exports, module2) { var assert = require("assert"); var ASN1 = require_types2(); var errors = require_errors(); var newInvalidAsn1Error = errors.newInvalidAsn1Error; function Reader(data) { if (!data || !Buffer.isBuffer(data)) { throw new TypeError("data must be a node Buffer"); } this._buf = data; this._size = data.length; this._len = 0; this._offset = 0; } Object.defineProperty(Reader.prototype, Symbol.toStringTag, { value: "BerReader" }); Object.defineProperty(Reader.prototype, "length", { enumerable: true, get: function() { return this._len; } }); Object.defineProperty(Reader.prototype, "offset", { enumerable: true, get: function() { return this._offset; } }); Object.defineProperty(Reader.prototype, "remain", { get: function() { return this._size - this._offset; } }); Object.defineProperty(Reader.prototype, "buffer", { get: function() { return this._buf.slice(this._offset); } }); Reader.prototype.readByte = function(peek) { if (this._size - this._offset < 1) { return null; } const b = this._buf[this._offset] & 255; if (!peek) { this._offset += 1; } return b; }; Reader.prototype.peek = function() { return this.readByte(true); }; Reader.prototype.readLength = function(offset) { if (offset === void 0) { offset = this._offset; } if (offset >= this._size) { return null; } let lenB = this._buf[offset++] & 255; if (lenB === null) { return null; } if ((lenB & 128) === 128) { lenB &= 127; if (lenB === 0) { throw newInvalidAsn1Error("Indefinite length not supported"); } if (lenB > 4) { throw newInvalidAsn1Error("encoding too long"); } if (this._size - offset < lenB) { return null; } this._len = 0; for (let i = 0; i < lenB; i++) { this._len = (this._len << 8) + (this._buf[offset++] & 255); } } else { this._len = lenB; } return offset; }; Reader.prototype.readSequence = function(tag) { const seq = this.peek(); if (seq === null) { return null; } if (tag !== void 0 && tag !== seq) { throw newInvalidAsn1Error("Expected 0x" + tag.toString(16) + ": got 0x" + seq.toString(16)); } const o = this.readLength(this._offset + 1); if (o === null) { return null; } this._offset = o; return seq; }; Reader.prototype.readInt = function() { return this._readTag(ASN1.Integer); }; Reader.prototype.readBoolean = function(tag) { return this._readTag(tag || ASN1.Boolean) !== 0; }; Reader.prototype.readEnumeration = function() { return this._readTag(ASN1.Enumeration); }; Reader.prototype.readString = function(tag, retbuf) { if (!tag) { tag = ASN1.OctetString; } const b = this.peek(); if (b === null) { return null; } if (b !== tag) { throw newInvalidAsn1Error("Expected 0x" + tag.toString(16) + ": got 0x" + b.toString(16)); } const o = this.readLength(this._offset + 1); if (o === null) { return null; } if (this.length > this._size - o) { return null; } this._offset = o; if (this.length === 0) { return retbuf ? Buffer.alloc(0) : ""; } const str = this._buf.slice(this._offset, this._offset + this.length); this._offset += this.length; return retbuf ? str : str.toString("utf8"); }; Reader.prototype.readOID = function(tag) { if (!tag) { tag = ASN1.OID; } const b = this.readString(tag, true); if (b === null) { return null; } const values = []; let value = 0; for (let i = 0; i < b.length; i++) { const byte = b[i] & 255; value <<= 7; value += byte & 127; if ((byte & 128) === 0) { values.push(value); value = 0; } } value = values.shift(); values.unshift(value % 40); values.unshift(value / 40 >> 0); return values.join("."); }; Reader.prototype._readTag = function(tag) { assert.ok(tag !== void 0); const b = this.peek(); if (b === null) { return null; } if (b !== tag) { throw newInvalidAsn1Error("Expected 0x" + tag.toString(16) + ": got 0x" + b.toString(16)); } const o = this.readLength(this._offset + 1); if (o === null) { return null; } if (this.length > 4) { throw newInvalidAsn1Error("Integer too long: " + this.length); } if (this.length > this._size - o) { return null; } this._offset = o; const fb = this._buf[this._offset]; let value = 0; let i; for (i = 0; i < this.length; i++) { value <<= 8; value |= this._buf[this._offset++] & 255; } if ((fb & 128) === 128 && i !== 4) { value -= 1 << i * 8; } return value >> 0; }; module2.exports = Reader; } }); // node_modules/@ldapjs/controls/node_modules/@ldapjs/asn1/lib/ber/writer.js var require_writer2 = __commonJS({ "node_modules/@ldapjs/controls/node_modules/@ldapjs/asn1/lib/ber/writer.js"(exports, module2) { var assert = require("assert"); var ASN1 = require_types2(); var errors = require_errors(); var newInvalidAsn1Error = errors.newInvalidAsn1Error; var DEFAULT_OPTS = { size: 1024, growthFactor: 8 }; function merge(from, to) { assert.ok(from); assert.equal(typeof from, "object"); assert.ok(to); assert.equal(typeof to, "object"); const keys = Object.getOwnPropertyNames(from); keys.forEach(function(key) { if (to[key]) { return; } const value = Object.getOwnPropertyDescriptor(from, key); Object.defineProperty(to, key, value); }); return to; } function Writer(options) { options = merge(DEFAULT_OPTS, options || {}); this._buf = Buffer.alloc(options.size || 1024); this._size = this._buf.length; this._offset = 0; this._options = options; this._seq = []; } Object.defineProperty(Writer.prototype, Symbol.toStringTag, { value: "BerWriter" }); Object.defineProperty(Writer.prototype, "buffer", { get: function() { if (this._seq.length) { throw newInvalidAsn1Error(this._seq.length + " unended sequence(s)"); } return this._buf.slice(0, this._offset); } }); Writer.prototype.appendBuffer = function appendBuffer(buffer) { if (Buffer.isBuffer(buffer) === false) { throw Error("buffer must be an instance of Buffer"); } for (const b of buffer.values()) { this.writeByte(b); } }; Writer.prototype.writeByte = function(b) { if (typeof b !== "number") { throw new TypeError("argument must be a Number"); } this._ensure(1); this._buf[this._offset++] = b; }; Writer.prototype.writeInt = function(i, tag) { if (typeof i !== "number") { throw new TypeError("argument must be a Number"); } if (typeof tag !== "number") { tag = ASN1.Integer; } let sz = 4; while (((i & 4286578688) === 0 || (i & 4286578688) === 4286578688 >> 0) && sz > 1) { sz--; i <<= 8; } if (sz > 4) { throw newInvalidAsn1Error("BER ints cannot be > 0xffffffff"); } this._ensure(2 + sz); this._buf[this._offset++] = tag; this._buf[this._offset++] = sz; while (sz-- > 0) { this._buf[this._offset++] = (i & 4278190080) >>> 24; i <<= 8; } }; Writer.prototype.writeNull = function() { this.writeByte(ASN1.Null); this.writeByte(0); }; Writer.prototype.writeEnumeration = function(i, tag) { if (typeof i !== "number") { throw new TypeError("argument must be a Number"); } if (typeof tag !== "number") { tag = ASN1.Enumeration; } return this.writeInt(i, tag); }; Writer.prototype.writeBoolean = function(b, tag) { if (typeof b !== "boolean") { throw new TypeError("argument must be a Boolean"); } if (typeof tag !== "number") { tag = ASN1.Boolean; } this._ensure(3); this._buf[this._offset++] = tag; this._buf[this._offset++] = 1; this._buf[this._offset++] = b ? 255 : 0; }; Writer.prototype.writeString = function(s, tag) { if (typeof s !== "string") { throw new TypeError("argument must be a string (was: " + typeof s + ")"); } if (typeof tag !== "number") { tag = ASN1.OctetString; } const len = Buffer.byteLength(s); this.writeByte(tag); this.writeLength(len); if (len) { this._ensure(len); this._buf.write(s, this._offset); this._offset += len; } }; Writer.prototype.writeBuffer = function(buf, tag) { if (typeof tag !== "number") { throw new TypeError("tag must be a number"); } if (!Buffer.isBuffer(buf)) { throw new TypeError("argument must be a buffer"); } this.writeByte(tag); this.writeLength(buf.length); this._ensure(buf.length); buf.copy(this._buf, this._offset, 0, buf.length); this._offset += buf.length; }; Writer.prototype.writeStringArray = function(strings) { if (Array.isArray(strings) === false) { throw new TypeError("argument must be an Array[String]"); } const self2 = this; strings.forEach(function(s) { self2.writeString(s); }); }; Writer.prototype.writeOID = function(s, tag) { if (typeof s !== "string") { throw new TypeError("argument must be a string"); } if (typeof tag !== "number") { tag = ASN1.OID; } if (!/^([0-9]+\.){3,}[0-9]+$/.test(s)) { throw new Error("argument is not a valid OID string"); } function encodeOctet(bytes2, octet) { if (octet < 128) { bytes2.push(octet); } else if (octet < 16384) { bytes2.push(octet >>> 7 | 128); bytes2.push(octet & 127); } else if (octet < 2097152) { bytes2.push(octet >>> 14 | 128); bytes2.push((octet >>> 7 | 128) & 255); bytes2.push(octet & 127); } else if (octet < 268435456) { bytes2.push(octet >>> 21 | 128); bytes2.push((octet >>> 14 | 128) & 255); bytes2.push((octet >>> 7 | 128) & 255); bytes2.push(octet & 127); } else { bytes2.push((octet >>> 28 | 128) & 255); bytes2.push((octet >>> 21 | 128) & 255); bytes2.push((octet >>> 14 | 128) & 255); bytes2.push((octet >>> 7 | 128) & 255); bytes2.push(octet & 127); } } const tmp = s.split("."); const bytes = []; bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10)); tmp.slice(2).forEach(function(b) { encodeOctet(bytes, parseInt(b, 10)); }); const self2 = this; this._ensure(2 + bytes.length); this.writeByte(tag); this.writeLength(bytes.length); bytes.forEach(function(b) { self2.writeByte(b); }); }; Writer.prototype.writeLength = function(len) { if (typeof len !== "number") { throw new TypeError("argument must be a Number"); } this._ensure(4); if (len <= 127) { this._buf[this._offset++] = len; } else if (len <= 255) { this._buf[this._offset++] = 129; this._buf[this._offset++] = len; } else if (len <= 65535) { this._buf[this._offset++] = 130; this._buf[this._offset++] = len >> 8; this._buf[this._offset++] = len; } else if (len <= 16777215) { this._buf[this._offset++] = 131; this._buf[this._offset++] = len >> 16; this._buf[this._offset++] = len >> 8; this._buf[this._offset++] = len; } else { throw newInvalidAsn1Error("Length too long (> 4 bytes)"); } }; Writer.prototype.startSequence = function(tag) { if (typeof tag !== "number") { tag = ASN1.Sequence | ASN1.Constructor; } this.writeByte(tag); this._seq.push(this._offset); this._ensure(3); this._offset += 3; }; Writer.prototype.endSequence = function() { const seq = this._seq.pop(); const start = seq + 3; const len = this._offset - start; if (len <= 127) { this._shift(start, len, -2); this._buf[seq] = len; } else if (len <= 255) { this._shift(start, len, -1); this._buf[seq] = 129; this._buf[seq + 1] = len; } else if (len <= 65535) { this._buf[seq] = 130; this._buf[seq + 1] = len >> 8; this._buf[seq + 2] = len; } else if (len <= 16777215) { this._shift(start, len, 1); this._buf[seq] = 131; this._buf[seq + 1] = len >> 16; this._buf[seq + 2] = len >> 8; this._buf[seq + 3] = len; } else { throw newInvalidAsn1Error("Sequence too long"); } }; Writer.prototype._shift = function(start, len, shift) { assert.ok(start !== void 0); assert.ok(len !== void 0); assert.ok(shift); this._buf.copy(this._buf, start + shift, start, start + len); this._offset += shift; }; Writer.prototype._ensure = function(len) { assert.ok(len); if (this._size - this._offset < len) { let sz = this._size * this._options.growthFactor; if (sz - this._offset < len) { sz += len; } const buf = Buffer.alloc(sz); this._buf.copy(buf, 0, 0, this._offset); this._buf = buf; this._size = sz; } }; module2.exports = Writer; } }); // node_modules/@ldapjs/controls/node_modules/@ldapjs/asn1/lib/ber/index.js var require_ber = __commonJS({ "node_modules/@ldapjs/controls/node_modules/@ldapjs/asn1/lib/ber/index.js"(exports, module2) { var errors = require_errors(); var types = require_types2(); var Reader = require_reader2(); var Writer = require_writer2(); module2.exports = { Reader, Writer }; for (const t in types) { if (Object.prototype.hasOwnProperty.call(types, t)) { module2.exports[t] = types[t]; } } for (const e in errors) { if (Object.prototype.hasOwnProperty.call(errors, e)) { module2.exports[e] = errors[e]; } } } }); // node_modules/@ldapjs/controls/node_modules/@ldapjs/asn1/lib/index.js var require_lib = __commonJS({ "node_modules/@ldapjs/controls/node_modules/@ldapjs/asn1/lib/index.js"(exports, module2) { var Ber = require_ber(); module2.exports = { Ber, BerReader: Ber.Reader, BerWriter: Ber.Writer }; } }); // node_modules/@ldapjs/controls/lib/control.js var require_control = __commonJS({ "node_modules/@ldapjs/controls/lib/control.js"(exports, module2) { "use strict"; var { BerWriter } = require_lib(); var Control = class { constructor(options = {}) { const opts = Object.assign({ type: "", criticality: false, value: null }, options); this.type = opts.type; this.criticality = opts.criticality; this.value = opts.value; } get [Symbol.toStringTag]() { return "LdapControl"; } get pojo() { const obj = { type: this.type, value: this.value, criticality: this.criticality }; if (typeof this._pojo === "function") { this._pojo(obj); } return obj; } toBer(ber = new BerWriter()) { ber.startSequence(); ber.writeString(this.type || ""); ber.writeBoolean(this.criticality); if (typeof this._toBer === "function") { this._toBer(ber); } else if (this.value !== void 0) { if (typeof this.value === "string") { ber.writeString(this.value); } else if (Buffer.isBuffer(this.value)) { ber.writeString(this.value.toString()); } } ber.endSequence(); return ber; } }; module2.exports = Control; } }); // node_modules/@ldapjs/controls/lib/is-object.js var require_is_object = __commonJS({ "node_modules/@ldapjs/controls/lib/is-object.js"(exports, module2) { "use strict"; module2.exports = function isObject(input) { return Object.prototype.toString.call(input) === "[object Object]"; }; } }); // node_modules/@ldapjs/controls/lib/has-own.js var require_has_own = __commonJS({ "node_modules/@ldapjs/controls/lib/has-own.js"(exports, module2) { "use strict"; module2.exports = function hasOwn(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }; } }); // node_modules/@ldapjs/controls/lib/controls/entry-change-notification-control.js var require_entry_change_notification_control = __commonJS({ "node_modules/@ldapjs/controls/lib/controls/entry-change-notification-control.js"(exports, module2) { "use strict"; var { BerReader, BerWriter } = require_lib(); var isObject = require_is_object(); var hasOwn = require_has_own(); var Control = require_control(); var _parse, parse_fn; var _EntryChangeNotificationControl = class extends Control { constructor(options = {}) { options.type = _EntryChangeNotificationControl.OID; super(options); __privateAdd(this, _parse); this._value = { changeType: 4 }; if (hasOwn(options, "value") === false) { return; } if (Buffer.isBuffer(options.value)) { __privateMethod(this, _parse, parse_fn).call(this, options.value); } else if (isObject(options.value)) { this._value = options.value; } else { throw new TypeError("options.value must be a Buffer or Object"); } } get value() { return this._value; } set value(obj) { this._value = Object.assign({}, this._value, obj); } _toBer(ber) { const writer = new BerWriter(); writer.startSequence(); writer.writeInt(this._value.changeType); if (this._value.previousDN) { writer.writeString(this._value.previousDN); } if (Object.prototype.hasOwnProperty.call(this._value, "changeNumber")) { writer.writeInt(parseInt(this._value.changeNumber, 10)); } writer.endSequence(); ber.writeBuffer(writer.buffer, 4); return ber; } _updatePlainObject(obj) { obj.controlValue = this.value; return obj; } }; var EntryChangeNotificationControl = _EntryChangeNotificationControl; _parse = new WeakSet(); parse_fn = function(buffer) { const ber = new BerReader(buffer); if (ber.readSequence()) { this._value = { changeType: ber.readInt() }; if (this._value.changeType === 8) { this._value.previousDN = ber.readString(); } this._value.changeNumber = ber.readInt(); } }; __publicField(EntryChangeNotificationControl, "OID", "2.16.840.1.113730.3.4.7"); module2.exports = EntryChangeNotificationControl; } }); // node_modules/@ldapjs/controls/lib/controls/paged-results-control.js var require_paged_results_control = __commonJS({ "node_modules/@ldapjs/controls/lib/controls/paged-results-control.js"(exports, module2) { "use strict"; var { Ber, BerReader, BerWriter } = require_lib(); var isObject = require_is_object(); var hasOwn = require_has_own(); var Control = require_control(); var _parse, parse_fn; var _PagedResultsControl = class extends Control { constructor(options = {}) { options.type = _PagedResultsControl.OID; super(options); __privateAdd(this, _parse); this._value = { size: 0, cookie: Buffer.alloc(0) }; if (hasOwn(options, "value") === false) { return; } if (Buffer.isBuffer(options.value)) { __privateMethod(this, _parse, parse_fn).call(this, options.value); } else if (isObject(options.value)) { this.value = options.value; } else { throw new TypeError("options.value must be a Buffer or Object"); } } get value() { return this._value; } set value(obj) { this._value = Object.assign({}, this._value, obj); if (typeof this._value.cookie === "string") { this._value.cookie = Buffer.from(this._value.cookie); } } _toBer(ber) { const writer = new BerWriter(); writer.startSequence(); writer.writeInt(this._value.size); if (this._value.cookie && this._value.cookie.length > 0) { writer.writeBuffer(this._value.cookie, Ber.OctetString); } else { writer.writeString(""); } writer.endSequence(); ber.writeBuffer(writer.buffer, Ber.OctetString); return ber; } _updatePlainObject(obj) { obj.controlValue = this.value; return obj; } }; var PagedResultsControl = _PagedResultsControl; _parse = new WeakSet(); parse_fn = function(buffer) { const ber = new BerReader(buffer); if (ber.readSequence()) { this._value = {}; this._value.size = ber.readInt(); this._value.cookie = ber.readString(Ber.OctetString, true); if (!this._value.cookie) { this._value.cookie = Buffer.alloc(0); } } }; __publicField(PagedResultsControl, "OID", "1.2.840.113556.1.4.319"); module2.exports = PagedResultsControl; } }); // node_modules/@ldapjs/controls/lib/controls/persistent-search-control.js var require_persistent_search_control = __commonJS({ "node_modules/@ldapjs/controls/lib/controls/persistent-search-control.js"(exports, module2) { "use strict"; var { BerReader, BerWriter } = require_lib(); var isObject = require_is_object(); var hasOwn = require_has_own(); var Control = require_control(); var _parse, parse_fn; var _PersistentSearchControl = class extends Control { constructor(options = {}) { options.type = _PersistentSearchControl.OID; super(options); __privateAdd(this, _parse); this._value = { changeTypes: 15, changesOnly: true, returnECs: true }; if (hasOwn(options, "value") === false) { return; } if (Buffer.isBuffer(options.value)) { __privateMethod(this, _parse, parse_fn).call(this, options.value); } else if (isObject(options.value)) { this._value = options.value; } else { throw new TypeError("options.value must be a Buffer or Object"); } } get value() { return this._value; } set value(obj) { this._value = Object.assign({}, this._value, obj); } _toBer(ber) { const writer = new BerWriter(); writer.startSequence(); writer.writeInt(this._value.changeTypes); writer.writeBoolean(this._value.changesOnly); writer.writeBoolean(this._value.returnECs); writer.endSequence(); ber.writeBuffer(writer.buffer, 4); return ber; } _updatePlainObject(obj) { obj.controlValue = this.value; return obj; } }; var PersistentSearchControl = _PersistentSearchControl; _parse = new WeakSet(); parse_fn = function(buffer) { const ber = new BerReader(buffer); if (ber.readSequence()) { this._value = { changeTypes: ber.readInt(), changesOnly: ber.readBoolean(), returnECs: ber.readBoolean() }; } }; __publicField(PersistentSearchControl, "OID", "2.16.840.1.113730.3.4.3"); module2.exports = PersistentSearchControl; } }); // node_modules/@ldapjs/controls/lib/controls/server-side-sorting-request-control.js var require_server_side_sorting_request_control = __commonJS({ "node_modules/@ldapjs/controls/lib/controls/server-side-sorting-request-control.js"(exports, module2) { "use strict"; var { Ber, BerReader, BerWriter } = require_lib(); var isObject = require_is_object(); var hasOwn = require_has_own(); var Control = require_control(); var _parse, parse_fn; var _ServerSideSortingRequestControl = class extends Control { constructor(options = { value: [] }) { var _a; options.type = _ServerSideSortingRequestControl.OID; super(options); __privateAdd(this, _parse); const inputValue = (_a = options.value) != null ? _a : []; if (Buffer.isBuffer(inputValue)) { __privateMethod(this, _parse, parse_fn).call(this, inputValue); } else if (Array.isArray(inputValue)) { for (const obj of inputValue) { if (isObject(obj) === false) { throw new Error("Control value must be an object"); } if (hasOwn(obj, "attributeType") === false) { throw new Error("Missing required key: attributeType"); } } this.value = inputValue; } else if (isObject(inputValue)) { if (hasOwn(inputValue, "attributeType") === false) { throw new Error("Missing required key: attributeType"); } this.value = [inputValue]; } else { throw new TypeError("options.value must be a Buffer, Array or Object"); } } get value() { return this._value; } set value(items) { if (Buffer.isBuffer(items) === true) return; if (Array.isArray(items) === false) { this._value = [items]; return; } this._value = items; } _pojo(obj) { obj.value = this.value; return obj; } _toBer(ber) { if (this.value.length === 0) { return; } const writer = new BerWriter(); writer.startSequence(48); for (let i = 0; i < this.value.length; i++) { const item = this.value[i]; writer.startSequence(48); if (hasOwn(item, "attributeType")) { writer.writeString(item.attributeType, Ber.OctetString); } if (hasOwn(item, "orderingRule")) { writer.writeString(item.orderingRule, 128); } if (hasOwn(item, "reverseOrder")) { writer.writeBoolean(item.reverseOrder, 129); } writer.endSequence(); } writer.endSequence(); ber.writeBuffer(writer.buffer, 4); } }; var ServerSideSortingRequestControl = _ServerSideSortingRequestControl; _parse = new WeakSet(); parse_fn = function(buffer) { const ber = new BerReader(buffer); let item; if (ber.readSequence(48)) { this.value = []; while (ber.readSequence(48)) { item = {}; item.attributeType = ber.readString(Ber.OctetString); if (ber.peek() === 128) { item.orderingRule = ber.readString(128); } if (ber.peek() === 129) { item.reverseOrder = ber._readTag(129) !== 0; } this.value.push(item); } } }; __publicField(ServerSideSortingRequestControl, "OID", "1.2.840.113556.1.4.473"); module2.exports = ServerSideSortingRequestControl; } }); // node_modules/@ldapjs/controls/lib/controls/server-side-sorting-response-control.js var require_server_side_sorting_response_control = __commonJS({ "node_modules/@ldapjs/controls/lib/controls/server-side-sorting-response-control.js"(exports, module2) { "use strict"; var { BerReader, BerWriter } = require_lib(); var Control = require_control(); var isObject = require_is_object(); var hasOwn = require_has_own(); var { resultCodes: RESULT_CODES } = require_protocol(); var validCodeNames = [ "SUCCESS", "OPERATIONS_ERROR", "TIME_LIMIT_EXCEEDED", "STRONGER_AUTH_REQUIRED", "ADMIN_LIMIT_EXCEEDED", "NO_SUCH_ATTRIBUTE", "INAPPROPRIATE_MATCHING", "INSUFFICIENT_ACCESS_RIGHTS", "BUSY", "UNWILLING_TO_PERFORM", "OTHER" ]; var filteredCodes = Object.entries(RESULT_CODES).filter(([k, v]) => validCodeNames.includes(k)); var VALID_CODES = new Map([ ...filteredCodes, ...filteredCodes.map(([k, v]) => { return [v, k]; }) ]); var _parse, parse_fn; var _ServerSideSortingResponseControl = class extends Control { constructor(options = {}) { options.type = _ServerSideSortingResponseControl.OID; options.criticality = false; super(options); __privateAdd(this, _parse); this.value = {}; if (hasOwn(options, "value") === false || !options.value) { return; } const value = options.value; if (Buffer.isBuffer(value)) { __privateMethod(this, _parse, parse_fn).call(this, value); } else if (isObject(value)) { if (VALID_CODES.has(value.result) === false) { throw new Error("Invalid result code"); } if (hasOwn(value, "failedAttribute") && typeof value.failedAttribute !== "string") { throw new Error("failedAttribute must be String"); } this.value = value; } else { throw new TypeError("options.value must be a Buffer or Object"); } } get value() { return this._value; } set value(obj) { this._value = Object.assign({}, this._value, obj); } _pojo(obj) { obj.value = this.value; return obj; } _toBer(ber) { if (!this._value || Object.keys(this._value).length === 0) { return; } const writer = new BerWriter(); writer.startSequence(48); writer.writeEnumeration(this.value.result); if (this.value.result !== RESULT_CODES.SUCCESS && this.value.failedAttribute) { writer.writeString(this.value.failedAttribute, 128); } writer.endSequence(); ber.writeBuffer(writer.buffer, 4); } }; var ServerSideSortingResponseControl = _ServerSideSortingResponseControl; _parse = new WeakSet(); parse_fn = function(buffer) { const ber = new BerReader(buffer); if (ber.readSequence(48)) { this._value = {}; this._value.result = ber.readEnumeration(); if (ber.peek() === 128) { this._value.failedAttribute = ber.readString(128); } } }; __publicField(ServerSideSortingResponseControl, "OID", "1.2.840.113556.1.4.474"); __publicField(ServerSideSortingResponseControl, "RESPONSE_CODES", Object.freeze(VALID_CODES)); module2.exports = ServerSideSortingResponseControl; } }); // node_modules/@ldapjs/controls/lib/controls/virtual-list-view-request-control.js var require_virtual_list_view_request_control = __commonJS({ "node_modules/@ldapjs/controls/lib/controls/virtual-list-view-request-control.js"(exports, module2) { "use strict"; var { BerReader, BerWriter } = require_lib(); var isObject = require_is_object(); var hasOwn = require_has_own(); var Control = require_control(); var _parse, parse_fn; var _VirtualListViewRequestControl = class extends Control { constructor(options = {}) { options.type = _VirtualListViewRequestControl.OID; super(options); __privateAdd(this, _parse); if (hasOwn(options, "value") === false) { throw Error("control is not enabled"); } if (Buffer.isBuffer(options.value)) { __privateMethod(this, _parse, parse_fn).call(this, options.value); } else if (isObject(options.value)) { if (Object.prototype.hasOwnProperty.call(options.value, "beforeCount") === false) { throw new Error("Missing required key: beforeCount"); } if (Object.prototype.hasOwnProperty.call(options.value, "afterCount") === false) { throw new Error("Missing required key: afterCount"); } this._value = options.value; } else { throw new TypeError("options.value must be a Buffer or Object"); } throw Error("control is not enabled"); } get value() { return this._value; } set value(items) { if (Buffer.isBuffer(items) === true) return; if (Array.isArray(items) === false) { this._value = [items]; return; } this._value = items; } _pojo(obj) { obj.value = this.value; return obj; } _toBer(ber) { if (!this._value || this._value.length === 0) { return; } const writer = new BerWriter(); writer.startSequence(48); writer.writeInt(this._value.beforeCount); writer.writeInt(this._value.afterCount); if (this._value.targetOffset !== void 0) { writer.startSequence(160); writer.writeInt(this._value.targetOffset); writer.writeInt(this._value.contentCount); writer.endSequence(); } else if (this._value.greaterThanOrEqual !== void 0) { writer.writeString(this._value.greaterThanOrEqual, 129); } writer.endSequence(); ber.writeBuffer(writer.buffer, 4); } }; var VirtualListViewRequestControl = _VirtualListViewRequestControl; _parse = new WeakSet(); parse_fn = function(buffer) { const ber = new BerReader(buffer); if (ber.readSequence()) { this._value = {}; this._value.beforeCount = ber.readInt(); this._value.afterCount = ber.readInt(); if (ber.peek() === 160) { if (ber.readSequence(160)) { this._value.targetOffset = ber.readInt(); this._value.contentCount = ber.readInt(); } } if (ber.peek() === 129) { this._value.greaterThanOrEqual = ber.readString(129); } return true; } return false; }; __publicField(VirtualListViewRequestControl, "OID", "2.16.840.1.113730.3.4.9"); module2.exports = VirtualListViewRequestControl; } }); // node_modules/@ldapjs/controls/lib/controls/virtual-list-view-response-control.js var require_virtual_list_view_response_control = __commonJS({ "node_modules/@ldapjs/controls/lib/controls/virtual-list-view-response-control.js"(exports, module2) { "use strict"; var { Ber, BerReader, BerWriter } = require_lib(); var isObject = require_is_object(); var hasOwn = require_has_own(); var Control = require_control(); var { resultCodes: RESULT_CODES } = require_protocol(); var validCodeNames = [ "SUCCESS", "OPERATIONS_ERROR", "UNWILLING_TO_PERFORM", "INSUFFICIENT_ACCESS_RIGHTS", "BUSY", "TIME_LIMIT_EXCEEDED", "STRONGER_AUTH_REQUIRED", "ADMIN_LIMIT_EXCEEDED", "SORT_CONTROL_MISSING", "OFFSET_RANGE_ERROR", "CONTROL_ERROR", "OTHER" ]; var filteredCodes = Object.entries(RESULT_CODES).filter(([k, v]) => validCodeNames.includes(k)); var VALID_CODES = new Map([ ...filteredCodes, ...filteredCodes.map(([k, v]) => { return [v, k]; }) ]); var _parse, parse_fn; var _VirtualListViewResponseControl = class extends Control { constructor(options = {}) { options.type = _VirtualListViewResponseControl.OID; options.criticality = false; super(options); __privateAdd(this, _parse); this.value = {}; if (hasOwn(options, "value") === false || !options.value) { throw Error("control not enabled"); } const value = options.value; if (Buffer.isBuffer(value)) { __privateMethod(this, _parse, parse_fn).call(this, options.value); } else if (isObject(value)) { if (VALID_CODES.has(value.result) === false) { throw new Error("Invalid result code"); } this.value = options.value; } else { throw new TypeError("options.value must be a Buffer or Object"); } throw Error("control not enabled"); } get value() { return this._value; } set value(obj) { this._value = Object.assign({}, this._value, obj); } _pojo(obj) { obj.value = this.value; return obj; } _toBer(ber) { if (this.value.length === 0) { return; } const writer = new BerWriter(); writer.startSequence(); if (this.value.targetPosition !== void 0) { writer.writeInt(this.value.targetPosition); } if (this.value.contentCount !== void 0) { writer.writeInt(this.value.contentCount); } writer.writeEnumeration(this.value.result); if (this.value.cookie && this.value.cookie.length > 0) { writer.writeBuffer(this.value.cookie, Ber.OctetString); } else { writer.writeString(""); } writer.endSequence(); ber.writeBuffer(writer.buffer, 4); } }; var VirtualListViewResponseControl = _VirtualListViewResponseControl; _parse = new WeakSet(); parse_fn = function(buffer) { const ber = new BerReader(buffer); if (ber.readSequence()) { this._value = {}; if (ber.peek(2)) { this._value.targetPosition = ber.readInt(); } if (ber.peek(2)) { this._value.contentCount = ber.readInt(); } this._value.result = ber.readEnumeration(); this._value.cookie = ber.readString(Ber.OctetString, true); if (!this._value.cookie) { this._value.cookie = Buffer.alloc(0); } return true; } return false; }; __publicField(VirtualListViewResponseControl, "OID", "2.16.840.1.113730.3.4.10"); __publicField(VirtualListViewResponseControl, "RESPONSE_CODES", Object.freeze(VALID_CODES)); module2.exports = VirtualListViewResponseControl; } }); // node_modules/@ldapjs/controls/index.js var require_controls = __commonJS({ "node_modules/@ldapjs/controls/index.js"(exports, module2) { "use strict"; var { Ber } = require_lib(); var Control = require_control(); var EntryChangeNotificationControl = require_entry_change_notification_control(); var PagedResultsControl = require_paged_results_control(); var PersistentSearchControl = require_persistent_search_control(); var ServerSideSortingRequestControl = require_server_side_sorting_request_control(); var ServerSideSortingResponseControl = require_server_side_sorting_response_control(); var VirtualListViewRequestControl = require_virtual_list_view_request_control(); var VirtualListViewResponseControl = require_virtual_list_view_response_control(); module2.exports = { getControl: function getControl(ber) { if (!ber) throw TypeError("ber must be provided"); if (ber.readSequence() === null) { return null; } let type; const opts = { criticality: false, value: null }; if (ber.length) { const end = ber.offset + ber.length; type = ber.readString(); if (ber.offset < end) { if (ber.peek() === Ber.Boolean) { opts.criticality = ber.readBoolean(); } } if (ber.offset < end) { opts.value = ber.readString(Ber.OctetString, true); } } let control; switch (type) { case EntryChangeNotificationControl.OID: { control = new EntryChangeNotificationControl(opts); break; } case PagedResultsControl.OID: { control = new PagedResultsControl(opts); break; } case PersistentSearchControl.OID: { control = new PersistentSearchControl(opts); break; } case ServerSideSortingRequestControl.OID: { control = new ServerSideSortingRequestControl(opts); break; } case ServerSideSortingResponseControl.OID: { control = new ServerSideSortingResponseControl(opts); break; } case VirtualListViewRequestControl.OID: { control = new VirtualListViewRequestControl(opts); break; } case VirtualListViewResponseControl.OID: { control = new VirtualListViewResponseControl(opts); break; } default: { opts.type = type; control = new Control(opts); break; } } return control; }, Control, EntryChangeNotificationControl, PagedResultsControl, PersistentSearchControl, ServerSideSortingRequestControl, ServerSideSortingResponseControl, VirtualListViewRequestControl, VirtualListViewResponseControl }; } }); // node_modules/@ldapjs/messages/lib/messages/abandon-request.js var require_abandon_request = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/abandon-request.js"(exports, module2) { "use strict"; var LdapMessage = require_ldap_message(); var Protocol = require_protocol(); var warning = require_deprecations(); var _abandonId; var AbandonRequest = class extends LdapMessage { constructor(options = {}) { options.protocolOp = Protocol.operations.LDAP_REQ_ABANDON; super(options); __privateAdd(this, _abandonId, void 0); const abandonId = options.abandonId || options.abandonID || 0; if (options.abandonID) { warning.emit("LDAP_MESSAGE_DEP_003"); } __privateSet(this, _abandonId, abandonId); } get abandonId() { return __privateGet(this, _abandonId); } get abandonID() { warning.emit("LDAP_MESSAGE_DEP_003"); return __privateGet(this, _abandonId); } get type() { return "AbandonRequest"; } _toBer(ber) { ber.writeInt(__privateGet(this, _abandonId), Protocol.operations.LDAP_REQ_ABANDON); return ber; } _pojo(obj = {}) { obj.abandonId = __privateGet(this, _abandonId); return obj; } static parseToPojo(ber) { const protocolOp = ber.peek(); if (protocolOp !== Protocol.operations.LDAP_REQ_ABANDON) { const op = protocolOp.toString(16).padStart(2, "0"); throw Error(`found wrong protocol operation: 0x${op}`); } const abandonId = ber.readInt(Protocol.operations.LDAP_REQ_ABANDON); return { protocolOp, abandonId }; } }; _abandonId = new WeakMap(); module2.exports = AbandonRequest; } }); // node_modules/@ldapjs/attribute/lib/deprecations.js var require_deprecations2 = __commonJS({ "node_modules/@ldapjs/attribute/lib/deprecations.js"(exports, module2) { "use strict"; var warning = require_process_warning()(); var clazz = "LdapjsAttributeWarning"; warning.create(clazz, "LDAP_ATTRIBUTE_DEP_001", "options.vals is deprecated. Use options.values instead."); warning.create(clazz, "LDAP_ATTRIBUTE_DEP_002", "Instance method .parse is deprecated. Use static .fromBer instead."); warning.create(clazz, "LDAP_ATTRIBUTE_DEP_003", "Instance property .vals is deprecated. Use property .values instead."); module2.exports = warning; } }); // node_modules/@ldapjs/attribute/index.js var require_attribute = __commonJS({ "node_modules/@ldapjs/attribute/index.js"(exports, module2) { "use strict"; var { core: { LBER_SET } } = require_protocol(); var { BerTypes, BerReader, BerWriter } = require_asn1(); var warning = require_deprecations2(); var _buffers, _type; var _Attribute = class { constructor(options = {}) { __privateAdd(this, _buffers, []); __privateAdd(this, _type, void 0); if (options.type && typeof options.type !== "string") { throw TypeError("options.type must be a string"); } this.type = options.type || ""; const values = options.values || options.vals || []; if (options.vals) { warning.emit("LDAP_ATTRIBUTE_DEP_001"); } this.values = values; } get [Symbol.toStringTag]() { return "LdapAttribute"; } get buffers() { return __privateGet(this, _buffers).slice(0); } get pojo() { return { type: this.type, values: this.values }; } get type() { return __privateGet(this, _type); } set type(name) { __privateSet(this, _type, name); } get values() { const encoding = _bufferEncoding(__privateGet(this, _type)); return __privateGet(this, _buffers).map(function(v) { return v.toString(encoding); }); } set values(vals) { if (Array.isArray(vals) === false) { return this.addValue(vals); } for (const value of vals) { this.addValue(value); } } get vals() { warning.emit("LDAP_ATTRIBUTE_DEP_003"); return this.values; } set vals(values) { warning.emit("LDAP_ATTRIBUTE_DEP_003"); this.values = values; } addValue(value) { if (Buffer.isBuffer(value)) { __privateGet(this, _buffers).push(value); } else { __privateGet(this, _buffers).push(Buffer.from(value + "", _bufferEncoding(__privateGet(this, _type)))); } } parse(ber) { const attr = _Attribute.fromBer(ber); __privateSet(this, _type, attr.type); this.values = attr.values; } toBer() { const ber = new BerWriter(); ber.startSequence(); ber.writeString(this.type); ber.startSequence(LBER_SET); if (__privateGet(this, _buffers).length > 0) { for (const buffer of __privateGet(this, _buffers)) { ber.writeByte(BerTypes.OctetString); ber.writeLength(buffer.length); ber.appendBuffer(buffer); } } else { ber.writeStringArray([]); } ber.endSequence(); ber.endSequence(); return new BerReader(ber.buffer); } toJSON() { return this.pojo; } static compare(attr1, attr2) { if (_Attribute.isAttribute(attr1) === false || _Attribute.isAttribute(attr2) === false) { throw TypeError("can only compare Attribute instances"); } if (attr1.type < attr2.type) return -1; if (attr1.type > attr2.type) return 1; const aValues = attr1.values; const bValues = attr2.values; if (aValues.length < bValues.length) return -1; if (aValues.length > bValues.length) return 1; for (let i = 0; i < aValues.length; i++) { if (aValues[i] < bValues[i]) return -1; if (aValues[i] > bValues[i]) return 1; } return 0; } static fromBer(ber) { ber.readSequence(); const type = ber.readString(); const values = []; if (ber.peek() === LBER_SET) { if (ber.readSequence(LBER_SET)) { const end = ber.offset + ber.length; while (ber.offset < end) { values.push(ber.readString(BerTypes.OctetString, true)); } } } const result = new _Attribute({ type, values }); return result; } static fromObject(obj) { const attributes = []; for (const [key, value] of Object.entries(obj)) { if (Array.isArray(value) === true) { attributes.push(new _Attribute({ type: key, values: value })); } else { attributes.push(new _Attribute({ type: key, values: [value] })); } } return attributes; } static isAttribute(attr) { if (typeof attr !== "object") { return false; } if (Object.prototype.toString.call(attr) === "[object LdapAttribute]") { return true; } const typeOk = typeof attr.type === "string"; let valuesOk = Array.isArray(attr.values); if (valuesOk === true) { for (const val of attr.values) { if (typeof val !== "string" && Buffer.isBuffer(val) === false) { valuesOk = false; break; } } } if (typeOk === true && valuesOk === true) { return true; } return false; } }; var Attribute = _Attribute; _buffers = new WeakMap(); _type = new WeakMap(); module2.exports = Attribute; function _bufferEncoding(type) { return /;binary$/.test(type) ? "base64" : "utf8"; } } }); // node_modules/@ldapjs/dn/lib/deprecations.js var require_deprecations3 = __commonJS({ "node_modules/@ldapjs/dn/lib/deprecations.js"(exports, module2) { "use strict"; var warning = require_process_warning()(); var clazz = "LdapjsDnWarning"; warning.create(clazz, "LDAP_DN_DEP_001", "attribute options is deprecated and are ignored"); warning.create(clazz, "LDAP_DN_DEP_002", ".format() is deprecated. Use .toString() instead"); warning.create(clazz, "LDAP_DN_DEP_003", ".set() is deprecated. Use .setAttribute() instead"); warning.create(clazz, "LDAP_DN_DEP_004", ".setFormat() is deprecated. Options will be ignored"); module2.exports = warning; } }); // node_modules/@ldapjs/dn/lib/utils/escape-value.js var require_escape_value = __commonJS({ "node_modules/@ldapjs/dn/lib/utils/escape-value.js"(exports, module2) { "use strict"; module2.exports = function escapeValue(value) { if (typeof value !== "string") { throw Error("value must be a string"); } const toEscape = Buffer.from(value, "utf8"); const escaped = []; const embeddedReservedChars = [ 34, 43, 44, 59, 60, 62 ]; for (let i = 0; i < toEscape.byteLength; ) { const charHex = toEscape[i]; if (i === 0 && (charHex === 32 || charHex === 35)) { escaped.push(toEscapedHexString(charHex)); i += 1; continue; } if (i === toEscape.byteLength - 1 && charHex === 32) { escaped.push(toEscapedHexString(charHex)); i += 1; continue; } if (embeddedReservedChars.includes(charHex) === true) { escaped.push(toEscapedHexString(charHex)); i += 1; continue; } if (charHex >= 192 && charHex <= 223) { escaped.push(toEscapedHexString(charHex)); escaped.push(toEscapedHexString(toEscape[i + 1])); i += 2; continue; } if (charHex >= 224 && charHex <= 239) { escaped.push(toEscapedHexString(charHex)); escaped.push(toEscapedHexString(toEscape[i + 1])); escaped.push(toEscapedHexString(toEscape[i + 2])); i += 3; continue; } if (charHex >= 240 && charHex <= 247) { escaped.push(toEscapedHexString(charHex)); escaped.push(toEscapedHexString(toEscape[i + 1])); escaped.push(toEscapedHexString(toEscape[i + 2])); escaped.push(toEscapedHexString(toEscape[i + 3])); i += 4; continue; } if (charHex <= 31) { escaped.push(toEscapedHexString(charHex)); i += 1; continue; } escaped.push(String.fromCharCode(charHex)); i += 1; continue; } return escaped.join(""); }; function toEscapedHexString(char) { return "\\" + char.toString(16).padStart(2, "0"); } } }); // node_modules/@ldapjs/dn/lib/utils/is-dotted-decimal.js var require_is_dotted_decimal = __commonJS({ "node_modules/@ldapjs/dn/lib/utils/is-dotted-decimal.js"(exports, module2) { "use strict"; var partIsNotNumeric = (part) => /^\d+$/.test(part) === false; module2.exports = function isDottedDecimal(value) { if (typeof value !== "string") return false; const parts = value.split("."); const nonNumericParts = parts.filter(partIsNotNumeric); return nonNumericParts.length === 0; }; } }); // node_modules/@ldapjs/dn/lib/rdn.js var require_rdn = __commonJS({ "node_modules/@ldapjs/dn/lib/rdn.js"(exports, module2) { "use strict"; var warning = require_deprecations3(); var escapeValue = require_escape_value(); var isDottedDecimal = require_is_dotted_decimal(); var _attributes; var RDN = class { constructor(rdn = {}) { __privateAdd(this, _attributes, /* @__PURE__ */ new Map()); for (const [key, val] of Object.entries(rdn)) { this.setAttribute({ name: key, value: val }); } } get [Symbol.toStringTag]() { return "LdapRdn"; } get size() { return __privateGet(this, _attributes).size; } equals(rdn) { if (Object.prototype.toString.call(rdn) !== "[object LdapRdn]") { return false; } if (this.size !== rdn.size) { return false; } for (const key of this.keys()) { if (rdn.has(key) === false) return false; if (this.getValue(key) !== rdn.getValue(key)) return false; } return true; } getValue(name) { var _a; return (_a = __privateGet(this, _attributes).get(name)) == null ? void 0 : _a.value; } has(name) { return __privateGet(this, _attributes).has(name); } keys() { return __privateGet(this, _attributes).keys(); } setAttribute({ name, value, options = {} }) { if (typeof name !== "string") { throw Error("name must be a string"); } const valType = Object.prototype.toString.call(value); if (typeof value !== "string" && valType !== "[object BerReader]") { throw Error("value must be a string or BerReader"); } if (Object.prototype.toString.call(options) !== "[object Object]") { throw Error("options must be an object"); } const startsWithAlpha = (str) => /^[a-zA-Z]/.test(str) === true; if (startsWithAlpha(name) === false && isDottedDecimal(name) === false) { throw Error("attribute name must start with an ASCII alpha character or be a numeric OID"); } const attr = { value, name }; for (const [key, val] of Object.entries(options)) { warning.emit("LDAP_DN_DEP_001"); if (key === "value") continue; attr[key] = val; } __privateGet(this, _attributes).set(name, attr); } toString({ unescaped = false } = {}) { let result = ""; const isHexEncodedValue = (val) => /^#([0-9a-fA-F]{2})+$/.test(val) === true; for (const entry of __privateGet(this, _attributes).values()) { result += entry.name + "="; if (isHexEncodedValue(entry.value)) { result += entry.value; } else if (Object.prototype.toString.call(entry.value) === "[object BerReader]") { let encoded = "#"; for (const byte of entry.value.buffer) { encoded += Number(byte).toString(16).padStart(2, "0"); } result += encoded; } else { result += unescaped === false ? escapeValue(entry.value) : entry.value; } result += "+"; } return result.substring(0, result.length - 1); } format() { warning.emit("LDAP_DN_DEP_002"); return this.toString(); } set(name, value, options) { warning.emit("LDAP_DN_DEP_003"); this.setAttribute({ name, value, options }); } static isRdn(rdn) { if (Object.prototype.toString.call(rdn) === "[object LdapRdn]") { return true; } const isObject = Object.prototype.toString.call(rdn) === "[object Object]"; if (isObject === false) { return false; } if (typeof rdn.name === "string" && typeof rdn.value === "string") { return true; } for (const value of Object.values(rdn)) { if (typeof value !== "string" && Object.prototype.toString.call(value) !== "[object BerReader]") return false; } return true; } }; _attributes = new WeakMap(); module2.exports = RDN; } }); // node_modules/@ldapjs/dn/lib/utils/parse-string/find-name-start.js var require_find_name_start = __commonJS({ "node_modules/@ldapjs/dn/lib/utils/parse-string/find-name-start.js"(exports, module2) { "use strict"; var isLeadChar = (c) => /[a-zA-Z0-9]/.test(c) === true; module2.exports = function findNameStart({ searchBuffer, startPos }) { let pos = startPos; while (pos < searchBuffer.byteLength) { if (searchBuffer[pos] === 32 || searchBuffer[pos] === 44) { pos += 1; continue; } const char = String.fromCharCode(searchBuffer[pos]); if (isLeadChar(char) === true) { return pos; } break; } return -1; }; } }); // node_modules/@ldapjs/dn/lib/utils/parse-string/find-name-end.js var require_find_name_end = __commonJS({ "node_modules/@ldapjs/dn/lib/utils/parse-string/find-name-end.js"(exports, module2) { "use strict"; module2.exports = function findNameEnd({ searchBuffer, startPos }) { let pos = startPos; while (pos < searchBuffer.byteLength) { const char = searchBuffer[pos]; if (char === 32 || char === 61) { break; } if (isValidNameChar(char) === true) { pos += 1; continue; } return -1; } return pos; }; function isValidNameChar(c) { if (c >= 65 && c <= 90) { return true; } if (c >= 97 && c <= 122) { return true; } if (c >= 48 && c <= 57) { return true; } if (c === 45 || c === 46) { return true; } return false; } } }); // node_modules/@ldapjs/dn/lib/utils/parse-string/is-valid-attribute-type-name.js var require_is_valid_attribute_type_name = __commonJS({ "node_modules/@ldapjs/dn/lib/utils/parse-string/is-valid-attribute-type-name.js"(exports, module2) { "use strict"; var isDigit = (c) => /[0-9]/.test(c) === true; var hasKeyChars = (input) => /[a-zA-Z-]/.test(input) === true; var isValidLeadChar = (c) => /[a-zA-Z]/.test(c) === true; var hasInvalidChars = (input) => /[^a-zA-Z0-9-]/.test(input) === true; module2.exports = function isValidAttributeTypeName(name) { if (isDigit(name[0]) === true) { return hasKeyChars(name) === false; } if (isValidLeadChar(name[0]) === false) { return false; } return hasInvalidChars(name) === false; }; } }); // node_modules/@ldapjs/dn/lib/utils/parse-string/read-hex-string.js var require_read_hex_string = __commonJS({ "node_modules/@ldapjs/dn/lib/utils/parse-string/read-hex-string.js"(exports, module2) { "use strict"; var { BerReader } = require_asn1(); var isValidHexCode = (code) => /[0-9a-fA-F]{2}/.test(code) === true; module2.exports = function readHexString({ searchBuffer, startPos }) { const bytes = []; let pos = startPos; while (pos < searchBuffer.byteLength) { if (isEndChar(searchBuffer[pos])) { break; } const hexPair = String.fromCharCode(searchBuffer[pos]) + String.fromCharCode(searchBuffer[pos + 1]); if (isValidHexCode(hexPair) === false) { throw Error("invalid hex pair encountered: 0x" + hexPair); } bytes.push(parseInt(hexPair, 16)); pos += 2; } return { endPos: pos, berReader: new BerReader(Buffer.from(bytes)) }; }; function isEndChar(c) { switch (c) { case 32: case 43: case 44: case 59: return true; default: return false; } } } }); // node_modules/@ldapjs/dn/lib/utils/parse-string/read-escape-sequence.js var require_read_escape_sequence = __commonJS({ "node_modules/@ldapjs/dn/lib/utils/parse-string/read-escape-sequence.js"(exports, module2) { "use strict"; module2.exports = function readEscapeSequence({ searchBuffer, startPos }) { let pos = startPos; const buf = []; while (pos < searchBuffer.byteLength) { const char = searchBuffer[pos]; const nextChar = searchBuffer[pos + 1]; if (char !== 92) { break; } const strHexCode = String.fromCharCode(nextChar) + String.fromCharCode(searchBuffer[pos + 2]); const hexCode = parseInt(strHexCode, 16); if (Number.isNaN(hexCode) === true) { if (nextChar >= 0 && nextChar <= 127) { buf.push(nextChar); pos += 2; continue; } else { throw Error("invalid hex code in escape sequence"); } } if (hexCode >= 192 && hexCode <= 223) { const secondByte = parseInt(String.fromCharCode(searchBuffer[pos + 4]) + String.fromCharCode(searchBuffer[pos + 5]), 16); buf.push(hexCode); buf.push(secondByte); pos += 6; continue; } if (hexCode >= 224 && hexCode <= 239) { const secondByte = parseInt(String.fromCharCode(searchBuffer[pos + 4]) + String.fromCharCode(searchBuffer[pos + 5]), 16); const thirdByte = parseInt(String.fromCharCode(searchBuffer[pos + 7]) + String.fromCharCode(searchBuffer[pos + 8]), 16); buf.push(hexCode); buf.push(secondByte); buf.push(thirdByte); pos += 9; continue; } if (hexCode >= 240 && hexCode <= 247) { const secondByte = parseInt(String.fromCharCode(searchBuffer[pos + 4]) + String.fromCharCode(searchBuffer[pos + 5]), 16); const thirdByte = parseInt(String.fromCharCode(searchBuffer[pos + 7]) + String.fromCharCode(searchBuffer[pos + 8]), 16); const fourthByte = parseInt(String.fromCharCode(searchBuffer[pos + 10]) + String.fromCharCode(searchBuffer[pos + 11]), 16); buf.push(hexCode); buf.push(secondByte); buf.push(thirdByte); buf.push(fourthByte); pos += 12; continue; } buf.push(hexCode); pos += 3; } return { endPos: pos, parsed: Buffer.from(buf) }; }; } }); // node_modules/@ldapjs/dn/lib/utils/parse-string/read-attribute-value.js var require_read_attribute_value = __commonJS({ "node_modules/@ldapjs/dn/lib/utils/parse-string/read-attribute-value.js"(exports, module2) { "use strict"; var readHexString = require_read_hex_string(); var readEscapeSequence = require_read_escape_sequence(); module2.exports = function readAttributeValue({ searchBuffer, startPos }) { let pos = startPos; while (pos < searchBuffer.byteLength && searchBuffer[pos] === 32) { pos += 1; } if (pos >= searchBuffer.byteLength || searchBuffer[pos] !== 61) { throw Error("attribute value does not start with equals sign"); } pos += 1; while (pos <= searchBuffer.byteLength && searchBuffer[pos] === 32) { pos += 1; } if (pos >= searchBuffer.byteLength) { return { endPos: pos, value: "" }; } if (searchBuffer[pos] === 35) { const result = readHexString({ searchBuffer, startPos: pos + 1 }); pos = result.endPos; return { endPos: pos, value: result.berReader }; } const readValueResult = readValueString({ searchBuffer, startPos: pos }); pos = readValueResult.endPos; return { endPos: pos, value: readValueResult.value.toString("utf8").trim() }; }; function readValueString({ searchBuffer, startPos }) { let pos = startPos; let inQuotes = false; let endQuotePresent = false; const bytes = []; while (pos <= searchBuffer.byteLength) { const char = searchBuffer[pos]; if (pos === searchBuffer.byteLength) { if (inQuotes === true && endQuotePresent === false) { throw Error("missing ending double quote for attribute value"); } break; } if (char === 34) { if (inQuotes === true) { pos += 1; endQuotePresent = true; while (pos < searchBuffer.byteLength) { const nextChar = searchBuffer[pos]; if (isEndChar(nextChar) === true) { break; } if (nextChar !== 32) { throw Error("significant rdn character found outside of quotes at position " + pos); } pos += 1; } break; } if (pos !== startPos) { throw Error('unexpected quote (") in rdn string at position ' + pos); } inQuotes = true; pos += 1; continue; } if (isEndChar(char) === true && inQuotes === false) { break; } if (char === 92) { const seqResult = readEscapeSequence({ searchBuffer, startPos: pos }); pos = seqResult.endPos; Array.prototype.push.apply(bytes, seqResult.parsed); continue; } bytes.push(char); pos += 1; } return { endPos: pos, value: Buffer.from(bytes) }; } function isEndChar(c) { switch (c) { case 43: case 44: case 59: return true; default: return false; } } } }); // node_modules/@ldapjs/dn/lib/utils/parse-string/read-attribute-pair.js var require_read_attribute_pair = __commonJS({ "node_modules/@ldapjs/dn/lib/utils/parse-string/read-attribute-pair.js"(exports, module2) { "use strict"; var findNameStart = require_find_name_start(); var findNameEnd = require_find_name_end(); var isValidAttributeTypeName = require_is_valid_attribute_type_name(); var readAttributeValue = require_read_attribute_value(); module2.exports = function readAttributePair({ searchBuffer, startPos }) { let pos = startPos; const nameStartPos = findNameStart({ searchBuffer, startPos: pos }); if (nameStartPos < 0) { throw Error("invalid attribute name leading character encountered"); } const nameEndPos = findNameEnd({ searchBuffer, startPos: nameStartPos }); if (nameStartPos < 0) { throw Error("invalid character in attribute name encountered"); } const attributeName = searchBuffer.subarray(nameStartPos, nameEndPos).toString("utf8"); if (isValidAttributeTypeName(attributeName) === false) { throw Error("invalid attribute type name: " + attributeName); } const valueReadResult = readAttributeValue({ searchBuffer, startPos: nameEndPos }); pos = valueReadResult.endPos; const attributeValue = valueReadResult.value; return { endPos: pos, pair: { [attributeName]: attributeValue } }; }; } }); // node_modules/@ldapjs/dn/lib/utils/parse-string/index.js var require_parse_string = __commonJS({ "node_modules/@ldapjs/dn/lib/utils/parse-string/index.js"(exports, module2) { "use strict"; var readAttributePair = require_read_attribute_pair(); module2.exports = function parseString(input) { if (typeof input !== "string") { throw Error("input must be a string"); } if (input.length === 0) { return []; } const searchBuffer = Buffer.from(input, "utf8"); const length = searchBuffer.byteLength; const rdns = []; let pos = 0; let rdn = {}; readRdnLoop: while (pos <= length) { if (pos === length) { const char = searchBuffer[pos - 1]; if (char === 43 || char === 44 || char === 59) { throw Error("rdn string ends abruptly with character: " + String.fromCharCode(char)); } } while (pos < length && searchBuffer[pos] === 32) { pos += 1; } const readAttrPairResult = readAttributePair({ searchBuffer, startPos: pos }); pos = readAttrPairResult.endPos; rdn = __spreadValues(__spreadValues({}, rdn), readAttrPairResult.pair); if (pos >= length) { rdns.push(rdn); break; } while (pos < length) { const char = searchBuffer[pos]; if (char === 43) { pos += 1; continue readRdnLoop; } if (char === 44 || char === 59) { rdns.push(rdn); rdn = {}; pos += 1; continue readRdnLoop; } } } return rdns; }; } }); // node_modules/@ldapjs/dn/lib/dn.js var require_dn = __commonJS({ "node_modules/@ldapjs/dn/lib/dn.js"(exports, module2) { "use strict"; var warning = require_deprecations3(); var RDN = require_rdn(); var parseString = require_parse_string(); var _rdns; var _DN = class { constructor({ rdns = [] } = {}) { __privateAdd(this, _rdns, []); if (Array.isArray(rdns) === false) { throw Error("rdns must be an array"); } const hasNonRdn = rdns.some((r) => RDN.isRdn(r) === false); if (hasNonRdn === true) { throw Error("rdns must be an array of RDN objects"); } Array.prototype.push.apply(__privateGet(this, _rdns), rdns.map((r) => { if (Object.prototype.toString.call(r) === "[object LdapRdn]") { return r; } return new RDN(r); })); } get [Symbol.toStringTag]() { return "LdapDn"; } get length() { return __privateGet(this, _rdns).length; } childOf(dn) { if (typeof dn === "string") { const parsedDn = _DN.fromString(dn); return parsedDn.parentOf(this); } return dn.parentOf(this); } clone() { return new _DN({ rdns: __privateGet(this, _rdns) }); } equals(dn) { if (typeof dn === "string") { const parsedDn = _DN.fromString(dn); return parsedDn.equals(this); } if (this.length !== dn.length) return false; for (let i = 0; i < this.length; i += 1) { if (__privateGet(this, _rdns)[i].equals(dn.rdnAt(i)) === false) { return false; } } return true; } format() { warning.emit("LDAP_DN_DEP_002"); return this.toString(); } isEmpty() { return __privateGet(this, _rdns).length === 0; } parent() { if (this.length === 0) return void 0; const save = this.shift(); const dn = new _DN({ rdns: __privateGet(this, _rdns) }); this.unshift(save); return dn; } parentOf(dn) { if (typeof dn === "string") { const parsedDn = _DN.fromString(dn); return this.parentOf(parsedDn); } if (this.length >= dn.length) { return false; } const numberOfElementsDifferent = dn.length - this.length; for (let i = this.length - 1; i >= 0; i -= 1) { const myRdn = __privateGet(this, _rdns)[i]; const theirRdn = dn.rdnAt(i + numberOfElementsDifferent); if (myRdn.equals(theirRdn) === false) { return false; } } return true; } pop() { return __privateGet(this, _rdns).pop(); } push(rdn) { if (Object.prototype.toString.call(rdn) !== "[object LdapRdn]") { throw Error("rdn must be a RDN instance"); } return __privateGet(this, _rdns).push(rdn); } rdnAt(index) { return __privateGet(this, _rdns)[index]; } reverse() { __privateGet(this, _rdns).reverse(); return this; } setFormat() { warning.emit("LDAP_DN_DEP_004"); } shift() { return __privateGet(this, _rdns).shift(); } toString() { let result = ""; for (const rdn of __privateGet(this, _rdns)) { const rdnString = rdn.toString(); result += `,${rdnString}`; } return result.substring(1); } unshift(rdn) { if (Object.prototype.toString.call(rdn) !== "[object LdapRdn]") { throw Error("rdn must be a RDN instance"); } return __privateGet(this, _rdns).unshift(rdn); } static isDn(dn) { if (Object.prototype.toString.call(dn) === "[object LdapDn]") { return true; } if (Object.prototype.toString.call(dn) !== "[object Object]" || Array.isArray(dn.rdns) === false) { return false; } if (dn.rdns.some((dn2) => RDN.isRdn(dn2) === false) === true) { return false; } return true; } static fromString(dnString) { const rdns = parseString(dnString); return new _DN({ rdns }); } }; var DN = _DN; _rdns = new WeakMap(); module2.exports = DN; } }); // node_modules/@ldapjs/dn/index.js var require_dn2 = __commonJS({ "node_modules/@ldapjs/dn/index.js"(exports, module2) { "use strict"; module2.exports = { DN: require_dn(), RDN: require_rdn() }; } }); // node_modules/@ldapjs/messages/lib/messages/add-request.js var require_add_request = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/add-request.js"(exports, module2) { "use strict"; var LdapMessage = require_ldap_message(); var Attribute = require_attribute(); var Protocol = require_protocol(); var { DN } = require_dn2(); var _entry, _attributes; var AddRequest = class extends LdapMessage { constructor(options = {}) { options.protocolOp = Protocol.operations.LDAP_REQ_ADD; super(options); __privateAdd(this, _entry, void 0); __privateAdd(this, _attributes, []); this.entry = options.entry || null; this.attributes = options.attributes || []; } get attributes() { return __privateGet(this, _attributes).slice(0); } set attributes(attrs) { if (Array.isArray(attrs) === false) { throw Error("attrs must be an array"); } const newAttrs = []; for (const attr of attrs) { if (Attribute.isAttribute(attr) === false) { throw Error("attr must be an Attribute instance or Attribute-like object"); } if (Object.prototype.toString.call(attr) !== "[object LdapAttribute]") { newAttrs.push(new Attribute(attr)); continue; } newAttrs.push(attr); } __privateSet(this, _attributes, newAttrs); } get entry() { var _a; return (_a = __privateGet(this, _entry)) != null ? _a : null; } set entry(path) { if (path === null) return; if (typeof path === "string") { __privateSet(this, _entry, DN.fromString(path)); } else if (Object.prototype.toString.call(path) === "[object LdapDn]") { __privateSet(this, _entry, path); } else { throw Error("entry must be a valid DN string or instance of LdapDn"); } } get _dn() { return this.entry; } get type() { return "AddRequest"; } addAttribute(attr) { if (Object.prototype.toString.call(attr) !== "[object LdapAttribute]") { throw Error("attr must be an instance of Attribute"); } __privateGet(this, _attributes).push(attr); } attributeNames() { return __privateGet(this, _attributes).map((attr) => attr.type); } getAttribute(attributeName) { if (typeof attributeName !== "string") { throw Error("attributeName must be a string"); } for (const attr of __privateGet(this, _attributes)) { if (attr.type === attributeName) { return attr; } } return null; } indexOf(attributeName) { if (typeof attributeName !== "string") { throw Error("attributeName must be a string"); } for (let i = 0; i < __privateGet(this, _attributes).length; i += 1) { if (__privateGet(this, _attributes)[i].type === attributeName) { return i; } } return -1; } _toBer(ber) { ber.startSequence(Protocol.operations.LDAP_REQ_ADD); ber.writeString(__privateGet(this, _entry).toString()); ber.startSequence(); for (const attr of __privateGet(this, _attributes)) { const attrBer = attr.toBer(); ber.appendBuffer(attrBer.buffer); } ber.endSequence(); ber.endSequence(); return ber; } _pojo(obj = {}) { obj.entry = __privateGet(this, _entry) ? __privateGet(this, _entry).toString() : null; obj.attributes = []; for (const attr of __privateGet(this, _attributes)) { obj.attributes.push(attr.pojo); } return obj; } static parseToPojo(ber) { const protocolOp = ber.readSequence(); if (protocolOp !== Protocol.operations.LDAP_REQ_ADD) { const op = protocolOp.toString(16).padStart(2, "0"); throw Error(`found wrong protocol operation: 0x${op}`); } const entry = ber.readString(); const attributes = []; ber.readSequence(); const endOfAttributesPos = ber.offset + ber.length; while (ber.offset < endOfAttributesPos) { const attribute = Attribute.fromBer(ber); attribute.type = attribute.type.toLowerCase(); if (attribute.type === "objectclass") { for (let i = 0; i < attribute.values.length; i++) { attribute.values[i] = attribute.values[i].toLowerCase(); } } attributes.push(attribute); } return { protocolOp, entry, attributes }; } }; _entry = new WeakMap(); _attributes = new WeakMap(); module2.exports = AddRequest; } }); // node_modules/@ldapjs/messages/lib/messages/bind-request.js var require_bind_request = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/bind-request.js"(exports, module2) { "use strict"; var LdapMessage = require_ldap_message(); var Protocol = require_protocol(); var { BerTypes } = require_asn1(); var _version, _name, _authentication, _credentials; var _BindRequest = class extends LdapMessage { constructor(options = {}) { options.protocolOp = Protocol.operations.LDAP_REQ_BIND; super(options); __privateAdd(this, _version, 3); __privateAdd(this, _name, void 0); __privateAdd(this, _authentication, _BindRequest.SIMPLE_BIND); __privateAdd(this, _credentials, ""); const { version = 3, name = null, authentication = _BindRequest.SIMPLE_BIND, credentials = "" } = options; __privateSet(this, _version, version); __privateSet(this, _name, name); __privateSet(this, _authentication, authentication); __privateSet(this, _credentials, credentials); } get credentials() { return __privateGet(this, _credentials); } get name() { return __privateGet(this, _name); } get type() { return "BindRequest"; } get version() { return __privateGet(this, _version); } get _dn() { return __privateGet(this, _name); } _toBer(ber) { ber.startSequence(Protocol.operations.LDAP_REQ_BIND); ber.writeInt(__privateGet(this, _version)); ber.writeString(__privateGet(this, _name) || ""); ber.writeString(__privateGet(this, _credentials) || "", BerTypes.Context); ber.endSequence(); return ber; } _pojo(obj = {}) { obj.version = __privateGet(this, _version); obj.name = __privateGet(this, _name); obj.authenticationType = __privateGet(this, _authentication); obj.credentials = __privateGet(this, _credentials); return obj; } static parseToPojo(ber) { const protocolOp = ber.readSequence(); if (protocolOp !== Protocol.operations.LDAP_REQ_BIND) { const op = protocolOp.toString(16).padStart(2, "0"); throw Error(`found wrong protocol operation: 0x${op}`); } const version = ber.readInt(); const name = ber.readString(); const tag = ber.peek(); if (tag !== BerTypes.Context) { const authType = tag.toString(16).padStart(2, "0"); throw Error(`authentication 0x${authType} not supported`); } const authentication = _BindRequest.SIMPLE_BIND; const credentials = ber.readString(BerTypes.Context); return { protocolOp, version, name, authentication, credentials }; } }; var BindRequest = _BindRequest; _version = new WeakMap(); _name = new WeakMap(); _authentication = new WeakMap(); _credentials = new WeakMap(); __publicField(BindRequest, "SIMPLE_BIND", "simple"); __publicField(BindRequest, "SASL_BIND", "sasl"); module2.exports = BindRequest; } }); // node_modules/@ldapjs/messages/lib/messages/compare-request.js var require_compare_request = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/compare-request.js"(exports, module2) { "use strict"; var { operations } = require_protocol(); var { DN } = require_dn2(); var LdapMessage = require_ldap_message(); var _attribute, _entry, _value; var CompareRequest = class extends LdapMessage { constructor(options = {}) { options.protocolOp = operations.LDAP_REQ_COMPARE; super(options); __privateAdd(this, _attribute, void 0); __privateAdd(this, _entry, void 0); __privateAdd(this, _value, void 0); this.attribute = options.attribute || ""; this.entry = options.entry || null; this.value = options.value || ""; } get attribute() { return __privateGet(this, _attribute); } set attribute(value) { __privateSet(this, _attribute, value); } get entry() { var _a; return (_a = __privateGet(this, _entry)) != null ? _a : null; } set entry(value) { if (value === null) return; if (typeof value === "string") { __privateSet(this, _entry, DN.fromString(value)); } else if (Object.prototype.toString.call(value) === "[object LdapDn]") { __privateSet(this, _entry, value); } else { throw Error("entry must be a valid DN string or instance of LdapDn"); } } get type() { return "CompareRequest"; } get value() { return __privateGet(this, _value); } set value(value) { __privateSet(this, _value, value); } get _dn() { return __privateGet(this, _entry); } _toBer(ber) { ber.startSequence(operations.LDAP_REQ_COMPARE); ber.writeString(__privateGet(this, _entry).toString()); ber.startSequence(); ber.writeString(__privateGet(this, _attribute)); ber.writeString(__privateGet(this, _value)); ber.endSequence(); ber.endSequence(); return ber; } _pojo(obj = {}) { obj.attribute = __privateGet(this, _attribute); obj.entry = __privateGet(this, _entry) ? __privateGet(this, _entry).toString() : null; obj.value = __privateGet(this, _value); return obj; } static parseToPojo(ber) { const protocolOp = ber.readSequence(); if (protocolOp !== operations.LDAP_REQ_COMPARE) { const op = protocolOp.toString(16).padStart(2, "0"); throw Error(`found wrong protocol operation: 0x${op}`); } const entry = ber.readString(); ber.readSequence(); const attribute = ber.readString(); const value = ber.readString(); return { protocolOp, entry, attribute, value }; } }; _attribute = new WeakMap(); _entry = new WeakMap(); _value = new WeakMap(); module2.exports = CompareRequest; } }); // node_modules/@ldapjs/messages/lib/messages/delete-request.js var require_delete_request = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/delete-request.js"(exports, module2) { "use strict"; var LdapMessage = require_ldap_message(); var Protocol = require_protocol(); var { DN } = require_dn2(); var _entry; var DeleteRequest = class extends LdapMessage { constructor(options = {}) { var _a; options.protocolOp = Protocol.operations.LDAP_REQ_DELETE; super(options); __privateAdd(this, _entry, void 0); this.entry = (_a = options.entry) != null ? _a : null; } get _dn() { return this.entry; } get entry() { var _a; return (_a = __privateGet(this, _entry)) != null ? _a : null; } set entry(value) { if (value === null) return; if (typeof value === "string") { __privateSet(this, _entry, DN.fromString(value)); } else if (Object.prototype.toString.call(value) === "[object LdapDn]") { __privateSet(this, _entry, value); } else { throw Error("entry must be a valid DN string or instance of LdapDn"); } } get type() { return "DeleteRequest"; } _toBer(ber) { ber.writeString(__privateGet(this, _entry).toString(), Protocol.operations.LDAP_REQ_DELETE); return ber; } _pojo(obj = {}) { obj.protocolOp = Protocol.operations.LDAP_REQ_DELETE; obj.entry = __privateGet(this, _entry) ? __privateGet(this, _entry).toString() : null; return obj; } static parseToPojo(ber) { const protocolOp = ber.peek(); if (protocolOp !== Protocol.operations.LDAP_REQ_DELETE) { const op = protocolOp.toString(16).padStart(2, "0"); throw Error(`found wrong protocol operation: 0x${op}`); } const entry = ber.readString(Protocol.operations.LDAP_REQ_DELETE); return { protocolOp, entry }; } }; _entry = new WeakMap(); module2.exports = DeleteRequest; } }); // node_modules/@ldapjs/messages/lib/messages/extension-utils/recognized-oids.js var require_recognized_oids = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/extension-utils/recognized-oids.js"(exports, module2) { "use strict"; var OIDS = /* @__PURE__ */ new Map([ ["CANCEL_REQUEST", "1.3.6.1.1.8"], ["DISCONNECTION_NOTIFICATION", "1.3.6.1.4.1.1466.20036"], ["PASSWORD_MODIFY", "1.3.6.1.4.1.4203.1.11.1"], ["START_TLS", "1.3.6.1.4.1.1466.20037"], ["WHO_AM_I", "1.3.6.1.4.1.4203.1.11.3"] ]); Object.defineProperty(OIDS, "lookupName", { value: function(oid) { for (const [key, value] of this.entries()) { if (value === oid) return key; } } }); Object.defineProperty(OIDS, "lookupOID", { value: function(name) { for (const [key, value] of this.entries()) { if (key === name) return value; } } }); module2.exports = OIDS; } }); // node_modules/@ldapjs/messages/lib/messages/extension-request.js var require_extension_request = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/extension-request.js"(exports, module2) { "use strict"; var LdapMessage = require_ldap_message(); var { operations } = require_protocol(); var RECOGNIZED_OIDS = require_recognized_oids(); var _requestName, _requestValue; var ExtensionRequest = class extends LdapMessage { constructor(options = {}) { options.protocolOp = operations.LDAP_REQ_EXTENSION; super(options); __privateAdd(this, _requestName, void 0); __privateAdd(this, _requestValue, void 0); this.requestName = options.requestName || ""; this.requestValue = options.requestValue; } get _dn() { return __privateGet(this, _requestName); } get requestName() { return __privateGet(this, _requestName); } set requestName(value) { __privateSet(this, _requestName, value); } get type() { return "ExtensionRequest"; } get requestValue() { return __privateGet(this, _requestValue); } set requestValue(val) { __privateSet(this, _requestValue, val); } _toBer(ber) { ber.startSequence(operations.LDAP_REQ_EXTENSION); ber.writeString(this.requestName, 128); if (this.requestValue) { switch (this.requestName) { case RECOGNIZED_OIDS.get("CANCEL_REQUEST"): { encodeCancelRequest({ ber, requestValue: this.requestValue }); break; } case RECOGNIZED_OIDS.get("PASSWORD_MODIFY"): { encodePasswordModify({ ber, requestValue: this.requestValue }); break; } default: { ber.writeString(this.requestValue, 129); } } } ber.endSequence(); return ber; } _pojo(obj = {}) { obj.requestName = this.requestName; obj.requestValue = this.requestValue; return obj; } static parseToPojo(ber) { const protocolOp = ber.readSequence(); if (protocolOp !== operations.LDAP_REQ_EXTENSION) { const op = protocolOp.toString(16).padStart(2, "0"); throw Error(`found wrong protocol operation: 0x${op}`); } const requestName = ber.readString(128); if (ber.peek() !== 129) { return { protocolOp, requestName }; } let requestValue; switch (requestName) { case RECOGNIZED_OIDS.get("CANCEL_REQUEST"): { requestValue = readCancelRequest(ber); break; } case RECOGNIZED_OIDS.get("PASSWORD_MODIFY"): { requestValue = readPasswordModify(ber); break; } default: { requestValue = ber.readString(129); break; } } return { protocolOp, requestName, requestValue }; } static recognizedOIDs() { return RECOGNIZED_OIDS; } }; _requestName = new WeakMap(); _requestValue = new WeakMap(); module2.exports = ExtensionRequest; function encodeCancelRequest({ ber, requestValue }) { ber.startSequence(129); ber.startSequence(); ber.writeInt(requestValue); ber.endSequence(); ber.endSequence(); } function readCancelRequest(ber) { ber.readSequence(129); ber.readSequence(); return ber.readInt(); } function encodePasswordModify({ ber, requestValue }) { ber.startSequence(129); ber.startSequence(); if (requestValue.userIdentity) { ber.writeString(requestValue.userIdentity, 128); } if (requestValue.oldPassword) { ber.writeString(requestValue.oldPassword, 129); } if (requestValue.newPassword) { ber.writeString(requestValue.newPassword, 130); } ber.endSequence(); ber.endSequence(); } function readPasswordModify(ber) { ber.readSequence(129); ber.readSequence(); let userIdentity; if (ber.peek() === 128) { userIdentity = ber.readString(128); } let oldPassword; if (ber.peek() === 129) { oldPassword = ber.readString(129); } let newPassword; if (ber.peek() === 130) { newPassword = ber.readString(130); } return { userIdentity, oldPassword, newPassword }; } } }); // node_modules/@ldapjs/change/index.js var require_change = __commonJS({ "node_modules/@ldapjs/change/index.js"(exports, module2) { "use strict"; var { BerReader, BerWriter } = require_asn1(); var Attribute = require_attribute(); var _operation, _modification; var _Change = class { constructor({ operation = "add", modification }) { __privateAdd(this, _operation, void 0); __privateAdd(this, _modification, void 0); this.operation = operation; this.modification = modification; } get [Symbol.toStringTag]() { return "LdapChange"; } get modification() { return __privateGet(this, _modification); } set modification(mod) { if (Attribute.isAttribute(mod) === false) { throw Error("modification must be an Attribute"); } if (Object.prototype.toString.call(mod) !== "[object LdapAttribute]") { mod = new Attribute(mod); } __privateSet(this, _modification, mod); } get pojo() { return { operation: this.operation, modification: this.modification.pojo }; } get operation() { switch (__privateGet(this, _operation)) { case 0: { return "add"; } case 1: { return "delete"; } case 2: { return "replace"; } } } set operation(op) { if (typeof op === "string") { op = op.toLowerCase(); } switch (op) { case 0: case "add": { __privateSet(this, _operation, 0); break; } case 1: case "delete": { __privateSet(this, _operation, 1); break; } case 2: case "replace": { __privateSet(this, _operation, 2); break; } default: { const type = Number.isInteger(op) ? "0x" + Number(op).toString(16) : op; throw Error(`invalid operation type: ${type}`); } } } toBer() { const writer = new BerWriter(); writer.startSequence(); writer.writeEnumeration(__privateGet(this, _operation)); const attrBer = __privateGet(this, _modification).toBer(); writer.appendBuffer(attrBer.buffer); writer.endSequence(); return new BerReader(writer.buffer); } toJSON() { return this.pojo; } static apply(change, target, scalar = false) { if (_Change.isChange(change) === false) { throw Error("change must be an instance of Change"); } const type = change.modification.type; const values = change.modification.values; let data = target[type]; if (data === void 0) { data = []; } else if (Array.isArray(data) === false) { data = [data]; } switch (change.operation) { case "add": { const newValues = values.filter((v) => data.indexOf(v) === -1); Array.prototype.push.apply(data, newValues); break; } case "delete": { data = data.filter((v) => values.indexOf(v) === -1); if (data.length === 0) { delete target[type]; return target; } break; } case "replace": { if (values.length === 0) { delete target[type]; return target; } data = values; break; } } if (scalar === true && data.length === 1) { target[type] = data[0]; } else { target[type] = data; } return target; } static isChange(change) { if (Object.prototype.toString.call(change) === "[object LdapChange]") { return true; } if (Object.prototype.toString.call(change) !== "[object Object]") { return false; } if (Attribute.isAttribute(change.modification) === true && (typeof change.operation === "string" || typeof change.operation === "number")) { return true; } return false; } static compare(change1, change2) { if (_Change.isChange(change1) === false || _Change.isChange(change2) === false) { throw Error("can only compare Change instances"); } if (change1.operation < change2.operation) { return -1; } if (change1.operation > change2.operation) { return 1; } return Attribute.compare(change1.modification, change2.modification); } static fromBer(ber) { ber.readSequence(); const operation = ber.readEnumeration(); const modification = Attribute.fromBer(ber); return new _Change({ operation, modification }); } }; var Change = _Change; _operation = new WeakMap(); _modification = new WeakMap(); module2.exports = Change; } }); // node_modules/@ldapjs/messages/lib/messages/modify-request.js var require_modify_request = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/modify-request.js"(exports, module2) { "use strict"; var { operations } = require_protocol(); var Change = require_change(); var LdapMessage = require_ldap_message(); var _object, _changes; var ModifyRequest = class extends LdapMessage { constructor(options = {}) { options.protocolOp = operations.LDAP_REQ_MODIFY; super(options); __privateAdd(this, _object, void 0); __privateAdd(this, _changes, void 0); __privateSet(this, _object, options.object || null); this.changes = options.changes || []; } get changes() { return __privateGet(this, _changes).slice(0); } set changes(values) { __privateSet(this, _changes, []); if (Array.isArray(values) === false) { throw Error("changes must be an array"); } for (let change of values) { if (Change.isChange(change) === false) { throw Error("change must be an instance of Change or a Change-like object"); } if (Object.prototype.toString.call(change) !== "[object LdapChange]") { change = new Change(change); } __privateGet(this, _changes).push(change); } } get object() { return __privateGet(this, _object); } set object(value) { __privateSet(this, _object, value); } get type() { return "ModifyRequest"; } get _dn() { return __privateGet(this, _object); } _toBer(ber) { ber.startSequence(operations.LDAP_REQ_MODIFY); ber.writeString(__privateGet(this, _object).toString()); ber.startSequence(); for (const change of __privateGet(this, _changes)) { ber.appendBuffer(change.toBer().buffer); } ber.endSequence(); ber.endSequence(); return ber; } _pojo(obj = {}) { obj.object = __privateGet(this, _object); obj.changes = __privateGet(this, _changes).map((c) => c.pojo); return obj; } static parseToPojo(ber) { const protocolOp = ber.readSequence(); if (protocolOp !== operations.LDAP_REQ_MODIFY) { const op = protocolOp.toString(16).padStart(2, "0"); throw Error(`found wrong protocol operation: 0x${op}`); } const object = ber.readString(); const changes = []; ber.readSequence(); const end = ber.offset + ber.length; while (ber.offset < end) { const change = Change.fromBer(ber); changes.push(change.pojo); } return { protocolOp, object, changes }; } }; _object = new WeakMap(); _changes = new WeakMap(); module2.exports = ModifyRequest; } }); // node_modules/@ldapjs/messages/lib/messages/modifydn-request.js var require_modifydn_request = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/modifydn-request.js"(exports, module2) { "use strict"; var LdapMessage = require_ldap_message(); var { operations } = require_protocol(); var { DN } = require_dn2(); var _entry, _newRdn, _deleteOldRdn, _newSuperior; var ModifyDnRequest = class extends LdapMessage { constructor(options = {}) { var _a; options.protocolOp = operations.LDAP_REQ_MODRDN; super(options); __privateAdd(this, _entry, void 0); __privateAdd(this, _newRdn, void 0); __privateAdd(this, _deleteOldRdn, void 0); __privateAdd(this, _newSuperior, void 0); this.entry = options.entry || ""; this.newRdn = options.newRdn || ""; this.deleteOldRdn = (_a = options.deleteOldRdn) != null ? _a : false; this.newSuperior = options.newSuperior; } get entry() { return __privateGet(this, _entry); } set entry(value) { if (typeof value === "string") { __privateSet(this, _entry, DN.fromString(value)); } else if (Object.prototype.toString.call(value) === "[object LdapDn]") { __privateSet(this, _entry, value); } else { throw Error("entry must be a valid DN string or instance of LdapDn"); } } get _dn() { return __privateGet(this, _entry); } get newRdn() { return __privateGet(this, _newRdn); } set newRdn(value) { if (typeof value === "string") { __privateSet(this, _newRdn, DN.fromString(value)); } else if (Object.prototype.toString.call(value) === "[object LdapDn]") { __privateSet(this, _newRdn, value); } else { throw Error("newRdn must be a valid DN string or instance of LdapDn"); } } get deleteOldRdn() { return __privateGet(this, _deleteOldRdn); } set deleteOldRdn(value) { if (typeof value !== "boolean") { throw Error("deleteOldRdn must be a boolean value"); } __privateSet(this, _deleteOldRdn, value); } get newSuperior() { return __privateGet(this, _newSuperior); } set newSuperior(value) { if (value) { if (typeof value === "string") { __privateSet(this, _newSuperior, DN.fromString(value)); } else if (Object.prototype.toString.call(value) === "[object LdapDn]") { __privateSet(this, _newSuperior, value); } else { throw Error("newSuperior must be a valid DN string or instance of LdapDn"); } } else { __privateSet(this, _newSuperior, void 0); } } get type() { return "ModifyDnRequest"; } _toBer(ber) { ber.startSequence(operations.LDAP_REQ_MODRDN); ber.writeString(__privateGet(this, _entry).toString()); ber.writeString(__privateGet(this, _newRdn).toString()); ber.writeBoolean(__privateGet(this, _deleteOldRdn)); if (__privateGet(this, _newSuperior) !== void 0) { ber.writeString(__privateGet(this, _newSuperior).toString(), 128); } ber.endSequence(); return ber; } _pojo(obj = {}) { obj.entry = __privateGet(this, _entry).toString(); obj.newRdn = __privateGet(this, _newRdn).toString(); obj.deleteOldRdn = __privateGet(this, _deleteOldRdn); obj.newSuperior = __privateGet(this, _newSuperior) ? __privateGet(this, _newSuperior).toString() : void 0; return obj; } static parseToPojo(ber) { const protocolOp = ber.readSequence(); if (protocolOp !== operations.LDAP_REQ_MODRDN) { const op = protocolOp.toString(16).padStart(2, "0"); throw Error(`found wrong protocol operation: 0x${op}`); } const entry = ber.readString(); const newRdn = ber.readString(); const deleteOldRdn = ber.readBoolean(); let newSuperior; if (ber.peek() === 128) { newSuperior = ber.readString(128); } return { protocolOp, entry, newRdn, deleteOldRdn, newSuperior }; } }; _entry = new WeakMap(); _newRdn = new WeakMap(); _deleteOldRdn = new WeakMap(); _newSuperior = new WeakMap(); module2.exports = ModifyDnRequest; } }); // node_modules/@ldapjs/filter/lib/utils/test-values.js var require_test_values = __commonJS({ "node_modules/@ldapjs/filter/lib/utils/test-values.js"(exports, module2) { "use strict"; module2.exports = testValues; function testValues({ rule, value, requireAllMatch = false }) { if (Array.isArray(value) === false) { return rule(value); } if (requireAllMatch === true) { for (let i = 0; i < value.length; i++) { if (rule(value[i]) === false) { return false; } } return true; } for (let i = 0; i < value.length; i++) { if (rule(value[i])) { return true; } } return false; } } }); // node_modules/@ldapjs/filter/lib/utils/get-attribute-value.js var require_get_attribute_value = __commonJS({ "node_modules/@ldapjs/filter/lib/utils/get-attribute-value.js"(exports, module2) { "use strict"; module2.exports = getAttributeValue; function getAttributeValue({ sourceObject, attributeName, strictCase = false }) { if (Object.prototype.toString.call(sourceObject) === "[object LdapAttribute]") { sourceObject = { [sourceObject.type]: sourceObject.values }; } if (Object.prototype.toString.call(sourceObject) !== "[object Object]") { throw Error("sourceObject must be an object"); } if (typeof attributeName !== "string") { throw Error("attributeName must be a string"); } if (Object.prototype.hasOwnProperty.call(sourceObject, attributeName)) { return sourceObject[attributeName]; } else if (strictCase === true) { return void 0; } const lowerName = attributeName.toLowerCase(); const foundName = Object.getOwnPropertyNames(sourceObject).find((name) => name.toLowerCase() === lowerName); return foundName && sourceObject[foundName]; } } }); // node_modules/@ldapjs/filter/lib/filter-string.js var require_filter_string = __commonJS({ "node_modules/@ldapjs/filter/lib/filter-string.js"(exports, module2) { "use strict"; var { BerReader, BerWriter } = require_asn1(); var _value, _clauses; var _FilterString = class { constructor({ attribute = "", value, clauses = [] } = {}) { __publicField(this, "TAG", 48); __publicField(this, "type", "FilterString"); __publicField(this, "attribute", ""); __privateAdd(this, _value, void 0); __privateAdd(this, _clauses, []); this.attribute = attribute; __privateSet(this, _value, value); if (Array.isArray(clauses) === false) { throw Error("clauses must be an array"); } Array.prototype.push.apply(__privateGet(this, _clauses), clauses); } get [Symbol.toStringTag]() { return "FilterString"; } get value() { return __privateGet(this, _value); } set value(val) { __privateSet(this, _value, val); } matches() { return false; } toString() { return "()"; } toBer() { const ber = new BerWriter(); ber.startSequence(this.TAG); this._toBer(ber); ber.endSequence(); return new BerReader(ber.buffer); } _toBer(ber) { ber.writeNull(); } get json() { return { type: this.type, attribute: this.attribute, value: __privateGet(this, _value) }; } get filter() { return this; } get filters() { return __privateGet(this, _clauses); } get clauses() { return __privateGet(this, _clauses); } forEach(callback) { __privateGet(this, _clauses).forEach((clause) => clause.forEach(callback)); callback(this); } map(callback) { if (__privateGet(this, _clauses).length === 0) { return callback(this); } const child = __privateGet(this, _clauses).map((clause) => clause.map(callback)).filter((clause) => clause !== null); if (child.length === 0) { return null; } __privateSet(this, _clauses, child); return callback(this); } addFilter(filter) { this.addClause(filter); } addClause(clause) { if (clause instanceof _FilterString === false) { throw Error("clause must be an instance of FilterString"); } __privateGet(this, _clauses).push(clause); } static parse(buffer) { if (buffer.length !== 4) { throw Error(`expected buffer length 4, got ${buffer.length}`); } const reader = new BerReader(buffer); let seq = reader.readSequence(); if (seq !== 48) { throw Error(`expected sequence start, got 0x${seq.toString(16).padStart(2, "0")}`); } seq = reader.readSequence(); if (seq !== 5) { throw Error(`expected null sequence start, got 0x${seq.toString(16).padStart(2, "0")}`); } return new _FilterString(); } }; var FilterString = _FilterString; _value = new WeakMap(); _clauses = new WeakMap(); module2.exports = FilterString; } }); // node_modules/@ldapjs/filter/lib/utils/escape-filter-value.js var require_escape_filter_value = __commonJS({ "node_modules/@ldapjs/filter/lib/utils/escape-filter-value.js"(exports, module2) { "use strict"; module2.exports = escapeFilterValue; function escapeFilterValue(toEscape) { if (typeof toEscape === "string") { return escapeBuffer(Buffer.from(toEscape)); } if (Buffer.isBuffer(toEscape)) { return escapeBuffer(toEscape); } throw Error("toEscape must be a string or a Buffer"); } function escapeBuffer(buf) { let result = ""; for (let i = 0; i < buf.length; i += 1) { if (buf[i] >= 192 && buf[i] <= 223) { result += "\\" + buf[i].toString(16) + "\\" + buf[i + 1].toString(16); i += 1; continue; } if (buf[i] >= 224 && buf[i] <= 239) { result += [ "\\", buf[i].toString(16), "\\", buf[i + 1].toString(16), "\\", buf[i + 2].toString(16) ].join(""); i += 2; continue; } if (buf[i] <= 31) { result += "\\" + buf[i].toString(16).padStart(2, "0"); continue; } const char = String.fromCharCode(buf[i]); switch (char) { case "*": { result += "\\2a"; break; } case "(": { result += "\\28"; break; } case ")": { result += "\\29"; break; } case "\\": { const escapedChars = readEscapedCharacters(buf, i); i += escapedChars.length; result += escapedChars.join(""); break; } default: { result += char; break; } } } return result; } function readEscapedCharacters(buf, start) { const chars = []; for (let i = start; ; ) { if (buf[i] === void 0) { chars[-1] = "\\5c"; break; } if (buf[i] === 92) { chars.push("\\"); i += 1; continue; } const strHexCode = String.fromCharCode(buf[i]) + String.fromCharCode(buf[i + 1]); const hexCode = parseInt(strHexCode, 16); if (Number.isNaN(hexCode)) { chars.push("5c" + strHexCode); break; } if (hexCode >= 192 && hexCode <= 223) { chars.push(hexCode.toString(16).padEnd(2, "0")); for (let x = i + 2; x < i + 4; x += 1) { chars.push(String.fromCharCode(buf[x])); } break; } if (hexCode >= 224 && hexCode <= 239) { chars.push(hexCode.toString(16).padStart(2, "0")); for (let x = i + 2; x < i + 8; x += 1) { chars.push(String.fromCharCode(buf[x])); } break; } chars.push(hexCode.toString(16).padStart(2, "0")); break; } return chars; } } }); // node_modules/@ldapjs/filter/lib/filters/approximate.js var require_approximate = __commonJS({ "node_modules/@ldapjs/filter/lib/filters/approximate.js"(exports, module2) { "use strict"; var FilterString = require_filter_string(); var { BerReader } = require_asn1(); var { search } = require_protocol(); var escapeFilterValue = require_escape_filter_value(); var ApproximateFilter = class extends FilterString { constructor({ attribute, value } = {}) { if (typeof attribute !== "string" || attribute.length < 1) { throw Error("attribute must be a string of at least one character"); } if (typeof value !== "string" || value.length < 1) { throw Error("value must be a string of at least one character"); } super({ attribute, value }); Object.defineProperties(this, { TAG: { value: search.FILTER_APPROX }, type: { value: "ApproximateFilter" } }); } matches() { throw Error("not implemented"); } toString() { return "(" + escapeFilterValue(this.attribute) + "~=" + escapeFilterValue(this.value) + ")"; } _toBer(ber) { ber.writeString(this.attribute); ber.writeString(this.value); return ber; } static parse(buffer) { const reader = new BerReader(buffer); const seq = reader.readSequence(); if (seq !== search.FILTER_APPROX) { const expected = "0x" + search.FILTER_APPROX.toString(16).padStart(2, "0"); const found = "0x" + seq.toString(16).padStart(2, "0"); throw Error(`expected approximate filter sequence ${expected}, got ${found}`); } const attribute = reader.readString(); const value = reader.readString(); return new ApproximateFilter({ attribute, value }); } }; module2.exports = ApproximateFilter; } }); // node_modules/@ldapjs/filter/lib/filters/equality.js var require_equality = __commonJS({ "node_modules/@ldapjs/filter/lib/filters/equality.js"(exports, module2) { "use strict"; var FilterString = require_filter_string(); var { BerReader, BerTypes } = require_asn1(); var { search } = require_protocol(); var escapeFilterValue = require_escape_filter_value(); var testValues = require_test_values(); var getAttributeValue = require_get_attribute_value(); var _raw; var _EqualityFilter = class extends FilterString { constructor({ attribute, raw, value } = {}) { if (typeof attribute !== "string" || attribute.length < 1) { throw Error("attribute must be a string of at least one character"); } super({ attribute, value }); __privateAdd(this, _raw, void 0); if (raw) { __privateSet(this, _raw, raw); } else { if (!value) { throw Error("must either provide a buffer via `raw` or some `value`"); } __privateSet(this, _raw, Buffer.from(value)); } Object.defineProperties(this, { TAG: { value: search.FILTER_EQUALITY }, type: { value: "EqualityFilter" } }); } get value() { return Buffer.isBuffer(__privateGet(this, _raw)) ? __privateGet(this, _raw).toString() : __privateGet(this, _raw); } set value(val) { if (typeof val === "string") { __privateSet(this, _raw, Buffer.from(val)); } else if (Buffer.isBuffer(val)) { __privateSet(this, _raw, Buffer.alloc(val.length)); val.copy(__privateGet(this, _raw)); } else { __privateSet(this, _raw, val); } } matches(obj, strictAttrCase = true) { if (Array.isArray(obj) === true) { for (const attr of obj) { if (Object.prototype.toString.call(attr) !== "[object LdapAttribute]") { throw Error("array element must be an instance of LdapAttribute"); } if (this.matches(attr, strictAttrCase) === true) { return true; } } return false; } let testValue = this.value; if (this.attribute.toLowerCase() === "objectclass") { const targetAttribute2 = getAttributeValue({ sourceObject: obj, attributeName: this.attribute, strictCase: false }); testValue = testValue.toLowerCase(); return testValues({ rule: (v) => testValue === v.toLowerCase(), value: targetAttribute2 }); } const targetAttribute = getAttributeValue({ sourceObject: obj, attributeName: this.attribute, strictCase: strictAttrCase }); return testValues({ rule: (v) => testValue === v, value: targetAttribute }); } toString() { let value; if (Buffer.isBuffer(__privateGet(this, _raw))) { value = __privateGet(this, _raw); const decoded = __privateGet(this, _raw).toString("utf8"); const validate = Buffer.from(decoded, "utf8"); if (validate.length === __privateGet(this, _raw).length) { value = decoded; } } else if (typeof __privateGet(this, _raw) === "string") { value = __privateGet(this, _raw); } else { throw new Error("invalid value type"); } return "(" + escapeFilterValue(this.attribute) + "=" + escapeFilterValue(value) + ")"; } _toBer(ber) { ber.writeString(this.attribute); ber.writeBuffer(__privateGet(this, _raw), BerTypes.OctetString); return ber; } static parse(buffer) { const reader = new BerReader(buffer); const tag = reader.readSequence(); if (tag !== search.FILTER_EQUALITY) { const expected = "0x" + search.FILTER_EQUALITY.toString(16).padStart(2, "0"); const found = "0x" + tag.toString(16).padStart(2, "0"); throw Error(`expected equality filter sequence ${expected}, got ${found}`); } const attribute = reader.readString(); const value = reader.readString(BerTypes.OctetString, true); return new _EqualityFilter({ attribute, value }); } }; var EqualityFilter = _EqualityFilter; _raw = new WeakMap(); module2.exports = EqualityFilter; } }); // node_modules/@ldapjs/filter/lib/filters/extensible.js var require_extensible = __commonJS({ "node_modules/@ldapjs/filter/lib/filters/extensible.js"(exports, module2) { "use strict"; var FilterString = require_filter_string(); var { search } = require_protocol(); var { BerReader } = require_asn1(); var _dnAttributes, _rule; var _ExtensibleFilter = class extends FilterString { constructor({ attribute, value, rule, matchType, dnAttributes = false } = {}) { if (typeof dnAttributes !== "boolean") { throw Error("dnAttributes must be a boolean value"); } if (rule && typeof rule !== "string") { throw Error("rule must be a string"); } super({ attribute, value }); __privateAdd(this, _dnAttributes, void 0); __privateAdd(this, _rule, void 0); if (matchType !== void 0) { this.attribute = matchType; } __privateSet(this, _dnAttributes, dnAttributes); __privateSet(this, _rule, rule); this.value = value != null ? value : ""; Object.defineProperties(this, { TAG: { value: search.FILTER_EXT }, type: { value: "ExtensibleFilter" } }); } get json() { return { type: this.type, matchRule: __privateGet(this, _rule), matchType: this.attribute, matchValue: this.value, dnAttributes: __privateGet(this, _dnAttributes) }; } get dnAttributes() { return __privateGet(this, _dnAttributes); } get matchingRule() { return __privateGet(this, _rule); } get matchValue() { return this.value; } get matchType() { return this.attribute; } toString() { let result = "("; if (this.attribute) { result += this.attribute; } result += ":"; if (__privateGet(this, _dnAttributes) === true) { result += "dn:"; } if (__privateGet(this, _rule)) { result += __privateGet(this, _rule) + ":"; } result += "=" + this.value + ")"; return result; } matches() { throw Error("not implemented"); } _toBer(ber) { if (__privateGet(this, _rule)) { ber.writeString(__privateGet(this, _rule), 129); } if (this.attribute) { ber.writeString(this.attribute, 130); } ber.writeString(this.value, 131); if (__privateGet(this, _dnAttributes) === true) { ber.writeBoolean(__privateGet(this, _dnAttributes), 132); } return ber; } static parse(buffer) { const reader = new BerReader(buffer); const seq = reader.readSequence(); if (seq !== search.FILTER_EXT) { const expected = "0x" + search.FILTER_EXT.toString(16).padStart(2, "0"); const found = "0x" + seq.toString(16).padStart(2, "0"); throw Error(`expected extensible filter sequence ${expected}, got ${found}`); } let rule; let attribute; let value; let dnAttributes; const end = reader.buffer.length; while (reader.offset < end) { const tag = reader.peek(); switch (tag) { case 129: { rule = reader.readString(tag); break; } case 130: { attribute = reader.readString(tag); break; } case 131: { value = reader.readString(tag); break; } case 132: { dnAttributes = reader.readBoolean(tag); break; } default: { throw Error("invalid extensible filter type: 0x" + tag.toString(16).padStart(2, "0")); } } } return new _ExtensibleFilter({ attribute, value, rule, dnAttributes }); } }; var ExtensibleFilter = _ExtensibleFilter; _dnAttributes = new WeakMap(); _rule = new WeakMap(); module2.exports = ExtensibleFilter; } }); // node_modules/@ldapjs/filter/lib/filters/greater-than-equals.js var require_greater_than_equals = __commonJS({ "node_modules/@ldapjs/filter/lib/filters/greater-than-equals.js"(exports, module2) { "use strict"; var FilterString = require_filter_string(); var { BerReader } = require_asn1(); var { search } = require_protocol(); var escapeFilterValue = require_escape_filter_value(); var testValues = require_test_values(); var getAttributeValue = require_get_attribute_value(); var GreaterThanEqualsFilter = class extends FilterString { constructor({ attribute, value } = {}) { if (typeof attribute !== "string" || attribute.length < 1) { throw Error("attribute must be a string of at least one character"); } if (typeof value !== "string" || value.length < 1) { throw Error("value must be a string of at least one character"); } super({ attribute, value }); Object.defineProperties(this, { TAG: { value: search.FILTER_GE }, type: { value: "GreaterThanEqualsFilter" } }); } matches(obj, strictAttrCase = true) { if (Array.isArray(obj) === true) { for (const attr of obj) { if (Object.prototype.toString.call(attr) !== "[object LdapAttribute]") { throw Error("array element must be an instance of LdapAttribute"); } if (this.matches(attr, strictAttrCase) === true) { return true; } } return false; } const testValue = this.value; const targetAttribute = getAttributeValue({ sourceObject: obj, attributeName: this.attribute, strictCase: strictAttrCase }); return testValues({ rule: (v) => testValue <= v, value: targetAttribute }); } toString() { return "(" + escapeFilterValue(this.attribute) + ">=" + escapeFilterValue(this.value) + ")"; } _toBer(ber) { ber.writeString(this.attribute); ber.writeString(this.value); return ber; } static parse(buffer) { const reader = new BerReader(buffer); const seq = reader.readSequence(); if (seq !== search.FILTER_GE) { const expected = "0x" + search.FILTER_GE.toString(16).padStart(2, "0"); const found = "0x" + seq.toString(16).padStart(2, "0"); throw Error(`expected greater-than-equals filter sequence ${expected}, got ${found}`); } const attribute = reader.readString(); const value = reader.readString(); return new GreaterThanEqualsFilter({ attribute, value }); } }; module2.exports = GreaterThanEqualsFilter; } }); // node_modules/@ldapjs/filter/lib/filters/less-than-equals.js var require_less_than_equals = __commonJS({ "node_modules/@ldapjs/filter/lib/filters/less-than-equals.js"(exports, module2) { "use strict"; var FilterString = require_filter_string(); var { BerReader } = require_asn1(); var { search } = require_protocol(); var escapeFilterValue = require_escape_filter_value(); var testValues = require_test_values(); var getAttributeValue = require_get_attribute_value(); var LessThanEqualsFilter = class extends FilterString { constructor({ attribute, value } = {}) { if (typeof attribute !== "string" || attribute.length < 1) { throw Error("attribute must be a string of at least one character"); } if (typeof value !== "string" || value.length < 1) { throw Error("value must be a string of at least one character"); } super({ attribute, value }); Object.defineProperties(this, { TAG: { value: search.FILTER_LE }, type: { value: "LessThanEqualsFilter" } }); } toString() { return "(" + escapeFilterValue(this.attribute) + "<=" + escapeFilterValue(this.value) + ")"; } matches(obj, strictAttrCase = true) { if (Array.isArray(obj) === true) { for (const attr of obj) { if (Object.prototype.toString.call(attr) !== "[object LdapAttribute]") { throw Error("array element must be an instance of LdapAttribute"); } if (this.matches(attr, strictAttrCase) === true) { return true; } } return false; } const testValue = this.value; const targetAttribute = getAttributeValue({ sourceObject: obj, attributeName: this.attribute, strictCase: strictAttrCase }); return testValues({ rule: (v) => v <= testValue, value: targetAttribute }); } _toBer(ber) { ber.writeString(this.attribute); ber.writeString(this.value); return ber; } static parse(buffer) { const reader = new BerReader(buffer); const seq = reader.readSequence(); if (seq !== search.FILTER_LE) { const expected = "0x" + search.FILTER_LE.toString(16).padStart(2, "0"); const found = "0x" + seq.toString(16).padStart(2, "0"); throw Error(`expected less-than-equals filter sequence ${expected}, got ${found}`); } const attribute = reader.readString(); const value = reader.readString(); return new LessThanEqualsFilter({ attribute, value }); } }; module2.exports = LessThanEqualsFilter; } }); // node_modules/@ldapjs/filter/lib/filters/not.js var require_not = __commonJS({ "node_modules/@ldapjs/filter/lib/filters/not.js"(exports, module2) { "use strict"; var FilterString = require_filter_string(); var { search } = require_protocol(); var NotFilter = class extends FilterString { constructor({ filter } = {}) { if (filter instanceof FilterString === false) { throw Error("filter is required and must be a filter instance"); } super(); this.attribute = void 0; this.filter = filter; Object.defineProperties(this, { TAG: { value: search.FILTER_NOT }, type: { value: "NotFilter" } }); } get json() { return { type: this.type, filter: this.filter.json }; } get filter() { return this.clauses[0]; } set filter(filter) { if (filter instanceof FilterString === false) { throw Error("filter must be a filter instance"); } this.clauses[0] = filter; } setFilter(filter) { this.clauses[0] = filter; } toString() { return "(!" + this.filter.toString() + ")"; } matches(obj, strictAttrCase = true) { return !this.filter.matches(obj, strictAttrCase); } _toBer(ber) { const innerBer = this.filter.toBer(ber); ber.appendBuffer(innerBer.buffer); return ber; } static parse(buffer) { const parseNestedFilter = require_parse_nested_filter(); return parseNestedFilter({ buffer, constructor: NotFilter, startTag: search.FILTER_NOT }); } }; module2.exports = NotFilter; } }); // node_modules/@ldapjs/filter/lib/filters/or.js var require_or = __commonJS({ "node_modules/@ldapjs/filter/lib/filters/or.js"(exports, module2) { "use strict"; var FilterString = require_filter_string(); var { search } = require_protocol(); var OrFilter = class extends FilterString { constructor({ filters = [] } = {}) { super({}); this.attribute = void 0; for (const filter of filters) { this.addClause(filter); } Object.defineProperties(this, { TAG: { value: search.FILTER_OR }, type: { value: "OrFilter" } }); } get json() { return { type: this.type, filters: this.clauses.map((clause) => clause.json) }; } toString() { let result = "(|"; for (const clause of this.clauses) { result += clause.toString(); } result += ")"; return result; } matches(obj, strictAttrCase = true) { if (this.clauses.length === 0) { return false; } for (const clause of this.clauses) { if (Array.isArray(obj) === true) { for (const attr of obj) { if (Object.prototype.toString.call(attr) !== "[object LdapAttribute]") { throw Error("array element must be an instance of LdapAttribute"); } if (attr.type !== clause.attribute) { continue; } if (clause.matches(attr, strictAttrCase) === true) { return true; } } } else { if (clause.matches(obj, strictAttrCase) === true) { return true; } } } return false; } _toBer(ber) { for (const clause of this.clauses) { const filterBer = clause.toBer(); ber.appendBuffer(filterBer.buffer); } return ber; } static parse(buffer) { const parseNestedFilter = require_parse_nested_filter(); return parseNestedFilter({ buffer, constructor: OrFilter, startTag: search.FILTER_OR }); } }; module2.exports = OrFilter; } }); // node_modules/@ldapjs/filter/lib/filters/presence.js var require_presence = __commonJS({ "node_modules/@ldapjs/filter/lib/filters/presence.js"(exports, module2) { "use strict"; var FilterString = require_filter_string(); var { BerReader } = require_asn1(); var { search } = require_protocol(); var escapeFilterValue = require_escape_filter_value(); var getAttributeValue = require_get_attribute_value(); var PresenceFilter = class extends FilterString { constructor({ attribute } = {}) { if (typeof attribute !== "string" || attribute.length < 1) { throw Error("attribute must be a string of at least one character"); } super({ attribute }); Object.defineProperties(this, { TAG: { value: search.FILTER_PRESENT }, type: { value: "PresenceFilter" } }); } matches(obj, strictAttributeCase = true) { if (Array.isArray(obj) === true) { for (const attr of obj) { if (Object.prototype.toString.call(attr) !== "[object LdapAttribute]") { throw Error("array element must be an instance of LdapAttribute"); } if (this.matches(attr, strictAttributeCase) === true) { return true; } } return false; } return getAttributeValue({ sourceObject: obj, attributeName: this.attribute, strictCase: strictAttributeCase }) !== void 0; } toString() { return `(${escapeFilterValue(this.attribute)}=*)`; } _toBer(ber) { for (let i = 0; i < this.attribute.length; i++) { ber.writeByte(this.attribute.charCodeAt(i)); } } static parse(buffer) { const reader = new BerReader(buffer); const tag = reader.peek(); if (tag !== search.FILTER_PRESENT) { const expected = "0x" + search.FILTER_PRESENT.toString(16).padStart(2, "0"); const found = "0x" + tag.toString(16).padStart(2, "0"); throw Error(`expected presence filter sequence ${expected}, got ${found}`); } const attribute = reader.readString(tag); return new PresenceFilter({ attribute }); } }; module2.exports = PresenceFilter; } }); // node_modules/@ldapjs/filter/lib/deprecations.js var require_deprecations4 = __commonJS({ "node_modules/@ldapjs/filter/lib/deprecations.js"(exports, module2) { "use strict"; var warning = require_process_warning()(); var clazz = "LdapjsFilterWarning"; warning.create(clazz, "LDAP_FILTER_DEP_001", "parse is deprecated. Use the parseString function instead."); warning.create(clazz, "LDAP_FILTER_DEP_002", "subInitial is deprecated. Use initial instead."); warning.create(clazz, "LDAP_FILTER_DEP_003", "subAny is deprecated. Use any instead."); warning.create(clazz, "LDAP_FILTER_DEP_004", "subFinal is deprecated. Use final instead."); module2.exports = warning; } }); // node_modules/@ldapjs/filter/lib/filters/substring.js var require_substring = __commonJS({ "node_modules/@ldapjs/filter/lib/filters/substring.js"(exports, module2) { "use strict"; var FilterString = require_filter_string(); var { BerReader } = require_asn1(); var { search } = require_protocol(); var escapeFilterValue = require_escape_filter_value(); var testValues = require_test_values(); var getAttributeValue = require_get_attribute_value(); var warning = require_deprecations4(); var _initial, _any, _final, _constructedWithSubPrefix; var _SubstringFilter = class extends FilterString { constructor({ attribute, initial, subInitial, any = [], subAny = [], final, subFinal } = {}) { if (subInitial) { warning.emit("LDAP_FILTER_DEP_002"); initial = subInitial; } if (Array.isArray(subAny) && subAny.length > 0) { warning.emit("LDAP_FILTER_DEP_003"); any = subAny; } if (subFinal) { warning.emit("LDAP_FILTER_DEP_004"); final = subFinal; } if (typeof attribute !== "string" || attribute.length < 1) { throw Error("attribute must be a string of at least one character"); } if (Array.isArray(any) === false) { throw Error("any must be an array of items"); } if (Array.isArray(subAny) === false) { throw Error("subAny must be an array of items"); } if (final && typeof final !== "string") { throw Error("final must be a string"); } super({ attribute }); __privateAdd(this, _initial, void 0); __privateAdd(this, _any, []); __privateAdd(this, _final, void 0); __privateAdd(this, _constructedWithSubPrefix, void 0); __privateSet(this, _initial, initial); Array.prototype.push.apply(__privateGet(this, _any), any); __privateSet(this, _final, final); __privateSet(this, _constructedWithSubPrefix, subInitial || subFinal || subAny.length > 0); Object.defineProperties(this, { TAG: { value: search.FILTER_SUBSTRINGS }, type: { value: "SubstringFilter" } }); } get initial() { return __privateGet(this, _initial); } get any() { return __privateGet(this, _any); } get final() { return __privateGet(this, _final); } get subInitial() { return __privateGet(this, _initial); } get subAny() { return __privateGet(this, _any); } get subFinal() { return __privateGet(this, _final); } get json() { if (__privateGet(this, _constructedWithSubPrefix)) { return { type: this.type, subInitial: __privateGet(this, _initial), subAny: __privateGet(this, _any), subFinal: __privateGet(this, _final) }; } else { return { type: this.type, initial: __privateGet(this, _initial), any: __privateGet(this, _any), final: __privateGet(this, _final) }; } } toString() { let result = "(" + escapeFilterValue(this.attribute) + "="; if (__privateGet(this, _initial)) { result += escapeFilterValue(__privateGet(this, _initial)); } result += "*"; for (const any of __privateGet(this, _any)) { result += escapeFilterValue(any) + "*"; } if (__privateGet(this, _final)) { result += escapeFilterValue(__privateGet(this, _final)); } result += ")"; return result; } matches(obj, strictAttrCase) { if (Array.isArray(obj) === true) { for (const attr of obj) { if (Object.prototype.toString.call(attr) !== "[object LdapAttribute]") { throw Error("array element must be an instance of LdapAttribute"); } if (this.matches(attr, strictAttrCase) === true) { return true; } } return false; } const targetValue = getAttributeValue({ sourceObject: obj, attributeName: this.attribute, strictCase: strictAttrCase }); if (targetValue === void 0 || targetValue === null) { return false; } let re = ""; if (__privateGet(this, _initial)) { re += "^" + escapeRegExp(__privateGet(this, _initial)) + ".*"; } __privateGet(this, _any).forEach(function(s) { re += escapeRegExp(s) + ".*"; }); if (__privateGet(this, _final)) { re += escapeRegExp(__privateGet(this, _final)) + "$"; } const matcher = new RegExp(re); return testValues({ rule: (v) => matcher.test(v), value: targetValue }); } _toBer(ber) { ber.writeString(this.attribute); ber.startSequence(); if (__privateGet(this, _initial)) { ber.writeString(__privateGet(this, _initial), 128); } if (__privateGet(this, _any).length > 0) { for (const sub of __privateGet(this, _any)) { ber.writeString(sub, 129); } } if (__privateGet(this, _final)) { ber.writeString(__privateGet(this, _final), 130); } ber.endSequence(); return ber; } static parse(buffer) { const reader = new BerReader(buffer); const seq = reader.readSequence(); if (seq !== search.FILTER_SUBSTRINGS) { const expected = "0x" + search.FILTER_SUBSTRINGS.toString(16).padStart(2, "0"); const found = "0x" + seq.toString(16).padStart(2, "0"); throw Error(`expected substring filter sequence ${expected}, got ${found}`); } let initial; const any = []; let final; const attribute = reader.readString(); reader.readSequence(); const end = reader.offset + reader.length; while (reader.offset < end) { const tag = reader.peek(); switch (tag) { case 128: { initial = reader.readString(tag); break; } case 129: { const anyVal = reader.readString(tag); any.push(anyVal); break; } case 130: { final = reader.readString(tag); break; } default: { throw new Error("Invalid substrings filter type: 0x" + tag.toString(16)); } } } return new _SubstringFilter({ attribute, initial, any, final }); } }; var SubstringFilter = _SubstringFilter; _initial = new WeakMap(); _any = new WeakMap(); _final = new WeakMap(); _constructedWithSubPrefix = new WeakMap(); function escapeRegExp(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); } module2.exports = SubstringFilter; } }); // node_modules/@ldapjs/filter/lib/filters/utils/parse-nested-filter.js var require_parse_nested_filter = __commonJS({ "node_modules/@ldapjs/filter/lib/filters/utils/parse-nested-filter.js"(exports, module2) { "use strict"; var { search } = require_protocol(); var { BerReader } = require_asn1(); module2.exports = function parseNestedFilter({ startTag, buffer, constructor }) { const FILTERS = { [search.FILTER_AND]: require_and(), [search.FILTER_APPROX]: require_approximate(), [search.FILTER_EQUALITY]: require_equality(), [search.FILTER_EXT]: require_extensible(), [search.FILTER_GE]: require_greater_than_equals(), [search.FILTER_LE]: require_less_than_equals(), [search.FILTER_NOT]: require_not(), [search.FILTER_OR]: require_or(), [search.FILTER_PRESENT]: require_presence(), [search.FILTER_SUBSTRINGS]: require_substring() }; const reader = new BerReader(buffer); const seq = reader.readSequence(); if (seq !== startTag) { const expected = "0x" + startTag.toString(16).padStart(2, "0"); const found = "0x" + seq.toString(16).padStart(2, "0"); throw Error(`expected filter tag ${expected}, got ${found}`); } const filters = []; const currentFilterLength = reader.length; while (reader.offset < currentFilterLength) { const tag = reader.peek(); const tagBuffer = reader.readRawBuffer(tag); const filter = FILTERS[tag].parse(tagBuffer); filters.push(filter); } if (constructor === FILTERS[search.FILTER_NOT]) { return new constructor({ filter: filters[0] }); } return new constructor({ filters }); }; } }); // node_modules/@ldapjs/filter/lib/filters/and.js var require_and = __commonJS({ "node_modules/@ldapjs/filter/lib/filters/and.js"(exports, module2) { "use strict"; var FilterString = require_filter_string(); var { search } = require_protocol(); var AndFilter = class extends FilterString { constructor({ filters = [] } = {}) { super({}); this.attribute = void 0; for (const filter of filters) { this.addClause(filter); } Object.defineProperties(this, { TAG: { value: search.FILTER_AND }, type: { value: "AndFilter" } }); } get json() { return { type: this.type, filters: this.clauses.map((clause) => clause.json) }; } toString() { let result = "(&"; for (const clause of this.clauses) { result += clause.toString(); } result += ")"; return result; } matches(obj, strictAttrCase = true) { if (this.clauses.length === 0) { return true; } for (const clause of this.clauses) { if (Array.isArray(obj) === true) { for (const attr of obj) { if (Object.prototype.toString.call(attr) !== "[object LdapAttribute]") { throw Error("array element must be an instance of LdapAttribute"); } if (attr.type !== clause.attribute) { continue; } if (clause.matches(attr, strictAttrCase) === false) { return false; } } } else { if (clause.matches(obj, strictAttrCase) === false) { return false; } } } return true; } _toBer(ber) { for (const clause of this.clauses) { const filterBer = clause.toBer(); ber.appendBuffer(filterBer.buffer); } return ber; } static parse(buffer) { const parseNestedFilter = require_parse_nested_filter(); return parseNestedFilter({ buffer, constructor: AndFilter, startTag: search.FILTER_AND }); } }; module2.exports = AndFilter; } }); // node_modules/@ldapjs/filter/lib/string-parsing/escape-substring.js var require_escape_substring = __commonJS({ "node_modules/@ldapjs/filter/lib/string-parsing/escape-substring.js"(exports, module2) { "use strict"; var escapeFilterValue = require_escape_filter_value(); module2.exports = function escapeSubstring(str) { const fields = str.split("*"); const out = { initial: "", final: "", any: [] }; if (fields.length <= 1) { throw Error("extensible filter delimiter missing"); } out.initial = escapeFilterValue(fields.shift()); out.final = escapeFilterValue(fields.pop()); Array.prototype.push.apply(out.any, fields.map(escapeFilterValue)); return out; }; } }); // node_modules/@ldapjs/filter/lib/string-parsing/parse-extensible-filter-string.js var require_parse_extensible_filter_string = __commonJS({ "node_modules/@ldapjs/filter/lib/string-parsing/parse-extensible-filter-string.js"(exports, module2) { "use strict"; var ExtensibleFilter = require_extensible(); var escapeFilterValue = require_escape_filter_value(); module2.exports = function parseExtensibleFilterString(filterString) { const fields = filterString.split(":"); const attribute = escapeFilterValue(fields.shift()); const params = { attribute, dnAttributes: false, rule: void 0, value: void 0 }; if (fields[0].toLowerCase() === "dn") { params.dnAttributes = true; fields.shift(); } if (fields.length !== 0 && fields[0][0] !== "=") { params.rule = fields.shift(); } if (fields.length === 0 || fields[0][0] !== "=") { throw new Error("missing := in extensible filter string"); } filterString = fields.join(":").substr(1); params.value = escapeFilterValue(filterString); return new ExtensibleFilter(params); }; } }); // node_modules/@ldapjs/filter/lib/string-parsing/parse-expression.js var require_parse_expression = __commonJS({ "node_modules/@ldapjs/filter/lib/string-parsing/parse-expression.js"(exports, module2) { "use strict"; var ApproximateFilter = require_approximate(); var EqualityFilter = require_equality(); var GreaterThanEqualsFilter = require_greater_than_equals(); var LessThanEqualsFilter = require_less_than_equals(); var PresenceFilter = require_presence(); var SubstringFilter = require_substring(); var escapeSubstring = require_escape_substring(); var escapeFilterValue = require_escape_filter_value(); var parseExtensibleFilterString = require_parse_extensible_filter_string(); var attrRegex = /^[-_a-zA-Z0-9]+/; module2.exports = function parseExpr(inputString) { let attribute; let match; let remainder; if (inputString[0] === ":" || inputString.indexOf(":=") > 0) { return parseExtensibleFilterString(inputString); } else if ((match = inputString.match(attrRegex)) !== null) { attribute = match[0]; remainder = inputString.substring(attribute.length); } else { throw new Error("invalid attribute name"); } if (remainder === "=*") { return new PresenceFilter({ attribute }); } else if (remainder[0] === "=") { remainder = remainder.substring(1); if (remainder.indexOf("*") !== -1) { const val = escapeSubstring(remainder); return new SubstringFilter({ attribute, initial: val.initial, any: val.any, final: val.final }); } else { return new EqualityFilter({ attribute, value: escapeFilterValue(remainder) }); } } else if (remainder[0] === ">" && remainder[1] === "=") { return new GreaterThanEqualsFilter({ attribute, value: escapeFilterValue(remainder.substring(2)) }); } else if (remainder[0] === "<" && remainder[1] === "=") { return new LessThanEqualsFilter({ attribute, value: escapeFilterValue(remainder.substring(2)) }); } else if (remainder[0] === "~" && remainder[1] === "=") { return new ApproximateFilter({ attribute, value: escapeFilterValue(remainder.substring(2)) }); } throw new Error("invalid expression"); }; } }); // node_modules/@ldapjs/filter/lib/string-parsing/parse-filter.js var require_parse_filter = __commonJS({ "node_modules/@ldapjs/filter/lib/string-parsing/parse-filter.js"(exports, module2) { "use strict"; var AndFilter = require_and(); var OrFilter = require_or(); var NotFilter = require_not(); var parseExpression = require_parse_expression(); var unbalancedError = Error("unbalanced parentheses"); module2.exports = function parseFilter(inputString, start = 0) { let cur = start; const len = inputString.length; let res; let end; let output; const children = []; if (inputString[cur++] !== "(") { throw Error("missing opening parentheses"); } if (inputString[cur] === "&") { cur++; if (inputString[cur] === ")") { output = new AndFilter({}); } else { do { res = parseFilter(inputString, cur); children.push(res.filter); cur = res.end + 1; } while (cur < len && inputString[cur] !== ")"); output = new AndFilter({ filters: children }); } } else if (inputString[cur] === "|") { cur++; do { res = parseFilter(inputString, cur); children.push(res.filter); cur = res.end + 1; } while (cur < len && inputString[cur] !== ")"); output = new OrFilter({ filters: children }); } else if (inputString[cur] === "!") { res = parseFilter(inputString, cur + 1); output = new NotFilter({ filter: res.filter }); cur = res.end + 1; if (inputString[cur] !== ")") { throw unbalancedError; } } else { end = inputString.indexOf(")", cur); if (end === -1) { throw unbalancedError; } output = parseExpression(inputString.substring(cur, end)); cur = end; } return { end: cur, filter: output }; }; } }); // node_modules/@ldapjs/filter/lib/string-parsing/parse-string.js var require_parse_string2 = __commonJS({ "node_modules/@ldapjs/filter/lib/string-parsing/parse-string.js"(exports, module2) { "use strict"; var parseFilter = require_parse_filter(); module2.exports = function parseString(inputString) { if (typeof inputString !== "string") { throw Error("input must be a string"); } if (inputString.length < 1) { throw Error("input string cannot be empty"); } let normalizedString = inputString; if (normalizedString.charAt(0) !== "(") { normalizedString = `(${normalizedString})`; } const parsed = parseFilter(normalizedString); if (parsed.end < inputString.length - 1) { throw Error("unbalanced parentheses"); } return parsed.filter; }; } }); // node_modules/@ldapjs/filter/lib/ber-parsing/index.js var require_ber_parsing = __commonJS({ "node_modules/@ldapjs/filter/lib/ber-parsing/index.js"(exports, module2) { "use strict"; var { search } = require_protocol(); var FILTERS = { [search.FILTER_AND]: require_and(), [search.FILTER_APPROX]: require_approximate(), [search.FILTER_EQUALITY]: require_equality(), [search.FILTER_EXT]: require_extensible(), [search.FILTER_GE]: require_greater_than_equals(), [search.FILTER_LE]: require_less_than_equals(), [search.FILTER_NOT]: require_not(), [search.FILTER_OR]: require_or(), [search.FILTER_PRESENT]: require_presence(), [search.FILTER_SUBSTRINGS]: require_substring() }; module2.exports = function parseBer(ber) { if (Object.prototype.toString.call(ber) !== "[object BerReader]") { throw new TypeError("ber (BerReader) required"); } return _parse(ber); }; function _parse(ber) { let f; const filterStartOffset = ber.offset; const type = ber.readSequence(); switch (type) { case search.FILTER_AND: case search.FILTER_OR: { f = new FILTERS[type](); parseSet(f); break; } case search.FILTER_NOT: { const innerFilter = _parse(ber); f = new FILTERS[type]({ filter: innerFilter }); break; } case search.FILTER_APPROX: case search.FILTER_EQUALITY: case search.FILTER_EXT: case search.FILTER_GE: case search.FILTER_LE: case search.FILTER_PRESENT: case search.FILTER_SUBSTRINGS: { f = FILTERS[type].parse(getBerBuffer(ber)); break; } default: { throw Error("invalid search filter type: 0x" + type.toString(16).padStart(2, "0")); } } return f; function parseSet(f2) { const end = ber.offset + ber.length; while (ber.offset < end) { const parsed = _parse(ber); f2.addClause(parsed); } } function getBerBuffer(inputBer) { ber.setOffset(filterStartOffset); const tag = inputBer.peek(); return inputBer.readRawBuffer(tag); } } } }); // node_modules/@ldapjs/filter/lib/index.js var require_lib2 = __commonJS({ "node_modules/@ldapjs/filter/lib/index.js"(exports, module2) { "use strict"; var testValues = require_test_values(); var getAttributeValue = require_get_attribute_value(); var FilterString = require_filter_string(); var AndFilter = require_and(); var ApproximateFilter = require_approximate(); var EqualityFilter = require_equality(); var ExtensibleFilter = require_extensible(); var GreaterThanEqualsFilter = require_greater_than_equals(); var LessThanEqualsFilter = require_less_than_equals(); var NotFilter = require_not(); var OrFilter = require_or(); var PresenceFilter = require_presence(); var SubstringFilter = require_substring(); var deprecations = require_deprecations4(); var parseString = require_parse_string2(); module2.exports = { parseBer: require_ber_parsing(), parse: (string) => { deprecations.emit("LDAP_FILTER_DEP_001"); return parseString(string); }, parseString, testValues, getAttrValue: getAttributeValue, getAttributeValue, FilterString, AndFilter, ApproximateFilter, EqualityFilter, ExtensibleFilter, GreaterThanEqualsFilter, LessThanEqualsFilter, NotFilter, OrFilter, PresenceFilter, SubstringFilter }; } }); // node_modules/@ldapjs/messages/lib/messages/search-request.js var require_search_request = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/search-request.js"(exports, module2) { "use strict"; var LdapMessage = require_ldap_message(); var { operations, search } = require_protocol(); var { DN } = require_dn2(); var filter = require_lib2(); var { BerReader, BerTypes } = require_asn1(); var warning = require_deprecations(); var recognizedScopes = /* @__PURE__ */ new Map([ ["base", [search.SCOPE_BASE_OBJECT, "base"]], ["single", [search.SCOPE_ONE_LEVEL, "single", "one"]], ["subtree", [search.SCOPE_SUBTREE, "subtree", "sub"]] ]); var scopeAliasToScope = (alias) => { alias = typeof alias === "string" ? alias.toLowerCase() : alias; if (recognizedScopes.has(alias)) { return recognizedScopes.get(alias)[0]; } for (const value of recognizedScopes.values()) { if (value.includes(alias)) { return value[0]; } } return void 0; }; var isValidAttributeString = (str) => { if (["*", "1.1", "+"].includes(str) === true) { return true; } if (/^@[a-zA-Z][\w\d.-]*$/.test(str) === true) { return true; } if (/^[a-zA-Z][\w\d.;-]*$/.test(str) === true) { return true; } return false; }; var _baseObject, _scope, _derefAliases, _sizeLimit, _timeLimit, _typesOnly, _filter, _attributes; var SearchRequest = class extends LdapMessage { constructor(options = {}) { var _a, _b, _c, _d, _e, _f, _g, _h; options.protocolOp = operations.LDAP_REQ_SEARCH; super(options); __privateAdd(this, _baseObject, void 0); __privateAdd(this, _scope, void 0); __privateAdd(this, _derefAliases, void 0); __privateAdd(this, _sizeLimit, void 0); __privateAdd(this, _timeLimit, void 0); __privateAdd(this, _typesOnly, void 0); __privateAdd(this, _filter, void 0); __privateAdd(this, _attributes, []); this.baseObject = (_a = options.baseObject) != null ? _a : ""; this.scope = (_b = options.scope) != null ? _b : search.SCOPE_BASE_OBJECT; this.derefAliases = (_c = options.derefAliases) != null ? _c : search.NEVER_DEREF_ALIASES; this.sizeLimit = (_d = options.sizeLimit) != null ? _d : 0; this.timeLimit = (_e = options.timeLimit) != null ? _e : 0; this.typesOnly = (_f = options.typesOnly) != null ? _f : false; this.filter = (_g = options.filter) != null ? _g : new filter.PresenceFilter({ attribute: "objectclass" }); this.attributes = (_h = options.attributes) != null ? _h : []; } get _dn() { return __privateGet(this, _baseObject); } get type() { return "SearchRequest"; } get attributes() { return __privateGet(this, _attributes); } set attributes(attrs) { if (Array.isArray(attrs) === false) { throw Error("attributes must be an array of attribute strings"); } const newAttrs = []; for (const attr of attrs) { if (typeof attr === "string" && isValidAttributeString(attr) === true) { newAttrs.push(attr); } else if (typeof attr === "string" && attr === "") { warning.emit("LDAP_ATTRIBUTE_SPEC_ERR_001"); } else { throw Error("attribute must be a valid string"); } } __privateSet(this, _attributes, newAttrs); } get baseObject() { return __privateGet(this, _baseObject); } set baseObject(obj) { if (typeof obj === "string") { __privateSet(this, _baseObject, DN.fromString(obj)); } else if (Object.prototype.toString.call(obj) === "[object LdapDn]") { __privateSet(this, _baseObject, obj); } else { throw Error("baseObject must be a DN string or DN instance"); } } get derefAliases() { return __privateGet(this, _derefAliases); } set derefAliases(value) { if (Number.isInteger(value) === false) { throw Error("derefAliases must be set to an integer"); } __privateSet(this, _derefAliases, value); } get filter() { return __privateGet(this, _filter); } set filter(value) { if (typeof value !== "string" && Object.prototype.toString.call(value) !== "[object FilterString]") { throw Error("filter must be a string or a FilterString instance"); } if (typeof value === "string") { __privateSet(this, _filter, filter.parseString(value)); } else { __privateSet(this, _filter, value); } } get scope() { return __privateGet(this, _scope); } set scope(value) { const resolvedScope = scopeAliasToScope(value); if (resolvedScope === void 0) { throw Error(value + " is an invalid search scope"); } __privateSet(this, _scope, resolvedScope); } get scopeName() { switch (__privateGet(this, _scope)) { case search.SCOPE_BASE_OBJECT: return "base"; case search.SCOPE_ONE_LEVEL: return "single"; case search.SCOPE_SUBTREE: return "subtree"; } } get sizeLimit() { return __privateGet(this, _sizeLimit); } set sizeLimit(value) { if (Number.isInteger(value) === false) { throw Error("sizeLimit must be an integer"); } __privateSet(this, _sizeLimit, value); } get timeLimit() { return __privateGet(this, _timeLimit); } set timeLimit(value) { if (Number.isInteger(value) === false) { throw Error("timeLimit must be an integer"); } __privateSet(this, _timeLimit, value); } get typesOnly() { return __privateGet(this, _typesOnly); } set typesOnly(value) { if (typeof value !== "boolean") { throw Error("typesOnly must be set to a boolean value"); } __privateSet(this, _typesOnly, value); } _toBer(ber) { ber.startSequence(operations.LDAP_REQ_SEARCH); ber.writeString(__privateGet(this, _baseObject).toString()); ber.writeEnumeration(__privateGet(this, _scope)); ber.writeEnumeration(__privateGet(this, _derefAliases)); ber.writeInt(__privateGet(this, _sizeLimit)); ber.writeInt(__privateGet(this, _timeLimit)); ber.writeBoolean(__privateGet(this, _typesOnly)); ber.appendBuffer(__privateGet(this, _filter).toBer().buffer); ber.startSequence(BerTypes.Sequence | BerTypes.Constructor); for (const attr of __privateGet(this, _attributes)) { ber.writeString(attr); } ber.endSequence(); ber.endSequence(); return ber; } _pojo(obj = {}) { obj.baseObject = this.baseObject.toString(); obj.scope = this.scopeName; obj.derefAliases = this.derefAliases; obj.sizeLimit = this.sizeLimit; obj.timeLimit = this.timeLimit; obj.typesOnly = this.typesOnly; obj.filter = this.filter.toString(); obj.attributes = []; for (const attr of __privateGet(this, _attributes)) { obj.attributes.push(attr); } return obj; } static parseToPojo(ber) { const protocolOp = ber.readSequence(); if (protocolOp !== operations.LDAP_REQ_SEARCH) { const op = protocolOp.toString(16).padStart(2, "0"); throw Error(`found wrong protocol operation: 0x${op}`); } const baseObject = ber.readString(); const scope = ber.readEnumeration(); const derefAliases = ber.readEnumeration(); const sizeLimit = ber.readInt(); const timeLimit = ber.readInt(); const typesOnly = ber.readBoolean(); const filterTag = ber.peek(); const filterBuffer = ber.readRawBuffer(filterTag); const parsedFilter = filter.parseBer(new BerReader(filterBuffer)); const attributes = []; ber.readSequence(); const endOfAttributesPos = ber.offset + ber.length; while (ber.offset < endOfAttributesPos) { const attribute = ber.readString(); attributes.push(attribute); } return { protocolOp, baseObject, scope, derefAliases, sizeLimit, timeLimit, typesOnly, filter: parsedFilter.toString(), attributes }; } }; _baseObject = new WeakMap(); _scope = new WeakMap(); _derefAliases = new WeakMap(); _sizeLimit = new WeakMap(); _timeLimit = new WeakMap(); _typesOnly = new WeakMap(); _filter = new WeakMap(); _attributes = new WeakMap(); __publicField(SearchRequest, "SCOPE_BASE", search.SCOPE_BASE_OBJECT); __publicField(SearchRequest, "SCOPE_SINGLE", search.SCOPE_ONE_LEVEL); __publicField(SearchRequest, "SCOPE_SUBTREE", search.SCOPE_SUBTREE); __publicField(SearchRequest, "DEREF_ALIASES_NEVER", search.NEVER_DEREF_ALIASES); __publicField(SearchRequest, "DEREF_IN_SEARCHING", search.DEREF_IN_SEARCHING); __publicField(SearchRequest, "DEREF_BASE_OBJECT", search.DEREF_BASE_OBJECT); __publicField(SearchRequest, "DEREF_ALWAYS", search.DEREF_ALWAYS); module2.exports = SearchRequest; } }); // node_modules/@ldapjs/messages/lib/messages/unbind-request.js var require_unbind_request = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/unbind-request.js"(exports, module2) { "use strict"; var LdapMessage = require_ldap_message(); var { operations } = require_protocol(); var UnbindRequest = class extends LdapMessage { constructor(options = {}) { options.protocolOp = operations.LDAP_REQ_UNBIND; super(options); } get type() { return "UnbindRequest"; } _toBer(ber) { ber.writeString("", operations.LDAP_REQ_UNBIND); return ber; } _pojo(obj = {}) { return obj; } static parseToPojo(ber) { const protocolOp = ber.readSequence(); if (protocolOp !== operations.LDAP_REQ_UNBIND) { const op = protocolOp.toString(16).padStart(2, "0"); throw Error(`found wrong protocol operation: 0x${op}`); } return { protocolOp }; } }; module2.exports = UnbindRequest; } }); // node_modules/@ldapjs/messages/lib/ldap-result.js var require_ldap_result = __commonJS({ "node_modules/@ldapjs/messages/lib/ldap-result.js"(exports, module2) { "use strict"; var LdapMessage = require_ldap_message(); var { resultCodes, operations } = require_protocol(); var warning = require_deprecations(); var _connection, _diagnosticMessage, _matchedDN, _referrals, _status; var LdapResult = class extends LdapMessage { constructor(options = {}) { var _a; super(options); __privateAdd(this, _connection, null); __privateAdd(this, _diagnosticMessage, void 0); __privateAdd(this, _matchedDN, void 0); __privateAdd(this, _referrals, []); __privateAdd(this, _status, void 0); __privateSet(this, _status, (_a = options.status) != null ? _a : resultCodes.SUCCESS); __privateSet(this, _matchedDN, options.matchedDN || ""); __privateSet(this, _referrals, options.referrals || []); __privateSet(this, _diagnosticMessage, options.diagnosticMessage || options.errorMessage || ""); if (options.errorMessage) { warning.emit("LDAP_MESSAGE_DEP_004"); } } get diagnosticMessage() { return __privateGet(this, _diagnosticMessage); } set diagnosticMessage(message) { __privateSet(this, _diagnosticMessage, message); } get matchedDN() { return __privateGet(this, _matchedDN); } set matchedDN(dn) { __privateSet(this, _matchedDN, dn); } get pojo() { let result = { status: this.status, matchedDN: this.matchedDN, diagnosticMessage: this.diagnosticMessage, referrals: this.referrals }; if (typeof this._pojo === "function") { result = this._pojo(result); } return result; } get referrals() { return __privateGet(this, _referrals).slice(0); } get status() { return __privateGet(this, _status); } set status(s) { __privateSet(this, _status, s); } get type() { return "LdapResult"; } addReferral(referral) { __privateGet(this, _referrals).push(referral); } _toBer(ber) { ber.startSequence(this.protocolOp); ber.writeEnumeration(this.status); ber.writeString(this.matchedDN); ber.writeString(this.diagnosticMessage); if (this.referrals.length > 0) { ber.startSequence(operations.LDAP_RES_REFERRAL); ber.writeStringArray(this.referrals); ber.endSequence(); } if (typeof this._writeResponse === "function") { this._writeResponse(ber); } ber.endSequence(); } static parseToPojo(ber) { throw Error("Use LdapMessage.parse, or a specific message type's parseToPojo, instead."); } static _parseToPojo({ opCode, berReader, pojo = {} }) { const protocolOp = berReader.readSequence(); if (protocolOp !== opCode) { const op = protocolOp.toString(16).padStart(2, "0"); throw Error(`found wrong protocol operation: 0x${op}`); } const status = berReader.readEnumeration(); const matchedDN = berReader.readString(); const diagnosticMessage = berReader.readString(); const referrals = []; if (berReader.peek() === operations.LDAP_RES_REFERRAL) { berReader.readSequence(operations.LDAP_RES_REFERRAL); const end = berReader.length; while (berReader.offset < end) { referrals.push(berReader.readString()); } } pojo.status = status; pojo.matchedDN = matchedDN; pojo.diagnosticMessage = diagnosticMessage; pojo.referrals = referrals; return pojo; } }; _connection = new WeakMap(); _diagnosticMessage = new WeakMap(); _matchedDN = new WeakMap(); _referrals = new WeakMap(); _status = new WeakMap(); module2.exports = LdapResult; } }); // node_modules/@ldapjs/messages/lib/messages/abandon-response.js var require_abandon_response = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/abandon-response.js"(exports, module2) { "use strict"; var LdapResult = require_ldap_result(); var AbandonResponse = class extends LdapResult { constructor(options = {}) { options.protocolOp = 0; super(options); } get type() { return "AbandonResponse"; } static parseToPojo(ber) { return LdapResult._parseToPojo({ opCode: 0, berReader: ber }); } }; module2.exports = AbandonResponse; } }); // node_modules/@ldapjs/messages/lib/messages/add-response.js var require_add_response = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/add-response.js"(exports, module2) { "use strict"; var LdapResult = require_ldap_result(); var { operations } = require_protocol(); var AddResponse = class extends LdapResult { constructor(options = {}) { options.protocolOp = operations.LDAP_RES_ADD; super(options); } get type() { return "AddResponse"; } static parseToPojo(ber) { return LdapResult._parseToPojo({ opCode: operations.LDAP_RES_ADD, berReader: ber }); } }; module2.exports = AddResponse; } }); // node_modules/@ldapjs/messages/lib/messages/bind-response.js var require_bind_response = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/bind-response.js"(exports, module2) { "use strict"; var LdapResult = require_ldap_result(); var { operations } = require_protocol(); var BindResponse = class extends LdapResult { constructor(options = {}) { options.protocolOp = operations.LDAP_RES_BIND; super(options); } get type() { return "BindResponse"; } static parseToPojo(ber) { return LdapResult._parseToPojo({ opCode: operations.LDAP_RES_BIND, berReader: ber }); } }; module2.exports = BindResponse; } }); // node_modules/@ldapjs/messages/lib/messages/compare-response.js var require_compare_response = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/compare-response.js"(exports, module2) { "use strict"; var LdapResult = require_ldap_result(); var { operations } = require_protocol(); var CompareResponse = class extends LdapResult { constructor(options = {}) { options.protocolOp = operations.LDAP_RES_COMPARE; super(options); } get type() { return "CompareResponse"; } static parseToPojo(ber) { return LdapResult._parseToPojo({ opCode: operations.LDAP_RES_COMPARE, berReader: ber }); } }; module2.exports = CompareResponse; } }); // node_modules/@ldapjs/messages/lib/messages/delete-response.js var require_delete_response = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/delete-response.js"(exports, module2) { "use strict"; var LdapResult = require_ldap_result(); var { operations } = require_protocol(); var DeleteResponse = class extends LdapResult { constructor(options = {}) { options.protocolOp = operations.LDAP_RES_DELETE; super(options); } get type() { return "DeleteResponse"; } static parseToPojo(ber) { return LdapResult._parseToPojo({ opCode: operations.LDAP_RES_DELETE, berReader: ber }); } }; module2.exports = DeleteResponse; } }); // node_modules/@ldapjs/messages/lib/messages/extension-response.js var require_extension_response = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/extension-response.js"(exports, module2) { "use strict"; var LdapResult = require_ldap_result(); var { operations } = require_protocol(); var _responseName, _responseValue; var ExtensionResponse = class extends LdapResult { constructor(options = {}) { options.protocolOp = operations.LDAP_RES_EXTENSION; super(options); __privateAdd(this, _responseName, void 0); __privateAdd(this, _responseValue, void 0); this.responseName = options.responseName; this.responseValue = options.responseValue; } get responseName() { return __privateGet(this, _responseName); } set responseName(value) { __privateSet(this, _responseName, value); } get responseValue() { return __privateGet(this, _responseValue); } set responseValue(value) { __privateSet(this, _responseValue, value); } get type() { return "ExtensionResponse"; } _writeResponse(ber) { if (this.responseName) { ber.writeString(this.responseName, 138); } if (this.responseValue === void 0) { return ber; } switch (this.responseName) { default: { ber.writeString(this.responseValue, 139); } } return ber; } static parseToPojo(ber) { const pojo = LdapResult._parseToPojo({ opCode: operations.LDAP_RES_EXTENSION, berReader: ber }); let responseName; if (ber.peek() === 138) { responseName = ber.readString(138); } if (ber.peek() !== 139) { return __spreadProps(__spreadValues({}, pojo), { responseName }); } const valueBuffer = ber.readTag(139); const responseValue = `${valueBuffer.toString("hex")}`; return __spreadProps(__spreadValues({}, pojo), { responseName, responseValue }); } }; _responseName = new WeakMap(); _responseValue = new WeakMap(); module2.exports = ExtensionResponse; } }); // node_modules/@ldapjs/messages/lib/messages/modify-response.js var require_modify_response = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/modify-response.js"(exports, module2) { "use strict"; var LdapResult = require_ldap_result(); var { operations } = require_protocol(); var ModifyResponse = class extends LdapResult { constructor(options = {}) { options.protocolOp = operations.LDAP_RES_MODIFY; super(options); } get type() { return "ModifyResponse"; } static parseToPojo(ber) { return LdapResult._parseToPojo({ opCode: operations.LDAP_RES_MODIFY, berReader: ber }); } }; module2.exports = ModifyResponse; } }); // node_modules/@ldapjs/messages/lib/messages/modifydn-response.js var require_modifydn_response = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/modifydn-response.js"(exports, module2) { "use strict"; var LdapResult = require_ldap_result(); var { operations } = require_protocol(); var ModifyDnResponse = class extends LdapResult { constructor(options = {}) { options.protocolOp = operations.LDAP_RES_MODRDN; super(options); } get type() { return "ModifyDnResponse"; } static parseToPojo(ber) { return LdapResult._parseToPojo({ opCode: operations.LDAP_RES_MODRDN, berReader: ber }); } }; module2.exports = ModifyDnResponse; } }); // node_modules/@ldapjs/messages/lib/messages/search-result-entry.js var require_search_result_entry = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/search-result-entry.js"(exports, module2) { "use strict"; var LdapMessage = require_ldap_message(); var Attribute = require_attribute(); var { operations } = require_protocol(); var { DN } = require_dn2(); var _objectName, _attributes; var SearchResultEntry = class extends LdapMessage { constructor(options = {}) { var _a, _b; options.protocolOp = operations.LDAP_RES_SEARCH_ENTRY; super(options); __privateAdd(this, _objectName, void 0); __privateAdd(this, _attributes, []); this.objectName = (_a = options.objectName) != null ? _a : ""; this.attributes = (_b = options.attributes) != null ? _b : []; } get _dn() { return __privateGet(this, _objectName); } get type() { return "SearchResultEntry"; } get attributes() { return __privateGet(this, _attributes).slice(0); } set attributes(attrs) { if (Array.isArray(attrs) === false) { throw Error("attrs must be an array"); } const newAttrs = []; for (const attr of attrs) { if (Attribute.isAttribute(attr) === false) { throw Error("attr must be an Attribute instance or Attribute-like object"); } if (Object.prototype.toString.call(attr) !== "[object LdapAttribute]") { newAttrs.push(new Attribute(attr)); continue; } newAttrs.push(attr); } __privateSet(this, _attributes, newAttrs); } get objectName() { return __privateGet(this, _objectName); } set objectName(value) { if (typeof value === "string") { __privateSet(this, _objectName, DN.fromString(value)); } else if (Object.prototype.toString.call(value) === "[object LdapDn]") { __privateSet(this, _objectName, value); } else { throw Error("objectName must be a DN string or an instance of LdapDn"); } } _toBer(ber) { ber.startSequence(operations.LDAP_RES_SEARCH_ENTRY); ber.writeString(__privateGet(this, _objectName).toString()); ber.startSequence(); for (const attr of __privateGet(this, _attributes)) { const attrBer = attr.toBer(); ber.appendBuffer(attrBer.buffer); } ber.endSequence(); ber.endSequence(); return ber; } _pojo(obj = {}) { obj.objectName = __privateGet(this, _objectName).toString(); obj.attributes = []; for (const attr of __privateGet(this, _attributes)) { obj.attributes.push(attr.pojo); } return obj; } static parseToPojo(ber) { const protocolOp = ber.readSequence(); if (protocolOp !== operations.LDAP_RES_SEARCH_ENTRY) { const op = protocolOp.toString(16).padStart(2, "0"); throw Error(`found wrong protocol operation: 0x${op}`); } const objectName = ber.readString(); const attributes = []; ber.readSequence(); const endOfAttributesPos = ber.offset + ber.length; while (ber.offset < endOfAttributesPos) { const attribute = Attribute.fromBer(ber); attributes.push(attribute); } return { protocolOp, objectName, attributes }; } }; _objectName = new WeakMap(); _attributes = new WeakMap(); module2.exports = SearchResultEntry; } }); // node_modules/@ldapjs/messages/lib/messages/search-result-reference.js var require_search_result_reference = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/search-result-reference.js"(exports, module2) { "use strict"; var LdapMessage = require_ldap_message(); var { operations } = require_protocol(); var _uri; var SearchResultReference = class extends LdapMessage { constructor(options = {}) { var _a; options.protocolOp = operations.LDAP_RES_SEARCH_REF; super(options); __privateAdd(this, _uri, void 0); this.uri = (_a = options.uri || options.uris) != null ? _a : []; } get type() { return "SearchResultReference"; } get uri() { return __privateGet(this, _uri).slice(0); } set uri(value) { if (Array.isArray(value) === false || value.some((v) => typeof v !== "string")) { throw Error("uri must be an array of strings"); } __privateSet(this, _uri, value.slice(0)); } get uris() { return this.uri; } set uris(value) { this.uri = value; } _toBer(ber) { ber.startSequence(operations.LDAP_RES_SEARCH_REF); for (const uri of __privateGet(this, _uri)) { ber.writeString(uri); } ber.endSequence(); return ber; } _pojo(obj = {}) { obj.uri = []; for (const uri of __privateGet(this, _uri)) { obj.uri.push(uri); } return obj; } static parseToPojo(ber) { const protocolOp = ber.readSequence(); if (protocolOp !== operations.LDAP_RES_SEARCH_REF) { const op = protocolOp.toString(16).padStart(2, "0"); throw Error(`found wrong protocol operation: 0x${op}`); } const uri = []; const endOfMessagePos = ber.offset + ber.length; while (ber.offset < endOfMessagePos) { const u = ber.readString(); uri.push(u); } return { protocolOp, uri }; } }; _uri = new WeakMap(); module2.exports = SearchResultReference; } }); // node_modules/@ldapjs/messages/lib/messages/search-result-done.js var require_search_result_done = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/search-result-done.js"(exports, module2) { "use strict"; var LdapResult = require_ldap_result(); var { operations } = require_protocol(); var _uri; var SearchResultDone = class extends LdapResult { constructor(options = {}) { options.protocolOp = operations.LDAP_RES_SEARCH_DONE; super(options); __privateAdd(this, _uri, void 0); } get type() { return "SearchResultDone"; } static parseToPojo(ber) { return LdapResult._parseToPojo({ opCode: operations.LDAP_RES_SEARCH_DONE, berReader: ber }); } }; _uri = new WeakMap(); module2.exports = SearchResultDone; } }); // node_modules/@ldapjs/messages/lib/messages/intermediate-response.js var require_intermediate_response = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/intermediate-response.js"(exports, module2) { "use strict"; var LdapMessage = require_ldap_message(); var { operations } = require_protocol(); var partIsNotNumeric = (part) => /^\d+$/.test(part) === false; function isDottedDecimal(value) { if (typeof value !== "string") return false; const parts = value.split("."); const nonNumericParts = parts.filter(partIsNotNumeric); return nonNumericParts.length === 0; } var _responseName, _responseValue; var IntermediateResponse = class extends LdapMessage { constructor(options = {}) { var _a, _b; options.protocolOp = operations.LDAP_RES_INTERMEDIATE; super(options); __privateAdd(this, _responseName, void 0); __privateAdd(this, _responseValue, void 0); this.responseName = (_a = options.responseName) != null ? _a : null; this.responseValue = (_b = options.responseValue) != null ? _b : null; } get type() { return "IntermediateResponse"; } get responseName() { return __privateGet(this, _responseName); } set responseName(value) { if (value === null) return; if (isDottedDecimal(value) === false) { throw Error("responseName must be a numeric OID"); } __privateSet(this, _responseName, value); } get responseValue() { return __privateGet(this, _responseValue); } set responseValue(value) { if (value === null) return; if (typeof value !== "string") { throw Error("responseValue must be a string"); } __privateSet(this, _responseValue, value); } _toBer(ber) { ber.startSequence(operations.LDAP_RES_INTERMEDIATE); if (__privateGet(this, _responseName)) { ber.writeString(__privateGet(this, _responseName), 128); } if (__privateGet(this, _responseValue)) { ber.writeString(__privateGet(this, _responseValue), 129); } ber.endSequence(); return ber; } _pojo(obj = {}) { obj.responseName = __privateGet(this, _responseName); obj.responseValue = __privateGet(this, _responseValue); return obj; } static parseToPojo(ber) { const protocolOp = ber.readSequence(); if (protocolOp !== operations.LDAP_RES_INTERMEDIATE) { const op = protocolOp.toString(16).padStart(2, "0"); throw Error(`found wrong protocol operation: 0x${op}`); } let responseName; let responseValue; let tag = ber.peek(); switch (tag) { case 128: { responseName = ber.readString(tag); tag = ber.peek(); if (tag === 129) { responseValue = ber.readString(tag); } break; } case 129: { responseValue = ber.readString(tag); } } return { protocolOp, responseName, responseValue }; } }; _responseName = new WeakMap(); _responseValue = new WeakMap(); module2.exports = IntermediateResponse; } }); // node_modules/@ldapjs/messages/lib/parse-to-message.js var require_parse_to_message = __commonJS({ "node_modules/@ldapjs/messages/lib/parse-to-message.js"(exports, module2) { "use strict"; var { operations } = require_protocol(); var { getControl } = require_controls(); var messageClasses = { AbandonRequest: require_abandon_request(), AddRequest: require_add_request(), BindRequest: require_bind_request(), CompareRequest: require_compare_request(), DeleteRequest: require_delete_request(), ExtensionRequest: require_extension_request(), ModifyRequest: require_modify_request(), ModifyDnRequest: require_modifydn_request(), SearchRequest: require_search_request(), UnbindRequest: require_unbind_request(), AbandonResponse: require_abandon_response(), AddResponse: require_add_response(), BindResponse: require_bind_response(), CompareResponse: require_compare_response(), DeleteResponse: require_delete_response(), ExtensionResponse: require_extension_response(), ModifyResponse: require_modify_response(), ModifyDnResponse: require_modifydn_response(), SearchResultEntry: require_search_result_entry(), SearchResultReference: require_search_result_reference(), SearchResultDone: require_search_result_done(), IntermediateResponse: require_intermediate_response() }; module2.exports = function parseToMessage(ber) { const inputType = Object.prototype.toString.apply(ber); if (inputType !== "[object BerReader]") { throw TypeError(`Expected BerReader but got ${inputType}.`); } ber.readSequence(); const messageId = ber.readInt(); const messageType = identifyType(ber); const MessageClass = messageClasses[messageType]; const pojoMessage = MessageClass.parseToPojo(ber); const message = new MessageClass(__spreadValues({ messageId }, pojoMessage)); if (ber.peek() === 160) { ber.readSequence(); const end = ber.offset + ber.length; while (ber.offset < end) { const c = getControl(ber); if (c) { message.addControl(c); } } } return message; }; function identifyType(ber) { let result; switch (ber.peek()) { case operations.LDAP_REQ_ABANDON: { result = "AbandonRequest"; break; } case 0: { result = "AbandonResponse"; break; } case operations.LDAP_REQ_ADD: { result = "AddRequest"; break; } case operations.LDAP_RES_ADD: { result = "AddResponse"; break; } case operations.LDAP_REQ_BIND: { result = "BindRequest"; break; } case operations.LDAP_RES_BIND: { result = "BindResponse"; break; } case operations.LDAP_REQ_COMPARE: { result = "CompareRequest"; break; } case operations.LDAP_RES_COMPARE: { result = "CompareResponse"; break; } case operations.LDAP_REQ_DELETE: { result = "DeleteRequest"; break; } case operations.LDAP_RES_DELETE: { result = "DeleteResponse"; break; } case operations.LDAP_REQ_EXTENSION: { result = "ExtensionRequest"; break; } case operations.LDAP_RES_EXTENSION: { result = "ExtensionResponse"; break; } case operations.LDAP_REQ_MODIFY: { result = "ModifyRequest"; break; } case operations.LDAP_RES_MODIFY: { result = "ModifyResponse"; break; } case operations.LDAP_REQ_MODRDN: { result = "ModifyDnRequest"; break; } case operations.LDAP_RES_MODRDN: { result = "ModifyDnResponse"; break; } case operations.LDAP_REQ_SEARCH: { result = "SearchRequest"; break; } case operations.LDAP_RES_SEARCH_ENTRY: { result = "SearchResultEntry"; break; } case operations.LDAP_RES_SEARCH_REF: { result = "SearchResultReference"; break; } case operations.LDAP_RES_SEARCH_DONE: { result = "SearchResultDone"; break; } case operations.LDAP_REQ_UNBIND: { result = "UnbindRequest"; break; } case operations.LDAP_RES_INTERMEDIATE: { result = "IntermediateResponse"; break; } } return result; } } }); // node_modules/@ldapjs/messages/lib/ldap-message.js var require_ldap_message = __commonJS({ "node_modules/@ldapjs/messages/lib/ldap-message.js"(exports, module2) { "use strict"; var { BerReader, BerWriter } = require_asn1(); var warning = require_deprecations(); var _messageId, _protocolOp, _controls; var LdapMessage = class { constructor(options = {}) { __privateAdd(this, _messageId, 0); __privateAdd(this, _protocolOp, void 0); __privateAdd(this, _controls, []); var _a, _b, _c; __privateSet(this, _messageId, parseInt((_b = (_a = options.messageId) != null ? _a : options.messageID) != null ? _b : "1", 10)); if (options.messageID !== void 0) { warning.emit("LDAP_MESSAGE_DEP_001"); } if (typeof options.protocolOp === "number") { __privateSet(this, _protocolOp, options.protocolOp); } this.controls = (_c = options.controls) != null ? _c : []; } get [Symbol.toStringTag]() { return "LdapMessage"; } get controls() { return __privateGet(this, _controls).slice(0); } set controls(values) { if (Array.isArray(values) !== true) { throw Error("controls must be an array"); } const newControls = []; for (const val of values) { if (Object.prototype.toString.call(val) !== "[object LdapControl]") { throw Error("control must be an instance of LdapControl"); } newControls.push(val); } __privateSet(this, _controls, newControls); } get id() { return __privateGet(this, _messageId); } set id(value) { if (Number.isInteger(value) === false) { throw Error("id must be an integer"); } __privateSet(this, _messageId, value); } get messageId() { return this.id; } set messageId(value) { this.id = value; } get messageID() { warning.emit("LDAP_MESSAGE_DEP_001"); return this.id; } set messageID(value) { warning.emit("LDAP_MESSAGE_DEP_001"); this.id = value; } get dn() { return this._dn; } get protocolOp() { return __privateGet(this, _protocolOp); } get type() { return "LdapMessage"; } get json() { warning.emit("LDAP_MESSAGE_DEP_002"); return this.pojo; } get pojo() { let result = { messageId: this.id, protocolOp: __privateGet(this, _protocolOp), type: this.type }; if (typeof this._pojo === "function") { result = this._pojo(result); } result.controls = __privateGet(this, _controls).map((c) => c.pojo); return result; } addControl(control) { __privateGet(this, _controls).push(control); } toBer() { if (typeof this._toBer !== "function") { throw Error(`${this.type} does not implement _toBer`); } const writer = new BerWriter(); writer.startSequence(); writer.writeInt(this.id); this._toBer(writer); if (__privateGet(this, _controls).length > 0) { writer.startSequence(160); for (const control of __privateGet(this, _controls)) { control.toBer(writer); } writer.endSequence(); } writer.endSequence(); return new BerReader(writer.buffer); } toString() { return JSON.stringify(this.pojo); } static parse(ber) { return require_parse_to_message()(ber); } static parseToPojo(ber) { throw Error("Use LdapMessage.parse, or a specific message type's parseToPojo, instead."); } }; _messageId = new WeakMap(); _protocolOp = new WeakMap(); _controls = new WeakMap(); module2.exports = LdapMessage; } }); // node_modules/@ldapjs/messages/lib/messages/extension-responses/password-modify.js var require_password_modify = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/extension-responses/password-modify.js"(exports, module2) { "use strict"; var { BerReader } = require_asn1(); var ExtensionResponse = require_extension_response(); var PasswordModifyResponse = class extends ExtensionResponse { static fromResponse(response) { if (response.responseValue === void 0) { return new PasswordModifyResponse(); } const valueBuffer = Buffer.from(response.responseValue.substring(8), "hex"); const reader = new BerReader(valueBuffer); reader.readSequence(); const responseValue = reader.readString(128); return new PasswordModifyResponse({ responseValue }); } }; module2.exports = PasswordModifyResponse; } }); // node_modules/@ldapjs/messages/lib/messages/extension-responses/who-am-i.js var require_who_am_i = __commonJS({ "node_modules/@ldapjs/messages/lib/messages/extension-responses/who-am-i.js"(exports, module2) { "use strict"; var ExtensionResponse = require_extension_response(); var WhoAmIResponse = class extends ExtensionResponse { static fromResponse(response) { if (response.responseValue === void 0) { return new WhoAmIResponse(); } const valueBuffer = Buffer.from(response.responseValue.substring(8), "hex"); const responseValue = valueBuffer.toString("utf8"); return new WhoAmIResponse({ responseValue }); } }; module2.exports = WhoAmIResponse; } }); // node_modules/@ldapjs/messages/index.js var require_messages = __commonJS({ "node_modules/@ldapjs/messages/index.js"(exports, module2) { "use strict"; module2.exports = { LdapMessage: require_ldap_message(), LdapResult: require_ldap_result(), AbandonRequest: require_abandon_request(), AddRequest: require_add_request(), BindRequest: require_bind_request(), CompareRequest: require_compare_request(), DeleteRequest: require_delete_request(), ExtensionRequest: require_extension_request(), ModifyRequest: require_modify_request(), ModifyDnRequest: require_modifydn_request(), SearchRequest: require_search_request(), UnbindRequest: require_unbind_request(), AbandonResponse: require_abandon_response(), AddResponse: require_add_response(), BindResponse: require_bind_response(), CompareResponse: require_compare_response(), DeleteResponse: require_delete_response(), ExtensionResponse: require_extension_response(), ModifyResponse: require_modify_response(), ModifyDnResponse: require_modifydn_response(), SearchResultEntry: require_search_result_entry(), SearchResultReference: require_search_result_reference(), SearchResultDone: require_search_result_done(), PasswordModifyResponse: require_password_modify(), WhoAmIResponse: require_who_am_i(), IntermediateResponse: require_intermediate_response() }; } }); // node_modules/ldapjs/lib/messages/search_response.js var require_search_response = __commonJS({ "node_modules/ldapjs/lib/messages/search_response.js"(exports, module2) { var assert = require_assert(); var Attribute = require_attribute(); var { SearchResultEntry: SearchEntry, SearchResultReference: SearchReference, SearchResultDone } = require_messages(); var parseDN = require_dn2().DN.fromString; var SearchResponse = class extends SearchResultDone { constructor(options = {}) { super(options); __publicField(this, "attributes"); __publicField(this, "notAttributes"); __publicField(this, "sentEntries"); this.attributes = options.attributes ? options.attributes.slice() : []; this.notAttributes = []; this.sentEntries = 0; } }; SearchResponse.prototype.send = function(entry, nofiltering) { if (!entry || typeof entry !== "object") { throw new TypeError("entry (SearchEntry) required"); } if (nofiltering === void 0) { nofiltering = false; } if (typeof nofiltering !== "boolean") { throw new TypeError("noFiltering must be a boolean"); } const self2 = this; const savedAttrs = {}; let save = null; if (entry instanceof SearchEntry || entry instanceof SearchReference) { if (!entry.messageId) { entry.messageId = this.messageId; } if (entry.messageId !== this.messageId) { throw new Error("SearchEntry messageId mismatch"); } } else { if (!entry.attributes) { throw new Error("entry.attributes required"); } const all = self2.attributes.indexOf("*") !== -1; Object.keys(entry.attributes).forEach(function(a) { const _a = a.toLowerCase(); if (!nofiltering && _a.length && _a[0] === "_") { savedAttrs[a] = entry.attributes[a]; delete entry.attributes[a]; } else if (!nofiltering && self2.notAttributes.indexOf(_a) !== -1) { savedAttrs[a] = entry.attributes[a]; delete entry.attributes[a]; } else if (all) { } else if (self2.attributes.length && self2.attributes.indexOf(_a) === -1) { savedAttrs[a] = entry.attributes[a]; delete entry.attributes[a]; } }); save = entry; entry = new SearchEntry({ objectName: typeof save.dn === "string" ? parseDN(save.dn) : save.dn, messageId: self2.messageId, attributes: Attribute.fromObject(entry.attributes) }); } try { this.log.debug("%s: sending: %j", this.connection.ldap.id, entry.pojo); this.connection.write(entry.toBer().buffer); this.sentEntries++; Object.keys(savedAttrs).forEach(function(k) { save.attributes[k] = savedAttrs[k]; }); } catch (e) { this.log.warn(e, "%s failure to write message %j", this.connection.ldap.id, this.pojo); } }; SearchResponse.prototype.createSearchEntry = function(object) { var _a; assert.object(object); const entry = new SearchEntry({ messageId: this.messageId, objectName: object.objectName || object.dn, attributes: (_a = object.attributes) != null ? _a : [] }); return entry; }; SearchResponse.prototype.createSearchReference = function(uris) { if (!uris) { throw new TypeError("uris ([string]) required"); } if (!Array.isArray(uris)) { uris = [uris]; } const self2 = this; return new SearchReference({ messageId: self2.messageId, uri: uris }); }; module2.exports = SearchResponse; } }); // node_modules/ldapjs/lib/messages/parser.js var require_parser = __commonJS({ "node_modules/ldapjs/lib/messages/parser.js"(exports, module2) { var EventEmitter = require("events").EventEmitter; var util = require("util"); var assert = require_assert(); var asn1 = require_asn1(); var logger = require_logger(); var messages = require_messages(); var AbandonRequest = messages.AbandonRequest; var AddRequest = messages.AddRequest; var AddResponse = messages.AddResponse; var BindRequest = messages.BindRequest; var BindResponse = messages.BindResponse; var CompareRequest = messages.CompareRequest; var CompareResponse = messages.CompareResponse; var DeleteRequest = messages.DeleteRequest; var DeleteResponse = messages.DeleteResponse; var ExtendedRequest = messages.ExtensionRequest; var ExtendedResponse = messages.ExtensionResponse; var ModifyRequest = messages.ModifyRequest; var ModifyResponse = messages.ModifyResponse; var ModifyDNRequest = messages.ModifyDnRequest; var ModifyDNResponse = messages.ModifyDnResponse; var SearchRequest = messages.SearchRequest; var SearchEntry = messages.SearchResultEntry; var SearchReference = messages.SearchResultReference; var SearchResponse = require_search_response(); var UnbindRequest = messages.UnbindRequest; var LDAPResult = messages.LdapResult; var Protocol = require_protocol(); var BerReader = asn1.BerReader; function Parser(options = {}) { assert.object(options); EventEmitter.call(this); this.buffer = null; this.log = options.log || logger; } util.inherits(Parser, EventEmitter); Parser.prototype.write = function(data) { if (!data || !Buffer.isBuffer(data)) { throw new TypeError("data (buffer) required"); } let nextMessage = null; const self2 = this; function end() { if (nextMessage) { return self2.write(nextMessage); } return true; } self2.buffer = self2.buffer ? Buffer.concat([self2.buffer, data]) : data; let ber = new BerReader(self2.buffer); let foundSeq = false; try { foundSeq = ber.readSequence(); } catch (e) { this.emit("error", e); } if (!foundSeq || ber.remain < ber.length) { return false; } else if (ber.remain > ber.length) { nextMessage = self2.buffer.slice(ber.offset + ber.length); const currOffset = ber.offset; ber = new BerReader(ber.buffer.subarray(0, currOffset + ber.length)); ber.readSequence(); assert.equal(ber.remain, ber.length); } self2.buffer = null; let message; try { if (Object.prototype.toString.call(ber) === "[object BerReader]") { message = messages.LdapMessage.parse(ber.sequenceToReader()); } else { message = this.getMessage(ber); } if (!message) { return end(); } message.log = this.log; } catch (e) { this.emit("error", e, message); return false; } this.emit("message", message); return end(); }; Parser.prototype.getMessage = function(ber) { assert.ok(ber); const self2 = this; const messageId = ber.readInt(); const type = ber.readSequence(); let Message; switch (type) { case Protocol.operations.LDAP_REQ_ABANDON: Message = AbandonRequest; break; case Protocol.operations.LDAP_REQ_ADD: Message = AddRequest; break; case Protocol.operations.LDAP_RES_ADD: Message = AddResponse; break; case Protocol.operations.LDAP_REQ_BIND: Message = BindRequest; break; case Protocol.operations.LDAP_RES_BIND: Message = BindResponse; break; case Protocol.operations.LDAP_REQ_COMPARE: Message = CompareRequest; break; case Protocol.operations.LDAP_RES_COMPARE: Message = CompareResponse; break; case Protocol.operations.LDAP_REQ_DELETE: Message = DeleteRequest; break; case Protocol.operations.LDAP_RES_DELETE: Message = DeleteResponse; break; case Protocol.operations.LDAP_REQ_EXTENSION: Message = ExtendedRequest; break; case Protocol.operations.LDAP_RES_EXTENSION: Message = ExtendedResponse; break; case Protocol.operations.LDAP_REQ_MODIFY: Message = ModifyRequest; break; case Protocol.operations.LDAP_RES_MODIFY: Message = ModifyResponse; break; case Protocol.operations.LDAP_REQ_MODRDN: Message = ModifyDNRequest; break; case Protocol.operations.LDAP_RES_MODRDN: Message = ModifyDNResponse; break; case Protocol.operations.LDAP_REQ_SEARCH: Message = SearchRequest; break; case Protocol.operations.LDAP_RES_SEARCH_ENTRY: Message = SearchEntry; break; case Protocol.operations.LDAP_RES_SEARCH_REF: Message = SearchReference; break; case Protocol.operations.LDAP_RES_SEARCH: Message = SearchResponse; break; case Protocol.operations.LDAP_REQ_UNBIND: Message = UnbindRequest; break; default: this.emit("error", new Error("Op 0x" + (type ? type.toString(16) : "??") + " not supported"), new LDAPResult({ messageId, protocolOp: type || Protocol.operations.LDAP_RES_EXTENSION })); return false; } return new Message({ messageId, log: self2.log }); }; module2.exports = Parser; } }); // node_modules/ldapjs/lib/messages/index.js var require_messages2 = __commonJS({ "node_modules/ldapjs/lib/messages/index.js"(exports, module2) { var messages = require_messages(); var Parser = require_parser(); var SearchResponse = require_search_response(); module2.exports = { LDAPMessage: messages.LdapMessage, LDAPResult: messages.LdapResult, Parser, AbandonRequest: messages.AbandonRequest, AbandonResponse: messages.AbandonResponse, AddRequest: messages.AddRequest, AddResponse: messages.AddResponse, BindRequest: messages.BindRequest, BindResponse: messages.BindResponse, CompareRequest: messages.CompareRequest, CompareResponse: messages.CompareResponse, DeleteRequest: messages.DeleteRequest, DeleteResponse: messages.DeleteResponse, ExtendedRequest: messages.ExtensionRequest, ExtendedResponse: messages.ExtensionResponse, ModifyRequest: messages.ModifyRequest, ModifyResponse: messages.ModifyResponse, ModifyDNRequest: messages.ModifyDnRequest, ModifyDNResponse: messages.ModifyDnResponse, SearchRequest: messages.SearchRequest, SearchEntry: messages.SearchResultEntry, SearchReference: messages.SearchResultReference, SearchResponse, UnbindRequest: messages.UnbindRequest }; } }); // node_modules/ldapjs/lib/errors/codes.js var require_codes = __commonJS({ "node_modules/ldapjs/lib/errors/codes.js"(exports, module2) { "use strict"; module2.exports = { LDAP_SUCCESS: 0, LDAP_OPERATIONS_ERROR: 1, LDAP_PROTOCOL_ERROR: 2, LDAP_TIME_LIMIT_EXCEEDED: 3, LDAP_SIZE_LIMIT_EXCEEDED: 4, LDAP_COMPARE_FALSE: 5, LDAP_COMPARE_TRUE: 6, LDAP_AUTH_METHOD_NOT_SUPPORTED: 7, LDAP_STRONG_AUTH_REQUIRED: 8, LDAP_REFERRAL: 10, LDAP_ADMIN_LIMIT_EXCEEDED: 11, LDAP_UNAVAILABLE_CRITICAL_EXTENSION: 12, LDAP_CONFIDENTIALITY_REQUIRED: 13, LDAP_SASL_BIND_IN_PROGRESS: 14, LDAP_NO_SUCH_ATTRIBUTE: 16, LDAP_UNDEFINED_ATTRIBUTE_TYPE: 17, LDAP_INAPPROPRIATE_MATCHING: 18, LDAP_CONSTRAINT_VIOLATION: 19, LDAP_ATTRIBUTE_OR_VALUE_EXISTS: 20, LDAP_INVALID_ATTRIBUTE_SYNTAX: 21, LDAP_NO_SUCH_OBJECT: 32, LDAP_ALIAS_PROBLEM: 33, LDAP_INVALID_DN_SYNTAX: 34, LDAP_ALIAS_DEREF_PROBLEM: 36, LDAP_INAPPROPRIATE_AUTHENTICATION: 48, LDAP_INVALID_CREDENTIALS: 49, LDAP_INSUFFICIENT_ACCESS_RIGHTS: 50, LDAP_BUSY: 51, LDAP_UNAVAILABLE: 52, LDAP_UNWILLING_TO_PERFORM: 53, LDAP_LOOP_DETECT: 54, LDAP_SORT_CONTROL_MISSING: 60, LDAP_INDEX_RANGE_ERROR: 61, LDAP_NAMING_VIOLATION: 64, LDAP_OBJECTCLASS_VIOLATION: 65, LDAP_NOT_ALLOWED_ON_NON_LEAF: 66, LDAP_NOT_ALLOWED_ON_RDN: 67, LDAP_ENTRY_ALREADY_EXISTS: 68, LDAP_OBJECTCLASS_MODS_PROHIBITED: 69, LDAP_AFFECTS_MULTIPLE_DSAS: 71, LDAP_CONTROL_ERROR: 76, LDAP_OTHER: 80, LDAP_PROXIED_AUTHORIZATION_DENIED: 123 }; } }); // node_modules/ldapjs/lib/errors/index.js var require_errors2 = __commonJS({ "node_modules/ldapjs/lib/errors/index.js"(exports, module2) { "use strict"; var util = require("util"); var assert = require_assert(); var LDAPResult = require_messages2().LDAPResult; var CODES = require_codes(); var ERRORS = []; function LDAPError(message, dn, caller) { if (Error.captureStackTrace) { Error.captureStackTrace(this, caller || LDAPError); } this.lde_message = message; this.lde_dn = dn; } util.inherits(LDAPError, Error); Object.defineProperties(LDAPError.prototype, { name: { get: function getName() { return "LDAPError"; }, configurable: false }, code: { get: function getCode() { return CODES.LDAP_OTHER; }, configurable: false }, message: { get: function getMessage() { return this.lde_message || this.name; }, set: function setMessage(message) { this.lde_message = message; }, configurable: false }, dn: { get: function getDN() { return this.lde_dn ? this.lde_dn.toString() : ""; }, configurable: false } }); module2.exports = {}; module2.exports.LDAPError = LDAPError; Object.keys(CODES).forEach(function(code) { module2.exports[code] = CODES[code]; if (code === "LDAP_SUCCESS") { return; } let err = ""; let msg = ""; const pieces = code.split("_").slice(1); for (let i = 0; i < pieces.length; i++) { const lc = pieces[i].toLowerCase(); const key = lc.charAt(0).toUpperCase() + lc.slice(1); err += key; msg += key + (i + 1 < pieces.length ? " " : ""); } if (!/\w+Error$/.test(err)) { err += "Error"; } module2.exports[err] = function(message, dn, caller) { LDAPError.call(this, message, dn, caller || module2.exports[err]); }; module2.exports[err].constructor = module2.exports[err]; util.inherits(module2.exports[err], LDAPError); Object.defineProperties(module2.exports[err].prototype, { name: { get: function getName() { return err; }, configurable: false }, code: { get: function getCode() { return CODES[code]; }, configurable: false } }); ERRORS[CODES[code]] = { err, message: msg }; }); module2.exports.getError = function(res) { assert.ok(res instanceof LDAPResult, "res (LDAPResult) required"); const errObj = ERRORS[res.status]; const E = module2.exports[errObj.err]; return new E(res.errorMessage || errObj.message, res.matchedDN || null, module2.exports.getError); }; module2.exports.getMessage = function(code) { assert.number(code, "code (number) required"); const errObj = ERRORS[code]; return errObj && errObj.message ? errObj.message : ""; }; function ConnectionError(message) { LDAPError.call(this, message, null, ConnectionError); } util.inherits(ConnectionError, LDAPError); module2.exports.ConnectionError = ConnectionError; Object.defineProperties(ConnectionError.prototype, { name: { get: function() { return "ConnectionError"; }, configurable: false } }); function AbandonedError(message) { LDAPError.call(this, message, null, AbandonedError); } util.inherits(AbandonedError, LDAPError); module2.exports.AbandonedError = AbandonedError; Object.defineProperties(AbandonedError.prototype, { name: { get: function() { return "AbandonedError"; }, configurable: false } }); function TimeoutError(message) { LDAPError.call(this, message, null, TimeoutError); } util.inherits(TimeoutError, LDAPError); module2.exports.TimeoutError = TimeoutError; Object.defineProperties(TimeoutError.prototype, { name: { get: function() { return "TimeoutError"; }, configurable: false } }); } }); // node_modules/ldapjs/lib/client/request-queue/purge.js var require_purge = __commonJS({ "node_modules/ldapjs/lib/client/request-queue/purge.js"(exports, module2) { "use strict"; var { TimeoutError } = require_errors2(); module2.exports = function purge() { this.flush(function flushCB(a, b, c, cb) { cb(new TimeoutError("request queue timeout")); }); }; } }); // node_modules/ldapjs/lib/client/request-queue/index.js var require_request_queue = __commonJS({ "node_modules/ldapjs/lib/client/request-queue/index.js"(exports, module2) { "use strict"; var enqueue = require_enqueue(); var flush = require_flush(); var purge = require_purge(); module2.exports = function requestQueueFactory(options) { const opts = Object.assign({}, options); const q = { size: opts.size > 0 ? opts.size : Infinity, timeout: opts.timeout > 0 ? opts.timeout : 0, _queue: /* @__PURE__ */ new Set(), _timer: null, _frozen: false }; q.enqueue = enqueue.bind(q); q.flush = flush.bind(q); q.purge = purge.bind(q); q.freeze = function freeze() { this._frozen = true; }; q.thaw = function thaw() { this._frozen = false; }; return q; }; } }); // node_modules/ldapjs/lib/client/constants.js var require_constants = __commonJS({ "node_modules/ldapjs/lib/client/constants.js"(exports, module2) { "use strict"; module2.exports = { MAX_MSGID: Math.pow(2, 31) - 1 }; } }); // node_modules/ldapjs/lib/client/message-tracker/id-generator.js var require_id_generator = __commonJS({ "node_modules/ldapjs/lib/client/message-tracker/id-generator.js"(exports, module2) { "use strict"; var { MAX_MSGID } = require_constants(); module2.exports = function idGeneratorFactory(start = 0) { let currentID = start; return function nextID() { const id = currentID + 1; currentID = id >= MAX_MSGID ? 1 : id; return currentID; }; }; } }); // node_modules/ldapjs/lib/client/message-tracker/ge-window.js var require_ge_window = __commonJS({ "node_modules/ldapjs/lib/client/message-tracker/ge-window.js"(exports, module2) { "use strict"; var { MAX_MSGID } = require_constants(); module2.exports = function geWindow(ref, comp) { let max = ref + Math.floor(MAX_MSGID / 2); const min = ref; if (max >= MAX_MSGID) { max = max - MAX_MSGID - 1; return comp <= max || comp >= min; } else { return comp <= max && comp >= min; } }; } }); // node_modules/ldapjs/lib/client/message-tracker/purge-abandoned.js var require_purge_abandoned = __commonJS({ "node_modules/ldapjs/lib/client/message-tracker/purge-abandoned.js"(exports, module2) { "use strict"; var { AbandonedError } = require_errors2(); var geWindow = require_ge_window(); module2.exports = function purgeAbandoned(msgID, abandoned) { abandoned.forEach((val, key) => { if (geWindow(val.age, msgID) === false) return; val.cb(new AbandonedError("client request abandoned")); abandoned.delete(key); }); }; } }); // node_modules/ldapjs/lib/client/message-tracker/index.js var require_message_tracker = __commonJS({ "node_modules/ldapjs/lib/client/message-tracker/index.js"(exports, module2) { "use strict"; var idGeneratorFactory = require_id_generator(); var purgeAbandoned = require_purge_abandoned(); module2.exports = function messageTrackerFactory(options) { if (Object.prototype.toString.call(options) !== "[object Object]") { throw Error("options object is required"); } if (!options.id || typeof options.id !== "string") { throw Error("options.id string is required"); } if (!options.parser || Object.prototype.toString.call(options.parser) !== "[object Object]") { throw Error("options.parser object is required"); } let currentID = 0; const nextID = idGeneratorFactory(); const messages = /* @__PURE__ */ new Map(); const abandoned = /* @__PURE__ */ new Map(); const tracker = { id: options.id, parser: options.parser }; Object.defineProperty(tracker, "pending", { get() { return messages.size; } }); tracker.abandon = function abandonMessage(msgID) { if (messages.has(msgID) === false) return false; const toAbandon = messages.get(msgID); abandoned.set(msgID, { age: currentID, message: toAbandon.message, cb: toAbandon.callback }); return messages.delete(msgID); }; tracker.fetch = function fetchMessage(msgID) { const tracked = messages.get(msgID); if (tracked) { purgeAbandoned(msgID, abandoned); return tracked; } const abandonedMsg = abandoned.get(msgID); if (abandonedMsg) { return { message: abandonedMsg, callback: abandonedMsg.cb }; } return null; }; tracker.purge = function purgeMessages(cb) { messages.forEach((val, key) => { purgeAbandoned(key, abandoned); tracker.remove(key); cb(key, val.callback); }); }; tracker.remove = function removeMessage(msgID) { if (messages.delete(msgID) === false) { abandoned.delete(msgID); } }; tracker.track = function trackMessage(message, callback) { currentID = nextID(); message.messageId = currentID; messages.set(currentID, { callback, message }); }; return tracker; }; } }); // node_modules/wrappy/wrappy.js var require_wrappy = __commonJS({ "node_modules/wrappy/wrappy.js"(exports, module2) { module2.exports = wrappy; function wrappy(fn, cb) { if (fn && cb) return wrappy(fn)(cb); if (typeof fn !== "function") throw new TypeError("need wrapper function"); Object.keys(fn).forEach(function(k) { wrapper[k] = fn[k]; }); return wrapper; function wrapper() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } var ret = fn.apply(this, args); var cb2 = args[args.length - 1]; if (typeof ret === "function" && ret !== cb2) { Object.keys(cb2).forEach(function(k) { ret[k] = cb2[k]; }); } return ret; } } } }); // node_modules/once/once.js var require_once = __commonJS({ "node_modules/once/once.js"(exports, module2) { var wrappy = require_wrappy(); module2.exports = wrappy(once); module2.exports.strict = wrappy(onceStrict); once.proto = once(function() { Object.defineProperty(Function.prototype, "once", { value: function() { return once(this); }, configurable: true }); Object.defineProperty(Function.prototype, "onceStrict", { value: function() { return onceStrict(this); }, configurable: true }); }); function once(fn) { var f = function() { if (f.called) return f.value; f.called = true; return f.value = fn.apply(this, arguments); }; f.called = false; return f; } function onceStrict(fn) { var f = function() { if (f.called) throw new Error(f.onceError); f.called = true; return f.value = fn.apply(this, arguments); }; var name = fn.name || "Function wrapped with `once`"; f.onceError = name + " shouldn't be called more than once"; f.called = false; return f; } } }); // node_modules/precond/lib/errors.js var require_errors3 = __commonJS({ "node_modules/precond/lib/errors.js"(exports, module2) { var util = require("util"); function IllegalArgumentError(message) { Error.call(this, message); this.message = message; } util.inherits(IllegalArgumentError, Error); IllegalArgumentError.prototype.name = "IllegalArgumentError"; function IllegalStateError(message) { Error.call(this, message); this.message = message; } util.inherits(IllegalStateError, Error); IllegalStateError.prototype.name = "IllegalStateError"; module2.exports.IllegalStateError = IllegalStateError; module2.exports.IllegalArgumentError = IllegalArgumentError; } }); // node_modules/precond/lib/checks.js var require_checks = __commonJS({ "node_modules/precond/lib/checks.js"(exports, module2) { var util = require("util"); var errors = module2.exports = require_errors3(); function failCheck(ExceptionConstructor, callee, messageFormat, formatArgs) { messageFormat = messageFormat || ""; var message = util.format.apply(this, [messageFormat].concat(formatArgs)); var error = new ExceptionConstructor(message); Error.captureStackTrace(error, callee); throw error; } function failArgumentCheck(callee, message, formatArgs) { failCheck(errors.IllegalArgumentError, callee, message, formatArgs); } function failStateCheck(callee, message, formatArgs) { failCheck(errors.IllegalStateError, callee, message, formatArgs); } module2.exports.checkArgument = function(value, message) { if (!value) { failArgumentCheck(arguments.callee, message, Array.prototype.slice.call(arguments, 2)); } }; module2.exports.checkState = function(value, message) { if (!value) { failStateCheck(arguments.callee, message, Array.prototype.slice.call(arguments, 2)); } }; module2.exports.checkIsDef = function(value, message) { if (value !== void 0) { return value; } failArgumentCheck(arguments.callee, message || "Expected value to be defined but was undefined.", Array.prototype.slice.call(arguments, 2)); }; module2.exports.checkIsDefAndNotNull = function(value, message) { if (value != null) { return value; } failArgumentCheck(arguments.callee, message || 'Expected value to be defined and not null but got "' + typeOf(value) + '".', Array.prototype.slice.call(arguments, 2)); }; function typeOf(value) { var s = typeof value; if (s == "object") { if (!value) { return "null"; } else if (value instanceof Array) { return "array"; } } return s; } function typeCheck(expect) { return function(value, message) { var type = typeOf(value); if (type == expect) { return value; } failArgumentCheck(arguments.callee, message || 'Expected "' + expect + '" but got "' + type + '".', Array.prototype.slice.call(arguments, 2)); }; } module2.exports.checkIsString = typeCheck("string"); module2.exports.checkIsArray = typeCheck("array"); module2.exports.checkIsNumber = typeCheck("number"); module2.exports.checkIsBoolean = typeCheck("boolean"); module2.exports.checkIsFunction = typeCheck("function"); module2.exports.checkIsObject = typeCheck("object"); } }); // node_modules/precond/index.js var require_precond = __commonJS({ "node_modules/precond/index.js"(exports, module2) { module2.exports = require_checks(); } }); // node_modules/backoff/lib/backoff.js var require_backoff = __commonJS({ "node_modules/backoff/lib/backoff.js"(exports, module2) { var events = require("events"); var precond = require_precond(); var util = require("util"); function Backoff(backoffStrategy) { events.EventEmitter.call(this); this.backoffStrategy_ = backoffStrategy; this.maxNumberOfRetry_ = -1; this.backoffNumber_ = 0; this.backoffDelay_ = 0; this.timeoutID_ = -1; this.handlers = { backoff: this.onBackoff_.bind(this) }; } util.inherits(Backoff, events.EventEmitter); Backoff.prototype.failAfter = function(maxNumberOfRetry) { precond.checkArgument(maxNumberOfRetry > 0, "Expected a maximum number of retry greater than 0 but got %s.", maxNumberOfRetry); this.maxNumberOfRetry_ = maxNumberOfRetry; }; Backoff.prototype.backoff = function(err) { precond.checkState(this.timeoutID_ === -1, "Backoff in progress."); if (this.backoffNumber_ === this.maxNumberOfRetry_) { this.emit("fail", err); this.reset(); } else { this.backoffDelay_ = this.backoffStrategy_.next(); this.timeoutID_ = setTimeout(this.handlers.backoff, this.backoffDelay_); this.emit("backoff", this.backoffNumber_, this.backoffDelay_, err); } }; Backoff.prototype.onBackoff_ = function() { this.timeoutID_ = -1; this.emit("ready", this.backoffNumber_, this.backoffDelay_); this.backoffNumber_++; }; Backoff.prototype.reset = function() { this.backoffNumber_ = 0; this.backoffStrategy_.reset(); clearTimeout(this.timeoutID_); this.timeoutID_ = -1; }; module2.exports = Backoff; } }); // node_modules/backoff/lib/strategy/strategy.js var require_strategy = __commonJS({ "node_modules/backoff/lib/strategy/strategy.js"(exports, module2) { var events = require("events"); var util = require("util"); function isDef(value) { return value !== void 0 && value !== null; } function BackoffStrategy(options) { options = options || {}; if (isDef(options.initialDelay) && options.initialDelay < 1) { throw new Error("The initial timeout must be greater than 0."); } else if (isDef(options.maxDelay) && options.maxDelay < 1) { throw new Error("The maximal timeout must be greater than 0."); } this.initialDelay_ = options.initialDelay || 100; this.maxDelay_ = options.maxDelay || 1e4; if (this.maxDelay_ <= this.initialDelay_) { throw new Error("The maximal backoff delay must be greater than the initial backoff delay."); } if (isDef(options.randomisationFactor) && (options.randomisationFactor < 0 || options.randomisationFactor > 1)) { throw new Error("The randomisation factor must be between 0 and 1."); } this.randomisationFactor_ = options.randomisationFactor || 0; } BackoffStrategy.prototype.getMaxDelay = function() { return this.maxDelay_; }; BackoffStrategy.prototype.getInitialDelay = function() { return this.initialDelay_; }; BackoffStrategy.prototype.next = function() { var backoffDelay = this.next_(); var randomisationMultiple = 1 + Math.random() * this.randomisationFactor_; var randomizedDelay = Math.round(backoffDelay * randomisationMultiple); return randomizedDelay; }; BackoffStrategy.prototype.next_ = function() { throw new Error("BackoffStrategy.next_() unimplemented."); }; BackoffStrategy.prototype.reset = function() { this.reset_(); }; BackoffStrategy.prototype.reset_ = function() { throw new Error("BackoffStrategy.reset_() unimplemented."); }; module2.exports = BackoffStrategy; } }); // node_modules/backoff/lib/strategy/exponential.js var require_exponential = __commonJS({ "node_modules/backoff/lib/strategy/exponential.js"(exports, module2) { var util = require("util"); var precond = require_precond(); var BackoffStrategy = require_strategy(); function ExponentialBackoffStrategy(options) { BackoffStrategy.call(this, options); this.backoffDelay_ = 0; this.nextBackoffDelay_ = this.getInitialDelay(); this.factor_ = ExponentialBackoffStrategy.DEFAULT_FACTOR; if (options && options.factor !== void 0) { precond.checkArgument(options.factor > 1, "Exponential factor should be greater than 1 but got %s.", options.factor); this.factor_ = options.factor; } } util.inherits(ExponentialBackoffStrategy, BackoffStrategy); ExponentialBackoffStrategy.DEFAULT_FACTOR = 2; ExponentialBackoffStrategy.prototype.next_ = function() { this.backoffDelay_ = Math.min(this.nextBackoffDelay_, this.getMaxDelay()); this.nextBackoffDelay_ = this.backoffDelay_ * this.factor_; return this.backoffDelay_; }; ExponentialBackoffStrategy.prototype.reset_ = function() { this.backoffDelay_ = 0; this.nextBackoffDelay_ = this.getInitialDelay(); }; module2.exports = ExponentialBackoffStrategy; } }); // node_modules/backoff/lib/strategy/fibonacci.js var require_fibonacci = __commonJS({ "node_modules/backoff/lib/strategy/fibonacci.js"(exports, module2) { var util = require("util"); var BackoffStrategy = require_strategy(); function FibonacciBackoffStrategy(options) { BackoffStrategy.call(this, options); this.backoffDelay_ = 0; this.nextBackoffDelay_ = this.getInitialDelay(); } util.inherits(FibonacciBackoffStrategy, BackoffStrategy); FibonacciBackoffStrategy.prototype.next_ = function() { var backoffDelay = Math.min(this.nextBackoffDelay_, this.getMaxDelay()); this.nextBackoffDelay_ += this.backoffDelay_; this.backoffDelay_ = backoffDelay; return backoffDelay; }; FibonacciBackoffStrategy.prototype.reset_ = function() { this.nextBackoffDelay_ = this.getInitialDelay(); this.backoffDelay_ = 0; }; module2.exports = FibonacciBackoffStrategy; } }); // node_modules/backoff/lib/function_call.js var require_function_call = __commonJS({ "node_modules/backoff/lib/function_call.js"(exports, module2) { var events = require("events"); var precond = require_precond(); var util = require("util"); var Backoff = require_backoff(); var FibonacciBackoffStrategy = require_fibonacci(); function FunctionCall(fn, args, callback) { events.EventEmitter.call(this); precond.checkIsFunction(fn, "Expected fn to be a function."); precond.checkIsArray(args, "Expected args to be an array."); precond.checkIsFunction(callback, "Expected callback to be a function."); this.function_ = fn; this.arguments_ = args; this.callback_ = callback; this.lastResult_ = []; this.numRetries_ = 0; this.backoff_ = null; this.strategy_ = null; this.failAfter_ = -1; this.retryPredicate_ = FunctionCall.DEFAULT_RETRY_PREDICATE_; this.state_ = FunctionCall.State_.PENDING; } util.inherits(FunctionCall, events.EventEmitter); FunctionCall.State_ = { PENDING: 0, RUNNING: 1, COMPLETED: 2, ABORTED: 3 }; FunctionCall.DEFAULT_RETRY_PREDICATE_ = function(err) { return true; }; FunctionCall.prototype.isPending = function() { return this.state_ == FunctionCall.State_.PENDING; }; FunctionCall.prototype.isRunning = function() { return this.state_ == FunctionCall.State_.RUNNING; }; FunctionCall.prototype.isCompleted = function() { return this.state_ == FunctionCall.State_.COMPLETED; }; FunctionCall.prototype.isAborted = function() { return this.state_ == FunctionCall.State_.ABORTED; }; FunctionCall.prototype.setStrategy = function(strategy) { precond.checkState(this.isPending(), "FunctionCall in progress."); this.strategy_ = strategy; return this; }; FunctionCall.prototype.retryIf = function(retryPredicate) { precond.checkState(this.isPending(), "FunctionCall in progress."); this.retryPredicate_ = retryPredicate; return this; }; FunctionCall.prototype.getLastResult = function() { return this.lastResult_.concat(); }; FunctionCall.prototype.getNumRetries = function() { return this.numRetries_; }; FunctionCall.prototype.failAfter = function(maxNumberOfRetry) { precond.checkState(this.isPending(), "FunctionCall in progress."); this.failAfter_ = maxNumberOfRetry; return this; }; FunctionCall.prototype.abort = function() { if (this.isCompleted() || this.isAborted()) { return; } if (this.isRunning()) { this.backoff_.reset(); } this.state_ = FunctionCall.State_.ABORTED; this.lastResult_ = [new Error("Backoff aborted.")]; this.emit("abort"); this.doCallback_(); }; FunctionCall.prototype.start = function(backoffFactory) { precond.checkState(!this.isAborted(), "FunctionCall is aborted."); precond.checkState(this.isPending(), "FunctionCall already started."); var strategy = this.strategy_ || new FibonacciBackoffStrategy(); this.backoff_ = backoffFactory ? backoffFactory(strategy) : new Backoff(strategy); this.backoff_.on("ready", this.doCall_.bind(this, true)); this.backoff_.on("fail", this.doCallback_.bind(this)); this.backoff_.on("backoff", this.handleBackoff_.bind(this)); if (this.failAfter_ > 0) { this.backoff_.failAfter(this.failAfter_); } this.state_ = FunctionCall.State_.RUNNING; this.doCall_(false); }; FunctionCall.prototype.doCall_ = function(isRetry) { if (isRetry) { this.numRetries_++; } var eventArgs = ["call"].concat(this.arguments_); events.EventEmitter.prototype.emit.apply(this, eventArgs); var callback = this.handleFunctionCallback_.bind(this); this.function_.apply(null, this.arguments_.concat(callback)); }; FunctionCall.prototype.doCallback_ = function() { this.callback_.apply(null, this.lastResult_); }; FunctionCall.prototype.handleFunctionCallback_ = function() { if (this.isAborted()) { return; } var args = Array.prototype.slice.call(arguments); this.lastResult_ = args; events.EventEmitter.prototype.emit.apply(this, ["callback"].concat(args)); var err = args[0]; if (err && this.retryPredicate_(err)) { this.backoff_.backoff(err); } else { this.state_ = FunctionCall.State_.COMPLETED; this.doCallback_(); } }; FunctionCall.prototype.handleBackoff_ = function(number, delay, err) { this.emit("backoff", number, delay, err); }; module2.exports = FunctionCall; } }); // node_modules/backoff/index.js var require_backoff2 = __commonJS({ "node_modules/backoff/index.js"(exports, module2) { var Backoff = require_backoff(); var ExponentialBackoffStrategy = require_exponential(); var FibonacciBackoffStrategy = require_fibonacci(); var FunctionCall = require_function_call(); module2.exports.Backoff = Backoff; module2.exports.FunctionCall = FunctionCall; module2.exports.FibonacciStrategy = FibonacciBackoffStrategy; module2.exports.ExponentialStrategy = ExponentialBackoffStrategy; module2.exports.fibonacci = function(options) { return new Backoff(new FibonacciBackoffStrategy(options)); }; module2.exports.exponential = function(options) { return new Backoff(new ExponentialBackoffStrategy(options)); }; module2.exports.call = function(fn, vargs, callback) { var args = Array.prototype.slice.call(arguments); fn = args[0]; vargs = args.slice(1, args.length - 1); callback = args[args.length - 1]; return new FunctionCall(fn, vargs, callback); }; } }); // node_modules/extsprintf/lib/extsprintf.js var require_extsprintf = __commonJS({ "node_modules/extsprintf/lib/extsprintf.js"(exports) { var mod_assert = require("assert"); var mod_util = require("util"); exports.sprintf = jsSprintf; exports.printf = jsPrintf; exports.fprintf = jsFprintf; function jsSprintf(ofmt) { var regex = [ "([^%]*)", "%", "(['\\-+ #0]*?)", "([1-9]\\d*)?", "(\\.([1-9]\\d*))?", "[lhjztL]*?", "([diouxXfFeEgGaAcCsSp%jr])" ].join(""); var re = new RegExp(regex); var args = Array.prototype.slice.call(arguments, 1); var fmt = ofmt; var flags, width, precision, conversion; var left, pad, sign, arg, match; var ret = ""; var argn = 1; var posn = 0; var convposn; var curconv; mod_assert.equal("string", typeof fmt, "first argument must be a format string"); while ((match = re.exec(fmt)) !== null) { ret += match[1]; fmt = fmt.substring(match[0].length); curconv = match[0].substring(match[1].length); convposn = posn + match[1].length + 1; posn += match[0].length; flags = match[2] || ""; width = match[3] || 0; precision = match[4] || ""; conversion = match[6]; left = false; sign = false; pad = " "; if (conversion == "%") { ret += "%"; continue; } if (args.length === 0) { throw jsError(ofmt, convposn, curconv, "has no matching argument (too few arguments passed)"); } arg = args.shift(); argn++; if (flags.match(/[\' #]/)) { throw jsError(ofmt, convposn, curconv, "uses unsupported flags"); } if (precision.length > 0) { throw jsError(ofmt, convposn, curconv, "uses non-zero precision (not supported)"); } if (flags.match(/-/)) left = true; if (flags.match(/0/)) pad = "0"; if (flags.match(/\+/)) sign = true; switch (conversion) { case "s": if (arg === void 0 || arg === null) { throw jsError(ofmt, convposn, curconv, "attempted to print undefined or null as a string (argument " + argn + " to sprintf)"); } ret += doPad(pad, width, left, arg.toString()); break; case "d": arg = Math.floor(arg); case "f": sign = sign && arg > 0 ? "+" : ""; ret += sign + doPad(pad, width, left, arg.toString()); break; case "x": ret += doPad(pad, width, left, arg.toString(16)); break; case "j": if (width === 0) width = 10; ret += mod_util.inspect(arg, false, width); break; case "r": ret += dumpException(arg); break; default: throw jsError(ofmt, convposn, curconv, "is not supported"); } } ret += fmt; return ret; } function jsError(fmtstr, convposn, curconv, reason) { mod_assert.equal(typeof fmtstr, "string"); mod_assert.equal(typeof curconv, "string"); mod_assert.equal(typeof convposn, "number"); mod_assert.equal(typeof reason, "string"); return new Error('format string "' + fmtstr + '": conversion specifier "' + curconv + '" at character ' + convposn + " " + reason); } function jsPrintf() { var args = Array.prototype.slice.call(arguments); args.unshift(process.stdout); jsFprintf.apply(null, args); } function jsFprintf(stream) { var args = Array.prototype.slice.call(arguments, 1); return stream.write(jsSprintf.apply(this, args)); } function doPad(chr, width, left, str) { var ret = str; while (ret.length < width) { if (left) ret += chr; else ret = chr + ret; } return ret; } function dumpException(ex) { var ret; if (!(ex instanceof Error)) throw new Error(jsSprintf("invalid type for %%r: %j", ex)); ret = "EXCEPTION: " + ex.constructor.name + ": " + ex.stack; if (ex.cause && typeof ex.cause === "function") { var cex = ex.cause(); if (cex) { ret += "\nCaused by: " + dumpException(cex); } } return ret; } } }); // node_modules/core-util-is/lib/util.js var require_util = __commonJS({ "node_modules/core-util-is/lib/util.js"(exports) { function isArray(arg) { if (Array.isArray) { return Array.isArray(arg); } return objectToString(arg) === "[object Array]"; } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === "boolean"; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === "number"; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === "string"; } exports.isString = isString; function isSymbol(arg) { return typeof arg === "symbol"; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return objectToString(re) === "[object RegExp]"; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === "object" && arg !== null; } exports.isObject = isObject; function isDate(d) { return objectToString(d) === "[object Date]"; } exports.isDate = isDate; function isError(e) { return objectToString(e) === "[object Error]" || e instanceof Error; } exports.isError = isError; function isFunction(arg) { return typeof arg === "function"; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === "boolean" || typeof arg === "number" || typeof arg === "string" || typeof arg === "symbol" || typeof arg === "undefined"; } exports.isPrimitive = isPrimitive; exports.isBuffer = Buffer.isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } } }); // node_modules/vasync/node_modules/verror/lib/verror.js var require_verror = __commonJS({ "node_modules/vasync/node_modules/verror/lib/verror.js"(exports, module2) { var mod_assertplus = require_assert(); var mod_util = require("util"); var mod_extsprintf = require_extsprintf(); var mod_isError = require_util().isError; var sprintf = mod_extsprintf.sprintf; module2.exports = VError; VError.VError = VError; VError.SError = SError; VError.WError = WError; VError.MultiError = MultiError; function parseConstructorArguments(args) { var argv, options, sprintf_args, shortmessage, k; mod_assertplus.object(args, "args"); mod_assertplus.bool(args.strict, "args.strict"); mod_assertplus.array(args.argv, "args.argv"); argv = args.argv; if (argv.length === 0) { options = {}; sprintf_args = []; } else if (mod_isError(argv[0])) { options = { "cause": argv[0] }; sprintf_args = argv.slice(1); } else if (typeof argv[0] === "object") { options = {}; for (k in argv[0]) { options[k] = argv[0][k]; } sprintf_args = argv.slice(1); } else { mod_assertplus.string(argv[0], "first argument to VError, SError, or WError constructor must be a string, object, or Error"); options = {}; sprintf_args = argv; } mod_assertplus.object(options); if (!options.strict && !args.strict) { sprintf_args = sprintf_args.map(function(a) { return a === null ? "null" : a === void 0 ? "undefined" : a; }); } if (sprintf_args.length === 0) { shortmessage = ""; } else { shortmessage = sprintf.apply(null, sprintf_args); } return { "options": options, "shortmessage": shortmessage }; } function VError() { var args, obj, parsed, cause, ctor, message, k; args = Array.prototype.slice.call(arguments, 0); if (!(this instanceof VError)) { obj = Object.create(VError.prototype); VError.apply(obj, arguments); return obj; } parsed = parseConstructorArguments({ "argv": args, "strict": false }); if (parsed.options.name) { mod_assertplus.string(parsed.options.name, `error's "name" must be a string`); this.name = parsed.options.name; } this.jse_shortmsg = parsed.shortmessage; message = parsed.shortmessage; cause = parsed.options.cause; if (cause) { mod_assertplus.ok(mod_isError(cause), "cause is not an Error"); this.jse_cause = cause; if (!parsed.options.skipCauseMessage) { message += ": " + cause.message; } } this.jse_info = {}; if (parsed.options.info) { for (k in parsed.options.info) { this.jse_info[k] = parsed.options.info[k]; } } this.message = message; Error.call(this, message); if (Error.captureStackTrace) { ctor = parsed.options.constructorOpt || this.constructor; Error.captureStackTrace(this, ctor); } return this; } mod_util.inherits(VError, Error); VError.prototype.name = "VError"; VError.prototype.toString = function ve_toString() { var str = this.hasOwnProperty("name") && this.name || this.constructor.name || this.constructor.prototype.name; if (this.message) str += ": " + this.message; return str; }; VError.prototype.cause = function ve_cause() { var cause = VError.cause(this); return cause === null ? void 0 : cause; }; VError.cause = function(err) { mod_assertplus.ok(mod_isError(err), "err must be an Error"); return mod_isError(err.jse_cause) ? err.jse_cause : null; }; VError.info = function(err) { var rv, cause, k; mod_assertplus.ok(mod_isError(err), "err must be an Error"); cause = VError.cause(err); if (cause !== null) { rv = VError.info(cause); } else { rv = {}; } if (typeof err.jse_info == "object" && err.jse_info !== null) { for (k in err.jse_info) { rv[k] = err.jse_info[k]; } } return rv; }; VError.findCauseByName = function(err, name) { var cause; mod_assertplus.ok(mod_isError(err), "err must be an Error"); mod_assertplus.string(name, "name"); mod_assertplus.ok(name.length > 0, "name cannot be empty"); for (cause = err; cause !== null; cause = VError.cause(cause)) { mod_assertplus.ok(mod_isError(cause)); if (cause.name == name) { return cause; } } return null; }; VError.hasCauseWithName = function(err, name) { return VError.findCauseByName(err, name) !== null; }; VError.fullStack = function(err) { mod_assertplus.ok(mod_isError(err), "err must be an Error"); var cause = VError.cause(err); if (cause) { return err.stack + "\ncaused by: " + VError.fullStack(cause); } return err.stack; }; VError.errorFromList = function(errors) { mod_assertplus.arrayOfObject(errors, "errors"); if (errors.length === 0) { return null; } errors.forEach(function(e) { mod_assertplus.ok(mod_isError(e)); }); if (errors.length == 1) { return errors[0]; } return new MultiError(errors); }; VError.errorForEach = function(err, func) { mod_assertplus.ok(mod_isError(err), "err must be an Error"); mod_assertplus.func(func, "func"); if (err instanceof MultiError) { err.errors().forEach(function iterError(e) { func(e); }); } else { func(err); } }; function SError() { var args, obj, parsed, options; args = Array.prototype.slice.call(arguments, 0); if (!(this instanceof SError)) { obj = Object.create(SError.prototype); SError.apply(obj, arguments); return obj; } parsed = parseConstructorArguments({ "argv": args, "strict": true }); options = parsed.options; VError.call(this, options, "%s", parsed.shortmessage); return this; } mod_util.inherits(SError, VError); function MultiError(errors) { mod_assertplus.array(errors, "list of errors"); mod_assertplus.ok(errors.length > 0, "must be at least one error"); this.ase_errors = errors; VError.call(this, { "cause": errors[0] }, "first of %d error%s", errors.length, errors.length == 1 ? "" : "s"); } mod_util.inherits(MultiError, VError); MultiError.prototype.name = "MultiError"; MultiError.prototype.errors = function me_errors() { return this.ase_errors.slice(0); }; function WError() { var args, obj, parsed, options; args = Array.prototype.slice.call(arguments, 0); if (!(this instanceof WError)) { obj = Object.create(WError.prototype); WError.apply(obj, args); return obj; } parsed = parseConstructorArguments({ "argv": args, "strict": false }); options = parsed.options; options["skipCauseMessage"] = true; VError.call(this, options, "%s", parsed.shortmessage); return this; } mod_util.inherits(WError, VError); WError.prototype.name = "WError"; WError.prototype.toString = function we_toString() { var str = this.hasOwnProperty("name") && this.name || this.constructor.name || this.constructor.prototype.name; if (this.message) str += ": " + this.message; if (this.jse_cause && this.jse_cause.message) str += "; caused by " + this.jse_cause.toString(); return str; }; WError.prototype.cause = function we_cause(c) { if (mod_isError(c)) this.jse_cause = c; return this.jse_cause; }; } }); // node_modules/vasync/lib/vasync.js var require_vasync = __commonJS({ "node_modules/vasync/lib/vasync.js"(exports) { var mod_assert = require("assert"); var mod_events = require("events"); var mod_util = require("util"); var mod_verror = require_verror(); exports.parallel = parallel; exports.forEachParallel = forEachParallel; exports.pipeline = pipeline; exports.tryEach = tryEach; exports.forEachPipeline = forEachPipeline; exports.filter = filter; exports.filterLimit = filterLimit; exports.filterSeries = filterSeries; exports.whilst = whilst; exports.queue = queue; exports.queuev = queuev; exports.barrier = barrier; exports.waterfall = waterfall; if (!global.setImmediate) { global.setImmediate = function(func) { var args = Array.prototype.slice.call(arguments, 1); args.unshift(0); args.unshift(func); setTimeout.apply(this, args); }; } function isEmpty(obj) { var key; for (key in obj) return false; return true; } function parallel(args, callback) { var funcs, rv, doneOne, i; mod_assert.equal(typeof args, "object", '"args" must be an object'); mod_assert.ok(Array.isArray(args["funcs"]), '"args.funcs" must be specified and must be an array'); mod_assert.equal(typeof callback, "function", "callback argument must be specified and must be a function"); funcs = args["funcs"].slice(0); rv = { "operations": new Array(funcs.length), "successes": [], "ndone": 0, "nerrors": 0 }; if (funcs.length === 0) { setImmediate(function() { callback(null, rv); }); return rv; } doneOne = function(entry) { return function(err, result) { mod_assert.equal(entry["status"], "pending"); entry["err"] = err; entry["result"] = result; entry["status"] = err ? "fail" : "ok"; if (err) rv["nerrors"]++; else rv["successes"].push(result); if (++rv["ndone"] < funcs.length) return; var errors = rv["operations"].filter(function(ent) { return ent["status"] == "fail"; }).map(function(ent) { return ent["err"]; }); if (errors.length > 0) callback(new mod_verror.MultiError(errors), rv); else callback(null, rv); }; }; for (i = 0; i < funcs.length; i++) { rv["operations"][i] = { "func": funcs[i], "funcname": funcs[i].name || "(anon)", "status": "pending" }; funcs[i](doneOne(rv["operations"][i])); } return rv; } function forEachParallel(args, callback) { var func, funcs; mod_assert.equal(typeof args, "object", '"args" must be an object'); mod_assert.equal(typeof args["func"], "function", '"args.func" must be specified and must be a function'); mod_assert.ok(Array.isArray(args["inputs"]), '"args.inputs" must be specified and must be an array'); func = args["func"]; funcs = args["inputs"].map(function(input) { return function(subcallback) { return func(input, subcallback); }; }); return parallel({ "funcs": funcs }, callback); } function pipeline(args, callback) { mod_assert.equal(typeof args, "object", '"args" must be an object'); mod_assert.ok(Array.isArray(args["funcs"]), '"args.funcs" must be specified and must be an array'); var opts = { "funcs": args["funcs"].slice(0), "callback": callback, "args": { impl: "pipeline", uarg: args["arg"] }, "stop_when": "error", "res_type": "rv" }; return waterfall_impl(opts); } function tryEach(funcs, callback) { mod_assert.ok(Array.isArray(funcs), '"funcs" must be specified and must be an array'); mod_assert.ok(arguments.length == 1 || typeof callback == "function", '"callback" must be a function'); var opts = { "funcs": funcs.slice(0), "callback": callback, "args": { impl: "tryEach" }, "stop_when": "success", "res_type": "array" }; return waterfall_impl(opts); } function forEachPipeline(args, callback) { mod_assert.equal(typeof args, "object", '"args" must be an object'); mod_assert.equal(typeof args["func"], "function", '"args.func" must be specified and must be a function'); mod_assert.ok(Array.isArray(args["inputs"]), '"args.inputs" must be specified and must be an array'); mod_assert.equal(typeof callback, "function", "callback argument must be specified and must be a function"); var func = args["func"]; var funcs = args["inputs"].map(function(input) { return function(_, subcallback) { return func(input, subcallback); }; }); return pipeline({ "funcs": funcs }, callback); } function filter(inputs, filterFunc, callback) { return filterLimit(inputs, Infinity, filterFunc, callback); } function filterSeries(inputs, filterFunc, callback) { return filterLimit(inputs, 1, filterFunc, callback); } function filterLimit(inputs, limit, filterFunc, callback) { mod_assert.ok(Array.isArray(inputs), '"inputs" must be specified and must be an array'); mod_assert.equal(typeof limit, "number", '"limit" must be a number'); mod_assert.equal(isNaN(limit), false, '"limit" must be a number'); mod_assert.equal(typeof filterFunc, "function", '"filterFunc" must be specified and must be a function'); mod_assert.equal(typeof callback, "function", '"callback" argument must be specified as a function'); var errors = []; var q = queue(processInput, limit); var results = []; function processInput(input, cb) { if (errors.length > 0) { cb(); return; } filterFunc(input.elem, function inputFiltered(err, ans) { if (results.hasOwnProperty(input.idx)) { throw new mod_verror.VError("vasync.filter*: filterFunc idx %d invoked its callback twice", input.idx); } results[input.idx] = { elem: input.elem, ans: !!ans }; if (err) { errors.push(err); cb(); return; } cb(); }); } q.once("end", function queueDrained() { if (errors.length > 0) { callback(mod_verror.errorFromList(errors)); return; } results = results.filter(function filterFalseInputs(input) { return input.ans; }).map(function mapInputElements(input) { return input.elem; }); callback(null, results); }); inputs.forEach(function iterateInput(elem, idx) { q.push({ elem, idx }); }); q.close(); return q; } function whilst(testFunc, iterateFunc, callback) { mod_assert.equal(typeof testFunc, "function", '"testFunc" must be specified and must be a function'); mod_assert.equal(typeof iterateFunc, "function", '"iterateFunc" must be specified and must be a function'); mod_assert.equal(typeof callback, "function", '"callback" argument must be specified as a function'); var o = { "finished": false, "iterations": 0 }; var args = []; function iterate() { var shouldContinue = testFunc(); if (!shouldContinue) { done(); return; } o.iterations++; iterateFunc(function whilstIteration(err) { args = Array.prototype.slice.call(arguments); if (err) { done(); return; } setImmediate(iterate); }); } function done() { mod_assert.ok(!o.finished, "whilst already finished"); o.finished = true; callback.apply(this, args); } setImmediate(iterate); return o; } function queue(worker, concurrency) { return new WorkQueue({ "worker": worker, "concurrency": concurrency }); } function queuev(args) { return new WorkQueue(args); } function WorkQueue(args) { mod_assert.ok(args.hasOwnProperty("worker")); mod_assert.equal(typeof args["worker"], "function"); mod_assert.ok(args.hasOwnProperty("concurrency")); mod_assert.equal(typeof args["concurrency"], "number"); mod_assert.equal(Math.floor(args["concurrency"]), args["concurrency"]); mod_assert.ok(args["concurrency"] > 0); mod_events.EventEmitter.call(this); this.nextid = 0; this.worker = args["worker"]; this.worker_name = args["worker"].name || "anon"; this.npending = 0; this.pending = {}; this.queued = []; this.closed = false; this.ended = false; this.concurrency = args["concurrency"]; this.saturated = void 0; this.empty = void 0; this.drain = void 0; } mod_util.inherits(WorkQueue, mod_events.EventEmitter); WorkQueue.prototype.push = function(tasks, callback) { if (!Array.isArray(tasks)) return this.pushOne(tasks, callback); var wq = this; return tasks.map(function(task) { return wq.pushOne(task, callback); }); }; WorkQueue.prototype.updateConcurrency = function(concurrency) { if (this.closed) throw new mod_verror.VError("update concurrency invoked after queue closed"); this.concurrency = concurrency; this.dispatchNext(); }; WorkQueue.prototype.close = function() { var wq = this; if (wq.closed) return; wq.closed = true; if (wq.npending === 0 && wq.queued.length === 0) { setImmediate(function() { if (!wq.ended) { wq.ended = true; wq.emit("end"); } }); } }; WorkQueue.prototype.pushOne = function(task, callback) { if (this.closed) throw new mod_verror.VError("push invoked after queue closed"); var id = ++this.nextid; var entry = { "id": id, "task": task, "callback": callback }; this.queued.push(entry); this.dispatchNext(); return id; }; WorkQueue.prototype.dispatchNext = function() { var wq = this; if (wq.npending === 0 && wq.queued.length === 0) { if (wq.drain) wq.drain(); wq.emit("drain"); if (wq.closed) { wq.ended = true; wq.emit("end"); } } else if (wq.queued.length > 0) { while (wq.queued.length > 0 && wq.npending < wq.concurrency) { var next = wq.queued.shift(); wq.dispatch(next); if (wq.queued.length === 0) { if (wq.empty) wq.empty(); wq.emit("empty"); } } } }; WorkQueue.prototype.dispatch = function(entry) { var wq = this; mod_assert.ok(!this.pending.hasOwnProperty(entry["id"])); mod_assert.ok(this.npending < this.concurrency); mod_assert.ok(!this.ended); this.npending++; this.pending[entry["id"]] = entry; if (this.npending === this.concurrency) { if (this.saturated) this.saturated(); this.emit("saturated"); } setImmediate(function() { wq.worker(entry["task"], function(err) { --wq.npending; delete wq.pending[entry["id"]]; if (entry["callback"]) entry["callback"].apply(null, arguments); wq.dispatchNext(); }); }); }; WorkQueue.prototype.length = function() { return this.queued.length; }; WorkQueue.prototype.kill = function() { this.killed = true; this.queued = []; this.drain = void 0; this.close(); }; function barrier(args) { return new Barrier(args); } function Barrier(args) { mod_assert.ok(!args || !args["nrecent"] || typeof args["nrecent"] == "number", '"nrecent" must have type "number"'); mod_events.EventEmitter.call(this); var nrecent = args && args["nrecent"] ? args["nrecent"] : 10; if (nrecent > 0) { this.nrecent = nrecent; this.recent = []; } this.pending = {}; this.scheduled = false; } mod_util.inherits(Barrier, mod_events.EventEmitter); Barrier.prototype.start = function(name) { mod_assert.ok(!this.pending.hasOwnProperty(name), 'operation "' + name + '" is already pending'); this.pending[name] = Date.now(); }; Barrier.prototype.done = function(name) { mod_assert.ok(this.pending.hasOwnProperty(name), 'operation "' + name + '" is not pending'); if (this.recent) { this.recent.push({ "name": name, "start": this.pending[name], "done": Date.now() }); if (this.recent.length > this.nrecent) this.recent.shift(); } delete this.pending[name]; if (!isEmpty(this.pending) || this.scheduled) return; this.scheduled = true; var self2 = this; setImmediate(function() { self2.scheduled = false; if (isEmpty(self2.pending)) self2.emit("drain"); }); }; function waterfall(funcs, callback) { mod_assert.ok(Array.isArray(funcs), '"funcs" must be specified and must be an array'); mod_assert.ok(arguments.length == 1 || typeof callback == "function", '"callback" must be a function'); var opts = { "funcs": funcs.slice(0), "callback": callback, "args": { impl: "waterfall" }, "stop_when": "error", "res_type": "values" }; return waterfall_impl(opts); } function waterfall_impl(opts) { mod_assert.ok(typeof opts === "object"); var rv, current, next; var funcs = opts.funcs; var callback = opts.callback; mod_assert.ok(Array.isArray(funcs), '"opts.funcs" must be specified and must be an array'); mod_assert.ok(arguments.length == 1, 'Function "waterfall_impl" must take only 1 arg'); mod_assert.ok(opts.res_type === "values" || opts.res_type === "array" || opts.res_type == "rv", '"opts.res_type" must either be "values", "array", or "rv"'); mod_assert.ok(opts.stop_when === "error" || opts.stop_when === "success", '"opts.stop_when" must either be "error" or "success"'); mod_assert.ok(opts.args.impl === "pipeline" || opts.args.impl === "waterfall" || opts.args.impl === "tryEach", '"opts.args.impl" must be "pipeline", "waterfall", or "tryEach"'); if (opts.args.impl === "pipeline") { mod_assert.ok(typeof opts.args.uarg !== void 0, '"opts.args.uarg" should be defined when pipeline is used'); } rv = { "operations": funcs.map(function(func) { return { "func": func, "funcname": func.name || "(anon)", "status": "waiting" }; }), "successes": [], "ndone": 0, "nerrors": 0 }; if (funcs.length === 0) { if (callback) setImmediate(function() { var res = opts.args.impl === "pipeline" ? rv : void 0; callback(null, res); }); return rv; } next = function(idx, err) { var res_key, nfunc_args, entry, nextentry; if (err === void 0) err = null; if (idx != current) { throw new mod_verror.VError('vasync.waterfall: function %d ("%s") invoked its callback twice', idx, rv["operations"][idx].funcname); } mod_assert.equal(idx, rv["ndone"], "idx should be equal to ndone"); entry = rv["operations"][rv["ndone"]++]; if (opts.args.impl === "tryEach" || opts.args.impl === "waterfall") { nfunc_args = Array.prototype.slice.call(arguments, 2); res_key = "results"; entry["results"] = nfunc_args; } else if (opts.args.impl === "pipeline") { nfunc_args = [opts.args.uarg]; res_key = "result"; entry["result"] = arguments[2]; } mod_assert.equal(entry["status"], "pending", "status should be pending"); entry["status"] = err ? "fail" : "ok"; entry["err"] = err; if (err) { rv["nerrors"]++; } else { rv["successes"].push(entry[res_key]); } if (opts.stop_when === "error" && err || opts.stop_when === "success" && rv["successes"].length > 0 || rv["ndone"] == funcs.length) { if (callback) { if (opts.res_type === "values" || opts.res_type === "array" && nfunc_args.length <= 1) { nfunc_args.unshift(err); callback.apply(null, nfunc_args); } else if (opts.res_type === "array") { callback(err, nfunc_args); } else if (opts.res_type === "rv") { callback(err, rv); } } } else { nextentry = rv["operations"][rv["ndone"]]; nextentry["status"] = "pending"; current++; nfunc_args.push(next.bind(null, current)); setImmediate(function() { var nfunc = nextentry["func"]; if (opts.args.impl !== "tryEach") { nfunc.apply(null, nfunc_args); } else { nfunc(next.bind(null, current)); } }); } }; rv["operations"][0]["status"] = "pending"; current = 0; if (opts.args.impl !== "pipeline") { funcs[0](next.bind(null, current)); } else { funcs[0](opts.args.uarg, next.bind(null, current)); } return rv; } } }); // node_modules/verror/lib/verror.js var require_verror2 = __commonJS({ "node_modules/verror/lib/verror.js"(exports, module2) { var mod_assertplus = require_assert(); var mod_util = require("util"); var mod_extsprintf = require_extsprintf(); var mod_isError = require_util().isError; var sprintf = mod_extsprintf.sprintf; module2.exports = VError; VError.VError = VError; VError.SError = SError; VError.WError = WError; VError.MultiError = MultiError; function parseConstructorArguments(args) { var argv, options, sprintf_args, shortmessage, k; mod_assertplus.object(args, "args"); mod_assertplus.bool(args.strict, "args.strict"); mod_assertplus.array(args.argv, "args.argv"); argv = args.argv; if (argv.length === 0) { options = {}; sprintf_args = []; } else if (mod_isError(argv[0])) { options = { "cause": argv[0] }; sprintf_args = argv.slice(1); } else if (typeof argv[0] === "object") { options = {}; for (k in argv[0]) { options[k] = argv[0][k]; } sprintf_args = argv.slice(1); } else { mod_assertplus.string(argv[0], "first argument to VError, SError, or WError constructor must be a string, object, or Error"); options = {}; sprintf_args = argv; } mod_assertplus.object(options); if (!options.strict && !args.strict) { sprintf_args = sprintf_args.map(function(a) { return a === null ? "null" : a === void 0 ? "undefined" : a; }); } if (sprintf_args.length === 0) { shortmessage = ""; } else { shortmessage = sprintf.apply(null, sprintf_args); } return { "options": options, "shortmessage": shortmessage }; } function VError() { var args, obj, parsed, cause, ctor, message, k; args = Array.prototype.slice.call(arguments, 0); if (!(this instanceof VError)) { obj = Object.create(VError.prototype); VError.apply(obj, arguments); return obj; } parsed = parseConstructorArguments({ "argv": args, "strict": false }); if (parsed.options.name) { mod_assertplus.string(parsed.options.name, `error's "name" must be a string`); this.name = parsed.options.name; } this.jse_shortmsg = parsed.shortmessage; message = parsed.shortmessage; cause = parsed.options.cause; if (cause) { mod_assertplus.ok(mod_isError(cause), "cause is not an Error"); this.jse_cause = cause; if (!parsed.options.skipCauseMessage) { message += ": " + cause.message; } } this.jse_info = {}; if (parsed.options.info) { for (k in parsed.options.info) { this.jse_info[k] = parsed.options.info[k]; } } this.message = message; Error.call(this, message); if (Error.captureStackTrace) { ctor = parsed.options.constructorOpt || this.constructor; Error.captureStackTrace(this, ctor); } return this; } mod_util.inherits(VError, Error); VError.prototype.name = "VError"; VError.prototype.toString = function ve_toString() { var str = this.hasOwnProperty("name") && this.name || this.constructor.name || this.constructor.prototype.name; if (this.message) str += ": " + this.message; return str; }; VError.prototype.cause = function ve_cause() { var cause = VError.cause(this); return cause === null ? void 0 : cause; }; VError.cause = function(err) { mod_assertplus.ok(mod_isError(err), "err must be an Error"); return mod_isError(err.jse_cause) ? err.jse_cause : null; }; VError.info = function(err) { var rv, cause, k; mod_assertplus.ok(mod_isError(err), "err must be an Error"); cause = VError.cause(err); if (cause !== null) { rv = VError.info(cause); } else { rv = {}; } if (typeof err.jse_info == "object" && err.jse_info !== null) { for (k in err.jse_info) { rv[k] = err.jse_info[k]; } } return rv; }; VError.findCauseByName = function(err, name) { var cause; mod_assertplus.ok(mod_isError(err), "err must be an Error"); mod_assertplus.string(name, "name"); mod_assertplus.ok(name.length > 0, "name cannot be empty"); for (cause = err; cause !== null; cause = VError.cause(cause)) { mod_assertplus.ok(mod_isError(cause)); if (cause.name == name) { return cause; } } return null; }; VError.hasCauseWithName = function(err, name) { return VError.findCauseByName(err, name) !== null; }; VError.fullStack = function(err) { mod_assertplus.ok(mod_isError(err), "err must be an Error"); var cause = VError.cause(err); if (cause) { return err.stack + "\ncaused by: " + VError.fullStack(cause); } return err.stack; }; VError.errorFromList = function(errors) { mod_assertplus.arrayOfObject(errors, "errors"); if (errors.length === 0) { return null; } errors.forEach(function(e) { mod_assertplus.ok(mod_isError(e)); }); if (errors.length == 1) { return errors[0]; } return new MultiError(errors); }; VError.errorForEach = function(err, func) { mod_assertplus.ok(mod_isError(err), "err must be an Error"); mod_assertplus.func(func, "func"); if (err instanceof MultiError) { err.errors().forEach(function iterError(e) { func(e); }); } else { func(err); } }; function SError() { var args, obj, parsed, options; args = Array.prototype.slice.call(arguments, 0); if (!(this instanceof SError)) { obj = Object.create(SError.prototype); SError.apply(obj, arguments); return obj; } parsed = parseConstructorArguments({ "argv": args, "strict": true }); options = parsed.options; VError.call(this, options, "%s", parsed.shortmessage); return this; } mod_util.inherits(SError, VError); function MultiError(errors) { mod_assertplus.array(errors, "list of errors"); mod_assertplus.ok(errors.length > 0, "must be at least one error"); this.ase_errors = errors; VError.call(this, { "cause": errors[0] }, "first of %d error%s", errors.length, errors.length == 1 ? "" : "s"); } mod_util.inherits(MultiError, VError); MultiError.prototype.name = "MultiError"; MultiError.prototype.errors = function me_errors() { return this.ase_errors.slice(0); }; function WError() { var args, obj, parsed, options; args = Array.prototype.slice.call(arguments, 0); if (!(this instanceof WError)) { obj = Object.create(WError.prototype); WError.apply(obj, args); return obj; } parsed = parseConstructorArguments({ "argv": args, "strict": false }); options = parsed.options; options["skipCauseMessage"] = true; VError.call(this, options, "%s", parsed.shortmessage); return this; } mod_util.inherits(WError, VError); WError.prototype.name = "WError"; WError.prototype.toString = function we_toString() { var str = this.hasOwnProperty("name") && this.name || this.constructor.name || this.constructor.prototype.name; if (this.message) str += ": " + this.message; if (this.jse_cause && this.jse_cause.message) str += "; caused by " + this.jse_cause.toString(); return str; }; WError.prototype.cause = function we_cause(c) { if (mod_isError(c)) this.jse_cause = c; return this.jse_cause; }; } }); // node_modules/ldapjs/lib/controls/index.js var require_controls2 = __commonJS({ "node_modules/ldapjs/lib/controls/index.js"(exports, module2) { var controls = require_controls(); module2.exports = controls; } }); // node_modules/ldapjs/lib/corked_emitter.js var require_corked_emitter = __commonJS({ "node_modules/ldapjs/lib/corked_emitter.js"(exports, module2) { "use strict"; var EventEmitter = require("events").EventEmitter; function CorkedEmitter() { const self2 = this; EventEmitter.call(self2); self2._outstandingEmits = []; self2._opened = false; self2.once("newListener", function() { setImmediate(function releaseStoredEvents() { self2._opened = true; self2._outstandingEmits.forEach(function(args) { self2.emit.apply(self2, args); }); }); }); } CorkedEmitter.prototype = Object.create(EventEmitter.prototype); CorkedEmitter.prototype.emit = function emit(eventName) { if (this._opened || eventName === "newListener") { EventEmitter.prototype.emit.apply(this, arguments); } else { this._outstandingEmits.push(arguments); } }; module2.exports = CorkedEmitter; } }); // node_modules/ldapjs/lib/client/search_pager.js var require_search_pager = __commonJS({ "node_modules/ldapjs/lib/client/search_pager.js"(exports, module2) { "use strict"; var EventEmitter = require("events").EventEmitter; var util = require("util"); var assert = require_assert(); var { PagedResultsControl } = require_controls(); var CorkedEmitter = require_corked_emitter(); function SearchPager(opts) { assert.object(opts); assert.func(opts.callback); assert.number(opts.pageSize); assert.func(opts.sendRequest); CorkedEmitter.call(this, {}); this.callback = opts.callback; this.controls = opts.controls; this.pageSize = opts.pageSize; this.pagePause = opts.pagePause; this.sendRequest = opts.sendRequest; this.controls.forEach(function(control) { if (control.type === PagedResultsControl.OID) { throw new Error("redundant pagedResultControl"); } }); this.finished = false; this.started = false; const emitter = new EventEmitter(); emitter.on("searchRequest", this.emit.bind(this, "searchRequest")); emitter.on("searchEntry", this.emit.bind(this, "searchEntry")); emitter.on("end", this._onEnd.bind(this)); emitter.on("error", this._onError.bind(this)); this.childEmitter = emitter; } util.inherits(SearchPager, CorkedEmitter); module2.exports = SearchPager; SearchPager.prototype.begin = function begin() { this._nextPage(null); }; SearchPager.prototype._onEnd = function _onEnd(res) { const self2 = this; let cookie = null; res.controls.forEach(function(control) { if (control.type === PagedResultsControl.OID) { cookie = control.value.cookie; } }); const nullCb = function() { }; if (cookie === null) { this.finished = true; this.emit("page", res, nullCb); const err = new Error("missing paged control"); err.name = "PagedError"; if (this.listeners("pageError").length > 0) { this.emit("pageError", err); this.emit("end", res); } else { this.emit("error", err); } return; } if (cookie.length === 0) { this.finished = true; this.emit("page", nullCb); this.emit("end", res); } else { if (this.pagePause) { this.emit("page", res, function(err) { if (!err) { self2._nextPage(cookie); } else { self2.emit("end", res); } }); } else { this.emit("page", res, nullCb); this._nextPage(cookie); } } }; SearchPager.prototype._onError = function _onError(err) { this.finished = true; this.emit("error", err); }; SearchPager.prototype._nextPage = function _nextPage(cookie) { const controls = this.controls.slice(0); controls.push(new PagedResultsControl({ value: { size: this.pageSize, cookie } })); this.sendRequest(controls, this.childEmitter, this._sendCallback.bind(this)); }; SearchPager.prototype._sendCallback = function _sendCallback(err) { if (err) { this.finished = true; if (!this.started) { this.callback(err, null); } else { this.emit("error", err); } } else { if (!this.started) { this.started = true; this.callback(null, this); } } }; } }); // node_modules/ldapjs/lib/url.js var require_url = __commonJS({ "node_modules/ldapjs/lib/url.js"(exports, module2) { "use strict"; var querystring = require("querystring"); var url = require("url"); var { DN } = require_dn2(); var filter = require_lib2(); module2.exports = { parse: function(urlStr, parseDN) { let parsedURL; try { parsedURL = new url.URL(urlStr); } catch (error) { throw new TypeError(urlStr + " is an invalid LDAP url (scope)"); } if (!parsedURL.protocol || !(parsedURL.protocol === "ldap:" || parsedURL.protocol === "ldaps:")) { throw new TypeError(urlStr + " is an invalid LDAP url (protocol)"); } const u = { protocol: parsedURL.protocol, hostname: parsedURL.hostname, port: parsedURL.port, pathname: parsedURL.pathname, search: parsedURL.search, href: parsedURL.href }; u.secure = u.protocol === "ldaps:"; if (!u.hostname) { u.hostname = "localhost"; } if (!u.port) { u.port = u.secure ? 636 : 389; } else { u.port = parseInt(u.port, 10); } if (u.pathname) { u.pathname = querystring.unescape(u.pathname.substr(1)); u.DN = parseDN ? DN.fromString(u.pathname) : u.pathname; } if (u.search) { u.attributes = []; const tmp = u.search.substr(1).split("?"); if (tmp && tmp.length) { if (tmp[0]) { tmp[0].split(",").forEach(function(a) { u.attributes.push(querystring.unescape(a.trim())); }); } } if (tmp[1]) { if (tmp[1] !== "base" && tmp[1] !== "one" && tmp[1] !== "sub") { throw new TypeError(urlStr + " is an invalid LDAP url (scope)"); } u.scope = tmp[1]; } if (tmp[2]) { u.filter = querystring.unescape(tmp[2]); } if (tmp[3]) { u.extensions = querystring.unescape(tmp[3]); } if (!u.scope) { u.scope = "base"; } if (!u.filter) { u.filter = filter.parseString("(objectclass=*)"); } else { u.filter = filter.parseString(u.filter); } } return u; } }; } }); // node_modules/ldapjs/lib/client/client.js var require_client = __commonJS({ "node_modules/ldapjs/lib/client/client.js"(exports, module2) { "use strict"; var requestQueueFactory = require_request_queue(); var messageTrackerFactory = require_message_tracker(); var { MAX_MSGID } = require_constants(); var EventEmitter = require("events").EventEmitter; var net = require("net"); var tls = require("tls"); var util = require("util"); var once = require_once(); var backoff = require_backoff2(); var vasync = require_vasync(); var assert = require_assert(); var VError = require_verror2().VError; var Attribute = require_attribute(); var Change = require_change(); var Control = require_controls2().Control; var { Control: LdapControl } = require_controls(); var SearchPager = require_search_pager(); var Protocol = require_protocol(); var { DN } = require_dn2(); var errors = require_errors2(); var filters = require_lib2(); var Parser = require_parser(); var url = require_url(); var CorkedEmitter = require_corked_emitter(); var messages = require_messages(); var { AbandonRequest, AddRequest, BindRequest, CompareRequest, DeleteRequest, ExtensionRequest: ExtendedRequest, ModifyRequest, ModifyDnRequest: ModifyDNRequest, SearchRequest, UnbindRequest, LdapResult: LDAPResult, SearchResultEntry: SearchEntry, SearchResultReference: SearchReference } = messages; var PresenceFilter = filters.PresenceFilter; var ConnectionError = errors.ConnectionError; var CMP_EXPECT = [errors.LDAP_COMPARE_TRUE, errors.LDAP_COMPARE_FALSE]; var CLIENT_ID = 0; function nextClientId() { if (++CLIENT_ID === MAX_MSGID) { return 1; } return CLIENT_ID; } function validateControls(controls) { if (Array.isArray(controls)) { controls.forEach(function(c) { if (!(c instanceof Control) && !(c instanceof LdapControl)) { throw new TypeError("controls must be [Control]"); } }); } else if (controls instanceof Control || controls instanceof LdapControl) { controls = [controls]; } else { throw new TypeError("controls must be [Control]"); } return controls; } function ensureDN(input) { if (DN.isDn(input)) { return input; } else if (typeof input === "string") { return DN.fromString(input); } else { throw new Error("invalid DN"); } } function Client(options) { assert.ok(options); EventEmitter.call(this, options); const self2 = this; this.urls = options.url ? [].concat(options.url).map(url.parse) : []; this._nextServer = 0; this.host = void 0; this.port = void 0; this.secure = void 0; this.url = void 0; this.tlsOptions = options.tlsOptions; this.socketPath = options.socketPath || false; this.log = options.log.child({ clazz: "Client" }, true); this.timeout = parseInt(options.timeout || 0, 10); this.connectTimeout = parseInt(options.connectTimeout || 0, 10); this.idleTimeout = parseInt(options.idleTimeout || 0, 10); if (options.reconnect) { const rOpts = typeof options.reconnect === "object" ? options.reconnect : {}; this.reconnect = { initialDelay: parseInt(rOpts.initialDelay || 100, 10), maxDelay: parseInt(rOpts.maxDelay || 1e4, 10), failAfter: parseInt(rOpts.failAfter, 10) || Infinity }; } this.queue = requestQueueFactory({ size: parseInt(options.queueSize || 0, 10), timeout: parseInt(options.queueTimeout || 0, 10) }); if (options.queueDisable) { this.queue.freeze(); } if (options.bindDN !== void 0 && options.bindCredentials !== void 0) { this.on("setup", function(clt, cb) { clt.bind(options.bindDN, options.bindCredentials, function(err) { if (err) { if (self2._socket) { self2._socket.destroy(); } self2.emit("error", err); } cb(err); }); }); } this._socket = null; this.connected = false; this.connect(); } util.inherits(Client, EventEmitter); module2.exports = Client; Client.prototype.abandon = function abandon(messageId, controls, callback) { assert.number(messageId, "messageId"); if (typeof controls === "function") { callback = controls; controls = []; } else { controls = validateControls(controls); } assert.func(callback, "callback"); const req = new AbandonRequest({ abandonId: messageId, controls }); return this._send(req, "abandon", null, callback); }; Client.prototype.add = function add(name, entry, controls, callback) { assert.ok(name !== void 0, "name"); assert.object(entry, "entry"); if (typeof controls === "function") { callback = controls; controls = []; } else { controls = validateControls(controls); } assert.func(callback, "callback"); if (Array.isArray(entry)) { entry.forEach(function(a) { if (!Attribute.isAttribute(a)) { throw new TypeError("entry must be an Array of Attributes"); } }); } else { const save = entry; entry = []; Object.keys(save).forEach(function(k) { const attr = new Attribute({ type: k }); if (Array.isArray(save[k])) { save[k].forEach(function(v) { attr.addValue(v.toString()); }); } else if (Buffer.isBuffer(save[k])) { attr.addValue(save[k]); } else { attr.addValue(save[k].toString()); } entry.push(attr); }); } const req = new AddRequest({ entry: ensureDN(name), attributes: entry, controls }); return this._send(req, [errors.LDAP_SUCCESS], null, callback); }; Client.prototype.bind = function bind(name, credentials, controls, callback, _bypass) { if (typeof name !== "string" && Object.prototype.toString.call(name) !== "[object LdapDn]") { throw new TypeError("name (string) required"); } assert.optionalString(credentials, "credentials"); if (typeof controls === "function") { callback = controls; controls = []; } else { controls = validateControls(controls); } assert.func(callback, "callback"); const req = new BindRequest({ name: name || "", authentication: "Simple", credentials: credentials || "", controls }); const self2 = this; function callbackWrapper(err, ret) { self2.removeListener("connectError", callbackWrapper); callback(err, ret); } this.addListener("connectError", callbackWrapper); return this._send(req, [errors.LDAP_SUCCESS], null, callbackWrapper, _bypass); }; Client.prototype.compare = function compare(name, attr, value, controls, callback) { assert.ok(name !== void 0, "name"); assert.string(attr, "attr"); assert.string(value, "value"); if (typeof controls === "function") { callback = controls; controls = []; } else { controls = validateControls(controls); } assert.func(callback, "callback"); const req = new CompareRequest({ entry: ensureDN(name), attribute: attr, value, controls }); return this._send(req, CMP_EXPECT, null, function(err, res) { if (err) { return callback(err); } return callback(null, res.status === errors.LDAP_COMPARE_TRUE, res); }); }; Client.prototype.del = function del(name, controls, callback) { assert.ok(name !== void 0, "name"); if (typeof controls === "function") { callback = controls; controls = []; } else { controls = validateControls(controls); } assert.func(callback, "callback"); const req = new DeleteRequest({ entry: ensureDN(name), controls }); return this._send(req, [errors.LDAP_SUCCESS], null, callback); }; Client.prototype.exop = function exop(name, value, controls, callback) { assert.string(name, "name"); if (typeof value === "function") { callback = value; controls = []; value = void 0; } if (typeof controls === "function") { callback = controls; controls = []; } else { controls = validateControls(controls); } assert.func(callback, "callback"); const req = new ExtendedRequest({ requestName: name, requestValue: value, controls }); return this._send(req, [errors.LDAP_SUCCESS], null, function(err, res) { if (err) { return callback(err); } return callback(null, res.responseValue || "", res); }); }; Client.prototype.modify = function modify(name, change, controls, callback) { assert.ok(name !== void 0, "name"); assert.object(change, "change"); const changes = []; function changeFromObject(obj) { if (!obj.operation && !obj.type) { throw new Error("change.operation required"); } if (typeof obj.modification !== "object") { throw new Error("change.modification (object) required"); } if (Object.keys(obj.modification).length === 2 && typeof obj.modification.type === "string" && Array.isArray(obj.modification.vals)) { changes.push(new Change({ operation: obj.operation || obj.type, modification: obj.modification })); } else { Object.keys(obj.modification).forEach(function(k) { const mod = {}; mod[k] = obj.modification[k]; changes.push(new Change({ operation: obj.operation || obj.type, modification: mod })); }); } } if (Change.isChange(change)) { changes.push(change); } else if (Array.isArray(change)) { change.forEach(function(c) { if (Change.isChange(c)) { changes.push(c); } else { changeFromObject(c); } }); } else { changeFromObject(change); } if (typeof controls === "function") { callback = controls; controls = []; } else { controls = validateControls(controls); } assert.func(callback, "callback"); const req = new ModifyRequest({ object: ensureDN(name), changes, controls }); return this._send(req, [errors.LDAP_SUCCESS], null, callback); }; Client.prototype.modifyDN = function modifyDN(name, newName, controls, callback) { assert.ok(name !== void 0, "name"); assert.string(newName, "newName"); if (typeof controls === "function") { callback = controls; controls = []; } else { controls = validateControls(controls); } assert.func(callback); const newDN = DN.fromString(newName); const req = new ModifyDNRequest({ entry: DN.fromString(name), deleteOldRdn: true, controls }); if (newDN.length !== 1) { req.newRdn = DN.fromString(newDN.shift().toString()); req.newSuperior = newDN; } else { req.newRdn = newDN; } return this._send(req, [errors.LDAP_SUCCESS], null, callback); }; Client.prototype.search = function search(base, options, controls, callback, _bypass) { assert.ok(base !== void 0, "search base"); if (Array.isArray(options) || options instanceof Control) { controls = options; options = {}; } else if (typeof options === "function") { callback = options; controls = []; options = { filter: new PresenceFilter({ attribute: "objectclass" }) }; } else if (typeof options === "string") { options = { filter: filters.parseString(options) }; } else if (typeof options !== "object") { throw new TypeError("options (object) required"); } if (typeof options.filter === "string") { options.filter = filters.parseString(options.filter); } else if (!options.filter) { options.filter = new PresenceFilter({ attribute: "objectclass" }); } else if (Object.prototype.toString.call(options.filter) !== "[object FilterString]") { throw new TypeError("options.filter (Filter) required"); } if (typeof controls === "function") { callback = controls; controls = []; } else { controls = validateControls(controls); } assert.func(callback, "callback"); if (options.attributes) { if (!Array.isArray(options.attributes)) { if (typeof options.attributes === "string") { options.attributes = [options.attributes]; } else { throw new TypeError("options.attributes must be an Array of Strings"); } } } const self2 = this; const baseDN = ensureDN(base); function sendRequest(ctrls, emitter, cb) { const req = new SearchRequest({ baseObject: baseDN, scope: options.scope || "base", filter: options.filter, derefAliases: options.derefAliases || Protocol.search.NEVER_DEREF_ALIASES, sizeLimit: options.sizeLimit || 0, timeLimit: options.timeLimit || 10, typesOnly: options.typesOnly || false, attributes: options.attributes || [], controls: ctrls }); return self2._send(req, [errors.LDAP_SUCCESS], emitter, cb, _bypass); } if (options.paged) { const pageOpts = typeof options.paged === "object" ? options.paged : {}; let size = 100; if (pageOpts.pageSize > 0) { size = pageOpts.pageSize; } else if (options.sizeLimit > 1) { size = options.sizeLimit - 1; } const pager = new SearchPager({ callback, controls, pageSize: size, pagePause: pageOpts.pagePause, sendRequest }); pager.begin(); } else { sendRequest(controls, new CorkedEmitter(), callback); } }; Client.prototype.unbind = function unbind(callback) { if (!callback) { callback = function() { }; } if (typeof callback !== "function") { throw new TypeError("callback must be a function"); } this.unbound = true; if (!this._socket) { return callback(); } const req = new UnbindRequest(); return this._send(req, "unbind", null, callback); }; Client.prototype.starttls = function starttls(options, controls, callback, _bypass) { assert.optionalObject(options); options = options || {}; callback = once(callback); const self2 = this; if (this._starttls) { return callback(new Error("STARTTLS already in progress or active")); } function onSend(sendErr, emitter) { if (sendErr) { callback(sendErr); return; } self2._starttls = { started: true }; emitter.on("error", function(err) { self2._starttls = null; callback(err); }); emitter.on("end", function(_res) { const sock = self2._socket; sock.removeAllListeners("data"); options.socket = sock; const secure = tls.connect(options); secure.once("secureConnect", function() { secure.removeAllListeners("error"); secure.on("data", function onData(data) { self2.log.trace("data event: %s", util.inspect(data)); self2._tracker.parser.write(data); }); secure.on("error", function(err) { self2.log.trace({ err }, "error event: %s", new Error().stack); self2.emit("error", err); sock.destroy(); }); callback(null); }); secure.once("error", function(err) { self2._starttls = null; secure.removeAllListeners(); callback(err); }); self2._starttls.success = true; self2._socket = secure; }); } const req = new ExtendedRequest({ requestName: "1.3.6.1.4.1.1466.20037", requestValue: null, controls }); return this._send(req, [errors.LDAP_SUCCESS], new EventEmitter(), onSend, _bypass); }; Client.prototype.destroy = function destroy(err) { this.destroyed = true; this.queue.freeze(); this.queue.flush(function(msg, expect, emitter, cb) { if (typeof cb === "function") { cb(new Error("client destroyed")); } }); if (this.connected) { this.unbind(); } if (this._socket) { this._socket.destroy(); } this.emit("destroy", err); }; Client.prototype.connect = function connect() { if (this.connecting || this.connected) { return; } const self2 = this; const log = this.log; let socket; let tracker; function connectSocket(cb) { const server = self2.urls[self2._nextServer]; self2._nextServer = (self2._nextServer + 1) % self2.urls.length; cb = once(cb); function onResult(err, res) { if (err) { if (self2.connectTimer) { clearTimeout(self2.connectTimer); self2.connectTimer = null; } self2.emit("connectError", err); } cb(err, res); } function onConnect() { if (self2.connectTimer) { clearTimeout(self2.connectTimer); self2.connectTimer = null; } socket.removeAllListeners("error").removeAllListeners("connect").removeAllListeners("secureConnect"); tracker.id = nextClientId() + "__" + tracker.id; self2.log = self2.log.child({ ldap_id: tracker.id }, true); setupClient(cb); } const port = server && server.port || self2.socketPath; const host = server && server.hostname; if (server && server.secure) { socket = tls.connect(port, host, self2.tlsOptions); socket.once("secureConnect", onConnect); } else { socket = net.connect(port, host); socket.once("connect", onConnect); } socket.once("error", onResult); initSocket(server); if (self2.connectTimeout) { self2.connectTimer = setTimeout(function onConnectTimeout() { if (!socket || !socket.readable || !socket.writeable) { socket.destroy(); self2._socket = null; onResult(new ConnectionError("connection timeout")); } }, self2.connectTimeout); } } function initSocket(server) { tracker = messageTrackerFactory({ id: server ? server.href : self2.socketPath, parser: new Parser({ log }) }); if (typeof socket.setKeepAlive !== "function") { socket.setKeepAlive = function setKeepAlive(enable, delay) { return socket.socket ? socket.socket.setKeepAlive(enable, delay) : false; }; } socket.on("data", function onData(data) { log.trace("data event: %s", util.inspect(data)); tracker.parser.write(data); }); tracker.parser.on("message", function onMessage(message) { message.connection = self2._socket; const trackedObject = tracker.fetch(message.messageId); if (!trackedObject) { log.error({ message: message.pojo }, "unmatched server message received"); return false; } const { message: trackedMessage, callback } = trackedObject; if (!callback) { log.error({ message: message.pojo }, "unsolicited message"); return false; } switch (trackedMessage.type) { case "ExtensionRequest": { const extensionType = ExtendedRequest.recognizedOIDs().lookupName(trackedMessage.requestName); switch (extensionType) { case "PASSWORD_MODIFY": { message = messages.PasswordModifyResponse.fromResponse(message); break; } case "WHO_AM_I": { message = messages.WhoAmIResponse.fromResponse(message); break; } default: } break; } default: } return callback(message); }); tracker.parser.on("error", function onParseError(err) { self2.emit("error", new VError(err, "Parser error for %s", tracker.id)); self2.connected = false; socket.end(); }); } function setupClient(cb) { cb = once(cb); function bail(err) { socket.destroy(); cb(err || new Error("client error during setup")); } (socket.socket ? socket.socket : socket).once("close", bail); socket.once("error", bail); socket.once("end", bail); socket.once("timeout", bail); socket.once("cleanupSetupListeners", function onCleanup() { socket.removeListener("error", bail).removeListener("close", bail).removeListener("end", bail).removeListener("timeout", bail); }); self2._socket = socket; self2._tracker = tracker; const basicClient = { bind: function bindBypass(name, credentials, controls, callback) { return self2.bind(name, credentials, controls, callback, true); }, search: function searchBypass(base, options, controls, callback) { return self2.search(base, options, controls, callback, true); }, starttls: function starttlsBypass(options, controls, callback) { return self2.starttls(options, controls, callback, true); }, unbind: self2.unbind.bind(self2) }; vasync.forEachPipeline({ func: function(f, callback) { f(basicClient, callback); }, inputs: self2.listeners("setup") }, function(err, _res) { if (err) { self2.emit("setupError", err); } cb(err); }); } function postSetup() { socket.emit("cleanupSetupListeners"); (socket.socket ? socket.socket : socket).once("close", self2._onClose.bind(self2)); socket.on("end", function onEnd() { log.trace("end event"); self2.emit("end"); socket.end(); }); socket.on("error", function onSocketError(err) { log.trace({ err }, "error event: %s", new Error().stack); self2.emit("error", err); socket.destroy(); }); socket.on("timeout", function onTimeout() { log.trace("timeout event"); self2.emit("socketTimeout"); socket.end(); }); const server = self2.urls[self2._nextServer]; if (server) { self2.host = server.hostname; self2.port = server.port; self2.secure = server.secure; } } let retry; let failAfter; if (this.reconnect) { retry = backoff.exponential({ initialDelay: this.reconnect.initialDelay, maxDelay: this.reconnect.maxDelay }); failAfter = this.reconnect.failAfter; if (this.urls.length > 1 && failAfter) { failAfter *= this.urls.length; } } else { retry = backoff.exponential({ initialDelay: 1, maxDelay: 2 }); failAfter = this.urls.length || 1; } retry.failAfter(failAfter); retry.on("ready", function(num, _delay) { if (self2.destroyed) { return; } connectSocket(function(err) { if (!err) { postSetup(); self2.connecting = false; self2.connected = true; self2.emit("connect", socket); self2.log.debug("connected after %d attempt(s)", num + 1); self2._flushQueue(); self2._connectRetry = null; } else { retry.backoff(err); } }); }); retry.on("fail", function(err) { if (self2.destroyed) { return; } self2.log.debug("failed to connect after %d attempts", failAfter); if (err instanceof ConnectionError) { self2.emitError("connectTimeout", err); } else if (err.code === "ECONNREFUSED") { self2.emitError("connectRefused", err); } else { self2.emit("error", err); } }); this._connectRetry = retry; this.connecting = true; retry.backoff(); }; Client.prototype._flushQueue = function _flushQueue() { this.queue.flush(this._send.bind(this)); }; Client.prototype._onClose = function _onClose(closeError) { const socket = this._socket; const tracker = this._tracker; socket.removeAllListeners("connect").removeAllListeners("data").removeAllListeners("drain").removeAllListeners("end").removeAllListeners("error").removeAllListeners("timeout"); this._socket = null; this.connected = false; (socket.socket ? socket.socket : socket).removeAllListeners("close"); this.log.trace("close event had_err=%s", closeError ? "yes" : "no"); this.emit("close", closeError); tracker.purge(function(msgid, cb) { if (socket.unbindMessageID !== msgid) { return cb(new ConnectionError(tracker.id + " closed")); } else { const Unbind = class extends LDAPResult { constructor() { super(...arguments); __publicField(this, "messageID", msgid); __publicField(this, "messageId", msgid); __publicField(this, "status", "unbind"); } }; const unbind = new Unbind(); return cb(unbind); } }); this._tracker = null; delete this._starttls; if (this.reconnect && !this.unbound) { this.connect(); } this.unbound = false; return false; }; Client.prototype._updateIdle = function _updateIdle(override) { if (this.idleTimeout === 0) { return; } const self2 = this; function isIdle(disable) { return disable !== true && (self2._socket && self2.connected) && self2._tracker.pending === 0; } if (isIdle(override)) { if (!this._idleTimer) { this._idleTimer = setTimeout(function() { if (isIdle()) { self2.emit("idle"); } }, this.idleTimeout); } } else { if (this._idleTimer) { clearTimeout(this._idleTimer); this._idleTimer = null; } } }; Client.prototype._send = function _send(message, expect, emitter, callback, _bypass) { assert.ok(message); assert.ok(expect); assert.optionalObject(emitter); assert.ok(callback); if (_bypass && this._socket && this._socket.writable) { return this._sendSocket(message, expect, emitter, callback); } if (!this._socket || !this.connected) { if (!this.queue.enqueue(message, expect, emitter, callback)) { callback(new ConnectionError("connection unavailable")); } if (this.reconnect) { this.connect(); } return false; } else { this._flushQueue(); return this._sendSocket(message, expect, emitter, callback); } }; Client.prototype._sendSocket = function _sendSocket(message, expect, emitter, callback) { const conn = this._socket; const tracker = this._tracker; const log = this.log; const self2 = this; let timer = false; let sentEmitter = false; function sendResult(event, obj) { if (event === "error") { self2.emit("resultError", obj); } if (emitter) { if (event === "error") { if (!sentEmitter) { return callback(obj); } } return emitter.emit(event, obj); } if (event === "error") { return callback(obj); } return callback(null, obj); } function messageCallback(msg) { if (timer) { clearTimeout(timer); } log.trace({ msg: msg ? msg.pojo : null }, "response received"); if (expect === "abandon") { return sendResult("end", null); } if (msg instanceof SearchEntry || msg instanceof SearchReference) { let event = msg.constructor.name; event = (event[0].toLowerCase() + event.slice(1)).replaceAll("Result", ""); return sendResult(event, msg); } else { tracker.remove(message.messageId); self2._updateIdle(); if (msg instanceof LDAPResult) { if (msg.status !== 0 && expect.indexOf(msg.status) === -1) { return sendResult("error", errors.getError(msg)); } return sendResult("end", msg); } else if (msg instanceof Error) { return sendResult("error", msg); } else { return sendResult("error", new errors.ProtocolError(msg.type)); } } } function onRequestTimeout() { self2.emit("timeout", message); const { callback: cb } = tracker.fetch(message.messageId); if (cb) { cb(new errors.TimeoutError("request timeout (client interrupt)")); } } function writeCallback() { if (expect === "abandon") { tracker.abandon(message.abandonId); tracker.remove(message.id); return callback(null); } else if (expect === "unbind") { conn.unbindMessageID = message.id; self2.connected = false; conn.removeAllListeners("error"); conn.on("error", function() { }); conn.end(); } else if (emitter) { sentEmitter = true; callback(null, emitter); emitter.emit("searchRequest", message); return; } return false; } tracker.track(message, messageCallback); this._updateIdle(true); if (self2.timeout) { log.trace("Setting timeout to %d", self2.timeout); timer = setTimeout(onRequestTimeout, self2.timeout); } log.trace("sending request %j", message.pojo); try { const messageBer = message.toBer(); return conn.write(messageBer.buffer, writeCallback); } catch (e) { if (timer) { clearTimeout(timer); } log.trace({ err: e }, "Error writing message to socket"); return callback(e); } }; Client.prototype.emitError = function emitError(event, err) { if (event !== "error" && err && this.listenerCount(event) === 0) { if (typeof err === "string") { err = event + ": " + err; } else if (err.message) { err.message = event + ": " + err.message; } this.emit("error", err); } this.emit(event, err); }; } }); // node_modules/ldapjs/lib/client/index.js var require_client2 = __commonJS({ "node_modules/ldapjs/lib/client/index.js"(exports, module2) { "use strict"; var logger = require_logger(); var Client = require_client(); module2.exports = { Client, createClient: function createClient2(options) { if (isObject(options) === false) throw TypeError("options (object) required"); if (options.url && typeof options.url !== "string" && !Array.isArray(options.url)) throw TypeError("options.url (string|array) required"); if (options.socketPath && typeof options.socketPath !== "string") throw TypeError("options.socketPath must be a string"); if (options.url && options.socketPath || !(options.url || options.socketPath)) throw TypeError("options.url ^ options.socketPath (String) required"); if (!options.log) options.log = logger; if (isObject(options.log) !== true) throw TypeError("options.log must be an object"); if (!options.log.child) options.log.child = function() { return options.log; }; return new Client(options); } }; function isObject(input) { return Object.prototype.toString.apply(input) === "[object Object]"; } } }); // node_modules/ldapjs/lib/server.js var require_server = __commonJS({ "node_modules/ldapjs/lib/server.js"(exports, module2) { var assert = require("assert"); var EventEmitter = require("events").EventEmitter; var net = require("net"); var tls = require("tls"); var util = require("util"); var VError = require_verror2().VError; var { DN, RDN } = require_dn2(); var errors = require_errors2(); var Protocol = require_protocol(); var messages = require_messages(); var Parser = require_messages2().Parser; var LdapResult = messages.LdapResult; var AbandonResponse = messages.AbandonResponse; var AddResponse = messages.AddResponse; var BindResponse = messages.BindResponse; var CompareResponse = messages.CompareResponse; var DeleteResponse = messages.DeleteResponse; var ExtendedResponse = messages.ExtensionResponse; var ModifyResponse = messages.ModifyResponse; var ModifyDnResponse = messages.ModifyDnResponse; var SearchRequest = messages.SearchRequest; var SearchResponse = require_search_response(); function mergeFunctionArgs(argv, start, end) { assert.ok(argv); if (!start) { start = 0; } if (!end) { end = argv.length; } const handlers = []; for (let i = start; i < end; i++) { if (Array.isArray(argv[i])) { const arr = argv[i]; for (let j = 0; j < arr.length; j++) { if (typeof arr[j] !== "function") { throw new TypeError("Invalid argument type: " + typeof arr[j]); } handlers.push(arr[j]); } } else if (typeof argv[i] === "function") { handlers.push(argv[i]); } else { throw new TypeError("Invalid argument type: " + typeof argv[i]); } } return handlers; } function getResponse(req) { assert.ok(req); let Response; switch (req.protocolOp) { case Protocol.operations.LDAP_REQ_BIND: Response = BindResponse; break; case Protocol.operations.LDAP_REQ_ABANDON: Response = AbandonResponse; break; case Protocol.operations.LDAP_REQ_ADD: Response = AddResponse; break; case Protocol.operations.LDAP_REQ_COMPARE: Response = CompareResponse; break; case Protocol.operations.LDAP_REQ_DELETE: Response = DeleteResponse; break; case Protocol.operations.LDAP_REQ_EXTENSION: Response = ExtendedResponse; break; case Protocol.operations.LDAP_REQ_MODIFY: Response = ModifyResponse; break; case Protocol.operations.LDAP_REQ_MODRDN: Response = ModifyDnResponse; break; case Protocol.operations.LDAP_REQ_SEARCH: Response = SearchResponse; break; case Protocol.operations.LDAP_REQ_UNBIND: Response = class extends LdapResult { constructor() { super(...arguments); __publicField(this, "status", 0); } end() { req.connection.end(); } }; break; default: return null; } assert.ok(Response); const res = new Response({ messageId: req.messageId, attributes: req instanceof SearchRequest ? req.attributes : void 0 }); res.log = req.log; res.connection = req.connection; res.logId = req.logId; if (typeof res.end !== "function") { switch (res.protocolOp) { case 0: { res.end = abandonResponseEnd; break; } case Protocol.operations.LDAP_RES_COMPARE: { res.end = compareResponseEnd; break; } default: { res.end = defaultResponseEnd; break; } } } return res; } function defaultResponseEnd(status) { if (typeof status === "number") { this.status = status; } const ber = this.toBer(); this.log.debug("%s: sending: %j", this.connection.ldap.id, this.pojo); try { this.connection.write(ber.buffer); } catch (error) { this.log.warn(error, "%s failure to write message %j", this.connection.ldap.id, this.pojo); } } function abandonResponseEnd() { } function compareResponseEnd(status) { let result = 6; if (typeof status === "boolean") { if (status === false) { result = 5; } } else { result = status; } return defaultResponseEnd.call(this, result); } function defaultHandler(req, res, next) { assert.ok(req); assert.ok(res); assert.ok(next); res.matchedDN = req.dn.toString(); res.errorMessage = "Server method not implemented"; res.end(errors.LDAP_OTHER); return next(); } function defaultNoOpHandler(req, res, next) { assert.ok(req); assert.ok(res); assert.ok(next); res.end(); return next(); } function noSuffixHandler(req, res, next) { assert.ok(req); assert.ok(res); assert.ok(next); res.errorMessage = "No tree found for: " + req.dn.toString(); res.end(errors.LDAP_NO_SUCH_OBJECT); return next(); } function noExOpHandler(req, res, next) { assert.ok(req); assert.ok(res); assert.ok(next); res.errorMessage = req.requestName + " not supported"; res.end(errors.LDAP_PROTOCOL_ERROR); return next(); } function Server(options) { if (options) { if (typeof options !== "object") { throw new TypeError("options (object) required"); } if (typeof options.log !== "object") { throw new TypeError("options.log must be an object"); } if (options.certificate || options.key) { if (!(options.certificate && options.key) || typeof options.certificate !== "string" && !Buffer.isBuffer(options.certificate) || typeof options.key !== "string" && !Buffer.isBuffer(options.key)) { throw new TypeError("options.certificate and options.key (string or buffer) are both required for TLS"); } } } else { options = {}; } const self2 = this; EventEmitter.call(this, options); this._chain = []; this.log = options.log; const log = this.log; function setupConnection(c) { assert.ok(c); if (c.type === "unix") { c.remoteAddress = self2.server.path; c.remotePort = c.fd; } else if (c.socket) { c.remoteAddress = c.socket.remoteAddress; c.remotePort = c.socket.remotePort; } const rdn = new RDN({ cn: "anonymous" }); c.ldap = { id: c.remoteAddress + ":" + c.remotePort, config: options, _bindDN: new DN({ rdns: [rdn] }) }; c.addListener("timeout", function() { log.trace("%s timed out", c.ldap.id); c.destroy(); }); c.addListener("end", function() { log.trace("%s shutdown", c.ldap.id); }); c.addListener("error", function(err) { log.warn("%s unexpected connection error", c.ldap.id, err); self2.emit("clientError", err); c.destroy(); }); c.addListener("close", function(closeError) { log.trace("%s close; had_err=%j", c.ldap.id, closeError); c.end(); }); c.ldap.__defineGetter__("bindDN", function() { return c.ldap._bindDN; }); c.ldap.__defineSetter__("bindDN", function(val) { if (Object.prototype.toString.call(val) !== "[object LdapDn]") { throw new TypeError("DN required"); } c.ldap._bindDN = val; return val; }); return c; } self2.newConnection = function(conn) { setupConnection(conn); log.trace("new connection from %s", conn.ldap.id); conn.parser = new Parser({ log: options.log }); conn.parser.on("message", function(req) { req.connection = conn; req.logId = conn.ldap.id + "::" + req.messageId; req.startTime = new Date().getTime(); log.debug("%s: message received: req=%j", conn.ldap.id, req.pojo); const res = getResponse(req); if (!res) { log.warn("Unimplemented server method: %s", req.type); conn.destroy(); return false; } try { switch (req.protocolOp) { case Protocol.operations.LDAP_REQ_BIND: { req.name = DN.fromString(req.name); break; } case Protocol.operations.LDAP_REQ_ADD: case Protocol.operations.LDAP_REQ_COMPARE: case Protocol.operations.LDAP_REQ_DELETE: { if (typeof req.entry === "string") { req.entry = DN.fromString(req.entry); } else if (Object.prototype.toString.call(req.entry) !== "[object LdapDn]") { throw Error("invalid entry object for operation"); } break; } case Protocol.operations.LDAP_REQ_MODIFY: { req.object = DN.fromString(req.object); break; } case Protocol.operations.LDAP_REQ_MODRDN: { if (typeof req.entry === "string") { req.entry = DN.fromString(req.entry); } else if (Object.prototype.toString.call(req.entry) !== "[object LdapDn]") { throw Error("invalid entry object for operation"); } break; } case Protocol.operations.LDAP_REQ_SEARCH: { break; } default: { break; } } } catch (e) { return res.end(errors.LDAP_INVALID_DN_SYNTAX); } res.connection = conn; res.logId = req.logId; res.requestDN = req.dn; const chain = self2._getHandlerChain(req, res); let i = 0; return function messageIIFE(err) { function sendError(sendErr) { res.status = sendErr.code || errors.LDAP_OPERATIONS_ERROR; res.matchedDN = req.suffix ? req.suffix.toString() : ""; res.errorMessage = sendErr.message || ""; return res.end(); } function after() { if (!self2._postChain || !self2._postChain.length) { return; } function next() { } self2._postChain.forEach(function(cb) { cb.call(self2, req, res, next); }); } if (err) { log.trace("%s sending error: %s", req.logId, err.stack || err); self2.emit("clientError", err); sendError(err); return after(); } try { const next = messageIIFE; if (chain.handlers[i]) { return chain.handlers[i++].call(chain.backend, req, res, next); } if (req.protocolOp === Protocol.operations.LDAP_REQ_BIND && res.status === 0) { if (req.dn.length === 0 && req.credentials === "") { conn.ldap.bindDN = new DN({ rdns: [new RDN({ cn: "anonymous" })] }); } else { conn.ldap.bindDN = DN.fromString(req.dn); } } if (req.protocolOp === Protocol.operations.LDAP_REQ_UNBIND && res.status === 0) { conn.ldap.bindDN = new DN({ rdns: [new RDN({ cn: "anonymous" })] }); } return after(); } catch (e) { if (!e.stack) { e.stack = e.toString(); } log.error("%s uncaught exception: %s", req.logId, e.stack); return sendError(new errors.OperationsError(e.message)); } }(); }); conn.parser.on("error", function(err, message) { self2.emit("error", new VError(err, "Parser error for %s", conn.ldap.id)); if (!message) { return conn.destroy(); } const res = getResponse(message); if (!res) { return conn.destroy(); } res.status = 2; res.errorMessage = err.toString(); return conn.end(res.toBer()); }); conn.on("data", function(data) { log.trace("data on %s: %s", conn.ldap.id, util.inspect(data)); conn.parser.write(data); }); }; this.routes = {}; if ((options.cert || options.certificate) && options.key) { options.cert = options.cert || options.certificate; this.server = tls.createServer(options, options.connectionRouter ? options.connectionRouter : self2.newConnection); } else { this.server = net.createServer(options.connectionRouter ? options.connectionRouter : self2.newConnection); } this.server.log = options.log; this.server.ldap = { config: options }; this.server.on("close", function() { self2.emit("close"); }); this.server.on("error", function(err) { self2.emit("error", err); }); } util.inherits(Server, EventEmitter); Object.defineProperties(Server.prototype, { maxConnections: { get: function getMaxConnections() { return this.server.maxConnections; }, set: function setMaxConnections(val) { this.server.maxConnections = val; }, configurable: false }, connections: { get: function getConnections() { return this.server.connections; }, configurable: false }, name: { get: function getName() { return "LDAPServer"; }, configurable: false }, url: { get: function getURL() { let str; const addr = this.server.address(); if (!addr) { return null; } if (!addr.family) { str = "ldapi://"; str += this.host.replace(/\//g, "%2f"); return str; } if (this.server instanceof tls.Server) { str = "ldaps://"; } else { str = "ldap://"; } let host = this.host; if (addr.family === "IPv6" || addr.family === 6) { host = "[" + this.host + "]"; } str += host + ":" + this.port; return str; }, configurable: false } }); module2.exports = Server; Server.prototype.add = function(name) { const args = Array.prototype.slice.call(arguments, 1); return this._mount(Protocol.operations.LDAP_REQ_ADD, name, args); }; Server.prototype.bind = function(name) { const args = Array.prototype.slice.call(arguments, 1); return this._mount(Protocol.operations.LDAP_REQ_BIND, name, args); }; Server.prototype.compare = function(name) { const args = Array.prototype.slice.call(arguments, 1); return this._mount(Protocol.operations.LDAP_REQ_COMPARE, name, args); }; Server.prototype.del = function(name) { const args = Array.prototype.slice.call(arguments, 1); return this._mount(Protocol.operations.LDAP_REQ_DELETE, name, args); }; Server.prototype.exop = function(name) { const args = Array.prototype.slice.call(arguments, 1); return this._mount(Protocol.operations.LDAP_REQ_EXTENSION, name, args, true); }; Server.prototype.modify = function(name) { const args = Array.prototype.slice.call(arguments, 1); return this._mount(Protocol.operations.LDAP_REQ_MODIFY, name, args); }; Server.prototype.modifyDN = function(name) { const args = Array.prototype.slice.call(arguments, 1); return this._mount(Protocol.operations.LDAP_REQ_MODRDN, name, args); }; Server.prototype.search = function(name) { const args = Array.prototype.slice.call(arguments, 1); return this._mount(Protocol.operations.LDAP_REQ_SEARCH, name, args); }; Server.prototype.unbind = function() { const args = Array.prototype.slice.call(arguments, 0); return this._mount(Protocol.operations.LDAP_REQ_UNBIND, "unbind", args, true); }; Server.prototype.use = function use() { const args = Array.prototype.slice.call(arguments); const chain = mergeFunctionArgs(args, 0, args.length); const self2 = this; chain.forEach(function(c) { self2._chain.push(c); }); }; Server.prototype.after = function() { if (!this._postChain) { this._postChain = []; } const self2 = this; mergeFunctionArgs(arguments).forEach(function(h) { self2._postChain.push(h); }); }; Server.prototype.listen = function(port, host, callback) { if (typeof port !== "number" && typeof port !== "string") { throw new TypeError("port (number or path) required"); } if (typeof host === "function") { callback = host; host = "127.0.0.1"; } if (typeof port === "string" && /^[0-9]+$/.test(port)) { port = parseInt(port, 10); } const self2 = this; function cbListen() { if (typeof port === "number") { self2.host = self2.address().address; self2.port = self2.address().port; } else { self2.host = port; self2.port = self2.server.fd; } if (typeof callback === "function") { callback(); } } if (typeof port === "number") { return this.server.listen(port, host, cbListen); } else { return this.server.listen(port, cbListen); } }; Server.prototype.listenFD = function(fd) { this.host = "unix-domain-socket"; this.port = fd; return this.server.listenFD(fd); }; Server.prototype.close = function(callback) { return this.server.close(callback); }; Server.prototype.address = function() { return this.server.address(); }; Server.prototype.getConnections = function(callback) { return this.server.getConnections(callback); }; Server.prototype._getRoute = function(_dn, backend) { if (!backend) { backend = this; } let name; if (Object.prototype.toString.call(_dn) === "[object LdapDn]") { name = _dn.toString(); } else { name = _dn; } if (!this.routes[name]) { this.routes[name] = {}; this.routes[name].backend = backend; this.routes[name].dn = _dn; this._routeKeyCache = null; } return this.routes[name]; }; Server.prototype._sortedRouteKeys = function _sortedRouteKeys() { if (!this._routeKeyCache) { const self2 = this; const reversedRDNsToKeys = {}; Object.keys(this.routes).forEach(function(key) { const _dn = self2.routes[key].dn; if (Object.prototype.toString.call(_dn) === "[object LdapDn]") { const reversed = _dn.clone(); reversed.reverse(); reversedRDNsToKeys[reversed.toString()] = key; } }); const output = []; Object.keys(reversedRDNsToKeys).sort().reverse().forEach(function(_dn) { output.push(reversedRDNsToKeys[_dn]); }); this._routeKeyCache = output; } return this._routeKeyCache; }; Server.prototype._getHandlerChain = function _getHandlerChain(req) { assert.ok(req); const self2 = this; const routes = this.routes; let route; if (req.protocolOp === Protocol.operations.LDAP_REQ_BIND && req.dn.toString() === "" && req.credentials === "") { return { backend: self2, handlers: [defaultNoOpHandler] }; } const op = "0x" + req.protocolOp.toString(16); if (req.protocolOp === Protocol.operations.LDAP_REQ_EXTENSION) { route = routes[req.requestName]; if (route) { return { backend: route.backend, handlers: route[op] ? route[op] : [noExOpHandler] }; } else { return { backend: self2, handlers: [noExOpHandler] }; } } else if (req.protocolOp === Protocol.operations.LDAP_REQ_UNBIND) { route = routes.unbind; if (route) { return { backend: route.backend, handlers: route[op] }; } else { return { backend: self2, handlers: [defaultNoOpHandler] }; } } else if (req.protocolOp === Protocol.operations.LDAP_REQ_ABANDON) { return { backend: self2, handlers: [defaultNoOpHandler] }; } assert.ok(req.dn); const keys = this._sortedRouteKeys(); let fallbackHandler = [noSuffixHandler]; const testDN = typeof req.dn === "string" ? DN.fromString(req.dn) : req.dn; for (let i = 0; i < keys.length; i++) { const suffix = keys[i]; route = routes[suffix]; assert.ok(route.dn); if (route.dn.equals(testDN) || route.dn.parentOf(testDN) || suffix === "") { if (route[op]) { req.suffix = route.dn; return { backend: route.backend, handlers: route[op] }; } else { if (suffix === "") { break; } else { fallbackHandler = [defaultHandler]; } } } } return { backend: self2, handlers: fallbackHandler }; }; Server.prototype._mount = function(op, name, argv, notDN) { assert.ok(op); assert.ok(name !== void 0); assert.ok(argv); if (typeof name !== "string") { throw new TypeError("name (string) required"); } if (!argv.length) { throw new Error("at least one handler required"); } let backend = this; let index = 0; if (typeof argv[0] === "object" && !Array.isArray(argv[0])) { backend = argv[0]; index = 1; } const route = this._getRoute(notDN ? name : DN.fromString(name), backend); const chain = this._chain.slice(); argv.slice(index).forEach(function(a) { chain.push(a); }); route["0x" + op.toString(16)] = mergeFunctionArgs(chain); return this; }; } }); // node_modules/ldapjs/lib/persistent_search.js var require_persistent_search = __commonJS({ "node_modules/ldapjs/lib/persistent_search.js"(exports, module2) { var EntryChangeNotificationControl = require_controls2().EntryChangeNotificationControl; function PersistentSearch() { this.clientList = []; } PersistentSearch.prototype.addClient = function(req, res, callback) { if (typeof req !== "object") { throw new TypeError("req must be an object"); } if (typeof res !== "object") { throw new TypeError("res must be an object"); } if (callback && typeof callback !== "function") { throw new TypeError("callback must be a function"); } const log = req.log; const client = {}; client.req = req; client.res = res; log.debug("%s storing client", req.logId); this.clientList.push(client); log.debug("%s stored client", req.logId); log.debug("%s total number of clients %s", req.logId, this.clientList.length); if (callback) { callback(client); } }; PersistentSearch.prototype.removeClient = function(req, res, callback) { if (typeof req !== "object") { throw new TypeError("req must be an object"); } if (typeof res !== "object") { throw new TypeError("res must be an object"); } if (callback && typeof callback !== "function") { throw new TypeError("callback must be a function"); } const log = req.log; log.debug("%s removing client", req.logId); const client = {}; client.req = req; client.res = res; this.clientList.forEach(function(element, index, array) { if (element.req === client.req) { log.debug("%s removing client from list", req.logId); array.splice(index, 1); } }); log.debug("%s number of persistent search clients %s", req.logId, this.clientList.length); if (callback) { callback(client); } }; function getOperationType(requestType) { switch (requestType) { case "AddRequest": case "add": return 1; case "DeleteRequest": case "delete": return 2; case "ModifyRequest": case "modify": return 4; case "ModifyDNRequest": case "modrdn": return 8; default: throw new TypeError("requestType %s, is an invalid request type", requestType); } } function getEntryChangeNotificationControl(req, obj) { if (req.persistentSearch.value.returnECs) { const attrs = obj.attributes; const value = {}; value.changeType = getOperationType(attrs.changetype); if (value.changeType === 8 && attrs.previousDN) { value.previousDN = attrs.previousDN; } value.changeNumber = attrs.changenumber; return new EntryChangeNotificationControl({ value }); } else { return false; } } function checkChangeType(req, requestType) { return req.persistentSearch.value.changeTypes & getOperationType(requestType); } module2.exports = { PersistentSearchCache: PersistentSearch, checkChangeType, getEntryChangeNotificationControl }; } }); // node_modules/ldapjs/lib/index.js var require_lib3 = __commonJS({ "node_modules/ldapjs/lib/index.js"(exports, module2) { var logger = require_logger(); var client = require_client2(); var Attribute = require_attribute(); var Change = require_change(); var Protocol = require_protocol(); var Server = require_server(); var controls = require_controls2(); var persistentSearch = require_persistent_search(); var dn = require_dn2(); var errors = require_errors2(); var filters = require_lib2(); var messages = require_messages2(); var url = require_url(); var hasOwnProperty = (target, val) => Object.prototype.hasOwnProperty.call(target, val); module2.exports = { Client: client.Client, createClient: client.createClient, Server, createServer: function(options) { if (options === void 0) { options = {}; } if (typeof options !== "object") { throw new TypeError("options (object) required"); } if (!options.log) { options.log = logger; } return new Server(options); }, Attribute, Change, dn, DN: dn.DN, RDN: dn.RDN, parseDN: dn.DN.fromString, persistentSearch, PersistentSearchCache: persistentSearch.PersistentSearchCache, filters, parseFilter: filters.parseString, url, parseURL: url.parse }; var k; for (k in Protocol) { if (hasOwnProperty(Protocol, k)) { module2.exports[k] = Protocol[k]; } } for (k in messages) { if (hasOwnProperty(messages, k)) { module2.exports[k] = messages[k]; } } for (k in controls) { if (hasOwnProperty(controls, k)) { module2.exports[k] = controls[k]; } } for (k in filters) { if (hasOwnProperty(filters, k)) { if (k !== "parse" && k !== "parseString") { module2.exports[k] = filters[k]; } } } for (k in errors) { if (hasOwnProperty(errors, k)) { module2.exports[k] = errors[k]; } } } }); // node_modules/nunjucks/browser/nunjucks.js var require_nunjucks = __commonJS({ "node_modules/nunjucks/browser/nunjucks.js"(exports, module2) { (function webpackUniversalModuleDefinition(root, factory) { if (typeof exports === "object" && typeof module2 === "object") module2.exports = factory(); else if (typeof define === "function" && define.amd) define([], factory); else if (typeof exports === "object") exports["nunjucks"] = factory(); else root["nunjucks"] = factory(); })(typeof self !== "undefined" ? self : exports, function() { return function(modules) { var installedModules = {}; function __webpack_require__(moduleId) { if (installedModules[moduleId]) { return installedModules[moduleId].exports; } var module3 = installedModules[moduleId] = { i: moduleId, l: false, exports: {} }; modules[moduleId].call(module3.exports, module3, module3.exports, __webpack_require__); module3.l = true; return module3.exports; } __webpack_require__.m = modules; __webpack_require__.c = installedModules; __webpack_require__.d = function(exports2, name, getter) { if (!__webpack_require__.o(exports2, name)) { Object.defineProperty(exports2, name, { configurable: false, enumerable: true, get: getter }); } }; __webpack_require__.n = function(module3) { var getter = module3 && module3.__esModule ? function getDefault() { return module3["default"]; } : function getModuleExports() { return module3; }; __webpack_require__.d(getter, "a", getter); return getter; }; __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; __webpack_require__.p = ""; return __webpack_require__(__webpack_require__.s = 11); }([ function(module3, exports2, __webpack_require__) { "use strict"; var ArrayProto = Array.prototype; var ObjProto = Object.prototype; var escapeMap = { "&": "&", '"': """, "'": "'", "<": "<", ">": ">", "\\": "\" }; var escapeRegex = /[&"'<>\\]/g; var exports2 = module3.exports = {}; function hasOwnProp(obj, k) { return ObjProto.hasOwnProperty.call(obj, k); } exports2.hasOwnProp = hasOwnProp; function lookupEscape(ch) { return escapeMap[ch]; } function _prettifyError(path, withInternals, err) { if (!err.Update) { err = new exports2.TemplateError(err); } err.Update(path); if (!withInternals) { var old = err; err = new Error(old.message); err.name = old.name; } return err; } exports2._prettifyError = _prettifyError; function TemplateError(message, lineno, colno) { var err; var cause; if (message instanceof Error) { cause = message; message = cause.name + ": " + cause.message; } if (Object.setPrototypeOf) { err = new Error(message); Object.setPrototypeOf(err, TemplateError.prototype); } else { err = this; Object.defineProperty(err, "message", { enumerable: false, writable: true, value: message }); } Object.defineProperty(err, "name", { value: "Template render error" }); if (Error.captureStackTrace) { Error.captureStackTrace(err, this.constructor); } var getStack; if (cause) { var stackDescriptor = Object.getOwnPropertyDescriptor(cause, "stack"); getStack = stackDescriptor && (stackDescriptor.get || function() { return stackDescriptor.value; }); if (!getStack) { getStack = function getStack2() { return cause.stack; }; } } else { var stack = new Error(message).stack; getStack = function getStack2() { return stack; }; } Object.defineProperty(err, "stack", { get: function get() { return getStack.call(err); } }); Object.defineProperty(err, "cause", { value: cause }); err.lineno = lineno; err.colno = colno; err.firstUpdate = true; err.Update = function Update(path) { var msg = "(" + (path || "unknown path") + ")"; if (this.firstUpdate) { if (this.lineno && this.colno) { msg += " [Line " + this.lineno + ", Column " + this.colno + "]"; } else if (this.lineno) { msg += " [Line " + this.lineno + "]"; } } msg += "\n "; if (this.firstUpdate) { msg += " "; } this.message = msg + (this.message || ""); this.firstUpdate = false; return this; }; return err; } if (Object.setPrototypeOf) { Object.setPrototypeOf(TemplateError.prototype, Error.prototype); } else { TemplateError.prototype = Object.create(Error.prototype, { constructor: { value: TemplateError } }); } exports2.TemplateError = TemplateError; function escape(val) { return val.replace(escapeRegex, lookupEscape); } exports2.escape = escape; function isFunction(obj) { return ObjProto.toString.call(obj) === "[object Function]"; } exports2.isFunction = isFunction; function isArray(obj) { return ObjProto.toString.call(obj) === "[object Array]"; } exports2.isArray = isArray; function isString(obj) { return ObjProto.toString.call(obj) === "[object String]"; } exports2.isString = isString; function isObject(obj) { return ObjProto.toString.call(obj) === "[object Object]"; } exports2.isObject = isObject; function _prepareAttributeParts(attr) { if (!attr) { return []; } if (typeof attr === "string") { return attr.split("."); } return [attr]; } function getAttrGetter(attribute) { var parts = _prepareAttributeParts(attribute); return function attrGetter(item) { var _item = item; for (var i = 0; i < parts.length; i++) { var part = parts[i]; if (hasOwnProp(_item, part)) { _item = _item[part]; } else { return void 0; } } return _item; }; } exports2.getAttrGetter = getAttrGetter; function groupBy(obj, val, throwOnUndefined) { var result = {}; var iterator = isFunction(val) ? val : getAttrGetter(val); for (var i = 0; i < obj.length; i++) { var value = obj[i]; var key = iterator(value, i); if (key === void 0 && throwOnUndefined === true) { throw new TypeError('groupby: attribute "' + val + '" resolved to undefined'); } (result[key] || (result[key] = [])).push(value); } return result; } exports2.groupBy = groupBy; function toArray(obj) { return Array.prototype.slice.call(obj); } exports2.toArray = toArray; function without(array) { var result = []; if (!array) { return result; } var length = array.length; var contains = toArray(arguments).slice(1); var index = -1; while (++index < length) { if (indexOf(contains, array[index]) === -1) { result.push(array[index]); } } return result; } exports2.without = without; function repeat(char_, n) { var str = ""; for (var i = 0; i < n; i++) { str += char_; } return str; } exports2.repeat = repeat; function each(obj, func, context) { if (obj == null) { return; } if (ArrayProto.forEach && obj.forEach === ArrayProto.forEach) { obj.forEach(func, context); } else if (obj.length === +obj.length) { for (var i = 0, l = obj.length; i < l; i++) { func.call(context, obj[i], i, obj); } } } exports2.each = each; function map(obj, func) { var results = []; if (obj == null) { return results; } if (ArrayProto.map && obj.map === ArrayProto.map) { return obj.map(func); } for (var i = 0; i < obj.length; i++) { results[results.length] = func(obj[i], i); } if (obj.length === +obj.length) { results.length = obj.length; } return results; } exports2.map = map; function asyncIter(arr, iter, cb) { var i = -1; function next() { i++; if (i < arr.length) { iter(arr[i], i, next, cb); } else { cb(); } } next(); } exports2.asyncIter = asyncIter; function asyncFor(obj, iter, cb) { var keys = keys_(obj || {}); var len = keys.length; var i = -1; function next() { i++; var k = keys[i]; if (i < len) { iter(k, obj[k], i, len, next); } else { cb(); } } next(); } exports2.asyncFor = asyncFor; function indexOf(arr, searchElement, fromIndex) { return Array.prototype.indexOf.call(arr || [], searchElement, fromIndex); } exports2.indexOf = indexOf; function keys_(obj) { var arr = []; for (var k in obj) { if (hasOwnProp(obj, k)) { arr.push(k); } } return arr; } exports2.keys = keys_; function _entries(obj) { return keys_(obj).map(function(k) { return [k, obj[k]]; }); } exports2._entries = _entries; function _values(obj) { return keys_(obj).map(function(k) { return obj[k]; }); } exports2._values = _values; function extend(obj1, obj2) { obj1 = obj1 || {}; keys_(obj2).forEach(function(k) { obj1[k] = obj2[k]; }); return obj1; } exports2._assign = exports2.extend = extend; function inOperator(key, val) { if (isArray(val) || isString(val)) { return val.indexOf(key) !== -1; } else if (isObject(val)) { return key in val; } throw new Error('Cannot use "in" operator to search for "' + key + '" in unexpected types.'); } exports2.inOperator = inOperator; }, function(module3, exports2, __webpack_require__) { "use strict"; function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== void 0) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) { o2.__proto__ = p2; return o2; }; return _setPrototypeOf(o, p); } var EventEmitter = __webpack_require__(16); var lib = __webpack_require__(0); function parentWrap(parent, prop) { if (typeof parent !== "function" || typeof prop !== "function") { return prop; } return function wrap() { var tmp = this.parent; this.parent = parent; var res = prop.apply(this, arguments); this.parent = tmp; return res; }; } function extendClass(cls, name, props) { props = props || {}; lib.keys(props).forEach(function(k) { props[k] = parentWrap(cls.prototype[k], props[k]); }); var subclass = /* @__PURE__ */ function(_cls) { _inheritsLoose(subclass2, _cls); function subclass2() { return _cls.apply(this, arguments) || this; } _createClass(subclass2, [{ key: "typename", get: function get() { return name; } }]); return subclass2; }(cls); lib._assign(subclass.prototype, props); return subclass; } var Obj = /* @__PURE__ */ function() { function Obj2() { this.init.apply(this, arguments); } var _proto = Obj2.prototype; _proto.init = function init() { }; Obj2.extend = function extend(name, props) { if (typeof name === "object") { props = name; name = "anonymous"; } return extendClass(this, name, props); }; _createClass(Obj2, [{ key: "typename", get: function get() { return this.constructor.name; } }]); return Obj2; }(); var EmitterObj = /* @__PURE__ */ function(_EventEmitter) { _inheritsLoose(EmitterObj2, _EventEmitter); function EmitterObj2() { var _this2; var _this; _this = _EventEmitter.call(this) || this; (_this2 = _this).init.apply(_this2, arguments); return _this; } var _proto2 = EmitterObj2.prototype; _proto2.init = function init() { }; EmitterObj2.extend = function extend(name, props) { if (typeof name === "object") { props = name; name = "anonymous"; } return extendClass(this, name, props); }; _createClass(EmitterObj2, [{ key: "typename", get: function get() { return this.constructor.name; } }]); return EmitterObj2; }(EventEmitter); module3.exports = { Obj, EmitterObj }; }, function(module3, exports2, __webpack_require__) { "use strict"; var lib = __webpack_require__(0); var arrayFrom = Array.from; var supportsIterators = typeof Symbol === "function" && Symbol.iterator && typeof arrayFrom === "function"; var Frame = /* @__PURE__ */ function() { function Frame2(parent, isolateWrites) { this.variables = /* @__PURE__ */ Object.create(null); this.parent = parent; this.topLevel = false; this.isolateWrites = isolateWrites; } var _proto = Frame2.prototype; _proto.set = function set(name, val, resolveUp) { var parts = name.split("."); var obj = this.variables; var frame = this; if (resolveUp) { if (frame = this.resolve(parts[0], true)) { frame.set(name, val); return; } } for (var i = 0; i < parts.length - 1; i++) { var id = parts[i]; if (!obj[id]) { obj[id] = {}; } obj = obj[id]; } obj[parts[parts.length - 1]] = val; }; _proto.get = function get(name) { var val = this.variables[name]; if (val !== void 0) { return val; } return null; }; _proto.lookup = function lookup(name) { var p = this.parent; var val = this.variables[name]; if (val !== void 0) { return val; } return p && p.lookup(name); }; _proto.resolve = function resolve(name, forWrite) { var p = forWrite && this.isolateWrites ? void 0 : this.parent; var val = this.variables[name]; if (val !== void 0) { return this; } return p && p.resolve(name); }; _proto.push = function push(isolateWrites) { return new Frame2(this, isolateWrites); }; _proto.pop = function pop() { return this.parent; }; return Frame2; }(); function makeMacro(argNames, kwargNames, func) { return function macro() { for (var _len = arguments.length, macroArgs = new Array(_len), _key = 0; _key < _len; _key++) { macroArgs[_key] = arguments[_key]; } var argCount = numArgs(macroArgs); var args; var kwargs = getKeywordArgs(macroArgs); if (argCount > argNames.length) { args = macroArgs.slice(0, argNames.length); macroArgs.slice(args.length, argCount).forEach(function(val, i2) { if (i2 < kwargNames.length) { kwargs[kwargNames[i2]] = val; } }); args.push(kwargs); } else if (argCount < argNames.length) { args = macroArgs.slice(0, argCount); for (var i = argCount; i < argNames.length; i++) { var arg = argNames[i]; args.push(kwargs[arg]); delete kwargs[arg]; } args.push(kwargs); } else { args = macroArgs; } return func.apply(this, args); }; } function makeKeywordArgs(obj) { obj.__keywords = true; return obj; } function isKeywordArgs(obj) { return obj && Object.prototype.hasOwnProperty.call(obj, "__keywords"); } function getKeywordArgs(args) { var len = args.length; if (len) { var lastArg = args[len - 1]; if (isKeywordArgs(lastArg)) { return lastArg; } } return {}; } function numArgs(args) { var len = args.length; if (len === 0) { return 0; } var lastArg = args[len - 1]; if (isKeywordArgs(lastArg)) { return len - 1; } else { return len; } } function SafeString(val) { if (typeof val !== "string") { return val; } this.val = val; this.length = val.length; } SafeString.prototype = Object.create(String.prototype, { length: { writable: true, configurable: true, value: 0 } }); SafeString.prototype.valueOf = function valueOf() { return this.val; }; SafeString.prototype.toString = function toString() { return this.val; }; function copySafeness(dest, target) { if (dest instanceof SafeString) { return new SafeString(target); } return target.toString(); } function markSafe(val) { var type = typeof val; if (type === "string") { return new SafeString(val); } else if (type !== "function") { return val; } else { return function wrapSafe(args) { var ret = val.apply(this, arguments); if (typeof ret === "string") { return new SafeString(ret); } return ret; }; } } function suppressValue(val, autoescape) { val = val !== void 0 && val !== null ? val : ""; if (autoescape && !(val instanceof SafeString)) { val = lib.escape(val.toString()); } return val; } function ensureDefined(val, lineno, colno) { if (val === null || val === void 0) { throw new lib.TemplateError("attempted to output null or undefined value", lineno + 1, colno + 1); } return val; } function memberLookup(obj, val) { if (obj === void 0 || obj === null) { return void 0; } if (typeof obj[val] === "function") { return function() { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return obj[val].apply(obj, args); }; } return obj[val]; } function callWrap(obj, name, context, args) { if (!obj) { throw new Error("Unable to call `" + name + "`, which is undefined or falsey"); } else if (typeof obj !== "function") { throw new Error("Unable to call `" + name + "`, which is not a function"); } return obj.apply(context, args); } function contextOrFrameLookup(context, frame, name) { var val = frame.lookup(name); return val !== void 0 ? val : context.lookup(name); } function handleError(error, lineno, colno) { if (error.lineno) { return error; } else { return new lib.TemplateError(error, lineno, colno); } } function asyncEach(arr, dimen, iter, cb) { if (lib.isArray(arr)) { var len = arr.length; lib.asyncIter(arr, function iterCallback(item, i, next) { switch (dimen) { case 1: iter(item, i, len, next); break; case 2: iter(item[0], item[1], i, len, next); break; case 3: iter(item[0], item[1], item[2], i, len, next); break; default: item.push(i, len, next); iter.apply(this, item); } }, cb); } else { lib.asyncFor(arr, function iterCallback(key, val, i, len2, next) { iter(key, val, i, len2, next); }, cb); } } function asyncAll(arr, dimen, func, cb) { var finished = 0; var len; var outputArr; function done(i2, output) { finished++; outputArr[i2] = output; if (finished === len) { cb(null, outputArr.join("")); } } if (lib.isArray(arr)) { len = arr.length; outputArr = new Array(len); if (len === 0) { cb(null, ""); } else { for (var i = 0; i < arr.length; i++) { var item = arr[i]; switch (dimen) { case 1: func(item, i, len, done); break; case 2: func(item[0], item[1], i, len, done); break; case 3: func(item[0], item[1], item[2], i, len, done); break; default: item.push(i, len, done); func.apply(this, item); } } } } else { var keys = lib.keys(arr || {}); len = keys.length; outputArr = new Array(len); if (len === 0) { cb(null, ""); } else { for (var _i = 0; _i < keys.length; _i++) { var k = keys[_i]; func(k, arr[k], _i, len, done); } } } } function fromIterator(arr) { if (typeof arr !== "object" || arr === null || lib.isArray(arr)) { return arr; } else if (supportsIterators && Symbol.iterator in arr) { return arrayFrom(arr); } else { return arr; } } module3.exports = { Frame, makeMacro, makeKeywordArgs, numArgs, suppressValue, ensureDefined, memberLookup, contextOrFrameLookup, callWrap, handleError, isArray: lib.isArray, keys: lib.keys, SafeString, copySafeness, markSafe, asyncEach, asyncAll, inOperator: lib.inOperator, fromIterator }; }, function(module3, exports2, __webpack_require__) { "use strict"; function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== void 0) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) { o2.__proto__ = p2; return o2; }; return _setPrototypeOf(o, p); } var _require = __webpack_require__(1), Obj = _require.Obj; function traverseAndCheck(obj, type, results) { if (obj instanceof type) { results.push(obj); } if (obj instanceof Node) { obj.findAll(type, results); } } var Node = /* @__PURE__ */ function(_Obj) { _inheritsLoose(Node2, _Obj); function Node2() { return _Obj.apply(this, arguments) || this; } var _proto = Node2.prototype; _proto.init = function init(lineno, colno) { var _arguments = arguments, _this = this; for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } this.lineno = lineno; this.colno = colno; this.fields.forEach(function(field, i) { var val = _arguments[i + 2]; if (val === void 0) { val = null; } _this[field] = val; }); }; _proto.findAll = function findAll(type, results) { var _this2 = this; results = results || []; if (this instanceof NodeList) { this.children.forEach(function(child) { return traverseAndCheck(child, type, results); }); } else { this.fields.forEach(function(field) { return traverseAndCheck(_this2[field], type, results); }); } return results; }; _proto.iterFields = function iterFields(func) { var _this3 = this; this.fields.forEach(function(field) { func(_this3[field], field); }); }; return Node2; }(Obj); var Value = /* @__PURE__ */ function(_Node) { _inheritsLoose(Value2, _Node); function Value2() { return _Node.apply(this, arguments) || this; } _createClass(Value2, [{ key: "typename", get: function get() { return "Value"; } }, { key: "fields", get: function get() { return ["value"]; } }]); return Value2; }(Node); var NodeList = /* @__PURE__ */ function(_Node2) { _inheritsLoose(NodeList2, _Node2); function NodeList2() { return _Node2.apply(this, arguments) || this; } var _proto2 = NodeList2.prototype; _proto2.init = function init(lineno, colno, nodes) { _Node2.prototype.init.call(this, lineno, colno, nodes || []); }; _proto2.addChild = function addChild(node) { this.children.push(node); }; _createClass(NodeList2, [{ key: "typename", get: function get() { return "NodeList"; } }, { key: "fields", get: function get() { return ["children"]; } }]); return NodeList2; }(Node); var Root = NodeList.extend("Root"); var Literal = Value.extend("Literal"); var _Symbol = Value.extend("Symbol"); var Group = NodeList.extend("Group"); var ArrayNode = NodeList.extend("Array"); var Pair = Node.extend("Pair", { fields: ["key", "value"] }); var Dict = NodeList.extend("Dict"); var LookupVal = Node.extend("LookupVal", { fields: ["target", "val"] }); var If = Node.extend("If", { fields: ["cond", "body", "else_"] }); var IfAsync = If.extend("IfAsync"); var InlineIf = Node.extend("InlineIf", { fields: ["cond", "body", "else_"] }); var For = Node.extend("For", { fields: ["arr", "name", "body", "else_"] }); var AsyncEach = For.extend("AsyncEach"); var AsyncAll = For.extend("AsyncAll"); var Macro = Node.extend("Macro", { fields: ["name", "args", "body"] }); var Caller = Macro.extend("Caller"); var Import = Node.extend("Import", { fields: ["template", "target", "withContext"] }); var FromImport = /* @__PURE__ */ function(_Node3) { _inheritsLoose(FromImport2, _Node3); function FromImport2() { return _Node3.apply(this, arguments) || this; } var _proto3 = FromImport2.prototype; _proto3.init = function init(lineno, colno, template, names, withContext) { _Node3.prototype.init.call(this, lineno, colno, template, names || new NodeList(), withContext); }; _createClass(FromImport2, [{ key: "typename", get: function get() { return "FromImport"; } }, { key: "fields", get: function get() { return ["template", "names", "withContext"]; } }]); return FromImport2; }(Node); var FunCall = Node.extend("FunCall", { fields: ["name", "args"] }); var Filter = FunCall.extend("Filter"); var FilterAsync = Filter.extend("FilterAsync", { fields: ["name", "args", "symbol"] }); var KeywordArgs = Dict.extend("KeywordArgs"); var Block = Node.extend("Block", { fields: ["name", "body"] }); var Super = Node.extend("Super", { fields: ["blockName", "symbol"] }); var TemplateRef = Node.extend("TemplateRef", { fields: ["template"] }); var Extends = TemplateRef.extend("Extends"); var Include = Node.extend("Include", { fields: ["template", "ignoreMissing"] }); var Set2 = Node.extend("Set", { fields: ["targets", "value"] }); var Switch = Node.extend("Switch", { fields: ["expr", "cases", "default"] }); var Case = Node.extend("Case", { fields: ["cond", "body"] }); var Output = NodeList.extend("Output"); var Capture = Node.extend("Capture", { fields: ["body"] }); var TemplateData = Literal.extend("TemplateData"); var UnaryOp = Node.extend("UnaryOp", { fields: ["target"] }); var BinOp = Node.extend("BinOp", { fields: ["left", "right"] }); var In = BinOp.extend("In"); var Is = BinOp.extend("Is"); var Or = BinOp.extend("Or"); var And = BinOp.extend("And"); var Not = UnaryOp.extend("Not"); var Add = BinOp.extend("Add"); var Concat = BinOp.extend("Concat"); var Sub = BinOp.extend("Sub"); var Mul = BinOp.extend("Mul"); var Div = BinOp.extend("Div"); var FloorDiv = BinOp.extend("FloorDiv"); var Mod = BinOp.extend("Mod"); var Pow = BinOp.extend("Pow"); var Neg = UnaryOp.extend("Neg"); var Pos = UnaryOp.extend("Pos"); var Compare = Node.extend("Compare", { fields: ["expr", "ops"] }); var CompareOperand = Node.extend("CompareOperand", { fields: ["expr", "type"] }); var CallExtension = Node.extend("CallExtension", { init: function init(ext, prop, args, contentArgs) { this.parent(); this.extName = ext.__name || ext; this.prop = prop; this.args = args || new NodeList(); this.contentArgs = contentArgs || []; this.autoescape = ext.autoescape; }, fields: ["extName", "prop", "args", "contentArgs"] }); var CallExtensionAsync = CallExtension.extend("CallExtensionAsync"); function print(str, indent, inline) { var lines = str.split("\n"); lines.forEach(function(line, i) { if (line && (inline && i > 0 || !inline)) { process.stdout.write(" ".repeat(indent)); } var nl = i === lines.length - 1 ? "" : "\n"; process.stdout.write("" + line + nl); }); } function printNodes(node, indent) { indent = indent || 0; print(node.typename + ": ", indent); if (node instanceof NodeList) { print("\n"); node.children.forEach(function(n) { printNodes(n, indent + 2); }); } else if (node instanceof CallExtension) { print(node.extName + "." + node.prop + "\n"); if (node.args) { printNodes(node.args, indent + 2); } if (node.contentArgs) { node.contentArgs.forEach(function(n) { printNodes(n, indent + 2); }); } } else { var nodes = []; var props = null; node.iterFields(function(val, fieldName) { if (val instanceof Node) { nodes.push([fieldName, val]); } else { props = props || {}; props[fieldName] = val; } }); if (props) { print(JSON.stringify(props, null, 2) + "\n", null, true); } else { print("\n"); } nodes.forEach(function(_ref) { var fieldName = _ref[0], n = _ref[1]; print("[" + fieldName + "] =>", indent + 2); printNodes(n, indent + 4); }); } } module3.exports = { Node, Root, NodeList, Value, Literal, Symbol: _Symbol, Group, Array: ArrayNode, Pair, Dict, Output, Capture, TemplateData, If, IfAsync, InlineIf, For, AsyncEach, AsyncAll, Macro, Caller, Import, FromImport, FunCall, Filter, FilterAsync, KeywordArgs, Block, Super, Extends, Include, Set: Set2, Switch, Case, LookupVal, BinOp, In, Is, Or, And, Not, Add, Concat, Sub, Mul, Div, FloorDiv, Mod, Pow, Neg, Pos, Compare, CompareOperand, CallExtension, CallExtensionAsync, printNodes }; }, function(module3, exports2) { }, function(module3, exports2, __webpack_require__) { "use strict"; function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) { o2.__proto__ = p2; return o2; }; return _setPrototypeOf(o, p); } var parser = __webpack_require__(8); var transformer = __webpack_require__(17); var nodes = __webpack_require__(3); var _require = __webpack_require__(0), TemplateError = _require.TemplateError; var _require2 = __webpack_require__(2), Frame = _require2.Frame; var _require3 = __webpack_require__(1), Obj = _require3.Obj; var compareOps = { "==": "==", "===": "===", "!=": "!=", "!==": "!==", "<": "<", ">": ">", "<=": "<=", ">=": ">=" }; var Compiler = /* @__PURE__ */ function(_Obj) { _inheritsLoose(Compiler2, _Obj); function Compiler2() { return _Obj.apply(this, arguments) || this; } var _proto = Compiler2.prototype; _proto.init = function init(templateName, throwOnUndefined) { this.templateName = templateName; this.codebuf = []; this.lastId = 0; this.buffer = null; this.bufferStack = []; this._scopeClosers = ""; this.inBlock = false; this.throwOnUndefined = throwOnUndefined; }; _proto.fail = function fail(msg, lineno, colno) { if (lineno !== void 0) { lineno += 1; } if (colno !== void 0) { colno += 1; } throw new TemplateError(msg, lineno, colno); }; _proto._pushBuffer = function _pushBuffer() { var id = this._tmpid(); this.bufferStack.push(this.buffer); this.buffer = id; this._emit("var " + this.buffer + ' = "";'); return id; }; _proto._popBuffer = function _popBuffer() { this.buffer = this.bufferStack.pop(); }; _proto._emit = function _emit(code) { this.codebuf.push(code); }; _proto._emitLine = function _emitLine(code) { this._emit(code + "\n"); }; _proto._emitLines = function _emitLines() { var _this = this; for (var _len = arguments.length, lines = new Array(_len), _key = 0; _key < _len; _key++) { lines[_key] = arguments[_key]; } lines.forEach(function(line) { return _this._emitLine(line); }); }; _proto._emitFuncBegin = function _emitFuncBegin(node, name) { this.buffer = "output"; this._scopeClosers = ""; this._emitLine("function " + name + "(env, context, frame, runtime, cb) {"); this._emitLine("var lineno = " + node.lineno + ";"); this._emitLine("var colno = " + node.colno + ";"); this._emitLine("var " + this.buffer + ' = "";'); this._emitLine("try {"); }; _proto._emitFuncEnd = function _emitFuncEnd(noReturn) { if (!noReturn) { this._emitLine("cb(null, " + this.buffer + ");"); } this._closeScopeLevels(); this._emitLine("} catch (e) {"); this._emitLine(" cb(runtime.handleError(e, lineno, colno));"); this._emitLine("}"); this._emitLine("}"); this.buffer = null; }; _proto._addScopeLevel = function _addScopeLevel() { this._scopeClosers += "})"; }; _proto._closeScopeLevels = function _closeScopeLevels() { this._emitLine(this._scopeClosers + ";"); this._scopeClosers = ""; }; _proto._withScopedSyntax = function _withScopedSyntax(func) { var _scopeClosers = this._scopeClosers; this._scopeClosers = ""; func.call(this); this._closeScopeLevels(); this._scopeClosers = _scopeClosers; }; _proto._makeCallback = function _makeCallback(res) { var err = this._tmpid(); return "function(" + err + (res ? "," + res : "") + ") {\nif(" + err + ") { cb(" + err + "); return; }"; }; _proto._tmpid = function _tmpid() { this.lastId++; return "t_" + this.lastId; }; _proto._templateName = function _templateName() { return this.templateName == null ? "undefined" : JSON.stringify(this.templateName); }; _proto._compileChildren = function _compileChildren(node, frame) { var _this2 = this; node.children.forEach(function(child) { _this2.compile(child, frame); }); }; _proto._compileAggregate = function _compileAggregate(node, frame, startChar, endChar) { var _this3 = this; if (startChar) { this._emit(startChar); } node.children.forEach(function(child, i) { if (i > 0) { _this3._emit(","); } _this3.compile(child, frame); }); if (endChar) { this._emit(endChar); } }; _proto._compileExpression = function _compileExpression(node, frame) { this.assertType(node, nodes.Literal, nodes.Symbol, nodes.Group, nodes.Array, nodes.Dict, nodes.FunCall, nodes.Caller, nodes.Filter, nodes.LookupVal, nodes.Compare, nodes.InlineIf, nodes.In, nodes.Is, nodes.And, nodes.Or, nodes.Not, nodes.Add, nodes.Concat, nodes.Sub, nodes.Mul, nodes.Div, nodes.FloorDiv, nodes.Mod, nodes.Pow, nodes.Neg, nodes.Pos, nodes.Compare, nodes.NodeList); this.compile(node, frame); }; _proto.assertType = function assertType(node) { for (var _len2 = arguments.length, types = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { types[_key2 - 1] = arguments[_key2]; } if (!types.some(function(t) { return node instanceof t; })) { this.fail("assertType: invalid type: " + node.typename, node.lineno, node.colno); } }; _proto.compileCallExtension = function compileCallExtension(node, frame, async) { var _this4 = this; var args = node.args; var contentArgs = node.contentArgs; var autoescape = typeof node.autoescape === "boolean" ? node.autoescape : true; if (!async) { this._emit(this.buffer + " += runtime.suppressValue("); } this._emit('env.getExtension("' + node.extName + '")["' + node.prop + '"]('); this._emit("context"); if (args || contentArgs) { this._emit(","); } if (args) { if (!(args instanceof nodes.NodeList)) { this.fail("compileCallExtension: arguments must be a NodeList, use `parser.parseSignature`"); } args.children.forEach(function(arg, i) { _this4._compileExpression(arg, frame); if (i !== args.children.length - 1 || contentArgs.length) { _this4._emit(","); } }); } if (contentArgs.length) { contentArgs.forEach(function(arg, i) { if (i > 0) { _this4._emit(","); } if (arg) { _this4._emitLine("function(cb) {"); _this4._emitLine("if(!cb) { cb = function(err) { if(err) { throw err; }}}"); var id = _this4._pushBuffer(); _this4._withScopedSyntax(function() { _this4.compile(arg, frame); _this4._emitLine("cb(null, " + id + ");"); }); _this4._popBuffer(); _this4._emitLine("return " + id + ";"); _this4._emitLine("}"); } else { _this4._emit("null"); } }); } if (async) { var res = this._tmpid(); this._emitLine(", " + this._makeCallback(res)); this._emitLine(this.buffer + " += runtime.suppressValue(" + res + ", " + autoescape + " && env.opts.autoescape);"); this._addScopeLevel(); } else { this._emit(")"); this._emit(", " + autoescape + " && env.opts.autoescape);\n"); } }; _proto.compileCallExtensionAsync = function compileCallExtensionAsync(node, frame) { this.compileCallExtension(node, frame, true); }; _proto.compileNodeList = function compileNodeList(node, frame) { this._compileChildren(node, frame); }; _proto.compileLiteral = function compileLiteral(node) { if (typeof node.value === "string") { var val = node.value.replace(/\\/g, "\\\\"); val = val.replace(/"/g, '\\"'); val = val.replace(/\n/g, "\\n"); val = val.replace(/\r/g, "\\r"); val = val.replace(/\t/g, "\\t"); val = val.replace(/\u2028/g, "\\u2028"); this._emit('"' + val + '"'); } else if (node.value === null) { this._emit("null"); } else { this._emit(node.value.toString()); } }; _proto.compileSymbol = function compileSymbol(node, frame) { var name = node.value; var v = frame.lookup(name); if (v) { this._emit(v); } else { this._emit('runtime.contextOrFrameLookup(context, frame, "' + name + '")'); } }; _proto.compileGroup = function compileGroup(node, frame) { this._compileAggregate(node, frame, "(", ")"); }; _proto.compileArray = function compileArray(node, frame) { this._compileAggregate(node, frame, "[", "]"); }; _proto.compileDict = function compileDict(node, frame) { this._compileAggregate(node, frame, "{", "}"); }; _proto.compilePair = function compilePair(node, frame) { var key = node.key; var val = node.value; if (key instanceof nodes.Symbol) { key = new nodes.Literal(key.lineno, key.colno, key.value); } else if (!(key instanceof nodes.Literal && typeof key.value === "string")) { this.fail("compilePair: Dict keys must be strings or names", key.lineno, key.colno); } this.compile(key, frame); this._emit(": "); this._compileExpression(val, frame); }; _proto.compileInlineIf = function compileInlineIf(node, frame) { this._emit("("); this.compile(node.cond, frame); this._emit("?"); this.compile(node.body, frame); this._emit(":"); if (node.else_ !== null) { this.compile(node.else_, frame); } else { this._emit('""'); } this._emit(")"); }; _proto.compileIn = function compileIn(node, frame) { this._emit("runtime.inOperator("); this.compile(node.left, frame); this._emit(","); this.compile(node.right, frame); this._emit(")"); }; _proto.compileIs = function compileIs(node, frame) { var right = node.right.name ? node.right.name.value : node.right.value; this._emit('env.getTest("' + right + '").call(context, '); this.compile(node.left, frame); if (node.right.args) { this._emit(","); this.compile(node.right.args, frame); } this._emit(") === true"); }; _proto._binOpEmitter = function _binOpEmitter(node, frame, str) { this.compile(node.left, frame); this._emit(str); this.compile(node.right, frame); }; _proto.compileOr = function compileOr(node, frame) { return this._binOpEmitter(node, frame, " || "); }; _proto.compileAnd = function compileAnd(node, frame) { return this._binOpEmitter(node, frame, " && "); }; _proto.compileAdd = function compileAdd(node, frame) { return this._binOpEmitter(node, frame, " + "); }; _proto.compileConcat = function compileConcat(node, frame) { return this._binOpEmitter(node, frame, ' + "" + '); }; _proto.compileSub = function compileSub(node, frame) { return this._binOpEmitter(node, frame, " - "); }; _proto.compileMul = function compileMul(node, frame) { return this._binOpEmitter(node, frame, " * "); }; _proto.compileDiv = function compileDiv(node, frame) { return this._binOpEmitter(node, frame, " / "); }; _proto.compileMod = function compileMod(node, frame) { return this._binOpEmitter(node, frame, " % "); }; _proto.compileNot = function compileNot(node, frame) { this._emit("!"); this.compile(node.target, frame); }; _proto.compileFloorDiv = function compileFloorDiv(node, frame) { this._emit("Math.floor("); this.compile(node.left, frame); this._emit(" / "); this.compile(node.right, frame); this._emit(")"); }; _proto.compilePow = function compilePow(node, frame) { this._emit("Math.pow("); this.compile(node.left, frame); this._emit(", "); this.compile(node.right, frame); this._emit(")"); }; _proto.compileNeg = function compileNeg(node, frame) { this._emit("-"); this.compile(node.target, frame); }; _proto.compilePos = function compilePos(node, frame) { this._emit("+"); this.compile(node.target, frame); }; _proto.compileCompare = function compileCompare(node, frame) { var _this5 = this; this.compile(node.expr, frame); node.ops.forEach(function(op) { _this5._emit(" " + compareOps[op.type] + " "); _this5.compile(op.expr, frame); }); }; _proto.compileLookupVal = function compileLookupVal(node, frame) { this._emit("runtime.memberLookup(("); this._compileExpression(node.target, frame); this._emit("),"); this._compileExpression(node.val, frame); this._emit(")"); }; _proto._getNodeName = function _getNodeName(node) { switch (node.typename) { case "Symbol": return node.value; case "FunCall": return "the return value of (" + this._getNodeName(node.name) + ")"; case "LookupVal": return this._getNodeName(node.target) + '["' + this._getNodeName(node.val) + '"]'; case "Literal": return node.value.toString(); default: return "--expression--"; } }; _proto.compileFunCall = function compileFunCall(node, frame) { this._emit("(lineno = " + node.lineno + ", colno = " + node.colno + ", "); this._emit("runtime.callWrap("); this._compileExpression(node.name, frame); this._emit(', "' + this._getNodeName(node.name).replace(/"/g, '\\"') + '", context, '); this._compileAggregate(node.args, frame, "[", "])"); this._emit(")"); }; _proto.compileFilter = function compileFilter(node, frame) { var name = node.name; this.assertType(name, nodes.Symbol); this._emit('env.getFilter("' + name.value + '").call(context, '); this._compileAggregate(node.args, frame); this._emit(")"); }; _proto.compileFilterAsync = function compileFilterAsync(node, frame) { var name = node.name; var symbol = node.symbol.value; this.assertType(name, nodes.Symbol); frame.set(symbol, symbol); this._emit('env.getFilter("' + name.value + '").call(context, '); this._compileAggregate(node.args, frame); this._emitLine(", " + this._makeCallback(symbol)); this._addScopeLevel(); }; _proto.compileKeywordArgs = function compileKeywordArgs(node, frame) { this._emit("runtime.makeKeywordArgs("); this.compileDict(node, frame); this._emit(")"); }; _proto.compileSet = function compileSet(node, frame) { var _this6 = this; var ids = []; node.targets.forEach(function(target) { var name = target.value; var id = frame.lookup(name); if (id === null || id === void 0) { id = _this6._tmpid(); _this6._emitLine("var " + id + ";"); } ids.push(id); }); if (node.value) { this._emit(ids.join(" = ") + " = "); this._compileExpression(node.value, frame); this._emitLine(";"); } else { this._emit(ids.join(" = ") + " = "); this.compile(node.body, frame); this._emitLine(";"); } node.targets.forEach(function(target, i) { var id = ids[i]; var name = target.value; _this6._emitLine('frame.set("' + name + '", ' + id + ", true);"); _this6._emitLine("if(frame.topLevel) {"); _this6._emitLine('context.setVariable("' + name + '", ' + id + ");"); _this6._emitLine("}"); if (name.charAt(0) !== "_") { _this6._emitLine("if(frame.topLevel) {"); _this6._emitLine('context.addExport("' + name + '", ' + id + ");"); _this6._emitLine("}"); } }); }; _proto.compileSwitch = function compileSwitch(node, frame) { var _this7 = this; this._emit("switch ("); this.compile(node.expr, frame); this._emit(") {"); node.cases.forEach(function(c, i) { _this7._emit("case "); _this7.compile(c.cond, frame); _this7._emit(": "); _this7.compile(c.body, frame); if (c.body.children.length) { _this7._emitLine("break;"); } }); if (node.default) { this._emit("default:"); this.compile(node.default, frame); } this._emit("}"); }; _proto.compileIf = function compileIf(node, frame, async) { var _this8 = this; this._emit("if("); this._compileExpression(node.cond, frame); this._emitLine(") {"); this._withScopedSyntax(function() { _this8.compile(node.body, frame); if (async) { _this8._emit("cb()"); } }); if (node.else_) { this._emitLine("}\nelse {"); this._withScopedSyntax(function() { _this8.compile(node.else_, frame); if (async) { _this8._emit("cb()"); } }); } else if (async) { this._emitLine("}\nelse {"); this._emit("cb()"); } this._emitLine("}"); }; _proto.compileIfAsync = function compileIfAsync(node, frame) { this._emit("(function(cb) {"); this.compileIf(node, frame, true); this._emit("})(" + this._makeCallback()); this._addScopeLevel(); }; _proto._emitLoopBindings = function _emitLoopBindings(node, arr, i, len) { var _this9 = this; var bindings = [{ name: "index", val: i + " + 1" }, { name: "index0", val: i }, { name: "revindex", val: len + " - " + i }, { name: "revindex0", val: len + " - " + i + " - 1" }, { name: "first", val: i + " === 0" }, { name: "last", val: i + " === " + len + " - 1" }, { name: "length", val: len }]; bindings.forEach(function(b) { _this9._emitLine('frame.set("loop.' + b.name + '", ' + b.val + ");"); }); }; _proto.compileFor = function compileFor(node, frame) { var _this10 = this; var i = this._tmpid(); var len = this._tmpid(); var arr = this._tmpid(); frame = frame.push(); this._emitLine("frame = frame.push();"); this._emit("var " + arr + " = "); this._compileExpression(node.arr, frame); this._emitLine(";"); this._emit("if(" + arr + ") {"); this._emitLine(arr + " = runtime.fromIterator(" + arr + ");"); if (node.name instanceof nodes.Array) { this._emitLine("var " + i + ";"); this._emitLine("if(runtime.isArray(" + arr + ")) {"); this._emitLine("var " + len + " = " + arr + ".length;"); this._emitLine("for(" + i + "=0; " + i + " < " + arr + ".length; " + i + "++) {"); node.name.children.forEach(function(child, u) { var tid = _this10._tmpid(); _this10._emitLine("var " + tid + " = " + arr + "[" + i + "][" + u + "];"); _this10._emitLine('frame.set("' + child + '", ' + arr + "[" + i + "][" + u + "]);"); frame.set(node.name.children[u].value, tid); }); this._emitLoopBindings(node, arr, i, len); this._withScopedSyntax(function() { _this10.compile(node.body, frame); }); this._emitLine("}"); this._emitLine("} else {"); var _node$name$children = node.name.children, key = _node$name$children[0], val = _node$name$children[1]; var k = this._tmpid(); var v = this._tmpid(); frame.set(key.value, k); frame.set(val.value, v); this._emitLine(i + " = -1;"); this._emitLine("var " + len + " = runtime.keys(" + arr + ").length;"); this._emitLine("for(var " + k + " in " + arr + ") {"); this._emitLine(i + "++;"); this._emitLine("var " + v + " = " + arr + "[" + k + "];"); this._emitLine('frame.set("' + key.value + '", ' + k + ");"); this._emitLine('frame.set("' + val.value + '", ' + v + ");"); this._emitLoopBindings(node, arr, i, len); this._withScopedSyntax(function() { _this10.compile(node.body, frame); }); this._emitLine("}"); this._emitLine("}"); } else { var _v = this._tmpid(); frame.set(node.name.value, _v); this._emitLine("var " + len + " = " + arr + ".length;"); this._emitLine("for(var " + i + "=0; " + i + " < " + arr + ".length; " + i + "++) {"); this._emitLine("var " + _v + " = " + arr + "[" + i + "];"); this._emitLine('frame.set("' + node.name.value + '", ' + _v + ");"); this._emitLoopBindings(node, arr, i, len); this._withScopedSyntax(function() { _this10.compile(node.body, frame); }); this._emitLine("}"); } this._emitLine("}"); if (node.else_) { this._emitLine("if (!" + len + ") {"); this.compile(node.else_, frame); this._emitLine("}"); } this._emitLine("frame = frame.pop();"); }; _proto._compileAsyncLoop = function _compileAsyncLoop(node, frame, parallel) { var _this11 = this; var i = this._tmpid(); var len = this._tmpid(); var arr = this._tmpid(); var asyncMethod = parallel ? "asyncAll" : "asyncEach"; frame = frame.push(); this._emitLine("frame = frame.push();"); this._emit("var " + arr + " = runtime.fromIterator("); this._compileExpression(node.arr, frame); this._emitLine(");"); if (node.name instanceof nodes.Array) { var arrayLen = node.name.children.length; this._emit("runtime." + asyncMethod + "(" + arr + ", " + arrayLen + ", function("); node.name.children.forEach(function(name) { _this11._emit(name.value + ","); }); this._emit(i + "," + len + ",next) {"); node.name.children.forEach(function(name) { var id2 = name.value; frame.set(id2, id2); _this11._emitLine('frame.set("' + id2 + '", ' + id2 + ");"); }); } else { var id = node.name.value; this._emitLine("runtime." + asyncMethod + "(" + arr + ", 1, function(" + id + ", " + i + ", " + len + ",next) {"); this._emitLine('frame.set("' + id + '", ' + id + ");"); frame.set(id, id); } this._emitLoopBindings(node, arr, i, len); this._withScopedSyntax(function() { var buf; if (parallel) { buf = _this11._pushBuffer(); } _this11.compile(node.body, frame); _this11._emitLine("next(" + i + (buf ? "," + buf : "") + ");"); if (parallel) { _this11._popBuffer(); } }); var output = this._tmpid(); this._emitLine("}, " + this._makeCallback(output)); this._addScopeLevel(); if (parallel) { this._emitLine(this.buffer + " += " + output + ";"); } if (node.else_) { this._emitLine("if (!" + arr + ".length) {"); this.compile(node.else_, frame); this._emitLine("}"); } this._emitLine("frame = frame.pop();"); }; _proto.compileAsyncEach = function compileAsyncEach(node, frame) { this._compileAsyncLoop(node, frame); }; _proto.compileAsyncAll = function compileAsyncAll(node, frame) { this._compileAsyncLoop(node, frame, true); }; _proto._compileMacro = function _compileMacro(node, frame) { var _this12 = this; var args = []; var kwargs = null; var funcId = "macro_" + this._tmpid(); var keepFrame = frame !== void 0; node.args.children.forEach(function(arg, i) { if (i === node.args.children.length - 1 && arg instanceof nodes.Dict) { kwargs = arg; } else { _this12.assertType(arg, nodes.Symbol); args.push(arg); } }); var realNames = [].concat(args.map(function(n) { return "l_" + n.value; }), ["kwargs"]); var argNames = args.map(function(n) { return '"' + n.value + '"'; }); var kwargNames = (kwargs && kwargs.children || []).map(function(n) { return '"' + n.key.value + '"'; }); var currFrame; if (keepFrame) { currFrame = frame.push(true); } else { currFrame = new Frame(); } this._emitLines("var " + funcId + " = runtime.makeMacro(", "[" + argNames.join(", ") + "], ", "[" + kwargNames.join(", ") + "], ", "function (" + realNames.join(", ") + ") {", "var callerFrame = frame;", "frame = " + (keepFrame ? "frame.push(true);" : "new runtime.Frame();"), "kwargs = kwargs || {};", 'if (Object.prototype.hasOwnProperty.call(kwargs, "caller")) {', 'frame.set("caller", kwargs.caller); }'); args.forEach(function(arg) { _this12._emitLine('frame.set("' + arg.value + '", l_' + arg.value + ");"); currFrame.set(arg.value, "l_" + arg.value); }); if (kwargs) { kwargs.children.forEach(function(pair) { var name = pair.key.value; _this12._emit('frame.set("' + name + '", '); _this12._emit('Object.prototype.hasOwnProperty.call(kwargs, "' + name + '")'); _this12._emit(' ? kwargs["' + name + '"] : '); _this12._compileExpression(pair.value, currFrame); _this12._emit(");"); }); } var bufferId = this._pushBuffer(); this._withScopedSyntax(function() { _this12.compile(node.body, currFrame); }); this._emitLine("frame = " + (keepFrame ? "frame.pop();" : "callerFrame;")); this._emitLine("return new runtime.SafeString(" + bufferId + ");"); this._emitLine("});"); this._popBuffer(); return funcId; }; _proto.compileMacro = function compileMacro(node, frame) { var funcId = this._compileMacro(node); var name = node.name.value; frame.set(name, funcId); if (frame.parent) { this._emitLine('frame.set("' + name + '", ' + funcId + ");"); } else { if (node.name.value.charAt(0) !== "_") { this._emitLine('context.addExport("' + name + '");'); } this._emitLine('context.setVariable("' + name + '", ' + funcId + ");"); } }; _proto.compileCaller = function compileCaller(node, frame) { this._emit("(function (){"); var funcId = this._compileMacro(node, frame); this._emit("return " + funcId + ";})()"); }; _proto._compileGetTemplate = function _compileGetTemplate(node, frame, eagerCompile, ignoreMissing) { var parentTemplateId = this._tmpid(); var parentName = this._templateName(); var cb = this._makeCallback(parentTemplateId); var eagerCompileArg = eagerCompile ? "true" : "false"; var ignoreMissingArg = ignoreMissing ? "true" : "false"; this._emit("env.getTemplate("); this._compileExpression(node.template, frame); this._emitLine(", " + eagerCompileArg + ", " + parentName + ", " + ignoreMissingArg + ", " + cb); return parentTemplateId; }; _proto.compileImport = function compileImport(node, frame) { var target = node.target.value; var id = this._compileGetTemplate(node, frame, false, false); this._addScopeLevel(); this._emitLine(id + ".getExported(" + (node.withContext ? "context.getVariables(), frame, " : "") + this._makeCallback(id)); this._addScopeLevel(); frame.set(target, id); if (frame.parent) { this._emitLine('frame.set("' + target + '", ' + id + ");"); } else { this._emitLine('context.setVariable("' + target + '", ' + id + ");"); } }; _proto.compileFromImport = function compileFromImport(node, frame) { var _this13 = this; var importedId = this._compileGetTemplate(node, frame, false, false); this._addScopeLevel(); this._emitLine(importedId + ".getExported(" + (node.withContext ? "context.getVariables(), frame, " : "") + this._makeCallback(importedId)); this._addScopeLevel(); node.names.children.forEach(function(nameNode) { var name; var alias; var id = _this13._tmpid(); if (nameNode instanceof nodes.Pair) { name = nameNode.key.value; alias = nameNode.value.value; } else { name = nameNode.value; alias = name; } _this13._emitLine("if(Object.prototype.hasOwnProperty.call(" + importedId + ', "' + name + '")) {'); _this13._emitLine("var " + id + " = " + importedId + "." + name + ";"); _this13._emitLine("} else {"); _this13._emitLine(`cb(new Error("cannot import '` + name + `'")); return;`); _this13._emitLine("}"); frame.set(alias, id); if (frame.parent) { _this13._emitLine('frame.set("' + alias + '", ' + id + ");"); } else { _this13._emitLine('context.setVariable("' + alias + '", ' + id + ");"); } }); }; _proto.compileBlock = function compileBlock(node) { var id = this._tmpid(); if (!this.inBlock) { this._emit('(parentTemplate ? function(e, c, f, r, cb) { cb(""); } : '); } this._emit('context.getBlock("' + node.name.value + '")'); if (!this.inBlock) { this._emit(")"); } this._emitLine("(env, context, frame, runtime, " + this._makeCallback(id)); this._emitLine(this.buffer + " += " + id + ";"); this._addScopeLevel(); }; _proto.compileSuper = function compileSuper(node, frame) { var name = node.blockName.value; var id = node.symbol.value; var cb = this._makeCallback(id); this._emitLine('context.getSuper(env, "' + name + '", b_' + name + ", frame, runtime, " + cb); this._emitLine(id + " = runtime.markSafe(" + id + ");"); this._addScopeLevel(); frame.set(id, id); }; _proto.compileExtends = function compileExtends(node, frame) { var k = this._tmpid(); var parentTemplateId = this._compileGetTemplate(node, frame, true, false); this._emitLine("parentTemplate = " + parentTemplateId); this._emitLine("for(var " + k + " in parentTemplate.blocks) {"); this._emitLine("context.addBlock(" + k + ", parentTemplate.blocks[" + k + "]);"); this._emitLine("}"); this._addScopeLevel(); }; _proto.compileInclude = function compileInclude(node, frame) { this._emitLine("var tasks = [];"); this._emitLine("tasks.push("); this._emitLine("function(callback) {"); var id = this._compileGetTemplate(node, frame, false, node.ignoreMissing); this._emitLine("callback(null," + id + ");});"); this._emitLine("});"); var id2 = this._tmpid(); this._emitLine("tasks.push("); this._emitLine("function(template, callback){"); this._emitLine("template.render(context.getVariables(), frame, " + this._makeCallback(id2)); this._emitLine("callback(null," + id2 + ");});"); this._emitLine("});"); this._emitLine("tasks.push("); this._emitLine("function(result, callback){"); this._emitLine(this.buffer + " += result;"); this._emitLine("callback(null);"); this._emitLine("});"); this._emitLine("env.waterfall(tasks, function(){"); this._addScopeLevel(); }; _proto.compileTemplateData = function compileTemplateData(node, frame) { this.compileLiteral(node, frame); }; _proto.compileCapture = function compileCapture(node, frame) { var _this14 = this; var buffer = this.buffer; this.buffer = "output"; this._emitLine("(function() {"); this._emitLine('var output = "";'); this._withScopedSyntax(function() { _this14.compile(node.body, frame); }); this._emitLine("return output;"); this._emitLine("})()"); this.buffer = buffer; }; _proto.compileOutput = function compileOutput(node, frame) { var _this15 = this; var children = node.children; children.forEach(function(child) { if (child instanceof nodes.TemplateData) { if (child.value) { _this15._emit(_this15.buffer + " += "); _this15.compileLiteral(child, frame); _this15._emitLine(";"); } } else { _this15._emit(_this15.buffer + " += runtime.suppressValue("); if (_this15.throwOnUndefined) { _this15._emit("runtime.ensureDefined("); } _this15.compile(child, frame); if (_this15.throwOnUndefined) { _this15._emit("," + node.lineno + "," + node.colno + ")"); } _this15._emit(", env.opts.autoescape);\n"); } }); }; _proto.compileRoot = function compileRoot(node, frame) { var _this16 = this; if (frame) { this.fail("compileRoot: root node can't have frame"); } frame = new Frame(); this._emitFuncBegin(node, "root"); this._emitLine("var parentTemplate = null;"); this._compileChildren(node, frame); this._emitLine("if(parentTemplate) {"); this._emitLine("parentTemplate.rootRenderFunc(env, context, frame, runtime, cb);"); this._emitLine("} else {"); this._emitLine("cb(null, " + this.buffer + ");"); this._emitLine("}"); this._emitFuncEnd(true); this.inBlock = true; var blockNames = []; var blocks = node.findAll(nodes.Block); blocks.forEach(function(block, i) { var name = block.name.value; if (blockNames.indexOf(name) !== -1) { throw new Error('Block "' + name + '" defined more than once.'); } blockNames.push(name); _this16._emitFuncBegin(block, "b_" + name); var tmpFrame = new Frame(); _this16._emitLine("var frame = frame.push(true);"); _this16.compile(block.body, tmpFrame); _this16._emitFuncEnd(); }); this._emitLine("return {"); blocks.forEach(function(block, i) { var blockName = "b_" + block.name.value; _this16._emitLine(blockName + ": " + blockName + ","); }); this._emitLine("root: root\n};"); }; _proto.compile = function compile(node, frame) { var _compile = this["compile" + node.typename]; if (_compile) { _compile.call(this, node, frame); } else { this.fail("compile: Cannot compile node: " + node.typename, node.lineno, node.colno); } }; _proto.getCode = function getCode() { return this.codebuf.join(""); }; return Compiler2; }(Obj); module3.exports = { compile: function compile(src, asyncFilters, extensions, name, opts) { if (opts === void 0) { opts = {}; } var c = new Compiler(name, opts.throwOnUndefined); var preprocessors = (extensions || []).map(function(ext) { return ext.preprocess; }).filter(function(f) { return !!f; }); var processedSrc = preprocessors.reduce(function(s, processor) { return processor(s); }, src); c.compile(transformer.transform(parser.parse(processedSrc, extensions, opts), asyncFilters, name)); return c.getCode(); }, Compiler }; }, function(module3, exports2, __webpack_require__) { "use strict"; function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) { o2.__proto__ = p2; return o2; }; return _setPrototypeOf(o, p); } var path = __webpack_require__(4); var _require = __webpack_require__(1), EmitterObj = _require.EmitterObj; module3.exports = /* @__PURE__ */ function(_EmitterObj) { _inheritsLoose(Loader, _EmitterObj); function Loader() { return _EmitterObj.apply(this, arguments) || this; } var _proto = Loader.prototype; _proto.resolve = function resolve(from, to) { return path.resolve(path.dirname(from), to); }; _proto.isRelative = function isRelative(filename) { return filename.indexOf("./") === 0 || filename.indexOf("../") === 0; }; return Loader; }(EmitterObj); }, function(module3, exports2, __webpack_require__) { "use strict"; function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) { o2.__proto__ = p2; return o2; }; return _setPrototypeOf(o, p); } var asap = __webpack_require__(12); var _waterfall = __webpack_require__(15); var lib = __webpack_require__(0); var compiler = __webpack_require__(5); var filters = __webpack_require__(18); var _require = __webpack_require__(10), FileSystemLoader = _require.FileSystemLoader, WebLoader = _require.WebLoader, PrecompiledLoader = _require.PrecompiledLoader; var tests = __webpack_require__(20); var globals = __webpack_require__(21); var _require2 = __webpack_require__(1), Obj = _require2.Obj, EmitterObj = _require2.EmitterObj; var globalRuntime = __webpack_require__(2); var handleError = globalRuntime.handleError, Frame = globalRuntime.Frame; var expressApp = __webpack_require__(22); function callbackAsap(cb, err, res) { asap(function() { cb(err, res); }); } var noopTmplSrc = { type: "code", obj: { root: function root(env, context, frame, runtime, cb) { try { cb(null, ""); } catch (e) { cb(handleError(e, null, null)); } } } }; var Environment = /* @__PURE__ */ function(_EmitterObj) { _inheritsLoose(Environment2, _EmitterObj); function Environment2() { return _EmitterObj.apply(this, arguments) || this; } var _proto = Environment2.prototype; _proto.init = function init(loaders, opts) { var _this = this; opts = this.opts = opts || {}; this.opts.dev = !!opts.dev; this.opts.autoescape = opts.autoescape != null ? opts.autoescape : true; this.opts.throwOnUndefined = !!opts.throwOnUndefined; this.opts.trimBlocks = !!opts.trimBlocks; this.opts.lstripBlocks = !!opts.lstripBlocks; this.loaders = []; if (!loaders) { if (FileSystemLoader) { this.loaders = [new FileSystemLoader("views")]; } else if (WebLoader) { this.loaders = [new WebLoader("/views")]; } } else { this.loaders = lib.isArray(loaders) ? loaders : [loaders]; } if (typeof window !== "undefined" && window.nunjucksPrecompiled) { this.loaders.unshift(new PrecompiledLoader(window.nunjucksPrecompiled)); } this._initLoaders(); this.globals = globals(); this.filters = {}; this.tests = {}; this.asyncFilters = []; this.extensions = {}; this.extensionsList = []; lib._entries(filters).forEach(function(_ref) { var name = _ref[0], filter = _ref[1]; return _this.addFilter(name, filter); }); lib._entries(tests).forEach(function(_ref2) { var name = _ref2[0], test = _ref2[1]; return _this.addTest(name, test); }); }; _proto._initLoaders = function _initLoaders() { var _this2 = this; this.loaders.forEach(function(loader) { loader.cache = {}; if (typeof loader.on === "function") { loader.on("update", function(name, fullname) { loader.cache[name] = null; _this2.emit("update", name, fullname, loader); }); loader.on("load", function(name, source) { _this2.emit("load", name, source, loader); }); } }); }; _proto.invalidateCache = function invalidateCache() { this.loaders.forEach(function(loader) { loader.cache = {}; }); }; _proto.addExtension = function addExtension(name, extension) { extension.__name = name; this.extensions[name] = extension; this.extensionsList.push(extension); return this; }; _proto.removeExtension = function removeExtension(name) { var extension = this.getExtension(name); if (!extension) { return; } this.extensionsList = lib.without(this.extensionsList, extension); delete this.extensions[name]; }; _proto.getExtension = function getExtension(name) { return this.extensions[name]; }; _proto.hasExtension = function hasExtension(name) { return !!this.extensions[name]; }; _proto.addGlobal = function addGlobal(name, value) { this.globals[name] = value; return this; }; _proto.getGlobal = function getGlobal(name) { if (typeof this.globals[name] === "undefined") { throw new Error("global not found: " + name); } return this.globals[name]; }; _proto.addFilter = function addFilter(name, func, async) { var wrapped = func; if (async) { this.asyncFilters.push(name); } this.filters[name] = wrapped; return this; }; _proto.getFilter = function getFilter(name) { if (!this.filters[name]) { throw new Error("filter not found: " + name); } return this.filters[name]; }; _proto.addTest = function addTest(name, func) { this.tests[name] = func; return this; }; _proto.getTest = function getTest(name) { if (!this.tests[name]) { throw new Error("test not found: " + name); } return this.tests[name]; }; _proto.resolveTemplate = function resolveTemplate(loader, parentName, filename) { var isRelative = loader.isRelative && parentName ? loader.isRelative(filename) : false; return isRelative && loader.resolve ? loader.resolve(parentName, filename) : filename; }; _proto.getTemplate = function getTemplate(name, eagerCompile, parentName, ignoreMissing, cb) { var _this3 = this; var that = this; var tmpl = null; if (name && name.raw) { name = name.raw; } if (lib.isFunction(parentName)) { cb = parentName; parentName = null; eagerCompile = eagerCompile || false; } if (lib.isFunction(eagerCompile)) { cb = eagerCompile; eagerCompile = false; } if (name instanceof Template) { tmpl = name; } else if (typeof name !== "string") { throw new Error("template names must be a string: " + name); } else { for (var i = 0; i < this.loaders.length; i++) { var loader = this.loaders[i]; tmpl = loader.cache[this.resolveTemplate(loader, parentName, name)]; if (tmpl) { break; } } } if (tmpl) { if (eagerCompile) { tmpl.compile(); } if (cb) { cb(null, tmpl); return void 0; } else { return tmpl; } } var syncResult; var createTemplate = function createTemplate2(err, info) { if (!info && !err && !ignoreMissing) { err = new Error("template not found: " + name); } if (err) { if (cb) { cb(err); return; } else { throw err; } } var newTmpl; if (!info) { newTmpl = new Template(noopTmplSrc, _this3, "", eagerCompile); } else { newTmpl = new Template(info.src, _this3, info.path, eagerCompile); if (!info.noCache) { info.loader.cache[name] = newTmpl; } } if (cb) { cb(null, newTmpl); } else { syncResult = newTmpl; } }; lib.asyncIter(this.loaders, function(loader2, i2, next, done) { function handle(err, src) { if (err) { done(err); } else if (src) { src.loader = loader2; done(null, src); } else { next(); } } name = that.resolveTemplate(loader2, parentName, name); if (loader2.async) { loader2.getSource(name, handle); } else { handle(null, loader2.getSource(name)); } }, createTemplate); return syncResult; }; _proto.express = function express(app2) { return expressApp(this, app2); }; _proto.render = function render(name, ctx, cb) { if (lib.isFunction(ctx)) { cb = ctx; ctx = null; } var syncResult = null; this.getTemplate(name, function(err, tmpl) { if (err && cb) { callbackAsap(cb, err); } else if (err) { throw err; } else { syncResult = tmpl.render(ctx, cb); } }); return syncResult; }; _proto.renderString = function renderString2(src, ctx, opts, cb) { if (lib.isFunction(opts)) { cb = opts; opts = {}; } opts = opts || {}; var tmpl = new Template(src, this, opts.path); return tmpl.render(ctx, cb); }; _proto.waterfall = function waterfall(tasks, callback, forceAsync) { return _waterfall(tasks, callback, forceAsync); }; return Environment2; }(EmitterObj); var Context = /* @__PURE__ */ function(_Obj) { _inheritsLoose(Context2, _Obj); function Context2() { return _Obj.apply(this, arguments) || this; } var _proto2 = Context2.prototype; _proto2.init = function init(ctx, blocks, env) { var _this4 = this; this.env = env || new Environment(); this.ctx = lib.extend({}, ctx); this.blocks = {}; this.exported = []; lib.keys(blocks).forEach(function(name) { _this4.addBlock(name, blocks[name]); }); }; _proto2.lookup = function lookup(name) { if (name in this.env.globals && !(name in this.ctx)) { return this.env.globals[name]; } else { return this.ctx[name]; } }; _proto2.setVariable = function setVariable(name, val) { this.ctx[name] = val; }; _proto2.getVariables = function getVariables() { return this.ctx; }; _proto2.addBlock = function addBlock(name, block) { this.blocks[name] = this.blocks[name] || []; this.blocks[name].push(block); return this; }; _proto2.getBlock = function getBlock(name) { if (!this.blocks[name]) { throw new Error('unknown block "' + name + '"'); } return this.blocks[name][0]; }; _proto2.getSuper = function getSuper(env, name, block, frame, runtime, cb) { var idx = lib.indexOf(this.blocks[name] || [], block); var blk = this.blocks[name][idx + 1]; var context = this; if (idx === -1 || !blk) { throw new Error('no super block available for "' + name + '"'); } blk(env, context, frame, runtime, cb); }; _proto2.addExport = function addExport(name) { this.exported.push(name); }; _proto2.getExported = function getExported() { var _this5 = this; var exported = {}; this.exported.forEach(function(name) { exported[name] = _this5.ctx[name]; }); return exported; }; return Context2; }(Obj); var Template = /* @__PURE__ */ function(_Obj2) { _inheritsLoose(Template2, _Obj2); function Template2() { return _Obj2.apply(this, arguments) || this; } var _proto3 = Template2.prototype; _proto3.init = function init(src, env, path, eagerCompile) { this.env = env || new Environment(); if (lib.isObject(src)) { switch (src.type) { case "code": this.tmplProps = src.obj; break; case "string": this.tmplStr = src.obj; break; default: throw new Error("Unexpected template object type " + src.type + "; expected 'code', or 'string'"); } } else if (lib.isString(src)) { this.tmplStr = src; } else { throw new Error("src must be a string or an object describing the source"); } this.path = path; if (eagerCompile) { try { this._compile(); } catch (err) { throw lib._prettifyError(this.path, this.env.opts.dev, err); } } else { this.compiled = false; } }; _proto3.render = function render(ctx, parentFrame, cb) { var _this6 = this; if (typeof ctx === "function") { cb = ctx; ctx = {}; } else if (typeof parentFrame === "function") { cb = parentFrame; parentFrame = null; } var forceAsync = !parentFrame; try { this.compile(); } catch (e) { var err = lib._prettifyError(this.path, this.env.opts.dev, e); if (cb) { return callbackAsap(cb, err); } else { throw err; } } var context = new Context(ctx || {}, this.blocks, this.env); var frame = parentFrame ? parentFrame.push(true) : new Frame(); frame.topLevel = true; var syncResult = null; var didError = false; this.rootRenderFunc(this.env, context, frame, globalRuntime, function(err2, res) { if (didError && cb && typeof res !== "undefined") { return; } if (err2) { err2 = lib._prettifyError(_this6.path, _this6.env.opts.dev, err2); didError = true; } if (cb) { if (forceAsync) { callbackAsap(cb, err2, res); } else { cb(err2, res); } } else { if (err2) { throw err2; } syncResult = res; } }); return syncResult; }; _proto3.getExported = function getExported(ctx, parentFrame, cb) { if (typeof ctx === "function") { cb = ctx; ctx = {}; } if (typeof parentFrame === "function") { cb = parentFrame; parentFrame = null; } try { this.compile(); } catch (e) { if (cb) { return cb(e); } else { throw e; } } var frame = parentFrame ? parentFrame.push() : new Frame(); frame.topLevel = true; var context = new Context(ctx || {}, this.blocks, this.env); this.rootRenderFunc(this.env, context, frame, globalRuntime, function(err) { if (err) { cb(err, null); } else { cb(null, context.getExported()); } }); }; _proto3.compile = function compile() { if (!this.compiled) { this._compile(); } }; _proto3._compile = function _compile() { var props; if (this.tmplProps) { props = this.tmplProps; } else { var source = compiler.compile(this.tmplStr, this.env.asyncFilters, this.env.extensionsList, this.path, this.env.opts); var func = new Function(source); props = func(); } this.blocks = this._getBlocks(props); this.rootRenderFunc = props.root; this.compiled = true; }; _proto3._getBlocks = function _getBlocks(props) { var blocks = {}; lib.keys(props).forEach(function(k) { if (k.slice(0, 2) === "b_") { blocks[k.slice(2)] = props[k]; } }); return blocks; }; return Template2; }(Obj); module3.exports = { Environment, Template }; }, function(module3, exports2, __webpack_require__) { "use strict"; function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) { o2.__proto__ = p2; return o2; }; return _setPrototypeOf(o, p); } var lexer = __webpack_require__(9); var nodes = __webpack_require__(3); var Obj = __webpack_require__(1).Obj; var lib = __webpack_require__(0); var Parser = /* @__PURE__ */ function(_Obj) { _inheritsLoose(Parser2, _Obj); function Parser2() { return _Obj.apply(this, arguments) || this; } var _proto = Parser2.prototype; _proto.init = function init(tokens) { this.tokens = tokens; this.peeked = null; this.breakOnBlocks = null; this.dropLeadingWhitespace = false; this.extensions = []; }; _proto.nextToken = function nextToken(withWhitespace) { var tok; if (this.peeked) { if (!withWhitespace && this.peeked.type === lexer.TOKEN_WHITESPACE) { this.peeked = null; } else { tok = this.peeked; this.peeked = null; return tok; } } tok = this.tokens.nextToken(); if (!withWhitespace) { while (tok && tok.type === lexer.TOKEN_WHITESPACE) { tok = this.tokens.nextToken(); } } return tok; }; _proto.peekToken = function peekToken() { this.peeked = this.peeked || this.nextToken(); return this.peeked; }; _proto.pushToken = function pushToken(tok) { if (this.peeked) { throw new Error("pushToken: can only push one token on between reads"); } this.peeked = tok; }; _proto.error = function error(msg, lineno, colno) { if (lineno === void 0 || colno === void 0) { var tok = this.peekToken() || {}; lineno = tok.lineno; colno = tok.colno; } if (lineno !== void 0) { lineno += 1; } if (colno !== void 0) { colno += 1; } return new lib.TemplateError(msg, lineno, colno); }; _proto.fail = function fail(msg, lineno, colno) { throw this.error(msg, lineno, colno); }; _proto.skip = function skip(type) { var tok = this.nextToken(); if (!tok || tok.type !== type) { this.pushToken(tok); return false; } return true; }; _proto.expect = function expect(type) { var tok = this.nextToken(); if (tok.type !== type) { this.fail("expected " + type + ", got " + tok.type, tok.lineno, tok.colno); } return tok; }; _proto.skipValue = function skipValue(type, val) { var tok = this.nextToken(); if (!tok || tok.type !== type || tok.value !== val) { this.pushToken(tok); return false; } return true; }; _proto.skipSymbol = function skipSymbol(val) { return this.skipValue(lexer.TOKEN_SYMBOL, val); }; _proto.advanceAfterBlockEnd = function advanceAfterBlockEnd(name) { var tok; if (!name) { tok = this.peekToken(); if (!tok) { this.fail("unexpected end of file"); } if (tok.type !== lexer.TOKEN_SYMBOL) { this.fail("advanceAfterBlockEnd: expected symbol token or explicit name to be passed"); } name = this.nextToken().value; } tok = this.nextToken(); if (tok && tok.type === lexer.TOKEN_BLOCK_END) { if (tok.value.charAt(0) === "-") { this.dropLeadingWhitespace = true; } } else { this.fail("expected block end in " + name + " statement"); } return tok; }; _proto.advanceAfterVariableEnd = function advanceAfterVariableEnd() { var tok = this.nextToken(); if (tok && tok.type === lexer.TOKEN_VARIABLE_END) { this.dropLeadingWhitespace = tok.value.charAt(tok.value.length - this.tokens.tags.VARIABLE_END.length - 1) === "-"; } else { this.pushToken(tok); this.fail("expected variable end"); } }; _proto.parseFor = function parseFor() { var forTok = this.peekToken(); var node; var endBlock; if (this.skipSymbol("for")) { node = new nodes.For(forTok.lineno, forTok.colno); endBlock = "endfor"; } else if (this.skipSymbol("asyncEach")) { node = new nodes.AsyncEach(forTok.lineno, forTok.colno); endBlock = "endeach"; } else if (this.skipSymbol("asyncAll")) { node = new nodes.AsyncAll(forTok.lineno, forTok.colno); endBlock = "endall"; } else { this.fail("parseFor: expected for{Async}", forTok.lineno, forTok.colno); } node.name = this.parsePrimary(); if (!(node.name instanceof nodes.Symbol)) { this.fail("parseFor: variable name expected for loop"); } var type = this.peekToken().type; if (type === lexer.TOKEN_COMMA) { var key = node.name; node.name = new nodes.Array(key.lineno, key.colno); node.name.addChild(key); while (this.skip(lexer.TOKEN_COMMA)) { var prim = this.parsePrimary(); node.name.addChild(prim); } } if (!this.skipSymbol("in")) { this.fail('parseFor: expected "in" keyword for loop', forTok.lineno, forTok.colno); } node.arr = this.parseExpression(); this.advanceAfterBlockEnd(forTok.value); node.body = this.parseUntilBlocks(endBlock, "else"); if (this.skipSymbol("else")) { this.advanceAfterBlockEnd("else"); node.else_ = this.parseUntilBlocks(endBlock); } this.advanceAfterBlockEnd(); return node; }; _proto.parseMacro = function parseMacro() { var macroTok = this.peekToken(); if (!this.skipSymbol("macro")) { this.fail("expected macro"); } var name = this.parsePrimary(true); var args = this.parseSignature(); var node = new nodes.Macro(macroTok.lineno, macroTok.colno, name, args); this.advanceAfterBlockEnd(macroTok.value); node.body = this.parseUntilBlocks("endmacro"); this.advanceAfterBlockEnd(); return node; }; _proto.parseCall = function parseCall() { var callTok = this.peekToken(); if (!this.skipSymbol("call")) { this.fail("expected call"); } var callerArgs = this.parseSignature(true) || new nodes.NodeList(); var macroCall = this.parsePrimary(); this.advanceAfterBlockEnd(callTok.value); var body = this.parseUntilBlocks("endcall"); this.advanceAfterBlockEnd(); var callerName = new nodes.Symbol(callTok.lineno, callTok.colno, "caller"); var callerNode = new nodes.Caller(callTok.lineno, callTok.colno, callerName, callerArgs, body); var args = macroCall.args.children; if (!(args[args.length - 1] instanceof nodes.KeywordArgs)) { args.push(new nodes.KeywordArgs()); } var kwargs = args[args.length - 1]; kwargs.addChild(new nodes.Pair(callTok.lineno, callTok.colno, callerName, callerNode)); return new nodes.Output(callTok.lineno, callTok.colno, [macroCall]); }; _proto.parseWithContext = function parseWithContext() { var tok = this.peekToken(); var withContext = null; if (this.skipSymbol("with")) { withContext = true; } else if (this.skipSymbol("without")) { withContext = false; } if (withContext !== null) { if (!this.skipSymbol("context")) { this.fail("parseFrom: expected context after with/without", tok.lineno, tok.colno); } } return withContext; }; _proto.parseImport = function parseImport() { var importTok = this.peekToken(); if (!this.skipSymbol("import")) { this.fail("parseImport: expected import", importTok.lineno, importTok.colno); } var template = this.parseExpression(); if (!this.skipSymbol("as")) { this.fail('parseImport: expected "as" keyword', importTok.lineno, importTok.colno); } var target = this.parseExpression(); var withContext = this.parseWithContext(); var node = new nodes.Import(importTok.lineno, importTok.colno, template, target, withContext); this.advanceAfterBlockEnd(importTok.value); return node; }; _proto.parseFrom = function parseFrom() { var fromTok = this.peekToken(); if (!this.skipSymbol("from")) { this.fail("parseFrom: expected from"); } var template = this.parseExpression(); if (!this.skipSymbol("import")) { this.fail("parseFrom: expected import", fromTok.lineno, fromTok.colno); } var names = new nodes.NodeList(); var withContext; while (1) { var nextTok = this.peekToken(); if (nextTok.type === lexer.TOKEN_BLOCK_END) { if (!names.children.length) { this.fail("parseFrom: Expected at least one import name", fromTok.lineno, fromTok.colno); } if (nextTok.value.charAt(0) === "-") { this.dropLeadingWhitespace = true; } this.nextToken(); break; } if (names.children.length > 0 && !this.skip(lexer.TOKEN_COMMA)) { this.fail("parseFrom: expected comma", fromTok.lineno, fromTok.colno); } var name = this.parsePrimary(); if (name.value.charAt(0) === "_") { this.fail("parseFrom: names starting with an underscore cannot be imported", name.lineno, name.colno); } if (this.skipSymbol("as")) { var alias = this.parsePrimary(); names.addChild(new nodes.Pair(name.lineno, name.colno, name, alias)); } else { names.addChild(name); } withContext = this.parseWithContext(); } return new nodes.FromImport(fromTok.lineno, fromTok.colno, template, names, withContext); }; _proto.parseBlock = function parseBlock() { var tag = this.peekToken(); if (!this.skipSymbol("block")) { this.fail("parseBlock: expected block", tag.lineno, tag.colno); } var node = new nodes.Block(tag.lineno, tag.colno); node.name = this.parsePrimary(); if (!(node.name instanceof nodes.Symbol)) { this.fail("parseBlock: variable name expected", tag.lineno, tag.colno); } this.advanceAfterBlockEnd(tag.value); node.body = this.parseUntilBlocks("endblock"); this.skipSymbol("endblock"); this.skipSymbol(node.name.value); var tok = this.peekToken(); if (!tok) { this.fail("parseBlock: expected endblock, got end of file"); } this.advanceAfterBlockEnd(tok.value); return node; }; _proto.parseExtends = function parseExtends() { var tagName = "extends"; var tag = this.peekToken(); if (!this.skipSymbol(tagName)) { this.fail("parseTemplateRef: expected " + tagName); } var node = new nodes.Extends(tag.lineno, tag.colno); node.template = this.parseExpression(); this.advanceAfterBlockEnd(tag.value); return node; }; _proto.parseInclude = function parseInclude() { var tagName = "include"; var tag = this.peekToken(); if (!this.skipSymbol(tagName)) { this.fail("parseInclude: expected " + tagName); } var node = new nodes.Include(tag.lineno, tag.colno); node.template = this.parseExpression(); if (this.skipSymbol("ignore") && this.skipSymbol("missing")) { node.ignoreMissing = true; } this.advanceAfterBlockEnd(tag.value); return node; }; _proto.parseIf = function parseIf() { var tag = this.peekToken(); var node; if (this.skipSymbol("if") || this.skipSymbol("elif") || this.skipSymbol("elseif")) { node = new nodes.If(tag.lineno, tag.colno); } else if (this.skipSymbol("ifAsync")) { node = new nodes.IfAsync(tag.lineno, tag.colno); } else { this.fail("parseIf: expected if, elif, or elseif", tag.lineno, tag.colno); } node.cond = this.parseExpression(); this.advanceAfterBlockEnd(tag.value); node.body = this.parseUntilBlocks("elif", "elseif", "else", "endif"); var tok = this.peekToken(); switch (tok && tok.value) { case "elseif": case "elif": node.else_ = this.parseIf(); break; case "else": this.advanceAfterBlockEnd(); node.else_ = this.parseUntilBlocks("endif"); this.advanceAfterBlockEnd(); break; case "endif": node.else_ = null; this.advanceAfterBlockEnd(); break; default: this.fail("parseIf: expected elif, else, or endif, got end of file"); } return node; }; _proto.parseSet = function parseSet() { var tag = this.peekToken(); if (!this.skipSymbol("set")) { this.fail("parseSet: expected set", tag.lineno, tag.colno); } var node = new nodes.Set(tag.lineno, tag.colno, []); var target; while (target = this.parsePrimary()) { node.targets.push(target); if (!this.skip(lexer.TOKEN_COMMA)) { break; } } if (!this.skipValue(lexer.TOKEN_OPERATOR, "=")) { if (!this.skip(lexer.TOKEN_BLOCK_END)) { this.fail("parseSet: expected = or block end in set tag", tag.lineno, tag.colno); } else { node.body = new nodes.Capture(tag.lineno, tag.colno, this.parseUntilBlocks("endset")); node.value = null; this.advanceAfterBlockEnd(); } } else { node.value = this.parseExpression(); this.advanceAfterBlockEnd(tag.value); } return node; }; _proto.parseSwitch = function parseSwitch() { var switchStart = "switch"; var switchEnd = "endswitch"; var caseStart = "case"; var caseDefault = "default"; var tag = this.peekToken(); if (!this.skipSymbol(switchStart) && !this.skipSymbol(caseStart) && !this.skipSymbol(caseDefault)) { this.fail('parseSwitch: expected "switch," "case" or "default"', tag.lineno, tag.colno); } var expr = this.parseExpression(); this.advanceAfterBlockEnd(switchStart); this.parseUntilBlocks(caseStart, caseDefault, switchEnd); var tok = this.peekToken(); var cases = []; var defaultCase; do { this.skipSymbol(caseStart); var cond = this.parseExpression(); this.advanceAfterBlockEnd(switchStart); var body = this.parseUntilBlocks(caseStart, caseDefault, switchEnd); cases.push(new nodes.Case(tok.line, tok.col, cond, body)); tok = this.peekToken(); } while (tok && tok.value === caseStart); switch (tok.value) { case caseDefault: this.advanceAfterBlockEnd(); defaultCase = this.parseUntilBlocks(switchEnd); this.advanceAfterBlockEnd(); break; case switchEnd: this.advanceAfterBlockEnd(); break; default: this.fail('parseSwitch: expected "case," "default" or "endswitch," got EOF.'); } return new nodes.Switch(tag.lineno, tag.colno, expr, cases, defaultCase); }; _proto.parseStatement = function parseStatement() { var tok = this.peekToken(); var node; if (tok.type !== lexer.TOKEN_SYMBOL) { this.fail("tag name expected", tok.lineno, tok.colno); } if (this.breakOnBlocks && lib.indexOf(this.breakOnBlocks, tok.value) !== -1) { return null; } switch (tok.value) { case "raw": return this.parseRaw(); case "verbatim": return this.parseRaw("verbatim"); case "if": case "ifAsync": return this.parseIf(); case "for": case "asyncEach": case "asyncAll": return this.parseFor(); case "block": return this.parseBlock(); case "extends": return this.parseExtends(); case "include": return this.parseInclude(); case "set": return this.parseSet(); case "macro": return this.parseMacro(); case "call": return this.parseCall(); case "import": return this.parseImport(); case "from": return this.parseFrom(); case "filter": return this.parseFilterStatement(); case "switch": return this.parseSwitch(); default: if (this.extensions.length) { for (var i = 0; i < this.extensions.length; i++) { var ext = this.extensions[i]; if (lib.indexOf(ext.tags || [], tok.value) !== -1) { return ext.parse(this, nodes, lexer); } } } this.fail("unknown block tag: " + tok.value, tok.lineno, tok.colno); } return node; }; _proto.parseRaw = function parseRaw(tagName) { tagName = tagName || "raw"; var endTagName = "end" + tagName; var rawBlockRegex = new RegExp("([\\s\\S]*?){%\\s*(" + tagName + "|" + endTagName + ")\\s*(?=%})%}"); var rawLevel = 1; var str = ""; var matches = null; var begun = this.advanceAfterBlockEnd(); while ((matches = this.tokens._extractRegex(rawBlockRegex)) && rawLevel > 0) { var all = matches[0]; var pre = matches[1]; var blockName = matches[2]; if (blockName === tagName) { rawLevel += 1; } else if (blockName === endTagName) { rawLevel -= 1; } if (rawLevel === 0) { str += pre; this.tokens.backN(all.length - pre.length); } else { str += all; } } return new nodes.Output(begun.lineno, begun.colno, [new nodes.TemplateData(begun.lineno, begun.colno, str)]); }; _proto.parsePostfix = function parsePostfix(node) { var lookup; var tok = this.peekToken(); while (tok) { if (tok.type === lexer.TOKEN_LEFT_PAREN) { node = new nodes.FunCall(tok.lineno, tok.colno, node, this.parseSignature()); } else if (tok.type === lexer.TOKEN_LEFT_BRACKET) { lookup = this.parseAggregate(); if (lookup.children.length > 1) { this.fail("invalid index"); } node = new nodes.LookupVal(tok.lineno, tok.colno, node, lookup.children[0]); } else if (tok.type === lexer.TOKEN_OPERATOR && tok.value === ".") { this.nextToken(); var val = this.nextToken(); if (val.type !== lexer.TOKEN_SYMBOL) { this.fail("expected name as lookup value, got " + val.value, val.lineno, val.colno); } lookup = new nodes.Literal(val.lineno, val.colno, val.value); node = new nodes.LookupVal(tok.lineno, tok.colno, node, lookup); } else { break; } tok = this.peekToken(); } return node; }; _proto.parseExpression = function parseExpression() { var node = this.parseInlineIf(); return node; }; _proto.parseInlineIf = function parseInlineIf() { var node = this.parseOr(); if (this.skipSymbol("if")) { var condNode = this.parseOr(); var bodyNode = node; node = new nodes.InlineIf(node.lineno, node.colno); node.body = bodyNode; node.cond = condNode; if (this.skipSymbol("else")) { node.else_ = this.parseOr(); } else { node.else_ = null; } } return node; }; _proto.parseOr = function parseOr() { var node = this.parseAnd(); while (this.skipSymbol("or")) { var node2 = this.parseAnd(); node = new nodes.Or(node.lineno, node.colno, node, node2); } return node; }; _proto.parseAnd = function parseAnd() { var node = this.parseNot(); while (this.skipSymbol("and")) { var node2 = this.parseNot(); node = new nodes.And(node.lineno, node.colno, node, node2); } return node; }; _proto.parseNot = function parseNot() { var tok = this.peekToken(); if (this.skipSymbol("not")) { return new nodes.Not(tok.lineno, tok.colno, this.parseNot()); } return this.parseIn(); }; _proto.parseIn = function parseIn() { var node = this.parseIs(); while (1) { var tok = this.nextToken(); if (!tok) { break; } var invert = tok.type === lexer.TOKEN_SYMBOL && tok.value === "not"; if (!invert) { this.pushToken(tok); } if (this.skipSymbol("in")) { var node2 = this.parseIs(); node = new nodes.In(node.lineno, node.colno, node, node2); if (invert) { node = new nodes.Not(node.lineno, node.colno, node); } } else { if (invert) { this.pushToken(tok); } break; } } return node; }; _proto.parseIs = function parseIs() { var node = this.parseCompare(); if (this.skipSymbol("is")) { var not = this.skipSymbol("not"); var node2 = this.parseCompare(); node = new nodes.Is(node.lineno, node.colno, node, node2); if (not) { node = new nodes.Not(node.lineno, node.colno, node); } } return node; }; _proto.parseCompare = function parseCompare() { var compareOps = ["==", "===", "!=", "!==", "<", ">", "<=", ">="]; var expr = this.parseConcat(); var ops = []; while (1) { var tok = this.nextToken(); if (!tok) { break; } else if (compareOps.indexOf(tok.value) !== -1) { ops.push(new nodes.CompareOperand(tok.lineno, tok.colno, this.parseConcat(), tok.value)); } else { this.pushToken(tok); break; } } if (ops.length) { return new nodes.Compare(ops[0].lineno, ops[0].colno, expr, ops); } else { return expr; } }; _proto.parseConcat = function parseConcat() { var node = this.parseAdd(); while (this.skipValue(lexer.TOKEN_TILDE, "~")) { var node2 = this.parseAdd(); node = new nodes.Concat(node.lineno, node.colno, node, node2); } return node; }; _proto.parseAdd = function parseAdd() { var node = this.parseSub(); while (this.skipValue(lexer.TOKEN_OPERATOR, "+")) { var node2 = this.parseSub(); node = new nodes.Add(node.lineno, node.colno, node, node2); } return node; }; _proto.parseSub = function parseSub() { var node = this.parseMul(); while (this.skipValue(lexer.TOKEN_OPERATOR, "-")) { var node2 = this.parseMul(); node = new nodes.Sub(node.lineno, node.colno, node, node2); } return node; }; _proto.parseMul = function parseMul() { var node = this.parseDiv(); while (this.skipValue(lexer.TOKEN_OPERATOR, "*")) { var node2 = this.parseDiv(); node = new nodes.Mul(node.lineno, node.colno, node, node2); } return node; }; _proto.parseDiv = function parseDiv() { var node = this.parseFloorDiv(); while (this.skipValue(lexer.TOKEN_OPERATOR, "/")) { var node2 = this.parseFloorDiv(); node = new nodes.Div(node.lineno, node.colno, node, node2); } return node; }; _proto.parseFloorDiv = function parseFloorDiv() { var node = this.parseMod(); while (this.skipValue(lexer.TOKEN_OPERATOR, "//")) { var node2 = this.parseMod(); node = new nodes.FloorDiv(node.lineno, node.colno, node, node2); } return node; }; _proto.parseMod = function parseMod() { var node = this.parsePow(); while (this.skipValue(lexer.TOKEN_OPERATOR, "%")) { var node2 = this.parsePow(); node = new nodes.Mod(node.lineno, node.colno, node, node2); } return node; }; _proto.parsePow = function parsePow() { var node = this.parseUnary(); while (this.skipValue(lexer.TOKEN_OPERATOR, "**")) { var node2 = this.parseUnary(); node = new nodes.Pow(node.lineno, node.colno, node, node2); } return node; }; _proto.parseUnary = function parseUnary(noFilters) { var tok = this.peekToken(); var node; if (this.skipValue(lexer.TOKEN_OPERATOR, "-")) { node = new nodes.Neg(tok.lineno, tok.colno, this.parseUnary(true)); } else if (this.skipValue(lexer.TOKEN_OPERATOR, "+")) { node = new nodes.Pos(tok.lineno, tok.colno, this.parseUnary(true)); } else { node = this.parsePrimary(); } if (!noFilters) { node = this.parseFilter(node); } return node; }; _proto.parsePrimary = function parsePrimary(noPostfix) { var tok = this.nextToken(); var val; var node = null; if (!tok) { this.fail("expected expression, got end of file"); } else if (tok.type === lexer.TOKEN_STRING) { val = tok.value; } else if (tok.type === lexer.TOKEN_INT) { val = parseInt(tok.value, 10); } else if (tok.type === lexer.TOKEN_FLOAT) { val = parseFloat(tok.value); } else if (tok.type === lexer.TOKEN_BOOLEAN) { if (tok.value === "true") { val = true; } else if (tok.value === "false") { val = false; } else { this.fail("invalid boolean: " + tok.value, tok.lineno, tok.colno); } } else if (tok.type === lexer.TOKEN_NONE) { val = null; } else if (tok.type === lexer.TOKEN_REGEX) { val = new RegExp(tok.value.body, tok.value.flags); } if (val !== void 0) { node = new nodes.Literal(tok.lineno, tok.colno, val); } else if (tok.type === lexer.TOKEN_SYMBOL) { node = new nodes.Symbol(tok.lineno, tok.colno, tok.value); } else { this.pushToken(tok); node = this.parseAggregate(); } if (!noPostfix) { node = this.parsePostfix(node); } if (node) { return node; } else { throw this.error("unexpected token: " + tok.value, tok.lineno, tok.colno); } }; _proto.parseFilterName = function parseFilterName() { var tok = this.expect(lexer.TOKEN_SYMBOL); var name = tok.value; while (this.skipValue(lexer.TOKEN_OPERATOR, ".")) { name += "." + this.expect(lexer.TOKEN_SYMBOL).value; } return new nodes.Symbol(tok.lineno, tok.colno, name); }; _proto.parseFilterArgs = function parseFilterArgs(node) { if (this.peekToken().type === lexer.TOKEN_LEFT_PAREN) { var call = this.parsePostfix(node); return call.args.children; } return []; }; _proto.parseFilter = function parseFilter(node) { while (this.skip(lexer.TOKEN_PIPE)) { var name = this.parseFilterName(); node = new nodes.Filter(name.lineno, name.colno, name, new nodes.NodeList(name.lineno, name.colno, [node].concat(this.parseFilterArgs(node)))); } return node; }; _proto.parseFilterStatement = function parseFilterStatement() { var filterTok = this.peekToken(); if (!this.skipSymbol("filter")) { this.fail("parseFilterStatement: expected filter"); } var name = this.parseFilterName(); var args = this.parseFilterArgs(name); this.advanceAfterBlockEnd(filterTok.value); var body = new nodes.Capture(name.lineno, name.colno, this.parseUntilBlocks("endfilter")); this.advanceAfterBlockEnd(); var node = new nodes.Filter(name.lineno, name.colno, name, new nodes.NodeList(name.lineno, name.colno, [body].concat(args))); return new nodes.Output(name.lineno, name.colno, [node]); }; _proto.parseAggregate = function parseAggregate() { var tok = this.nextToken(); var node; switch (tok.type) { case lexer.TOKEN_LEFT_PAREN: node = new nodes.Group(tok.lineno, tok.colno); break; case lexer.TOKEN_LEFT_BRACKET: node = new nodes.Array(tok.lineno, tok.colno); break; case lexer.TOKEN_LEFT_CURLY: node = new nodes.Dict(tok.lineno, tok.colno); break; default: return null; } while (1) { var type = this.peekToken().type; if (type === lexer.TOKEN_RIGHT_PAREN || type === lexer.TOKEN_RIGHT_BRACKET || type === lexer.TOKEN_RIGHT_CURLY) { this.nextToken(); break; } if (node.children.length > 0) { if (!this.skip(lexer.TOKEN_COMMA)) { this.fail("parseAggregate: expected comma after expression", tok.lineno, tok.colno); } } if (node instanceof nodes.Dict) { var key = this.parsePrimary(); if (!this.skip(lexer.TOKEN_COLON)) { this.fail("parseAggregate: expected colon after dict key", tok.lineno, tok.colno); } var value = this.parseExpression(); node.addChild(new nodes.Pair(key.lineno, key.colno, key, value)); } else { var expr = this.parseExpression(); node.addChild(expr); } } return node; }; _proto.parseSignature = function parseSignature(tolerant, noParens) { var tok = this.peekToken(); if (!noParens && tok.type !== lexer.TOKEN_LEFT_PAREN) { if (tolerant) { return null; } else { this.fail("expected arguments", tok.lineno, tok.colno); } } if (tok.type === lexer.TOKEN_LEFT_PAREN) { tok = this.nextToken(); } var args = new nodes.NodeList(tok.lineno, tok.colno); var kwargs = new nodes.KeywordArgs(tok.lineno, tok.colno); var checkComma = false; while (1) { tok = this.peekToken(); if (!noParens && tok.type === lexer.TOKEN_RIGHT_PAREN) { this.nextToken(); break; } else if (noParens && tok.type === lexer.TOKEN_BLOCK_END) { break; } if (checkComma && !this.skip(lexer.TOKEN_COMMA)) { this.fail("parseSignature: expected comma after expression", tok.lineno, tok.colno); } else { var arg = this.parseExpression(); if (this.skipValue(lexer.TOKEN_OPERATOR, "=")) { kwargs.addChild(new nodes.Pair(arg.lineno, arg.colno, arg, this.parseExpression())); } else { args.addChild(arg); } } checkComma = true; } if (kwargs.children.length) { args.addChild(kwargs); } return args; }; _proto.parseUntilBlocks = function parseUntilBlocks() { var prev = this.breakOnBlocks; for (var _len = arguments.length, blockNames = new Array(_len), _key = 0; _key < _len; _key++) { blockNames[_key] = arguments[_key]; } this.breakOnBlocks = blockNames; var ret = this.parse(); this.breakOnBlocks = prev; return ret; }; _proto.parseNodes = function parseNodes() { var tok; var buf = []; while (tok = this.nextToken()) { if (tok.type === lexer.TOKEN_DATA) { var data = tok.value; var nextToken = this.peekToken(); var nextVal = nextToken && nextToken.value; if (this.dropLeadingWhitespace) { data = data.replace(/^\s*/, ""); this.dropLeadingWhitespace = false; } if (nextToken && (nextToken.type === lexer.TOKEN_BLOCK_START && nextVal.charAt(nextVal.length - 1) === "-" || nextToken.type === lexer.TOKEN_VARIABLE_START && nextVal.charAt(this.tokens.tags.VARIABLE_START.length) === "-" || nextToken.type === lexer.TOKEN_COMMENT && nextVal.charAt(this.tokens.tags.COMMENT_START.length) === "-")) { data = data.replace(/\s*$/, ""); } buf.push(new nodes.Output(tok.lineno, tok.colno, [new nodes.TemplateData(tok.lineno, tok.colno, data)])); } else if (tok.type === lexer.TOKEN_BLOCK_START) { this.dropLeadingWhitespace = false; var n = this.parseStatement(); if (!n) { break; } buf.push(n); } else if (tok.type === lexer.TOKEN_VARIABLE_START) { var e = this.parseExpression(); this.dropLeadingWhitespace = false; this.advanceAfterVariableEnd(); buf.push(new nodes.Output(tok.lineno, tok.colno, [e])); } else if (tok.type === lexer.TOKEN_COMMENT) { this.dropLeadingWhitespace = tok.value.charAt(tok.value.length - this.tokens.tags.COMMENT_END.length - 1) === "-"; } else { this.fail("Unexpected token at top-level: " + tok.type, tok.lineno, tok.colno); } } return buf; }; _proto.parse = function parse() { return new nodes.NodeList(0, 0, this.parseNodes()); }; _proto.parseAsRoot = function parseAsRoot() { return new nodes.Root(0, 0, this.parseNodes()); }; return Parser2; }(Obj); module3.exports = { parse: function parse(src, extensions, opts) { var p = new Parser(lexer.lex(src, opts)); if (extensions !== void 0) { p.extensions = extensions; } return p.parseAsRoot(); }, Parser }; }, function(module3, exports2, __webpack_require__) { "use strict"; var lib = __webpack_require__(0); var whitespaceChars = " \n \r\xA0"; var delimChars = "()[]{}%*-+~/#,:|.<>=!"; var intChars = "0123456789"; var BLOCK_START = "{%"; var BLOCK_END = "%}"; var VARIABLE_START = "{{"; var VARIABLE_END = "}}"; var COMMENT_START = "{#"; var COMMENT_END = "#}"; var TOKEN_STRING = "string"; var TOKEN_WHITESPACE = "whitespace"; var TOKEN_DATA = "data"; var TOKEN_BLOCK_START = "block-start"; var TOKEN_BLOCK_END = "block-end"; var TOKEN_VARIABLE_START = "variable-start"; var TOKEN_VARIABLE_END = "variable-end"; var TOKEN_COMMENT = "comment"; var TOKEN_LEFT_PAREN = "left-paren"; var TOKEN_RIGHT_PAREN = "right-paren"; var TOKEN_LEFT_BRACKET = "left-bracket"; var TOKEN_RIGHT_BRACKET = "right-bracket"; var TOKEN_LEFT_CURLY = "left-curly"; var TOKEN_RIGHT_CURLY = "right-curly"; var TOKEN_OPERATOR = "operator"; var TOKEN_COMMA = "comma"; var TOKEN_COLON = "colon"; var TOKEN_TILDE = "tilde"; var TOKEN_PIPE = "pipe"; var TOKEN_INT = "int"; var TOKEN_FLOAT = "float"; var TOKEN_BOOLEAN = "boolean"; var TOKEN_NONE = "none"; var TOKEN_SYMBOL = "symbol"; var TOKEN_SPECIAL = "special"; var TOKEN_REGEX = "regex"; function token(type, value, lineno, colno) { return { type, value, lineno, colno }; } var Tokenizer = /* @__PURE__ */ function() { function Tokenizer2(str, opts) { this.str = str; this.index = 0; this.len = str.length; this.lineno = 0; this.colno = 0; this.in_code = false; opts = opts || {}; var tags = opts.tags || {}; this.tags = { BLOCK_START: tags.blockStart || BLOCK_START, BLOCK_END: tags.blockEnd || BLOCK_END, VARIABLE_START: tags.variableStart || VARIABLE_START, VARIABLE_END: tags.variableEnd || VARIABLE_END, COMMENT_START: tags.commentStart || COMMENT_START, COMMENT_END: tags.commentEnd || COMMENT_END }; this.trimBlocks = !!opts.trimBlocks; this.lstripBlocks = !!opts.lstripBlocks; } var _proto = Tokenizer2.prototype; _proto.nextToken = function nextToken() { var lineno = this.lineno; var colno = this.colno; var tok; if (this.in_code) { var cur = this.current(); if (this.isFinished()) { return null; } else if (cur === '"' || cur === "'") { return token(TOKEN_STRING, this._parseString(cur), lineno, colno); } else if (tok = this._extract(whitespaceChars)) { return token(TOKEN_WHITESPACE, tok, lineno, colno); } else if ((tok = this._extractString(this.tags.BLOCK_END)) || (tok = this._extractString("-" + this.tags.BLOCK_END))) { this.in_code = false; if (this.trimBlocks) { cur = this.current(); if (cur === "\n") { this.forward(); } else if (cur === "\r") { this.forward(); cur = this.current(); if (cur === "\n") { this.forward(); } else { this.back(); } } } return token(TOKEN_BLOCK_END, tok, lineno, colno); } else if ((tok = this._extractString(this.tags.VARIABLE_END)) || (tok = this._extractString("-" + this.tags.VARIABLE_END))) { this.in_code = false; return token(TOKEN_VARIABLE_END, tok, lineno, colno); } else if (cur === "r" && this.str.charAt(this.index + 1) === "/") { this.forwardN(2); var regexBody = ""; while (!this.isFinished()) { if (this.current() === "/" && this.previous() !== "\\") { this.forward(); break; } else { regexBody += this.current(); this.forward(); } } var POSSIBLE_FLAGS = ["g", "i", "m", "y"]; var regexFlags = ""; while (!this.isFinished()) { var isCurrentAFlag = POSSIBLE_FLAGS.indexOf(this.current()) !== -1; if (isCurrentAFlag) { regexFlags += this.current(); this.forward(); } else { break; } } return token(TOKEN_REGEX, { body: regexBody, flags: regexFlags }, lineno, colno); } else if (delimChars.indexOf(cur) !== -1) { this.forward(); var complexOps = ["==", "===", "!=", "!==", "<=", ">=", "//", "**"]; var curComplex = cur + this.current(); var type; if (lib.indexOf(complexOps, curComplex) !== -1) { this.forward(); cur = curComplex; if (lib.indexOf(complexOps, curComplex + this.current()) !== -1) { cur = curComplex + this.current(); this.forward(); } } switch (cur) { case "(": type = TOKEN_LEFT_PAREN; break; case ")": type = TOKEN_RIGHT_PAREN; break; case "[": type = TOKEN_LEFT_BRACKET; break; case "]": type = TOKEN_RIGHT_BRACKET; break; case "{": type = TOKEN_LEFT_CURLY; break; case "}": type = TOKEN_RIGHT_CURLY; break; case ",": type = TOKEN_COMMA; break; case ":": type = TOKEN_COLON; break; case "~": type = TOKEN_TILDE; break; case "|": type = TOKEN_PIPE; break; default: type = TOKEN_OPERATOR; } return token(type, cur, lineno, colno); } else { tok = this._extractUntil(whitespaceChars + delimChars); if (tok.match(/^[-+]?[0-9]+$/)) { if (this.current() === ".") { this.forward(); var dec = this._extract(intChars); return token(TOKEN_FLOAT, tok + "." + dec, lineno, colno); } else { return token(TOKEN_INT, tok, lineno, colno); } } else if (tok.match(/^(true|false)$/)) { return token(TOKEN_BOOLEAN, tok, lineno, colno); } else if (tok === "none") { return token(TOKEN_NONE, tok, lineno, colno); } else if (tok === "null") { return token(TOKEN_NONE, tok, lineno, colno); } else if (tok) { return token(TOKEN_SYMBOL, tok, lineno, colno); } else { throw new Error("Unexpected value while parsing: " + tok); } } } else { var beginChars = this.tags.BLOCK_START.charAt(0) + this.tags.VARIABLE_START.charAt(0) + this.tags.COMMENT_START.charAt(0) + this.tags.COMMENT_END.charAt(0); if (this.isFinished()) { return null; } else if ((tok = this._extractString(this.tags.BLOCK_START + "-")) || (tok = this._extractString(this.tags.BLOCK_START))) { this.in_code = true; return token(TOKEN_BLOCK_START, tok, lineno, colno); } else if ((tok = this._extractString(this.tags.VARIABLE_START + "-")) || (tok = this._extractString(this.tags.VARIABLE_START))) { this.in_code = true; return token(TOKEN_VARIABLE_START, tok, lineno, colno); } else { tok = ""; var data; var inComment = false; if (this._matches(this.tags.COMMENT_START)) { inComment = true; tok = this._extractString(this.tags.COMMENT_START); } while ((data = this._extractUntil(beginChars)) !== null) { tok += data; if ((this._matches(this.tags.BLOCK_START) || this._matches(this.tags.VARIABLE_START) || this._matches(this.tags.COMMENT_START)) && !inComment) { if (this.lstripBlocks && this._matches(this.tags.BLOCK_START) && this.colno > 0 && this.colno <= tok.length) { var lastLine = tok.slice(-this.colno); if (/^\s+$/.test(lastLine)) { tok = tok.slice(0, -this.colno); if (!tok.length) { return this.nextToken(); } } } break; } else if (this._matches(this.tags.COMMENT_END)) { if (!inComment) { throw new Error("unexpected end of comment"); } tok += this._extractString(this.tags.COMMENT_END); break; } else { tok += this.current(); this.forward(); } } if (data === null && inComment) { throw new Error("expected end of comment, got end of file"); } return token(inComment ? TOKEN_COMMENT : TOKEN_DATA, tok, lineno, colno); } } }; _proto._parseString = function _parseString(delimiter) { this.forward(); var str = ""; while (!this.isFinished() && this.current() !== delimiter) { var cur = this.current(); if (cur === "\\") { this.forward(); switch (this.current()) { case "n": str += "\n"; break; case "t": str += " "; break; case "r": str += "\r"; break; default: str += this.current(); } this.forward(); } else { str += cur; this.forward(); } } this.forward(); return str; }; _proto._matches = function _matches(str) { if (this.index + str.length > this.len) { return null; } var m = this.str.slice(this.index, this.index + str.length); return m === str; }; _proto._extractString = function _extractString(str) { if (this._matches(str)) { this.forwardN(str.length); return str; } return null; }; _proto._extractUntil = function _extractUntil(charString) { return this._extractMatching(true, charString || ""); }; _proto._extract = function _extract(charString) { return this._extractMatching(false, charString); }; _proto._extractMatching = function _extractMatching(breakOnMatch, charString) { if (this.isFinished()) { return null; } var first = charString.indexOf(this.current()); if (breakOnMatch && first === -1 || !breakOnMatch && first !== -1) { var t = this.current(); this.forward(); var idx = charString.indexOf(this.current()); while ((breakOnMatch && idx === -1 || !breakOnMatch && idx !== -1) && !this.isFinished()) { t += this.current(); this.forward(); idx = charString.indexOf(this.current()); } return t; } return ""; }; _proto._extractRegex = function _extractRegex(regex) { var matches = this.currentStr().match(regex); if (!matches) { return null; } this.forwardN(matches[0].length); return matches; }; _proto.isFinished = function isFinished() { return this.index >= this.len; }; _proto.forwardN = function forwardN(n) { for (var i = 0; i < n; i++) { this.forward(); } }; _proto.forward = function forward() { this.index++; if (this.previous() === "\n") { this.lineno++; this.colno = 0; } else { this.colno++; } }; _proto.backN = function backN(n) { for (var i = 0; i < n; i++) { this.back(); } }; _proto.back = function back() { this.index--; if (this.current() === "\n") { this.lineno--; var idx = this.src.lastIndexOf("\n", this.index - 1); if (idx === -1) { this.colno = this.index; } else { this.colno = this.index - idx; } } else { this.colno--; } }; _proto.current = function current() { if (!this.isFinished()) { return this.str.charAt(this.index); } return ""; }; _proto.currentStr = function currentStr() { if (!this.isFinished()) { return this.str.substr(this.index); } return ""; }; _proto.previous = function previous() { return this.str.charAt(this.index - 1); }; return Tokenizer2; }(); module3.exports = { lex: function lex(src, opts) { return new Tokenizer(src, opts); }, TOKEN_STRING, TOKEN_WHITESPACE, TOKEN_DATA, TOKEN_BLOCK_START, TOKEN_BLOCK_END, TOKEN_VARIABLE_START, TOKEN_VARIABLE_END, TOKEN_COMMENT, TOKEN_LEFT_PAREN, TOKEN_RIGHT_PAREN, TOKEN_LEFT_BRACKET, TOKEN_RIGHT_BRACKET, TOKEN_LEFT_CURLY, TOKEN_RIGHT_CURLY, TOKEN_OPERATOR, TOKEN_COMMA, TOKEN_COLON, TOKEN_TILDE, TOKEN_PIPE, TOKEN_INT, TOKEN_FLOAT, TOKEN_BOOLEAN, TOKEN_NONE, TOKEN_SYMBOL, TOKEN_SPECIAL, TOKEN_REGEX }; }, function(module3, exports2, __webpack_require__) { "use strict"; function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) { o2.__proto__ = p2; return o2; }; return _setPrototypeOf(o, p); } var Loader = __webpack_require__(6); var _require = __webpack_require__(19), PrecompiledLoader = _require.PrecompiledLoader; var WebLoader = /* @__PURE__ */ function(_Loader) { _inheritsLoose(WebLoader2, _Loader); function WebLoader2(baseURL, opts) { var _this; _this = _Loader.call(this) || this; _this.baseURL = baseURL || "."; opts = opts || {}; _this.useCache = !!opts.useCache; _this.async = !!opts.async; return _this; } var _proto = WebLoader2.prototype; _proto.resolve = function resolve(from, to) { throw new Error("relative templates not support in the browser yet"); }; _proto.getSource = function getSource(name, cb) { var _this2 = this; var useCache = this.useCache; var result; this.fetch(this.baseURL + "/" + name, function(err, src) { if (err) { if (cb) { cb(err.content); } else if (err.status === 404) { result = null; } else { throw err.content; } } else { result = { src, path: name, noCache: !useCache }; _this2.emit("load", name, result); if (cb) { cb(null, result); } } }); return result; }; _proto.fetch = function fetch(url, cb) { if (typeof window === "undefined") { throw new Error("WebLoader can only by used in a browser"); } var ajax = new XMLHttpRequest(); var loading = true; ajax.onreadystatechange = function() { if (ajax.readyState === 4 && loading) { loading = false; if (ajax.status === 0 || ajax.status === 200) { cb(null, ajax.responseText); } else { cb({ status: ajax.status, content: ajax.responseText }); } } }; url += (url.indexOf("?") === -1 ? "?" : "&") + "s=" + new Date().getTime(); ajax.open("GET", url, this.async); ajax.send(); }; return WebLoader2; }(Loader); module3.exports = { WebLoader, PrecompiledLoader }; }, function(module3, exports2, __webpack_require__) { "use strict"; var lib = __webpack_require__(0); var _require = __webpack_require__(7), Environment = _require.Environment, Template = _require.Template; var Loader = __webpack_require__(6); var loaders = __webpack_require__(10); var precompile = __webpack_require__(23); var compiler = __webpack_require__(5); var parser = __webpack_require__(8); var lexer = __webpack_require__(9); var runtime = __webpack_require__(2); var nodes = __webpack_require__(3); var installJinjaCompat = __webpack_require__(25); var e; function configure(templatesPath, opts) { opts = opts || {}; if (lib.isObject(templatesPath)) { opts = templatesPath; templatesPath = null; } var TemplateLoader; if (loaders.FileSystemLoader) { TemplateLoader = new loaders.FileSystemLoader(templatesPath, { watch: opts.watch, noCache: opts.noCache }); } else if (loaders.WebLoader) { TemplateLoader = new loaders.WebLoader(templatesPath, { useCache: opts.web && opts.web.useCache, async: opts.web && opts.web.async }); } e = new Environment(TemplateLoader, opts); if (opts && opts.express) { e.express(opts.express); } return e; } module3.exports = { Environment, Template, Loader, FileSystemLoader: loaders.FileSystemLoader, NodeResolveLoader: loaders.NodeResolveLoader, PrecompiledLoader: loaders.PrecompiledLoader, WebLoader: loaders.WebLoader, compiler, parser, lexer, runtime, lib, nodes, installJinjaCompat, configure, reset: function reset() { e = void 0; }, compile: function compile(src, env, path, eagerCompile) { if (!e) { configure(); } return new Template(src, env, path, eagerCompile); }, render: function render(name, ctx, cb) { if (!e) { configure(); } return e.render(name, ctx, cb); }, renderString: function renderString2(src, ctx, cb) { if (!e) { configure(); } return e.renderString(src, ctx, cb); }, precompile: precompile ? precompile.precompile : void 0, precompileString: precompile ? precompile.precompileString : void 0 }; }, function(module3, exports2, __webpack_require__) { "use strict"; var rawAsap = __webpack_require__(13); var freeTasks = []; var pendingErrors = []; var requestErrorThrow = rawAsap.makeRequestCallFromTimer(throwFirstError); function throwFirstError() { if (pendingErrors.length) { throw pendingErrors.shift(); } } module3.exports = asap; function asap(task) { var rawTask; if (freeTasks.length) { rawTask = freeTasks.pop(); } else { rawTask = new RawTask(); } rawTask.task = task; rawAsap(rawTask); } function RawTask() { this.task = null; } RawTask.prototype.call = function() { try { this.task.call(); } catch (error) { if (asap.onerror) { asap.onerror(error); } else { pendingErrors.push(error); requestErrorThrow(); } } finally { this.task = null; freeTasks[freeTasks.length] = this; } }; }, function(module3, exports2, __webpack_require__) { "use strict"; (function(global2) { module3.exports = rawAsap; function rawAsap(task) { if (!queue.length) { requestFlush(); flushing = true; } queue[queue.length] = task; } var queue = []; var flushing = false; var requestFlush; var index = 0; var capacity = 1024; function flush() { while (index < queue.length) { var currentIndex = index; index = index + 1; queue[currentIndex].call(); if (index > capacity) { for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { queue[scan] = queue[scan + index]; } queue.length -= index; index = 0; } } queue.length = 0; index = 0; flushing = false; } var scope = typeof global2 !== "undefined" ? global2 : self; var BrowserMutationObserver = scope.MutationObserver || scope.WebKitMutationObserver; if (typeof BrowserMutationObserver === "function") { requestFlush = makeRequestCallFromMutationObserver(flush); } else { requestFlush = makeRequestCallFromTimer(flush); } rawAsap.requestFlush = requestFlush; function makeRequestCallFromMutationObserver(callback) { var toggle = 1; var observer = new BrowserMutationObserver(callback); var node = document.createTextNode(""); observer.observe(node, { characterData: true }); return function requestCall() { toggle = -toggle; node.data = toggle; }; } function makeRequestCallFromTimer(callback) { return function requestCall() { var timeoutHandle = setTimeout(handleTimer, 0); var intervalHandle = setInterval(handleTimer, 50); function handleTimer() { clearTimeout(timeoutHandle); clearInterval(intervalHandle); callback(); } }; } rawAsap.makeRequestCallFromTimer = makeRequestCallFromTimer; }).call(exports2, __webpack_require__(14)); }, function(module3, exports2) { var g; g = function() { return this; }(); try { g = g || Function("return this")() || (1, eval)("this"); } catch (e) { if (typeof window === "object") g = window; } module3.exports = g; }, function(module3, exports2, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__; (function(globals) { "use strict"; var executeSync = function() { var args = Array.prototype.slice.call(arguments); if (typeof args[0] === "function") { args[0].apply(null, args.splice(1)); } }; var executeAsync = function(fn) { if (typeof setImmediate === "function") { setImmediate(fn); } else if (typeof process !== "undefined" && process.nextTick) { process.nextTick(fn); } else { setTimeout(fn, 0); } }; var makeIterator = function(tasks) { var makeCallback = function(index) { var fn = function() { if (tasks.length) { tasks[index].apply(null, arguments); } return fn.next(); }; fn.next = function() { return index < tasks.length - 1 ? makeCallback(index + 1) : null; }; return fn; }; return makeCallback(0); }; var _isArray = Array.isArray || function(maybeArray) { return Object.prototype.toString.call(maybeArray) === "[object Array]"; }; var waterfall = function(tasks, callback, forceAsync) { var nextTick = forceAsync ? executeAsync : executeSync; callback = callback || function() { }; if (!_isArray(tasks)) { var err = new Error("First argument to waterfall must be an array of functions"); return callback(err); } if (!tasks.length) { return callback(); } var wrapIterator = function(iterator) { return function(err2) { if (err2) { callback.apply(null, arguments); callback = function() { }; } else { var args = Array.prototype.slice.call(arguments, 1); var next = iterator.next(); if (next) { args.push(wrapIterator(next)); } else { args.push(callback); } nextTick(function() { iterator.apply(null, args); }); } }; }; wrapIterator(makeIterator(tasks))(); }; if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return waterfall; }.apply(exports2, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== void 0 && (module3.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof module3 !== "undefined" && module3.exports) { module3.exports = waterfall; } else { globals.waterfall = waterfall; } })(this); }, function(module3, exports2, __webpack_require__) { "use strict"; var R = typeof Reflect === "object" ? Reflect : null; var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply2(target, receiver, args) { return Function.prototype.apply.call(target, receiver, args); }; var ReflectOwnKeys; if (R && typeof R.ownKeys === "function") { ReflectOwnKeys = R.ownKeys; } else if (Object.getOwnPropertySymbols) { ReflectOwnKeys = function ReflectOwnKeys2(target) { return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); }; } else { ReflectOwnKeys = function ReflectOwnKeys2(target) { return Object.getOwnPropertyNames(target); }; } function ProcessEmitWarning(warning) { if (console && console.warn) console.warn(warning); } var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value) { return value !== value; }; function EventEmitter() { EventEmitter.init.call(this); } module3.exports = EventEmitter; module3.exports.once = once; EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = void 0; EventEmitter.prototype._eventsCount = 0; EventEmitter.prototype._maxListeners = void 0; var defaultMaxListeners = 10; function checkListener(listener) { if (typeof listener !== "function") { throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); } } Object.defineProperty(EventEmitter, "defaultMaxListeners", { enumerable: true, get: function() { return defaultMaxListeners; }, set: function(arg) { if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) { throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + "."); } defaultMaxListeners = arg; } }); EventEmitter.init = function() { if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { this._events = /* @__PURE__ */ Object.create(null); this._eventsCount = 0; } this._maxListeners = this._maxListeners || void 0; }; EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) { throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + "."); } this._maxListeners = n; return this; }; function _getMaxListeners(that) { if (that._maxListeners === void 0) return EventEmitter.defaultMaxListeners; return that._maxListeners; } EventEmitter.prototype.getMaxListeners = function getMaxListeners() { return _getMaxListeners(this); }; EventEmitter.prototype.emit = function emit(type) { var args = []; for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); var doError = type === "error"; var events = this._events; if (events !== void 0) doError = doError && events.error === void 0; else if (!doError) return false; if (doError) { var er; if (args.length > 0) er = args[0]; if (er instanceof Error) { throw er; } var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : "")); err.context = er; throw err; } var handler = events[type]; if (handler === void 0) return false; if (typeof handler === "function") { ReflectApply(handler, this, args); } else { var len = handler.length; var listeners = arrayClone(handler, len); for (var i = 0; i < len; ++i) ReflectApply(listeners[i], this, args); } return true; }; function _addListener(target, type, listener, prepend) { var m; var events; var existing; checkListener(listener); events = target._events; if (events === void 0) { events = target._events = /* @__PURE__ */ Object.create(null); target._eventsCount = 0; } else { if (events.newListener !== void 0) { target.emit("newListener", type, listener.listener ? listener.listener : listener); events = target._events; } existing = events[type]; } if (existing === void 0) { existing = events[type] = listener; ++target._eventsCount; } else { if (typeof existing === "function") { existing = events[type] = prepend ? [listener, existing] : [existing, listener]; } else if (prepend) { existing.unshift(listener); } else { existing.push(listener); } m = _getMaxListeners(target); if (m > 0 && existing.length > m && !existing.warned) { existing.warned = true; var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit"); w.name = "MaxListenersExceededWarning"; w.emitter = target; w.type = type; w.count = existing.length; ProcessEmitWarning(w); } } return target; } EventEmitter.prototype.addListener = function addListener(type, listener) { return _addListener(this, type, listener, false); }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.prependListener = function prependListener(type, listener) { return _addListener(this, type, listener, true); }; function onceWrapper() { if (!this.fired) { this.target.removeListener(this.type, this.wrapFn); this.fired = true; if (arguments.length === 0) return this.listener.call(this.target); return this.listener.apply(this.target, arguments); } } function _onceWrap(target, type, listener) { var state = { fired: false, wrapFn: void 0, target, type, listener }; var wrapped = onceWrapper.bind(state); wrapped.listener = listener; state.wrapFn = wrapped; return wrapped; } EventEmitter.prototype.once = function once2(type, listener) { checkListener(listener); this.on(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { checkListener(listener); this.prependListener(type, _onceWrap(this, type, listener)); return this; }; EventEmitter.prototype.removeListener = function removeListener(type, listener) { var list, events, position, i, originalListener; checkListener(listener); events = this._events; if (events === void 0) return this; list = events[type]; if (list === void 0) return this; if (list === listener || list.listener === listener) { if (--this._eventsCount === 0) this._events = /* @__PURE__ */ Object.create(null); else { delete events[type]; if (events.removeListener) this.emit("removeListener", type, list.listener || listener); } } else if (typeof list !== "function") { position = -1; for (i = list.length - 1; i >= 0; i--) { if (list[i] === listener || list[i].listener === listener) { originalListener = list[i].listener; position = i; break; } } if (position < 0) return this; if (position === 0) list.shift(); else { spliceOne(list, position); } if (list.length === 1) events[type] = list[0]; if (events.removeListener !== void 0) this.emit("removeListener", type, originalListener || listener); } return this; }; EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events, i; events = this._events; if (events === void 0) return this; if (events.removeListener === void 0) { if (arguments.length === 0) { this._events = /* @__PURE__ */ Object.create(null); this._eventsCount = 0; } else if (events[type] !== void 0) { if (--this._eventsCount === 0) this._events = /* @__PURE__ */ Object.create(null); else delete events[type]; } return this; } if (arguments.length === 0) { var keys = Object.keys(events); var key; for (i = 0; i < keys.length; ++i) { key = keys[i]; if (key === "removeListener") continue; this.removeAllListeners(key); } this.removeAllListeners("removeListener"); this._events = /* @__PURE__ */ Object.create(null); this._eventsCount = 0; return this; } listeners = events[type]; if (typeof listeners === "function") { this.removeListener(type, listeners); } else if (listeners !== void 0) { for (i = listeners.length - 1; i >= 0; i--) { this.removeListener(type, listeners[i]); } } return this; }; function _listeners(target, type, unwrap) { var events = target._events; if (events === void 0) return []; var evlistener = events[type]; if (evlistener === void 0) return []; if (typeof evlistener === "function") return unwrap ? [evlistener.listener || evlistener] : [evlistener]; return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); } EventEmitter.prototype.listeners = function listeners(type) { return _listeners(this, type, true); }; EventEmitter.prototype.rawListeners = function rawListeners(type) { return _listeners(this, type, false); }; EventEmitter.listenerCount = function(emitter, type) { if (typeof emitter.listenerCount === "function") { return emitter.listenerCount(type); } else { return listenerCount.call(emitter, type); } }; EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; if (events !== void 0) { var evlistener = events[type]; if (typeof evlistener === "function") { return 1; } else if (evlistener !== void 0) { return evlistener.length; } } return 0; } EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; }; function arrayClone(arr, n) { var copy = new Array(n); for (var i = 0; i < n; ++i) copy[i] = arr[i]; return copy; } function spliceOne(list, index) { for (; index + 1 < list.length; index++) list[index] = list[index + 1]; list.pop(); } function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { ret[i] = arr[i].listener || arr[i]; } return ret; } function once(emitter, name) { return new Promise(function(resolve, reject) { function errorListener(err) { emitter.removeListener(name, resolver); reject(err); } function resolver() { if (typeof emitter.removeListener === "function") { emitter.removeListener("error", errorListener); } resolve([].slice.call(arguments)); } ; eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); if (name !== "error") { addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); } }); } function addErrorHandlerIfEventEmitter(emitter, handler, flags) { if (typeof emitter.on === "function") { eventTargetAgnosticAddListener(emitter, "error", handler, flags); } } function eventTargetAgnosticAddListener(emitter, name, listener, flags) { if (typeof emitter.on === "function") { if (flags.once) { emitter.once(name, listener); } else { emitter.on(name, listener); } } else if (typeof emitter.addEventListener === "function") { emitter.addEventListener(name, function wrapListener(arg) { if (flags.once) { emitter.removeEventListener(name, wrapListener); } listener(arg); }); } else { throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); } } }, function(module3, exports2, __webpack_require__) { "use strict"; var nodes = __webpack_require__(3); var lib = __webpack_require__(0); var sym = 0; function gensym() { return "hole_" + sym++; } function mapCOW(arr, func) { var res = null; for (var i = 0; i < arr.length; i++) { var item = func(arr[i]); if (item !== arr[i]) { if (!res) { res = arr.slice(); } res[i] = item; } } return res || arr; } function walk(ast, func, depthFirst) { if (!(ast instanceof nodes.Node)) { return ast; } if (!depthFirst) { var astT = func(ast); if (astT && astT !== ast) { return astT; } } if (ast instanceof nodes.NodeList) { var children = mapCOW(ast.children, function(node) { return walk(node, func, depthFirst); }); if (children !== ast.children) { ast = new nodes[ast.typename](ast.lineno, ast.colno, children); } } else if (ast instanceof nodes.CallExtension) { var args = walk(ast.args, func, depthFirst); var contentArgs = mapCOW(ast.contentArgs, function(node) { return walk(node, func, depthFirst); }); if (args !== ast.args || contentArgs !== ast.contentArgs) { ast = new nodes[ast.typename](ast.extName, ast.prop, args, contentArgs); } } else { var props = ast.fields.map(function(field) { return ast[field]; }); var propsT = mapCOW(props, function(prop) { return walk(prop, func, depthFirst); }); if (propsT !== props) { ast = new nodes[ast.typename](ast.lineno, ast.colno); propsT.forEach(function(prop, i) { ast[ast.fields[i]] = prop; }); } } return depthFirst ? func(ast) || ast : ast; } function depthWalk(ast, func) { return walk(ast, func, true); } function _liftFilters(node, asyncFilters, prop) { var children = []; var walked = depthWalk(prop ? node[prop] : node, function(descNode) { var symbol; if (descNode instanceof nodes.Block) { return descNode; } else if (descNode instanceof nodes.Filter && lib.indexOf(asyncFilters, descNode.name.value) !== -1 || descNode instanceof nodes.CallExtensionAsync) { symbol = new nodes.Symbol(descNode.lineno, descNode.colno, gensym()); children.push(new nodes.FilterAsync(descNode.lineno, descNode.colno, descNode.name, descNode.args, symbol)); } return symbol; }); if (prop) { node[prop] = walked; } else { node = walked; } if (children.length) { children.push(node); return new nodes.NodeList(node.lineno, node.colno, children); } else { return node; } } function liftFilters(ast, asyncFilters) { return depthWalk(ast, function(node) { if (node instanceof nodes.Output) { return _liftFilters(node, asyncFilters); } else if (node instanceof nodes.Set) { return _liftFilters(node, asyncFilters, "value"); } else if (node instanceof nodes.For) { return _liftFilters(node, asyncFilters, "arr"); } else if (node instanceof nodes.If) { return _liftFilters(node, asyncFilters, "cond"); } else if (node instanceof nodes.CallExtension) { return _liftFilters(node, asyncFilters, "args"); } else { return void 0; } }); } function liftSuper(ast) { return walk(ast, function(blockNode) { if (!(blockNode instanceof nodes.Block)) { return; } var hasSuper = false; var symbol = gensym(); blockNode.body = walk(blockNode.body, function(node) { if (node instanceof nodes.FunCall && node.name.value === "super") { hasSuper = true; return new nodes.Symbol(node.lineno, node.colno, symbol); } }); if (hasSuper) { blockNode.body.children.unshift(new nodes.Super(0, 0, blockNode.name, new nodes.Symbol(0, 0, symbol))); } }); } function convertStatements(ast) { return depthWalk(ast, function(node) { if (!(node instanceof nodes.If) && !(node instanceof nodes.For)) { return void 0; } var async = false; walk(node, function(child) { if (child instanceof nodes.FilterAsync || child instanceof nodes.IfAsync || child instanceof nodes.AsyncEach || child instanceof nodes.AsyncAll || child instanceof nodes.CallExtensionAsync) { async = true; return child; } return void 0; }); if (async) { if (node instanceof nodes.If) { return new nodes.IfAsync(node.lineno, node.colno, node.cond, node.body, node.else_); } else if (node instanceof nodes.For && !(node instanceof nodes.AsyncAll)) { return new nodes.AsyncEach(node.lineno, node.colno, node.arr, node.name, node.body, node.else_); } } return void 0; }); } function cps(ast, asyncFilters) { return convertStatements(liftSuper(liftFilters(ast, asyncFilters))); } function transform(ast, asyncFilters) { return cps(ast, asyncFilters || []); } module3.exports = { transform }; }, function(module3, exports2, __webpack_require__) { "use strict"; var lib = __webpack_require__(0); var r = __webpack_require__(2); var exports2 = module3.exports = {}; function normalize(value, defaultValue) { if (value === null || value === void 0 || value === false) { return defaultValue; } return value; } exports2.abs = Math.abs; function isNaN2(num) { return num !== num; } function batch(arr, linecount, fillWith) { var i; var res = []; var tmp = []; for (i = 0; i < arr.length; i++) { if (i % linecount === 0 && tmp.length) { res.push(tmp); tmp = []; } tmp.push(arr[i]); } if (tmp.length) { if (fillWith) { for (i = tmp.length; i < linecount; i++) { tmp.push(fillWith); } } res.push(tmp); } return res; } exports2.batch = batch; function capitalize(str) { str = normalize(str, ""); var ret = str.toLowerCase(); return r.copySafeness(str, ret.charAt(0).toUpperCase() + ret.slice(1)); } exports2.capitalize = capitalize; function center(str, width) { str = normalize(str, ""); width = width || 80; if (str.length >= width) { return str; } var spaces = width - str.length; var pre = lib.repeat(" ", spaces / 2 - spaces % 2); var post = lib.repeat(" ", spaces / 2); return r.copySafeness(str, pre + str + post); } exports2.center = center; function default_(val, def, bool) { if (bool) { return val || def; } else { return val !== void 0 ? val : def; } } exports2["default"] = default_; function dictsort(val, caseSensitive, by) { if (!lib.isObject(val)) { throw new lib.TemplateError("dictsort filter: val must be an object"); } var array = []; for (var k in val) { array.push([k, val[k]]); } var si; if (by === void 0 || by === "key") { si = 0; } else if (by === "value") { si = 1; } else { throw new lib.TemplateError("dictsort filter: You can only sort by either key or value"); } array.sort(function(t1, t2) { var a = t1[si]; var b = t2[si]; if (!caseSensitive) { if (lib.isString(a)) { a = a.toUpperCase(); } if (lib.isString(b)) { b = b.toUpperCase(); } } return a > b ? 1 : a === b ? 0 : -1; }); return array; } exports2.dictsort = dictsort; function dump(obj, spaces) { return JSON.stringify(obj, null, spaces); } exports2.dump = dump; function escape(str) { if (str instanceof r.SafeString) { return str; } str = str === null || str === void 0 ? "" : str; return r.markSafe(lib.escape(str.toString())); } exports2.escape = escape; function safe(str) { if (str instanceof r.SafeString) { return str; } str = str === null || str === void 0 ? "" : str; return r.markSafe(str.toString()); } exports2.safe = safe; function first(arr) { return arr[0]; } exports2.first = first; function forceescape(str) { str = str === null || str === void 0 ? "" : str; return r.markSafe(lib.escape(str.toString())); } exports2.forceescape = forceescape; function groupby(arr, attr) { return lib.groupBy(arr, attr, this.env.opts.throwOnUndefined); } exports2.groupby = groupby; function indent(str, width, indentfirst) { str = normalize(str, ""); if (str === "") { return ""; } width = width || 4; var lines = str.split("\n"); var sp = lib.repeat(" ", width); var res = lines.map(function(l, i) { return i === 0 && !indentfirst ? l : "" + sp + l; }).join("\n"); return r.copySafeness(str, res); } exports2.indent = indent; function join(arr, del, attr) { del = del || ""; if (attr) { arr = lib.map(arr, function(v) { return v[attr]; }); } return arr.join(del); } exports2.join = join; function last(arr) { return arr[arr.length - 1]; } exports2.last = last; function lengthFilter(val) { var value = normalize(val, ""); if (value !== void 0) { if (typeof Map === "function" && value instanceof Map || typeof Set === "function" && value instanceof Set) { return value.size; } if (lib.isObject(value) && !(value instanceof r.SafeString)) { return lib.keys(value).length; } return value.length; } return 0; } exports2.length = lengthFilter; function list(val) { if (lib.isString(val)) { return val.split(""); } else if (lib.isObject(val)) { return lib._entries(val || {}).map(function(_ref) { var key = _ref[0], value = _ref[1]; return { key, value }; }); } else if (lib.isArray(val)) { return val; } else { throw new lib.TemplateError("list filter: type not iterable"); } } exports2.list = list; function lower(str) { str = normalize(str, ""); return str.toLowerCase(); } exports2.lower = lower; function nl2br(str) { if (str === null || str === void 0) { return ""; } return r.copySafeness(str, str.replace(/\r\n|\n/g, "
\n")); } exports2.nl2br = nl2br; function random(arr) { return arr[Math.floor(Math.random() * arr.length)]; } exports2.random = random; function getSelectOrReject(expectedTestResult) { function filter(arr, testName, secondArg) { if (testName === void 0) { testName = "truthy"; } var context = this; var test = context.env.getTest(testName); return lib.toArray(arr).filter(function examineTestResult(item) { return test.call(context, item, secondArg) === expectedTestResult; }); } return filter; } exports2.reject = getSelectOrReject(false); function rejectattr(arr, attr) { return arr.filter(function(item) { return !item[attr]; }); } exports2.rejectattr = rejectattr; exports2.select = getSelectOrReject(true); function selectattr(arr, attr) { return arr.filter(function(item) { return !!item[attr]; }); } exports2.selectattr = selectattr; function replace(str, old, new_, maxCount) { var originalStr = str; if (old instanceof RegExp) { return str.replace(old, new_); } if (typeof maxCount === "undefined") { maxCount = -1; } var res = ""; if (typeof old === "number") { old = "" + old; } else if (typeof old !== "string") { return str; } if (typeof str === "number") { str = "" + str; } if (typeof str !== "string" && !(str instanceof r.SafeString)) { return str; } if (old === "") { res = new_ + str.split("").join(new_) + new_; return r.copySafeness(str, res); } var nextIndex = str.indexOf(old); if (maxCount === 0 || nextIndex === -1) { return str; } var pos = 0; var count = 0; while (nextIndex > -1 && (maxCount === -1 || count < maxCount)) { res += str.substring(pos, nextIndex) + new_; pos = nextIndex + old.length; count++; nextIndex = str.indexOf(old, pos); } if (pos < str.length) { res += str.substring(pos); } return r.copySafeness(originalStr, res); } exports2.replace = replace; function reverse(val) { var arr; if (lib.isString(val)) { arr = list(val); } else { arr = lib.map(val, function(v) { return v; }); } arr.reverse(); if (lib.isString(val)) { return r.copySafeness(val, arr.join("")); } return arr; } exports2.reverse = reverse; function round(val, precision, method) { precision = precision || 0; var factor = Math.pow(10, precision); var rounder; if (method === "ceil") { rounder = Math.ceil; } else if (method === "floor") { rounder = Math.floor; } else { rounder = Math.round; } return rounder(val * factor) / factor; } exports2.round = round; function slice(arr, slices, fillWith) { var sliceLength = Math.floor(arr.length / slices); var extra = arr.length % slices; var res = []; var offset = 0; for (var i = 0; i < slices; i++) { var start = offset + i * sliceLength; if (i < extra) { offset++; } var end = offset + (i + 1) * sliceLength; var currSlice = arr.slice(start, end); if (fillWith && i >= extra) { currSlice.push(fillWith); } res.push(currSlice); } return res; } exports2.slice = slice; function sum(arr, attr, start) { if (start === void 0) { start = 0; } if (attr) { arr = lib.map(arr, function(v) { return v[attr]; }); } return start + arr.reduce(function(a, b) { return a + b; }, 0); } exports2.sum = sum; exports2.sort = r.makeMacro(["value", "reverse", "case_sensitive", "attribute"], [], function sortFilter(arr, reversed, caseSens, attr) { var _this = this; var array = lib.map(arr, function(v) { return v; }); var getAttribute = lib.getAttrGetter(attr); array.sort(function(a, b) { var x = attr ? getAttribute(a) : a; var y = attr ? getAttribute(b) : b; if (_this.env.opts.throwOnUndefined && attr && (x === void 0 || y === void 0)) { throw new TypeError('sort: attribute "' + attr + '" resolved to undefined'); } if (!caseSens && lib.isString(x) && lib.isString(y)) { x = x.toLowerCase(); y = y.toLowerCase(); } if (x < y) { return reversed ? 1 : -1; } else if (x > y) { return reversed ? -1 : 1; } else { return 0; } }); return array; }); function string(obj) { return r.copySafeness(obj, obj); } exports2.string = string; function striptags(input, preserveLinebreaks) { input = normalize(input, ""); var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>|/gi; var trimmedInput = trim(input.replace(tags, "")); var res = ""; if (preserveLinebreaks) { res = trimmedInput.replace(/^ +| +$/gm, "").replace(/ +/g, " ").replace(/(\r\n)/g, "\n").replace(/\n\n\n+/g, "\n\n"); } else { res = trimmedInput.replace(/\s+/gi, " "); } return r.copySafeness(input, res); } exports2.striptags = striptags; function title(str) { str = normalize(str, ""); var words = str.split(" ").map(function(word) { return capitalize(word); }); return r.copySafeness(str, words.join(" ")); } exports2.title = title; function trim(str) { return r.copySafeness(str, str.replace(/^\s*|\s*$/g, "")); } exports2.trim = trim; function truncate(input, length, killwords, end) { var orig = input; input = normalize(input, ""); length = length || 255; if (input.length <= length) { return input; } if (killwords) { input = input.substring(0, length); } else { var idx = input.lastIndexOf(" ", length); if (idx === -1) { idx = length; } input = input.substring(0, idx); } input += end !== void 0 && end !== null ? end : "..."; return r.copySafeness(orig, input); } exports2.truncate = truncate; function upper(str) { str = normalize(str, ""); return str.toUpperCase(); } exports2.upper = upper; function urlencode(obj) { var enc = encodeURIComponent; if (lib.isString(obj)) { return enc(obj); } else { var keyvals = lib.isArray(obj) ? obj : lib._entries(obj); return keyvals.map(function(_ref2) { var k = _ref2[0], v = _ref2[1]; return enc(k) + "=" + enc(v); }).join("&"); } } exports2.urlencode = urlencode; var puncRe = /^(?:\(|<|<)?(.*?)(?:\.|,|\)|\n|>)?$/; var emailRe = /^[\w.!#$%&'*+\-\/=?\^`{|}~]+@[a-z\d\-]+(\.[a-z\d\-]+)+$/i; var httpHttpsRe = /^https?:\/\/.*$/; var wwwRe = /^www\./; var tldRe = /\.(?:org|net|com)(?:\:|\/|$)/; function urlize(str, length, nofollow) { if (isNaN2(length)) { length = Infinity; } var noFollowAttr = nofollow === true ? ' rel="nofollow"' : ""; var words = str.split(/(\s+)/).filter(function(word) { return word && word.length; }).map(function(word) { var matches = word.match(puncRe); var possibleUrl = matches ? matches[1] : word; var shortUrl = possibleUrl.substr(0, length); if (httpHttpsRe.test(possibleUrl)) { return '" + shortUrl + ""; } if (wwwRe.test(possibleUrl)) { return '" + shortUrl + ""; } if (emailRe.test(possibleUrl)) { return '' + possibleUrl + ""; } if (tldRe.test(possibleUrl)) { return '" + shortUrl + ""; } return word; }); return words.join(""); } exports2.urlize = urlize; function wordcount(str) { str = normalize(str, ""); var words = str ? str.match(/\w+/g) : null; return words ? words.length : null; } exports2.wordcount = wordcount; function float(val, def) { var res = parseFloat(val); return isNaN2(res) ? def : res; } exports2.float = float; var intFilter = r.makeMacro(["value", "default", "base"], [], function doInt(value, defaultValue, base) { if (base === void 0) { base = 10; } var res = parseInt(value, base); return isNaN2(res) ? defaultValue : res; }); exports2.int = intFilter; exports2.d = exports2.default; exports2.e = exports2.escape; }, function(module3, exports2, __webpack_require__) { "use strict"; function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) { o2.__proto__ = p2; return o2; }; return _setPrototypeOf(o, p); } var Loader = __webpack_require__(6); var PrecompiledLoader = /* @__PURE__ */ function(_Loader) { _inheritsLoose(PrecompiledLoader2, _Loader); function PrecompiledLoader2(compiledTemplates) { var _this; _this = _Loader.call(this) || this; _this.precompiled = compiledTemplates || {}; return _this; } var _proto = PrecompiledLoader2.prototype; _proto.getSource = function getSource(name) { if (this.precompiled[name]) { return { src: { type: "code", obj: this.precompiled[name] }, path: name }; } return null; }; return PrecompiledLoader2; }(Loader); module3.exports = { PrecompiledLoader }; }, function(module3, exports2, __webpack_require__) { "use strict"; var SafeString = __webpack_require__(2).SafeString; function callable(value) { return typeof value === "function"; } exports2.callable = callable; function defined(value) { return value !== void 0; } exports2.defined = defined; function divisibleby(one, two) { return one % two === 0; } exports2.divisibleby = divisibleby; function escaped(value) { return value instanceof SafeString; } exports2.escaped = escaped; function equalto(one, two) { return one === two; } exports2.equalto = equalto; exports2.eq = exports2.equalto; exports2.sameas = exports2.equalto; function even(value) { return value % 2 === 0; } exports2.even = even; function falsy(value) { return !value; } exports2.falsy = falsy; function ge(one, two) { return one >= two; } exports2.ge = ge; function greaterthan(one, two) { return one > two; } exports2.greaterthan = greaterthan; exports2.gt = exports2.greaterthan; function le(one, two) { return one <= two; } exports2.le = le; function lessthan(one, two) { return one < two; } exports2.lessthan = lessthan; exports2.lt = exports2.lessthan; function lower(value) { return value.toLowerCase() === value; } exports2.lower = lower; function ne(one, two) { return one !== two; } exports2.ne = ne; function nullTest(value) { return value === null; } exports2.null = nullTest; function number(value) { return typeof value === "number"; } exports2.number = number; function odd(value) { return value % 2 === 1; } exports2.odd = odd; function string(value) { return typeof value === "string"; } exports2.string = string; function truthy(value) { return !!value; } exports2.truthy = truthy; function undefinedTest(value) { return value === void 0; } exports2.undefined = undefinedTest; function upper(value) { return value.toUpperCase() === value; } exports2.upper = upper; function iterable(value) { if (typeof Symbol !== "undefined") { return !!value[Symbol.iterator]; } else { return Array.isArray(value) || typeof value === "string"; } } exports2.iterable = iterable; function mapping(value) { var bool = value !== null && value !== void 0 && typeof value === "object" && !Array.isArray(value); if (Set) { return bool && !(value instanceof Set); } else { return bool; } } exports2.mapping = mapping; }, function(module3, exports2, __webpack_require__) { "use strict"; function _cycler(items) { var index = -1; return { current: null, reset: function reset() { index = -1; this.current = null; }, next: function next() { index++; if (index >= items.length) { index = 0; } this.current = items[index]; return this.current; } }; } function _joiner(sep) { sep = sep || ","; var first = true; return function() { var val = first ? "" : sep; first = false; return val; }; } function globals() { return { range: function range(start, stop, step) { if (typeof stop === "undefined") { stop = start; start = 0; step = 1; } else if (!step) { step = 1; } var arr = []; if (step > 0) { for (var i = start; i < stop; i += step) { arr.push(i); } } else { for (var _i = start; _i > stop; _i += step) { arr.push(_i); } } return arr; }, cycler: function cycler() { return _cycler(Array.prototype.slice.call(arguments)); }, joiner: function joiner(sep) { return _joiner(sep); } }; } module3.exports = globals; }, function(module3, exports2, __webpack_require__) { var path = __webpack_require__(4); module3.exports = function express(env, app2) { function NunjucksView(name, opts) { this.name = name; this.path = name; this.defaultEngine = opts.defaultEngine; this.ext = path.extname(name); if (!this.ext && !this.defaultEngine) { throw new Error("No default engine was specified and no extension was provided."); } if (!this.ext) { this.name += this.ext = (this.defaultEngine[0] !== "." ? "." : "") + this.defaultEngine; } } NunjucksView.prototype.render = function render(opts, cb) { env.render(this.name, opts, cb); }; app2.set("view", NunjucksView); app2.set("nunjucksEnv", env); return env; }; }, function(module3, exports2, __webpack_require__) { "use strict"; var fs = __webpack_require__(4); var path = __webpack_require__(4); var _require = __webpack_require__(0), _prettifyError = _require._prettifyError; var compiler = __webpack_require__(5); var _require2 = __webpack_require__(7), Environment = _require2.Environment; var precompileGlobal = __webpack_require__(24); function match(filename, patterns) { if (!Array.isArray(patterns)) { return false; } return patterns.some(function(pattern) { return filename.match(pattern); }); } function precompileString(str, opts) { opts = opts || {}; opts.isString = true; var env = opts.env || new Environment([]); var wrapper = opts.wrapper || precompileGlobal; if (!opts.name) { throw new Error('the "name" option is required when compiling a string'); } return wrapper([_precompile(str, opts.name, env)], opts); } function precompile(input, opts) { opts = opts || {}; var env = opts.env || new Environment([]); var wrapper = opts.wrapper || precompileGlobal; if (opts.isString) { return precompileString(input, opts); } var pathStats = fs.existsSync(input) && fs.statSync(input); var precompiled = []; var templates = []; function addTemplates(dir) { fs.readdirSync(dir).forEach(function(file) { var filepath = path.join(dir, file); var subpath = filepath.substr(path.join(input, "/").length); var stat = fs.statSync(filepath); if (stat && stat.isDirectory()) { subpath += "/"; if (!match(subpath, opts.exclude)) { addTemplates(filepath); } } else if (match(subpath, opts.include)) { templates.push(filepath); } }); } if (pathStats.isFile()) { precompiled.push(_precompile(fs.readFileSync(input, "utf-8"), opts.name || input, env)); } else if (pathStats.isDirectory()) { addTemplates(input); for (var i = 0; i < templates.length; i++) { var name = templates[i].replace(path.join(input, "/"), ""); try { precompiled.push(_precompile(fs.readFileSync(templates[i], "utf-8"), name, env)); } catch (e) { if (opts.force) { console.error(e); } else { throw e; } } } } return wrapper(precompiled, opts); } function _precompile(str, name, env) { env = env || new Environment([]); var asyncFilters = env.asyncFilters; var extensions = env.extensionsList; var template; name = name.replace(/\\/g, "/"); try { template = compiler.compile(str, asyncFilters, extensions, name, env.opts); } catch (err) { throw _prettifyError(name, false, err); } return { name, template }; } module3.exports = { precompile, precompileString }; }, function(module3, exports2, __webpack_require__) { "use strict"; function precompileGlobal(templates, opts) { var out = ""; opts = opts || {}; for (var i = 0; i < templates.length; i++) { var name = JSON.stringify(templates[i].name); var template = templates[i].template; out += "(function() {(window.nunjucksPrecompiled = window.nunjucksPrecompiled || {})[" + name + "] = (function() {\n" + template + "\n})();\n"; if (opts.asFunction) { out += "return function(ctx, cb) { return nunjucks.render(" + name + ", ctx, cb); }\n"; } out += "})();\n"; } return out; } module3.exports = precompileGlobal; }, function(module3, exports2, __webpack_require__) { function installCompat() { "use strict"; var runtime = this.runtime; var lib = this.lib; var Compiler = this.compiler.Compiler; var Parser = this.parser.Parser; var nodes = this.nodes; var lexer = this.lexer; var orig_contextOrFrameLookup = runtime.contextOrFrameLookup; var orig_memberLookup = runtime.memberLookup; var orig_Compiler_assertType; var orig_Parser_parseAggregate; if (Compiler) { orig_Compiler_assertType = Compiler.prototype.assertType; } if (Parser) { orig_Parser_parseAggregate = Parser.prototype.parseAggregate; } function uninstall() { runtime.contextOrFrameLookup = orig_contextOrFrameLookup; runtime.memberLookup = orig_memberLookup; if (Compiler) { Compiler.prototype.assertType = orig_Compiler_assertType; } if (Parser) { Parser.prototype.parseAggregate = orig_Parser_parseAggregate; } } runtime.contextOrFrameLookup = function contextOrFrameLookup(context, frame, key) { var val = orig_contextOrFrameLookup.apply(this, arguments); if (val !== void 0) { return val; } switch (key) { case "True": return true; case "False": return false; case "None": return null; default: return void 0; } }; function getTokensState(tokens) { return { index: tokens.index, lineno: tokens.lineno, colno: tokens.colno }; } if (nodes && Compiler && Parser) { var Slice = nodes.Node.extend("Slice", { fields: ["start", "stop", "step"], init: function init(lineno, colno, start, stop, step) { start = start || new nodes.Literal(lineno, colno, null); stop = stop || new nodes.Literal(lineno, colno, null); step = step || new nodes.Literal(lineno, colno, 1); this.parent(lineno, colno, start, stop, step); } }); Compiler.prototype.assertType = function assertType(node) { if (node instanceof Slice) { return; } orig_Compiler_assertType.apply(this, arguments); }; Compiler.prototype.compileSlice = function compileSlice(node, frame) { this._emit("("); this._compileExpression(node.start, frame); this._emit("),("); this._compileExpression(node.stop, frame); this._emit("),("); this._compileExpression(node.step, frame); this._emit(")"); }; Parser.prototype.parseAggregate = function parseAggregate() { var _this = this; var origState = getTokensState(this.tokens); origState.colno--; origState.index--; try { return orig_Parser_parseAggregate.apply(this); } catch (e) { var errState = getTokensState(this.tokens); var rethrow = function rethrow2() { lib._assign(_this.tokens, errState); return e; }; lib._assign(this.tokens, origState); this.peeked = false; var tok = this.peekToken(); if (tok.type !== lexer.TOKEN_LEFT_BRACKET) { throw rethrow(); } else { this.nextToken(); } var node = new Slice(tok.lineno, tok.colno); var isSlice = false; for (var i = 0; i <= node.fields.length; i++) { if (this.skip(lexer.TOKEN_RIGHT_BRACKET)) { break; } if (i === node.fields.length) { if (isSlice) { this.fail("parseSlice: too many slice components", tok.lineno, tok.colno); } else { break; } } if (this.skip(lexer.TOKEN_COLON)) { isSlice = true; } else { var field = node.fields[i]; node[field] = this.parseExpression(); isSlice = this.skip(lexer.TOKEN_COLON) || isSlice; } } if (!isSlice) { throw rethrow(); } return new nodes.Array(tok.lineno, tok.colno, [node]); } }; } function sliceLookup(obj, start, stop, step) { obj = obj || []; if (start === null) { start = step < 0 ? obj.length - 1 : 0; } if (stop === null) { stop = step < 0 ? -1 : obj.length; } else if (stop < 0) { stop += obj.length; } if (start < 0) { start += obj.length; } var results = []; for (var i = start; ; i += step) { if (i < 0 || i > obj.length) { break; } if (step > 0 && i >= stop) { break; } if (step < 0 && i <= stop) { break; } results.push(runtime.memberLookup(obj, i)); } return results; } function hasOwnProp(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); } var ARRAY_MEMBERS = { pop: function pop(index) { if (index === void 0) { return this.pop(); } if (index >= this.length || index < 0) { throw new Error("KeyError"); } return this.splice(index, 1); }, append: function append(element) { return this.push(element); }, remove: function remove(element) { for (var i = 0; i < this.length; i++) { if (this[i] === element) { return this.splice(i, 1); } } throw new Error("ValueError"); }, count: function count(element) { var count2 = 0; for (var i = 0; i < this.length; i++) { if (this[i] === element) { count2++; } } return count2; }, index: function index(element) { var i; if ((i = this.indexOf(element)) === -1) { throw new Error("ValueError"); } return i; }, find: function find(element) { return this.indexOf(element); }, insert: function insert(index, elem) { return this.splice(index, 0, elem); } }; var OBJECT_MEMBERS = { items: function items() { return lib._entries(this); }, values: function values() { return lib._values(this); }, keys: function keys() { return lib.keys(this); }, get: function get(key, def) { var output = this[key]; if (output === void 0) { output = def; } return output; }, has_key: function has_key(key) { return hasOwnProp(this, key); }, pop: function pop(key, def) { var output = this[key]; if (output === void 0 && def !== void 0) { output = def; } else if (output === void 0) { throw new Error("KeyError"); } else { delete this[key]; } return output; }, popitem: function popitem() { var keys = lib.keys(this); if (!keys.length) { throw new Error("KeyError"); } var k = keys[0]; var val = this[k]; delete this[k]; return [k, val]; }, setdefault: function setdefault(key, def) { if (def === void 0) { def = null; } if (!(key in this)) { this[key] = def; } return this[key]; }, update: function update(kwargs) { lib._assign(this, kwargs); return null; } }; OBJECT_MEMBERS.iteritems = OBJECT_MEMBERS.items; OBJECT_MEMBERS.itervalues = OBJECT_MEMBERS.values; OBJECT_MEMBERS.iterkeys = OBJECT_MEMBERS.keys; runtime.memberLookup = function memberLookup(obj, val, autoescape) { if (arguments.length === 4) { return sliceLookup.apply(this, arguments); } obj = obj || {}; if (lib.isArray(obj) && hasOwnProp(ARRAY_MEMBERS, val)) { return ARRAY_MEMBERS[val].bind(obj); } if (lib.isObject(obj) && hasOwnProp(OBJECT_MEMBERS, val)) { return OBJECT_MEMBERS[val].bind(obj); } return orig_memberLookup.apply(this, arguments); }; return uninstall; } module3.exports = installCompat; } ]); }); } }); // src/main.ts var main_exports = {}; __export(main_exports, { default: () => LDAPSearch }); module.exports = __toCommonJS(main_exports); var import_ldapjs = __toESM(require_lib3()); // src/settings.ts var import_obsidian = require("obsidian"); var DEFAULT_SETTINGS = { server: "", port: "389", login: "", password: "", baseDN: "", fileNameTempalte: "", template: "", fields: "", path: "", photoFlag: false, photoPath: "", photoNameTemplate: "", photoField: "thumbnailPhoto" }; var LDAPSearchSettingTab = class extends import_obsidian.PluginSettingTab { constructor(app2, plugin) { super(app2, plugin); this.plugin = plugin; } display() { const { containerEl } = this; containerEl.empty(); containerEl.createEl("h2", { text: "LDAP Search settings." }); new import_obsidian.Setting(containerEl).setName("Login").setDesc("Login or BindDN for LDAP server auth").addText((text) => text.setValue(this.plugin.settings.login).onChange((value) => __async(this, null, function* () { this.plugin.settings.login = value; yield this.plugin.saveSettings(); }))); new import_obsidian.Setting(containerEl).setName("Password").setDesc("Password for LDAP server auth").addText((text) => text.setValue(this.plugin.settings.password).onChange((value) => __async(this, null, function* () { this.plugin.settings.password = value; yield this.plugin.saveSettings(); }))); new import_obsidian.Setting(containerEl).setName("Host").setDesc("LDAP server host").addText((text) => text.setValue(this.plugin.settings.server).onChange((value) => __async(this, null, function* () { this.plugin.settings.server = value; yield this.plugin.saveSettings(); }))); new import_obsidian.Setting(containerEl).setName("Port").setDesc("LDAP server port").addText((text) => text.setValue(this.plugin.settings.port).setPlaceholder("389").onChange((value) => __async(this, null, function* () { this.plugin.settings.port = value; yield this.plugin.saveSettings(); }))); new import_obsidian.Setting(containerEl).setName("BaseDN").setDesc(createFragment((fragment) => { fragment.append("Base object for search. See details ", fragment.createEl("a", { text: "here", href: "https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol#Search_and_compare" })); })).addText((text) => text.setValue(this.plugin.settings.baseDN).onChange((value) => __async(this, null, function* () { this.plugin.settings.baseDN = value; yield this.plugin.saveSettings(); }))); new import_obsidian.Setting(containerEl).setName("Fields").setDesc("Comma-separated list of fields to be retrieved from LDAP").addText((text) => text.setValue(this.plugin.settings.fields).onChange((value) => __async(this, null, function* () { this.plugin.settings.fields = value; yield this.plugin.saveSettings(); }))); new import_obsidian.Setting(containerEl).setName("Target folder").setDesc("Folder where the contact page will be saved").addText((text) => { text.setValue(this.plugin.settings.path).setPlaceholder("/people").onChange((value) => __async(this, null, function* () { this.plugin.settings.path = value; yield this.plugin.saveSettings(); })); }); new import_obsidian.Setting(containerEl).setName("File name template").setDesc(createFragment((fragment) => { fragment.append("Template for filling with fields received from LDAP. You can use ", fragment.createEl("a", { text: "Nunjucks", href: "https://mozilla.github.io/nunjucks/templating.html" }), " library specifications"); })).addText((text) => { text.setValue(this.plugin.settings.fileNameTempalte).setPlaceholder("{{ sn }} {{ givenName }}.md").onChange((value) => __async(this, null, function* () { this.plugin.settings.fileNameTempalte = value; yield this.plugin.saveSettings(); })); }); new import_obsidian.Setting(containerEl).setName("Page template").setDesc(createFragment((fragment) => { fragment.append("Template for filling with fields received from LDAP. You can use ", fragment.createEl("a", { text: "Nunjucks", href: "https://mozilla.github.io/nunjucks/templating.html" }), " library specifications"); })).addTextArea((text) => { text.setValue(this.plugin.settings.template).onChange((value) => __async(this, null, function* () { this.plugin.settings.template = value; yield this.plugin.saveSettings(); })); text.inputEl.setAttr("rows", 25); text.inputEl.setAttr("cols", 50); }); containerEl.createEl("h5", { text: "Advanced Settings" }); new import_obsidian.Setting(containerEl).setName("Store photo").setDesc("Enable or disable saving photo from ldap").addToggle((toggle) => { toggle.setValue(this.plugin.settings.photoFlag).onChange((value) => __async(this, null, function* () { this.plugin.settings.photoFlag = value; yield this.plugin.saveSettings(); })); }); new import_obsidian.Setting(containerEl).setName("Photo LDAP fields").setDesc("LDAP fields contains photo").addText((text) => { text.setValue(this.plugin.settings.photoField).onChange((value) => __async(this, null, function* () { this.plugin.settings.photoField = value; yield this.plugin.saveSettings(); })); }); new import_obsidian.Setting(containerEl).setName("Target folder").setDesc("Folder where the contact photo will be saved").addText((text) => { text.setValue(this.plugin.settings.photoPath).onChange((value) => __async(this, null, function* () { this.plugin.settings.photoPath = value; yield this.plugin.saveSettings(); })); }); new import_obsidian.Setting(containerEl).setName("Photo file name template").setDesc(createFragment((fragment) => { fragment.append("Template for photo file name. You can use the same fields as in the page template. The ", fragment.createEl("a", { text: "Nunjucks", href: "https://mozilla.github.io/nunjucks/templating.html" }), " library is used"); })).addText((text) => { text.setValue(this.plugin.settings.photoNameTemplate).onChange((value) => __async(this, null, function* () { this.plugin.settings.photoNameTemplate = value; yield this.plugin.saveSettings(); })); }); } }; // src/main.ts var import_obsidian3 = require("obsidian"); // src/modal.ts var import_obsidian2 = require("obsidian"); var LDAPModal = class extends import_obsidian2.Modal { constructor(app2, onSubmit) { super(app2); this.onSubmit = onSubmit; } onOpen() { const { contentEl } = this; contentEl.createEl("h1", { text: "Enter search term" }); new import_obsidian2.Setting(contentEl).setName("Search term").addText((text) => text.onChange((value) => { this.username = value; })); new import_obsidian2.Setting(contentEl).addButton((btn) => btn.setButtonText("Submit").setCta().onClick(() => { this.close(); this.onSubmit(this.username); })); } onClose() { const { contentEl } = this; contentEl.empty(); } }; // src/main.ts var import_nunjucks = __toESM(require_nunjucks()); var LDAPSearch = class extends import_obsidian3.Plugin { onload() { return __async(this, null, function* () { yield this.loadSettings(); console.log("LDAP search plugin started"); this.addCommand({ id: "ldap-contact-lookup", name: "LDAP contact lookup", callback: () => { this.ldapsearch(); } }); this.addSettingTab(new LDAPSearchSettingTab(this.app, this)); }); } ldapsearch() { return __async(this, null, function* () { const client = (0, import_ldapjs.createClient)({ url: [`ldap://${this.settings.server}:${this.settings.port}`] }); client.bind(this.settings.login, this.settings.password, (err) => { if (err) { new import_obsidian3.Notice(`LDAP Bind Error: ${err.message}`); console.error("Bind ERROR", err); } }); new LDAPModal(this.app, (username) => { const fields = this.settings.fields.split(","); if (this.settings.photoFlag && !fields.contains(this.settings.photoField)) { fields.push(this.settings.photoField); } const opts = { filter: `(sAMAccountname=${username})`, scope: "sub", attributes: fields }; client.search(this.settings.baseDN, opts, (err, res) => { res.on("searchEntry", (entry) => __async(this, null, function* () { console.log("Entry finded"); const myMap = /* @__PURE__ */ new Map(); entry.attributes.forEach((element) => __async(this, null, function* () { if (element.type !== this.settings.photoField) { myMap.set(element.type, element.vals[0]); } })); if (this.settings.photoFlag) { entry.attributes.forEach((element) => __async(this, null, function* () { if (element.type === this.settings.photoField) { yield app.vault.adapter.writeBinary(`${this.settings.photoPath}/${(0, import_nunjucks.renderString)(this.settings.photoNameTemplate, Object.fromEntries(myMap))}`, element.buffers[0]); } })); } console.log(`${this.settings.path}/${(0, import_nunjucks.renderString)(this.settings.fileNameTempalte, Object.fromEntries(myMap))}`); yield app.vault.adapter.write(`${this.settings.path}/${(0, import_nunjucks.renderString)(this.settings.fileNameTempalte, Object.fromEntries(myMap))}`, (0, import_nunjucks.renderString)(this.settings.template, Object.fromEntries(myMap))); })); res.on("error", (err2) => { new import_obsidian3.Notice(`LDAP Error: ${err2.message}`); console.error("error: " + err2); }); }); console.log("LDAP finish"); }).open(); }); } onunload() { console.log("LDAP Exit"); } loadSettings() { return __async(this, null, function* () { this.settings = Object.assign({}, DEFAULT_SETTINGS, yield this.loadData()); }); } saveSettings() { return __async(this, null, function* () { yield this.saveData(this.settings); }); } }; /*! Browser bundle of nunjucks 3.2.4 */