code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Browser = void 0;
const dns_txt_1 = __importDefault(require("./dns-txt"));
const dns_equal_1 = __importDefault(require("./utils/dns-equal"));
const events_1 = require("events");
const service_types_1 = require("./service-types");
const filter_service_1 = __importDefault(require("./utils/filter-service"));
const filter_txt_1 = __importDefault(require("./utils/filter-txt"));
const equal_txt_1 = __importDefault(require("./utils/equal-txt"));
const TLD = '.local';
const WILDCARD = '_services._dns-sd._udp' + TLD;
class Browser extends events_1.EventEmitter {
    constructor(mdns, opts, onup) {
        super();
        this.onresponse = undefined;
        this.serviceMap = {};
        this.wildcard = false;
        this._services = [];
        if (typeof opts === 'function')
            return new Browser(mdns, null, opts);
        this.mdns = mdns;
        this.txt = new dns_txt_1.default(opts !== null && opts.txt != null ? opts.txt : undefined);
        if (opts === null || opts.type === undefined) {
            this.name = WILDCARD;
            this.wildcard = true;
        }
        else {
            this.name = (0, service_types_1.toString)({ name: opts.type, protocol: opts.protocol || 'tcp' }) + TLD;
            if (opts.name)
                this.name = opts.name + '.' + this.name;
            this.wildcard = false;
        }
        if (opts != null && opts.txt !== undefined)
            this.txtQuery = (0, filter_txt_1.default)(opts.txt);
        if (onup)
            this.on('up', onup);
        this.start();
    }
    start() {
        if (this.onresponse || this.name === undefined)
            return;
        var self = this;
        var nameMap = {};
        if (!this.wildcard)
            nameMap[this.name] = true;
        this.onresponse = (packet, rinfo) => {
            if (self.wildcard) {
                packet.answers.forEach((answer) => {
                    if (answer.type !== 'PTR' || answer.name !== self.name || answer.name in nameMap)
                        return;
                    nameMap[answer.data] = true;
                    self.mdns.query(answer.data, 'PTR');
                });
            }
            Object.keys(nameMap).forEach(function (name) {
                self.goodbyes(name, packet).forEach(self.removeService.bind(self));
                var matches = self.buildServicesFor(name, packet, self.txt, rinfo);
                if (matches.length === 0)
                    return;
                matches.forEach((service) => {
                    if (self.serviceMap[service.fqdn]) {
                        self.updateService(service);
                        return;
                    }
                    self.addService(service);
                });
            });
        };
        this.mdns.on('response', this.onresponse);
        this.update();
    }
    stop() {
        if (!this.onresponse)
            return;
        this.mdns.removeListener('response', this.onresponse);
        this.onresponse = undefined;
    }
    update() {
        this.mdns.query(this.name, 'PTR');
    }
    get services() {
        return this._services;
    }
    addService(service) {
        if ((0, filter_service_1.default)(service, this.txtQuery) === false)
            return;
        this._services.push(service);
        this.serviceMap[service.fqdn] = true;
        this.emit('up', service);
    }
    updateService(service) {
        var _a;
        if ((0, equal_txt_1.default)(service.txt, ((_a = this._services.find((s) => (0, dns_equal_1.default)(s.fqdn, service.fqdn))) === null || _a === void 0 ? void 0 : _a.txt) || {}))
            return;
        if (!(0, filter_service_1.default)(service, this.txtQuery)) {
            this.removeService(service.fqdn);
            return;
        }
        this._services = this._services.map(function (s) {
            if (!(0, dns_equal_1.default)(s.fqdn, service.fqdn))
                return s;
            return service;
        });
        this.emit('txt-update', service);
    }
    removeService(fqdn) {
        var service, index;
        this._services.some(function (s, i) {
            if ((0, dns_equal_1.default)(s.fqdn, fqdn)) {
                service = s;
                index = i;
                return true;
            }
        });
        if (!service || index === undefined)
            return;
        this._services.splice(index, 1);
        delete this.serviceMap[fqdn];
        this.emit('down', service);
    }
    goodbyes(name, packet) {
        return packet.answers.concat(packet.additionals)
            .filter((rr) => rr.type === 'PTR' && rr.ttl === 0 && (0, dns_equal_1.default)(rr.name, name))
            .map((rr) => rr.data);
    }
    buildServicesFor(name, packet, txt, referer) {
        var records = packet.answers.concat(packet.additionals).filter((rr) => rr.ttl > 0);
        return records
            .filter((rr) => rr.type === 'PTR' && (0, dns_equal_1.default)(rr.name, name))
            .map((ptr) => {
            const service = {
                addresses: [],
                subtypes: []
            };
            records.filter((rr) => {
                return (rr.type === 'PTR' && (0, dns_equal_1.default)(rr.data, ptr.data) && rr.name.includes('._sub'));
            }).forEach((rr) => {
                const types = (0, service_types_1.toType)(rr.name);
                service.subtypes.push(types.subtype);
            });
            records
                .filter((rr) => {
                return (rr.type === 'SRV' || rr.type === 'TXT') && (0, dns_equal_1.default)(rr.name, ptr.data);
            })
                .forEach((rr) => {
                if (rr.type === 'SRV') {
                    var parts = rr.name.split('.');
                    var name = parts[0];
                    var types = (0, service_types_1.toType)(parts.slice(1, -1).join('.'));
                    service.name = name;
                    service.fqdn = rr.name;
                    service.host = rr.data.target;
                    service.referer = referer;
                    service.port = rr.data.port;
                    service.type = types.name;
                    service.protocol = types.protocol;
                }
                else if (rr.type === 'TXT') {
                    service.rawTxt = rr.data;
                    service.txt = this.txt.decodeAll(rr.data);
                }
            });
            if (!service.name)
                return;
            records
                .filter((rr) => (rr.type === 'A' || rr.type === 'AAAA') && (0, dns_equal_1.default)(rr.name, service.host))
                .forEach((rr) => service.addresses.push(rr.data));
            return service;
        })
            .filter((rr) => !!rr);
    }
}
exports.Browser = Browser;
exports.default = Browser;
//# sourceMappingURL=browser.js.map


code:
/// <reference types="node" />
import KeyValue from './KeyValue';
export declare class DnsTxt {
    private binary;
    constructor(opts?: KeyValue);
    encode(data?: KeyValue): Buffer[];
    decode(buffer: Buffer): KeyValue;
    decodeAll(buffer: Array<Buffer>): KeyValue;
}
export default DnsTxt;

license: mit


code:
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
exports.DnsTxt = void 0;
class DnsTxt {
    constructor(opts = {}) {
        this.binary = opts ? opts.binary : false;
    }
    encode(data = {}) {
        return Object.entries(data)
            .map(([key, value]) => {
            let item = `${key}=${value}`;
            return Buffer.from(item);
        });
    }
    decode(buffer) {
        var data = {};
        try {
            let format = buffer.toString();
            let parts = format.split(/=(.+)/);
            let key = parts[0];
            let value = parts[1];
            data[key] = value;
        }
        catch (_) { }
        return data;
    }
    decodeAll(buffer) {
        return buffer
            .filter(i => i.length > 1)
            .map(i => this.decode(i))
            .reduce((prev, curr) => {
            var obj = prev;
            let [key] = Object.keys(curr);
            let [value] = Object.values(curr);
            obj[key] = value;
            return obj;
        }, {});
    }
}
exports.DnsTxt = DnsTxt;
exports.default = DnsTxt;
//# sourceMappingURL=dns-txt.js.map


code:
import { ServiceConfig, ServiceRecord } from './service';
export declare class Server {
    mdns: any;
    private registry;
    private errorCallback;
    constructor(opts: Partial<ServiceConfig>, errorCallback?: Function | undefined);
    register(records: Array<ServiceRecord> | ServiceRecord): void;
    unregister(records: Array<ServiceRecord> | ServiceRecord): void;
    private respondToQuery;
    private recordsFor;
    private isDuplicateRecord;
    private unique;
}
export default Server;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Server = void 0;
const multicast_dns_1 = __importDefault(require("multicast-dns"));
const es6_1 = __importDefault(require("fast-deep-equal/es6"));
const dns_equal_1 = __importDefault(require("./utils/dns-equal"));
class Server {
    constructor(opts, errorCallback) {
        this.registry = {};
        this.mdns = (0, multicast_dns_1.default)(opts);
        this.mdns.setMaxListeners(0);
        this.mdns.on('query', this.respondToQuery.bind(this));
        this.errorCallback = errorCallback !== null && errorCallback !== void 0 ? errorCallback : function (err) { throw err; };
    }
    register(records) {
        const shouldRegister = (record) => {
            var subRegistry = this.registry[record.type];
            if (!subRegistry) {
                subRegistry = this.registry[record.type] = [];
            }
            else if (subRegistry.some(this.isDuplicateRecord(record))) {
                return;
            }
            subRegistry.push(record);
        };
        if (Array.isArray(records)) {
            records.forEach(shouldRegister);
        }
        else {
            shouldRegister(records);
        }
    }
    unregister(records) {
        const shouldUnregister = (record) => {
            let type = record.type;
            if (!(type in this.registry)) {
                return;
            }
            this.registry[type] = this.registry[type].filter((i) => i.name !== record.name);
        };
        if (Array.isArray(records)) {
            records.forEach(shouldUnregister);
        }
        else {
            shouldUnregister(records);
        }
    }
    respondToQuery(query) {
        let self = this;
        query.questions.forEach((question) => {
            var type = question.type;
            var name = question.name;
            var answers = type === 'ANY'
                ? Object.keys(self.registry).map(self.recordsFor.bind(self, name)).flat(1)
                : self.recordsFor(name, type);
            if (answers.length === 0)
                return;
            var additionals = [];
            if (type !== 'ANY') {
                answers.forEach((answer) => {
                    if (answer.type !== 'PTR')
                        return;
                    additionals = additionals
                        .concat(self.recordsFor(answer.data, 'SRV'))
                        .concat(self.recordsFor(answer.data, 'TXT'));
                });
                additionals
                    .filter(function (record) {
                    return record.type === 'SRV';
                })
                    .map(function (record) {
                    return record.data.target;
                })
                    .filter(this.unique())
                    .forEach(function (target) {
                    additionals = additionals
                        .concat(self.recordsFor(target, 'A'))
                        .concat(self.recordsFor(target, 'AAAA'));
                });
            }
            self.mdns.respond({ answers: answers, additionals: additionals }, (err) => {
                if (err) {
                    this.errorCallback(err);
                }
            });
        });
    }
    recordsFor(name, type) {
        if (!(type in this.registry)) {
            return [];
        }
        return this.registry[type].filter((record) => {
            var _name = ~name.indexOf('.') ? record.name : record.name.split('.')[0];
            return (0, dns_equal_1.default)(_name, name);
        });
    }
    isDuplicateRecord(a) {
        return (b) => {
            return a.type === b.type &&
                a.name === b.name &&
                (0, es6_1.default)(a.data, b.data);
        };
    }
    unique() {
        var set = [];
        return (obj) => {
            if (~set.indexOf(obj))
                return false;
            set.push(obj);
            return true;
        };
    }
}
exports.Server = Server;
exports.default = Server;
//# sourceMappingURL=mdns-server.js.map


code:
import Server from './mdns-server';
import Service, { ServiceConfig } from './service';
export declare class Registry {
    private server;
    private services;
    constructor(server: Server);
    publish(config: ServiceConfig): Service;
    unpublishAll(callback: CallableFunction | undefined): void;
    destroy(): void;
    private probe;
    private announce;
    private teardown;
}
export default Registry;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Registry = void 0;
const dns_equal_1 = __importDefault(require("./utils/dns-equal"));
const service_1 = __importDefault(require("./service"));
const REANNOUNCE_MAX_MS = 60 * 60 * 1000;
const REANNOUNCE_FACTOR = 3;
const noop = function () { };
class Registry {
    constructor(server) {
        this.services = [];
        this.server = server;
    }
    publish(config) {
        function start(service, registry, opts) {
            if (service.activated)
                return;
            service.activated = true;
            registry.services.push(service);
            if (!(service instanceof service_1.default))
                return;
            if (opts === null || opts === void 0 ? void 0 : opts.probe) {
                registry.probe(registry.server.mdns, service, (exists) => {
                    if (exists) {
                        if (service.stop !== undefined)
                            service.stop();
                        console.log(new Error('Service name is already in use on the network'));
                        return;
                    }
                    registry.announce(registry.server, service);
                });
            }
            else {
                registry.announce(registry.server, service);
            }
        }
        function stop(service, registry, callback) {
            if (!callback)
                callback = noop;
            if (!service.activated)
                return process.nextTick(callback);
            if (!(service instanceof service_1.default))
                return process.nextTick(callback);
            registry.teardown(registry.server, service, callback);
            const index = registry.services.indexOf(service);
            if (index !== -1)
                registry.services.splice(index, 1);
        }
        const service = new service_1.default(config);
        service.start = start.bind(null, service, this);
        service.stop = stop.bind(null, service, this);
        service.start({ probe: config.probe !== false });
        return service;
    }
    unpublishAll(callback) {
        this.teardown(this.server, this.services, callback);
        this.services = [];
    }
    destroy() {
        this.services.map(service => service.destroyed = true);
    }
    probe(mdns, service, callback) {
        var sent = false;
        var retries = 0;
        var timer;
        const send = () => {
            if (!service.activated || service.destroyed)
                return;
            mdns.query(service.fqdn, 'ANY', function () {
                sent = true;
                timer = setTimeout(++retries < 3 ? send : done, 250);
                timer.unref();
            });
        };
        const onresponse = (packet) => {
            if (!sent)
                return;
            if (packet.answers.some(matchRR) || packet.additionals.some(matchRR))
                done(true);
        };
        const matchRR = (rr) => {
            return (0, dns_equal_1.default)(rr.name, service.fqdn);
        };
        const done = (exists) => {
            mdns.removeListener('response', onresponse);
            clearTimeout(timer);
            callback(!!exists);
        };
        mdns.on('response', onresponse);
        setTimeout(send, Math.random() * 250);
    }
    announce(server, service) {
        var delay = 1000;
        var packet = service.records();
        server.register(packet);
        const broadcast = () => {
            if (!service.activated || service.destroyed)
                return;
            server.mdns.respond(packet, function () {
                if (!service.published) {
                    service.activated = true;
                    service.published = true;
                    service.emit('up');
                }
                delay = delay * REANNOUNCE_FACTOR;
                if (delay < REANNOUNCE_MAX_MS && !service.destroyed) {
                    setTimeout(broadcast, delay).unref();
                }
            });
        };
        broadcast();
    }
    teardown(server, services, callback) {
        if (!Array.isArray(services))
            services = [services];
        services = services.filter((service) => service.activated);
        var records = services.flatMap(function (service) {
            service.activated = false;
            var records = service.records();
            records.forEach((record) => {
                record.ttl = 0;
            });
            return records;
        });
        if (records.length === 0)
            return callback && process.nextTick(callback);
        server.unregister(records);
        server.mdns.respond(records, function () {
            services.forEach(function (service) {
                service.published = false;
            });
            if (typeof callback === "function") {
                callback.apply(null, arguments);
            }
        });
    }
}
exports.Registry = Registry;
exports.default = Registry;
//# sourceMappingURL=registry.js.map


code:
export interface ServiceType {
    name?: string;
    protocol?: 'tcp' | 'udp' | string | null | undefined;
    subtype?: string | undefined;
}
export declare const toString: (data: ServiceType) => any;
export declare const toType: (string: string) => ServiceType;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toType = exports.toString = void 0;
const Prefix = (name) => {
    return '_' + name;
};
const AllowedProp = (key) => {
    let keys = ['name', 'protocol', 'subtype'];
    return keys.includes(key);
};
const toString = (data) => {
    let formatted = {
        name: data.name,
        protocol: data.protocol,
        subtype: data.subtype
    };
    let entries = Object.entries(formatted);
    return entries
        .filter(([key, val]) => AllowedProp(key) && val !== undefined)
        .reduce((prev, [key, val]) => {
        switch (typeof val) {
            case 'object':
                val.map((i) => prev.push(Prefix(i)));
                break;
            default:
                prev.push(Prefix(val));
                break;
        }
        return prev;
    }, [])
        .join('.');
};
exports.toString = toString;
const toType = (string) => {
    let parts = string.split('.');
    let subtype;
    for (let i in parts) {
        if (parts[i][0] !== '_')
            continue;
        parts[i] = parts[i].slice(1);
    }
    if (parts.includes('sub')) {
        subtype = parts.shift();
        parts.shift();
    }
    return {
        name: parts.shift(),
        protocol: parts.shift() || null,
        subtype: subtype
    };
};
exports.toType = toType;
//# sourceMappingURL=service-types.js.map


code:
/// <reference types="node" />
import KeyValue from './KeyValue';
import { EventEmitter } from 'events';
export interface ServiceConfig {
    name: string;
    type: string;
    port: number;
    protocol?: 'tcp' | 'udp';
    host?: string;
    fqdn?: string;
    subtypes?: Array<string>;
    txt?: KeyValue;
    probe?: boolean;
    disableIPv6?: boolean;
}
export interface ServiceRecord {
    name: string;
    type: 'PTR' | 'SRV' | 'TXT' | 'A' | 'AAAA';
    ttl: number;
    data: KeyValue | string | any;
}
export interface ServiceReferer {
    address: string;
    family: 'IPv4' | 'IPv6';
    port: number;
    size: number;
}
export declare class Service extends EventEmitter {
    name: string;
    type: string;
    protocol: 'tcp' | 'udp';
    port: number;
    host: string;
    fqdn: string;
    txt?: any;
    subtypes?: Array<string>;
    addresses?: Array<string>;
    referer?: ServiceReferer;
    disableIPv6: boolean;
    probe: boolean;
    published: boolean;
    activated: boolean;
    destroyed: boolean;
    start?: CallableFunction;
    stop?: CallableFunction;
    private txtService;
    constructor(config: ServiceConfig);
    records(): Array<ServiceRecord>;
    private RecordPTR;
    private RecordSubtypePTR;
    private RecordSRV;
    private RecordTXT;
    private RecordA;
    private RecordAAAA;
}
export default Service;


code:
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Service = void 0;
const os_1 = __importDefault(require("os"));
const dns_txt_1 = __importDefault(require("./dns-txt"));
const events_1 = require("events");
const service_types_1 = require("./service-types");
const TLD = '.local';
class Service extends events_1.EventEmitter {
    constructor(config) {
        super();
        this.probe = true;
        this.published = false;
        this.activated = false;
        this.destroyed = false;
        this.txtService = new dns_txt_1.default();
        if (!config.name)
            throw new Error('ServiceConfig requires `name` property to be set');
        if (!config.type)
            throw new Error('ServiceConfig requires `type` property to be set');
        if (!config.port)
            throw new Error('ServiceConfig requires `port` property to be set');
        this.name = config.name.split('.').join('-');
        this.protocol = config.protocol || 'tcp';
        this.type = (0, service_types_1.toString)({ name: config.type, protocol: this.protocol });
        this.port = config.port;
        this.host = config.host || os_1.default.hostname();
        this.fqdn = `${this.name}.${this.type}${TLD}`;
        this.txt = config.txt;
        this.subtypes = config.subtypes;
        this.disableIPv6 = !!config.disableIPv6;
    }
    records() {
        var records = [this.RecordPTR(this), this.RecordSRV(this), this.RecordTXT(this)];
        for (let subtype of this.subtypes || []) {
            records.push(this.RecordSubtypePTR(this, subtype));
        }
        let ifaces = Object.values(os_1.default.networkInterfaces());
        for (let iface of ifaces) {
            let addrs = iface;
            for (let addr of addrs) {
                if (addr.internal || addr.mac === '00:00:00:00:00:00')
                    continue;
                switch (addr.family) {
                    case 'IPv4':
                        records.push(this.RecordA(this, addr.address));
                        break;
                    case 'IPv6':
                        if (this.disableIPv6)
                            break;
                        records.push(this.RecordAAAA(this, addr.address));
                        break;
                }
            }
        }
        return records;
    }
    RecordPTR(service) {
        return {
            name: `${service.type}${TLD}`,
            type: 'PTR',
            ttl: 28800,
            data: service.fqdn
        };
    }
    RecordSubtypePTR(service, subtype) {
        return {
            name: `_${subtype}._sub.${service.type}${TLD}`,
            type: 'PTR',
            ttl: 28800,
            data: `${service.name}.${service.type}${TLD}`
        };
    }
    RecordSRV(service) {
        return {
            name: service.fqdn,
            type: 'SRV',
            ttl: 120,
            data: {
                port: service.port,
                target: service.host
            }
        };
    }
    RecordTXT(service) {
        return {
            name: service.fqdn,
            type: 'TXT',
            ttl: 4500,
            data: this.txtService.encode(service.txt)
        };
    }
    RecordA(service, ip) {
        return {
            name: service.host,
            type: 'A',
            ttl: 120,
            data: ip
        };
    }
    RecordAAAA(service, ip) {
        return {
            name: service.host,
            type: 'AAAA',
            ttl: 120,
            data: ip
        };
    }
}
exports.Service = Service;
exports.default = Service;
//# sourceMappingURL=service.js.map


code: export default function dnsEqual(a: string, b: string): boolean;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const capitalLetterRegex = /[A-Z]/g;
function toLowerCase(input) {
    return input.toLowerCase();
}
function dnsEqual(a, b) {
    const aFormatted = a.replace(capitalLetterRegex, toLowerCase);
    const bFormatted = b.replace(capitalLetterRegex, toLowerCase);
    return aFormatted === bFormatted;
}
exports.default = dnsEqual;
//# sourceMappingURL=dns-equal.js.map


code: export default function equalTxt(a: Record<string, string>, b: Record<string, string>): boolean;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function equalTxt(a, b) {
    if (a === undefined || b === undefined)
        return false;
    let aKeys = Object.keys(a);
    let bKeys = Object.keys(b);
    if (aKeys.length != bKeys.length)
        return false;
    for (let key of aKeys) {
        if (a[key] != b[key])
            return false;
    }
    return true;
}
exports.default = equalTxt;
//# sourceMappingURL=equal-txt.js.map


code:
import KeyValue from '../KeyValue';
import Service from '../service';
declare const _default: (service: Service, txtQuery: KeyValue | undefined) => boolean;
export default _default;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = (service, txtQuery) => {
    if (txtQuery === undefined)
        return true;
    let serviceTxt = service.txt;
    let query = Object.entries(txtQuery)
        .map(([key, value]) => {
        let queryValue = serviceTxt[key];
        if (queryValue === undefined)
            return false;
        if (value != queryValue)
            return false;
        return true;
    });
    if (query.length == 0)
        return true;
    if (query.includes(false))
        return false;
    return true;
};
//# sourceMappingURL=filter-service.js.map


code:
import KeyValue from '../KeyValue';
declare const _default: (data: KeyValue) => {};
export default _default;


code:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = (data) => Object.keys(data)
    .filter((key) => !key.includes('binary'))
    .reduce((cur, key) => { return Object.assign(cur, { [key]: data[key] }); }, {});
//# sourceMappingURL=filter-txt.js.map


bonjour-service

description: A Bonjour/Zeroconf implementation in TypeScript

test: standard --fix && tape test/*.js

build: tsc --removeComments true

dev: ts-node-dev --respawn --transpile-only ./src/index.ts

example:simple: node examples/simple

type: git

keywords: bonjour zeroconf zero configuration mdns dns service discovery multicast broadcast dns-sd

author: ON LX Lited <team@onlx.ltd> (https://labs.onlx.ltd)

license: MIT


code:
declare module 'multicast-dns' {
    function init(opts: { [key: string]: any })
    export = init
}


code:
#boolbase
This very simple module provides two basic functions, one that always returns true (`trueFunc`) and one that always returns false (`falseFunc`).

###WTF?

By having only a single instance of these functions around, it's possible to do some nice optimizations. Eg. [`CSSselect`](https://github.com/fb55/CSSselect) uses these functions to determine whether a selector won't match any elements. If that's the case, the DOM doesn't even have to be touched.

###And why is this a separate module?

I'm trying to modularize `CSSselect` and most modules depend on these functions. IMHO, having a separate module is the easiest solution to this problem.


code:
module.exports = {
	trueFunc: function trueFunc(){
		return true;
	},
	falseFunc: function falseFunc(){
		return false;
	}
};


boolbase

description: two functions: One that returns true, one that returns false

test: echo "Error: no test specified" && exit 1

keywords: boolean function

author: Felix Boehm <me@feedic.com>

license: ISC


code:
# brace-expansion

[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html),
as known from sh/bash, in JavaScript.

[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion)
[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion)
[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/)

[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion)

## Example

```js
var expand = require('brace-expansion');

expand('file-{a,b,c}.jpg')
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']

expand('-v{,,}')
// => ['-v', '-v', '-v']

expand('file{0..2}.jpg')
// => ['file0.jpg', 'file1.jpg', 'file2.jpg']

expand('file-{a..c}.jpg')
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']

expand('file{2..0}.jpg')
// => ['file2.jpg', 'file1.jpg', 'file0.jpg']

expand('file{0..4..2}.jpg')
// => ['file0.jpg', 'file2.jpg', 'file4.jpg']

expand('file-{a..e..2}.jpg')
// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg']

expand('file{00..10..5}.jpg')
// => ['file00.jpg', 'file05.jpg', 'file10.jpg']

expand('{{A..C},{a..c}}')
// => ['A', 'B', 'C', 'a', 'b', 'c']

expand('ppp{,config,oe{,conf}}')
// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf']
```

## API

```js
var expand = require('brace-expansion');
```

### var expanded = expand(str)

Return an array of all possible and valid expansions of `str`. If none are
found, `[str]` is returned.

Valid expansions are:

```js
/^(.*,)+(.+)?$/
// {a,b,...}
```

A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`.

```js
/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
// {x..y[..incr]}
```

A numeric sequence from `x` to `y` inclusive, with optional increment.
If `x` or `y` start with a leading `0`, all the numbers will be padded
to have equal length. Negative numbers and backwards iteration work too.

```js
/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
// {x..y[..incr]}
```

An alphabetic sequence from `x` to `y` inclusive, with optional increment.
`x` and `y` must be exactly one character, and if given, `incr` must be a
number.

For compatibility reasons, the string `${` is not eligible for brace expansion.

## Installation

With [npm](https://npmjs.org) do:

```bash
npm install brace-expansion
```

## Contributors

- [Julian Gruber](https://github.com/juliangruber)
- [Isaac Z. Schlueter](https://github.com/isaacs)

## Sponsors

This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)!

Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)!

## License

(MIT)

Copyright (c) 2013 Julian Gruber <julian@juliangruber.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


code:
var concatMap = require('concat-map');
var balanced = require('balanced-match');

module.exports = expandTop;

var escSlash = '\0SLASH'+Math.random()+'\0';
var escOpen = '\0OPEN'+Math.random()+'\0';
var escClose = '\0CLOSE'+Math.random()+'\0';
var escComma = '\0COMMA'+Math.random()+'\0';
var escPeriod = '\0PERIOD'+Math.random()+'\0';

function numeric(str) {
  return parseInt(str, 10) == str
    ? parseInt(str, 10)
    : str.charCodeAt(0);
}

function escapeBraces(str) {
  return str.split('\\\\').join(escSlash)
            .split('\\{').join(escOpen)
            .split('\\}').join(escClose)
            .split('\\,').join(escComma)
            .split('\\.').join(escPeriod);
}

function unescapeBraces(str) {
  return str.split(escSlash).join('\\')
            .split(escOpen).join('{')
            .split(escClose).join('}')
            .split(escComma).join(',')
            .split(escPeriod).join('.');
}

// Basically just str.split(","), but handling cases
// where we have nested braced sections, which should be
// treated as individual members, like {a,{b,c},d}
function parseCommaParts(str) {
  if (!str)
    return [''];

  var parts = [];
  var m = balanced('{', '}', str);

  if (!m)
    return str.split(',');

  var pre = m.pre;
  var body = m.body;
  var post = m.post;
  var p = pre.split(',');

  p[p.length-1] += '{' + body + '}';
  var postParts = parseCommaParts(post);
  if (post.length) {
    p[p.length-1] += postParts.shift();
    p.push.apply(p, postParts);
  }

  parts.push.apply(parts, p);

  return parts;
}

function expandTop(str) {
  if (!str)
    return [];

  // I don't know why Bash 4.3 does this, but it does.
  // Anything starting with {} will have the first two bytes preserved
  // but *only* at the top level, so {},a}b will not expand to anything,
  // but a{},b}c will be expanded to [a}c,abc].
  // One could argue that this is a bug in Bash, but since the goal of
  // this module is to match Bash's rules, we escape a leading {}
  if (str.substr(0, 2) === '{}') {
    str = '\\{\\}' + str.substr(2);
  }

  return expand(escapeBraces(str), true).map(unescapeBraces);
}

function identity(e) {
  return e;
}

function embrace(str) {
  return '{' + str + '}';
}
function isPadded(el) {
  return /^-?0\d/.test(el);
}

function lte(i, y) {
  return i <= y;
}
function gte(i, y) {
  return i >= y;
}

function expand(str, isTop) {
  var expansions = [];

  var m = balanced('{', '}', str);
  if (!m || /\$$/.test(m.pre)) return [str];

  var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
  var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
  var isSequence = isNumericSequence || isAlphaSequence;
  var isOptions = m.body.indexOf(',') >= 0;
  if (!isSequence && !isOptions) {
    // {a},b}
    if (m.post.match(/,.*\}/)) {
      str = m.pre + '{' + m.body + escClose + m.post;
      return expand(str);
    }
    return [str];
  }

  var n;
  if (isSequence) {
    n = m.body.split(/\.\./);
  } else {
    n = parseCommaParts(m.body);
    if (n.length === 1) {
      // x{{a,b}}y ==> x{a}y x{b}y
      n = expand(n[0], false).map(embrace);
      if (n.length === 1) {
        var post = m.post.length
          ? expand(m.post, false)
          : [''];
        return post.map(function(p) {
          return m.pre + n[0] + p;
        });
      }
    }
  }

  // at this point, n is the parts, and we know it's not a comma set
  // with a single entry.

  // no need to expand pre, since it is guaranteed to be free of brace-sets
  var pre = m.pre;
  var post = m.post.length
    ? expand(m.post, false)
    : [''];

  var N;

  if (isSequence) {
    var x = numeric(n[0]);
    var y = numeric(n[1]);
    var width = Math.max(n[0].length, n[1].length)
    var incr = n.length == 3
      ? Math.abs(numeric(n[2]))
      : 1;
    var test = lte;
    var reverse = y < x;
    if (reverse) {
      incr *= -1;
      test = gte;
    }
    var pad = n.some(isPadded);

    N = [];

    for (var i = x; test(i, y); i += incr) {
      var c;
      if (isAlphaSequence) {
        c = String.fromCharCode(i);
        if (c === '\\')
          c = '';
      } else {
        c = String(i);
        if (pad) {
          var need = width - c.length;
          if (need > 0) {
            var z = new Array(need + 1).join('0');
            if (i < 0)
              c = '-' + z + c.slice(1);
            else
              c = z + c;
          }
        }
      }
      N.push(c);
    }
  } else {
    N = concatMap(n, function(el) { return expand(el, false) });
  }

  for (var j = 0; j < N.length; j++) {
    for (var k = 0; k < post.length; k++) {
      var expansion = pre + N[j] + post[k];
      if (!isTop || isSequence || expansion)
        expansions.push(expansion);
    }
  }

  return expansions;
}


brace-expansion

description: Brace expansion as known from sh/bash

test: tape test/*.js

gentest: bash test/generate.sh

bench: matcha test/perf/bench.js


code:
# braces [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W8YFZ425KND68) [![NPM version](https://img.shields.io/npm/v/braces.svg?style=flat)](https://www.npmjs.com/package/braces) [![NPM monthly downloads](https://img.shields.io/npm/dm/braces.svg?style=flat)](https://npmjs.org/package/braces) [![NPM total downloads](https://img.shields.io/npm/dt/braces.svg?style=flat)](https://npmjs.org/package/braces) [![Linux Build Status](https://img.shields.io/travis/micromatch/braces.svg?style=flat&label=Travis)](https://travis-ci.org/micromatch/braces)

> Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.

Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.

## Install

Install with [npm](https://www.npmjs.com/):

```sh
$ npm install --save braces
```

## v3.0.0 Released!!

See the [changelog](CHANGELOG.md) for details.

## Why use braces?

Brace patterns make globs more powerful by adding the ability to match specific ranges and sequences of characters.

- **Accurate** - complete support for the [Bash 4.3 Brace Expansion](www.gnu.org/software/bash/) specification (passes all of the Bash braces tests)
- **[fast and performant](#benchmarks)** - Starts fast, runs fast and [scales well](#performance) as patterns increase in complexity.
- **Organized code base** - The parser and compiler are easy to maintain and update when edge cases crop up.
- **Well-tested** - Thousands of test assertions, and passes all of the Bash, minimatch, and [brace-expansion](https://github.com/juliangruber/brace-expansion) unit tests (as of the date this was written).
- **Safer** - You shouldn't have to worry about users defining aggressive or malicious brace patterns that can break your application. Braces takes measures to prevent malicious regex that can be used for DDoS attacks (see [catastrophic backtracking](https://www.regular-expressions.info/catastrophic.html)).
- [Supports lists](#lists) - (aka "sets") `a/{b,c}/d` => `['a/b/d', 'a/c/d']`
- [Supports sequences](#sequences) - (aka "ranges") `{01..03}` => `['01', '02', '03']`
- [Supports steps](#steps) - (aka "increments") `{2..10..2}` => `['2', '4', '6', '8', '10']`
- [Supports escaping](#escaping) - To prevent evaluation of special characters.

## Usage

The main export is a function that takes one or more brace `patterns` and `options`.

```js
const braces = require('braces');
// braces(patterns[, options]);

console.log(braces(['{01..05}', '{a..e}']));
//=> ['(0[1-5])', '([a-e])']

console.log(braces(['{01..05}', '{a..e}'], { expand: true }));
//=> ['01', '02', '03', '04', '05', 'a', 'b', 'c', 'd', 'e']
```

### Brace Expansion vs. Compilation

By default, brace patterns are compiled into strings that are optimized for creating regular expressions and matching.

**Compiled**

```js
console.log(braces('a/{x,y,z}/b'));
//=> ['a/(x|y|z)/b']
console.log(braces(['a/{01..20}/b', 'a/{1..5}/b']));
//=> [ 'a/(0[1-9]|1[0-9]|20)/b', 'a/([1-5])/b' ]
```

**Expanded**

Enable brace expansion by setting the `expand` option to true, or by using [braces.expand()](#expand) (returns an array similar to what you'd expect from Bash, or `echo {1..5}`, or [minimatch](https://github.com/isaacs/minimatch)):

```js
console.log(braces('a/{x,y,z}/b', { expand: true }));
//=> ['a/x/b', 'a/y/b', 'a/z/b']

console.log(braces.expand('{01..10}'));
//=> ['01','02','03','04','05','06','07','08','09','10']
```

### Lists

Expand lists (like Bash "sets"):

```js
console.log(braces('a/{foo,bar,baz}/*.js'));
//=> ['a/(foo|bar|baz)/*.js']

console.log(braces.expand('a/{foo,bar,baz}/*.js'));
//=> ['a/foo/*.js', 'a/bar/*.js', 'a/baz/*.js']
```

### Sequences

Expand ranges of characters (like Bash "sequences"):

```js
console.log(braces.expand('{1..3}')); // ['1', '2', '3']
console.log(braces.expand('a/{1..3}/b')); // ['a/1/b', 'a/2/b', 'a/3/b']
console.log(braces('{a..c}', { expand: true })); // ['a', 'b', 'c']
console.log(braces('foo/{a..c}', { expand: true })); // ['foo/a', 'foo/b', 'foo/c']

// supports zero-padded ranges
console.log(braces('a/{01..03}/b')); //=> ['a/(0[1-3])/b']
console.log(braces('a/{001..300}/b')); //=> ['a/(0{2}[1-9]|0[1-9][0-9]|[12][0-9]{2}|300)/b']
```

See [fill-range](https://github.com/jonschlinkert/fill-range) for all available range-expansion options.

### Steppped ranges

Steps, or increments, may be used with ranges:

```js
console.log(braces.expand('{2..10..2}'));
//=> ['2', '4', '6', '8', '10']

console.log(braces('{2..10..2}'));
//=> ['(2|4|6|8|10)']
```

When the [.optimize](#optimize) method is used, or [options.optimize](#optionsoptimize) is set to true, sequences are passed to [to-regex-range](https://github.com/jonschlinkert/to-regex-range) for expansion.

### Nesting

Brace patterns may be nested. The results of each expanded string are not sorted, and left to right order is preserved.

**"Expanded" braces**

```js
console.log(braces.expand('a{b,c,/{x,y}}/e'));
//=> ['ab/e', 'ac/e', 'a/x/e', 'a/y/e']

console.log(braces.expand('a/{x,{1..5},y}/c'));
//=> ['a/x/c', 'a/1/c', 'a/2/c', 'a/3/c', 'a/4/c', 'a/5/c', 'a/y/c']
```

**"Optimized" braces**

```js
console.log(braces('a{b,c,/{x,y}}/e'));
//=> ['a(b|c|/(x|y))/e']

console.log(braces('a/{x,{1..5},y}/c'));
//=> ['a/(x|([1-5])|y)/c']
```

### Escaping

**Escaping braces**

A brace pattern will not be expanded or evaluted if _either the opening or closing brace is escaped_:

```js
console.log(braces.expand('a\\{d,c,b}e'));
//=> ['a{d,c,b}e']

console.log(braces.expand('a{d,c,b\\}e'));
//=> ['a{d,c,b}e']
```

**Escaping commas**

Commas inside braces may also be escaped:

```js
console.log(braces.expand('a{b\\,c}d'));
//=> ['a{b,c}d']

console.log(braces.expand('a{d\\,c,b}e'));
//=> ['ad,ce', 'abe']
```

**Single items**

Following bash conventions, a brace pattern is also not expanded when it contains a single character:

```js
console.log(braces.expand('a{b}c'));
//=> ['a{b}c']
```

## Options

### options.maxLength

**Type**: `Number`

**Default**: `10,000`

**Description**: Limit the length of the input string. Useful when the input string is generated or your application allows users to pass a string, et cetera.

```js
console.log(braces('a/{b,c}/d', { maxLength: 3 })); //=> throws an error
```

### options.expand

**Type**: `Boolean`

**Default**: `undefined`

**Description**: Generate an "expanded" brace pattern (alternatively you can use the `braces.expand()` method, which does the same thing).

```js
console.log(braces('a/{b,c}/d', { expand: true }));
//=> [ 'a/b/d', 'a/c/d' ]
```

### options.nodupes

**Type**: `Boolean`

**Default**: `undefined`

**Description**: Remove duplicates from the returned array.

### options.rangeLimit

**Type**: `Number`

**Default**: `1000`

**Description**: To prevent malicious patterns from being passed by users, an error is thrown when `braces.expand()` is used or `options.expand` is true and the generated range will exceed the `rangeLimit`.

You can customize `options.rangeLimit` or set it to `Inifinity` to disable this altogether.

**Examples**

```js
// pattern exceeds the "rangeLimit", so it's optimized automatically
console.log(braces.expand('{1..1000}'));
//=> ['([1-9]|[1-9][0-9]{1,2}|1000)']

// pattern does not exceed "rangeLimit", so it's NOT optimized
console.log(braces.expand('{1..100}'));
//=> ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100']
```

### options.transform

**Type**: `Function`

**Default**: `undefined`

**Description**: Customize range expansion.

**Example: Transforming non-numeric values**

```js
const alpha = braces.expand('x/{a..e}/y', {
  transform(value, index) {
    // When non-numeric values are passed, "value" is a character code.
    return 'foo/' + String.fromCharCode(value) + '-' + index;
  },
});
console.log(alpha);
//=> [ 'x/foo/a-0/y', 'x/foo/b-1/y', 'x/foo/c-2/y', 'x/foo/d-3/y', 'x/foo/e-4/y' ]
```

**Example: Transforming numeric values**

```js
const numeric = braces.expand('{1..5}', {
  transform(value) {
    // when numeric values are passed, "value" is a number
    return 'foo/' + value * 2;
  },
});
console.log(numeric);
//=> [ 'foo/2', 'foo/4', 'foo/6', 'foo/8', 'foo/10' ]
```

### options.quantifiers

**Type**: `Boolean`

**Default**: `undefined`

**Description**: In regular expressions, quanitifiers can be used to specify how many times a token can be repeated. For example, `a{1,3}` will match the letter `a` one to three times.

Unfortunately, regex quantifiers happen to share the same syntax as [Bash lists](#lists)

The `quantifiers` option tells braces to detect when [regex quantifiers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#quantifiers) are defined in the given pattern, and not to try to expand them as lists.

**Examples**

```js
const braces = require('braces');
console.log(braces('a/b{1,3}/{x,y,z}'));
//=> [ 'a/b(1|3)/(x|y|z)' ]
console.log(braces('a/b{1,3}/{x,y,z}', { quantifiers: true }));
//=> [ 'a/b{1,3}/(x|y|z)' ]
console.log(braces('a/b{1,3}/{x,y,z}', { quantifiers: true, expand: true }));
//=> [ 'a/b{1,3}/x', 'a/b{1,3}/y', 'a/b{1,3}/z' ]
```

### options.keepEscaping

**Type**: `Boolean`

**Default**: `undefined`

**Description**: Do not strip backslashes that were used for escaping from the result.

## What is "brace expansion"?

Brace expansion is a type of parameter expansion that was made popular by unix shells for generating lists of strings, as well as regex-like matching when used alongside wildcards (globs).

In addition to "expansion", braces are also used for matching. In other words:

- [brace expansion](#brace-expansion) is for generating new lists
- [brace matching](#brace-matching) is for filtering existing lists

More about brace expansion (click to expand)

There are two main types of brace expansion:

1. **lists**: which are defined using comma-separated values inside curly braces: `{a,b,c}`
2. **sequences**: which are defined using a starting value and an ending value, separated by two dots: `a{1..3}b`. Optionally, a third argument may be passed to define a "step" or increment to use: `a{1..100..10}b`. These are also sometimes referred to as "ranges".

Here are some example brace patterns to illustrate how they work:

**Sets**

```
{a,b,c}       => a b c
{a,b,c}{1,2}  => a1 a2 b1 b2 c1 c2
```

**Sequences**

```
{1..9}        => 1 2 3 4 5 6 7 8 9
{4..-4}       => 4 3 2 1 0 -1 -2 -3 -4
{1..20..3}    => 1 4 7 10 13 16 19
{a..j}        => a b c d e f g h i j
{j..a}        => j i h g f e d c b a
{a..z..3}     => a d g j m p s v y
```

**Combination**

Sets and sequences can be mixed together or used along with any other strings.

```
{a,b,c}{1..3}   => a1 a2 a3 b1 b2 b3 c1 c2 c3
foo/{a,b,c}/bar => foo/a/bar foo/b/bar foo/c/bar
```

The fact that braces can be "expanded" from relatively simple patterns makes them ideal for quickly generating test fixtures, file paths, and similar use cases.

## Brace matching

In addition to _expansion_, brace patterns are also useful for performing regular-expression-like matching.

For example, the pattern `foo/{1..3}/bar` would match any of following strings:

```
foo/1/bar
foo/2/bar
foo/3/bar
```

But not:

```
baz/1/qux
baz/2/qux
baz/3/qux
```

Braces can also be combined with [glob patterns](https://github.com/jonschlinkert/micromatch) to perform more advanced wildcard matching. For example, the pattern `*/{1..3}/*` would match any of following strings:

```
foo/1/bar
foo/2/bar
foo/3/bar
baz/1/qux
baz/2/qux
baz/3/qux
```

## Brace matching pitfalls

Although brace patterns offer a user-friendly way of matching ranges or sets of strings, there are also some major disadvantages and potential risks you should be aware of.

### tldr

**"brace bombs"**

- brace expansion can eat up a huge amount of processing resources
- as brace patterns increase _linearly in size_, the system resources required to expand the pattern increase exponentially
- users can accidentally (or intentially) exhaust your system's resources resulting in the equivalent of a DoS attack (bonus: no programming knowledge is required!)

For a more detailed explanation with examples, see the [geometric complexity](#geometric-complexity) section.

### The solution

Jump to the [performance section](#performance) to see how Braces solves this problem in comparison to other libraries.

### Geometric complexity

At minimum, brace patterns with sets limited to two elements have quadradic or `O(n^2)` complexity. But the complexity of the algorithm increases exponentially as the number of sets, _and elements per set_, increases, which is `O(n^c)`.

For example, the following sets demonstrate quadratic (`O(n^2)`) complexity:

```
{1,2}{3,4}      => (2X2)    => 13 14 23 24
{1,2}{3,4}{5,6} => (2X2X2)  => 135 136 145 146 235 236 245 246
```

But add an element to a set, and we get a n-fold Cartesian product with `O(n^c)` complexity:

```
{1,2,3}{4,5,6}{7,8,9} => (3X3X3) => 147 148 149 157 158 159 167 168 169 247 248
                                    249 257 258 259 267 268 269 347 348 349 357
                                    358 359 367 368 369
```

Now, imagine how this complexity grows given that each element is a n-tuple:

```
{1..100}{1..100}         => (100X100)     => 10,000 elements (38.4 kB)
{1..100}{1..100}{1..100} => (100X100X100) => 1,000,000 elements (5.76 MB)
```

Although these examples are clearly contrived, they demonstrate how brace patterns can quickly grow out of control.

**More information**

Interested in learning more about brace expansion?

- [linuxjournal/bash-brace-expansion](http://www.linuxjournal.com/content/bash-brace-expansion)
- [rosettacode/Brace_expansion](https://rosettacode.org/wiki/Brace_expansion)
- [cartesian product](https://en.wikipedia.org/wiki/Cartesian_product)

## Performance

Braces is not only screaming fast, it's also more accurate the other brace expansion libraries.

### Better algorithms

Fortunately there is a solution to the ["brace bomb" problem](#brace-matching-pitfalls): _don't expand brace patterns into an array when they're used for matching_.

Instead, convert the pattern into an optimized regular expression. This is easier said than done, and braces is the only library that does this currently.

**The proof is in the numbers**

Minimatch gets exponentially slower as patterns increase in complexity, braces does not. The following results were generated using `braces()` and `minimatch.braceExpand()`, respectively.

| **Pattern**                 | **braces**          | **[minimatch][]**            |
| --------------------------- | ------------------- | ---------------------------- |
| `{1..9007199254740991}`[^1] | `298 B` (5ms 459μs) | N/A (freezes)                |
| `{1..1000000000000000}`     | `41 B` (1ms 15μs)   | N/A (freezes)                |
| `{1..100000000000000}`      | `40 B` (890μs)      | N/A (freezes)                |
| `{1..10000000000000}`       | `39 B` (2ms 49μs)   | N/A (freezes)                |
| `{1..1000000000000}`        | `38 B` (608μs)      | N/A (freezes)                |
| `{1..100000000000}`         | `37 B` (397μs)      | N/A (freezes)                |
| `{1..10000000000}`          | `35 B` (983μs)      | N/A (freezes)                |
| `{1..1000000000}`           | `34 B` (798μs)      | N/A (freezes)                |
| `{1..100000000}`            | `33 B` (733μs)      | N/A (freezes)                |
| `{1..10000000}`             | `32 B` (5ms 632μs)  | `78.89 MB` (16s 388ms 569μs) |
| `{1..1000000}`              | `31 B` (1ms 381μs)  | `6.89 MB` (1s 496ms 887μs)   |
| `{1..100000}`               | `30 B` (950μs)      | `588.89 kB` (146ms 921μs)    |
| `{1..10000}`                | `29 B` (1ms 114μs)  | `48.89 kB` (14ms 187μs)      |
| `{1..1000}`                 | `28 B` (760μs)      | `3.89 kB` (1ms 453μs)        |
| `{1..100}`                  | `22 B` (345μs)      | `291 B` (196μs)              |
| `{1..10}`                   | `10 B` (533μs)      | `20 B` (37μs)                |
| `{1..3}`                    | `7 B` (190μs)       | `5 B` (27μs)                 |

### Faster algorithms

When you need expansion, braces is still much faster.

_(the following results were generated using `braces.expand()` and `minimatch.braceExpand()`, respectively)_

| **Pattern**     | **braces**                  | **[minimatch][]**            |
| --------------- | --------------------------- | ---------------------------- |
| `{1..10000000}` | `78.89 MB` (2s 698ms 642μs) | `78.89 MB` (18s 601ms 974μs) |
| `{1..1000000}`  | `6.89 MB` (458ms 576μs)     | `6.89 MB` (1s 491ms 621μs)   |
| `{1..100000}`   | `588.89 kB` (20ms 728μs)    | `588.89 kB` (156ms 919μs)    |
| `{1..10000}`    | `48.89 kB` (2ms 202μs)      | `48.89 kB` (13ms 641μs)      |
| `{1..1000}`     | `3.89 kB` (1ms 796μs)       | `3.89 kB` (1ms 958μs)        |
| `{1..100}`      | `291 B` (424μs)             | `291 B` (211μs)              |
| `{1..10}`       | `20 B` (487μs)              | `20 B` (72μs)                |
| `{1..3}`        | `5 B` (166μs)               | `5 B` (27μs)                 |

If you'd like to run these comparisons yourself, see [test/support/generate.js](test/support/generate.js).

## Benchmarks

### Running benchmarks

Install dev dependencies:

```bash
npm i -d && npm benchmark
```

### Latest results

Braces is more accurate, without sacrificing performance.

```bash
● expand - range (expanded)
     braces x 53,167 ops/sec ±0.12% (102 runs sampled)
  minimatch x 11,378 ops/sec ±0.10% (102 runs sampled)
● expand - range (optimized for regex)
     braces x 373,442 ops/sec ±0.04% (100 runs sampled)
  minimatch x 3,262 ops/sec ±0.18% (100 runs sampled)
● expand - nested ranges (expanded)
     braces x 33,921 ops/sec ±0.09% (99 runs sampled)
  minimatch x 10,855 ops/sec ±0.28% (100 runs sampled)
● expand - nested ranges (optimized for regex)
     braces x 287,479 ops/sec ±0.52% (98 runs sampled)
  minimatch x 3,219 ops/sec ±0.28% (101 runs sampled)
● expand - set (expanded)
     braces x 238,243 ops/sec ±0.19% (97 runs sampled)
  minimatch x 538,268 ops/sec ±0.31% (96 runs sampled)
● expand - set (optimized for regex)
     braces x 321,844 ops/sec ±0.10% (97 runs sampled)
  minimatch x 140,600 ops/sec ±0.15% (100 runs sampled)
● expand - nested sets (expanded)
     braces x 165,371 ops/sec ±0.42% (96 runs sampled)
  minimatch x 337,720 ops/sec ±0.28% (100 runs sampled)
● expand - nested sets (optimized for regex)
     braces x 242,948 ops/sec ±0.12% (99 runs sampled)
  minimatch x 87,403 ops/sec ±0.79% (96 runs sampled)
```

## About

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).

Running Tests

Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:

```sh
$ npm install && npm test
```

Building docs

_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_

To generate the readme, run the following command:

```sh
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```

### Contributors

| **Commits** | **Contributor**                                               |
| ----------- | ------------------------------------------------------------- |
| 197         | [jonschlinkert](https://github.com/jonschlinkert)             |
| 4           | [doowb](https://github.com/doowb)                             |
| 1           | [es128](https://github.com/es128)                             |
| 1           | [eush77](https://github.com/eush77)                           |
| 1           | [hemanth](https://github.com/hemanth)                         |
| 1           | [wtgtybhertgeghgtwtg](https://github.com/wtgtybhertgeghgtwtg) |

### Author

**Jon Schlinkert**

- [GitHub Profile](https://github.com/jonschlinkert)
- [Twitter Profile](https://twitter.com/jonschlinkert)
- [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)

### License

Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).

---

_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on April 08, 2019._


code:
'use strict';

const stringify = require('./lib/stringify');
const compile = require('./lib/compile');
const expand = require('./lib/expand');
const parse = require('./lib/parse');

/**
 * Expand the given pattern or create a regex-compatible string.
 *
 * ```js
 * const braces = require('braces');
 * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
 * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
 * ```
 * @param {String} `str`
 * @param {Object} `options`
 * @return {String}
 * @api public
 */

const braces = (input, options = {}) => {
  let output = [];

  if (Array.isArray(input)) {
    for (const pattern of input) {
      const result = braces.create(pattern, options);
      if (Array.isArray(result)) {
        output.push(...result);
      } else {
        output.push(result);
      }
    }
  } else {
    output = [].concat(braces.create(input, options));
  }

  if (options && options.expand === true && options.nodupes === true) {
    output = [...new Set(output)];
  }
  return output;
};

/**
 * Parse the given `str` with the given `options`.
 *
 * ```js
 * // braces.parse(pattern, [, options]);
 * const ast = braces.parse('a/{b,c}/d');
 * console.log(ast);
 * ```
 * @param {String} pattern Brace pattern to parse
 * @param {Object} options
 * @return {Object} Returns an AST
 * @api public
 */

braces.parse = (input, options = {}) => parse(input, options);

/**
 * Creates a braces string from an AST, or an AST node.
 *
 * ```js
 * const braces = require('braces');
 * let ast = braces.parse('foo/{a,b}/bar');
 * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
 * ```
 * @param {String} `input` Brace pattern or AST.
 * @param {Object} `options`
 * @return {Array} Returns an array of expanded values.
 * @api public
 */

braces.stringify = (input, options = {}) => {
  if (typeof input === 'string') {
    return stringify(braces.parse(input, options), options);
  }
  return stringify(input, options);
};

/**
 * Compiles a brace pattern into a regex-compatible, optimized string.
 * This method is called by the main [braces](#braces) function by default.
 *
 * ```js
 * const braces = require('braces');
 * console.log(braces.compile('a/{b,c}/d'));
 * //=> ['a/(b|c)/d']
 * ```
 * @param {String} `input` Brace pattern or AST.
 * @param {Object} `options`
 * @return {Array} Returns an array of expanded values.
 * @api public
 */

braces.compile = (input, options = {}) => {
  if (typeof input === 'string') {
    input = braces.parse(input, options);
  }
  return compile(input, options);
};

/**
 * Expands a brace pattern into an array. This method is called by the
 * main [braces](#braces) function when `options.expand` is true. Before
 * using this method it's recommended that you read the [performance notes](#performance))
 * and advantages of using [.compile](#compile) instead.
 *
 * ```js
 * const braces = require('braces');
 * console.log(braces.expand('a/{b,c}/d'));
 * //=> ['a/b/d', 'a/c/d'];
 * ```
 * @param {String} `pattern` Brace pattern
 * @param {Object} `options`
 * @return {Array} Returns an array of expanded values.
 * @api public
 */

braces.expand = (input, options = {}) => {
  if (typeof input === 'string') {
    input = braces.parse(input, options);
  }

  let result = expand(input, options);

  // filter out empty strings if specified
  if (options.noempty === true) {
    result = result.filter(Boolean);
  }

  // filter out duplicates if specified
  if (options.nodupes === true) {
    result = [...new Set(result)];
  }

  return result;
};

/**
 * Processes a brace pattern and returns either an expanded array
 * (if `options.expand` is true), a highly optimized regex-compatible string.
 * This method is called by the main [braces](#braces) function.
 *
 * ```js
 * const braces = require('braces');
 * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
 * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
 * ```
 * @param {String} `pattern` Brace pattern
 * @param {Object} `options`
 * @return {Array} Returns an array of expanded values.
 * @api public
 */

braces.create = (input, options = {}) => {
  if (input === '' || input.length < 3) {
    return [input];
  }

  return options.expand !== true
    ? braces.compile(input, options)
    : braces.expand(input, options);
};

/**
 * Expose "braces"
 */

module.exports = braces;


code:
'use strict';

const fill = require('fill-range');
const utils = require('./utils');

const compile = (ast, options = {}) => {
  const walk = (node, parent = {}) => {
    const invalidBlock = utils.isInvalidBrace(parent);
    const invalidNode = node.invalid === true && options.escapeInvalid === true;
    const invalid = invalidBlock === true || invalidNode === true;
    const prefix = options.escapeInvalid === true ? '\\' : '';
    let output = '';

    if (node.isOpen === true) {
      return prefix + node.value;
    }

    if (node.isClose === true) {
      console.log('node.isClose', prefix, node.value);
      return prefix + node.value;
    }

    if (node.type === 'open') {
      return invalid ? prefix + node.value : '(';
    }

    if (node.type === 'close') {
      return invalid ? prefix + node.value : ')';
    }

    if (node.type === 'comma') {
      return node.prev.type === 'comma' ? '' : invalid ? node.value : '|';
    }

    if (node.value) {
      return node.value;
    }

    if (node.nodes && node.ranges > 0) {
      const args = utils.reduce(node.nodes);
      const range = fill(...args, { ...options, wrap: false, toRegex: true, strictZeros: true });

      if (range.length !== 0) {
        return args.length > 1 && range.length > 1 ? `(${range})` : range;
      }
    }

    if (node.nodes) {
      for (const child of node.nodes) {
        output += walk(child, node);
      }
    }

    return output;
  };

  return walk(ast);
};

module.exports = compile;


code:
'use strict';

module.exports = {
  MAX_LENGTH: 10000,

  // Digits
  CHAR_0: '0', /* 0 */
  CHAR_9: '9', /* 9 */

  // Alphabet chars.
  CHAR_UPPERCASE_A: 'A', /* A */
  CHAR_LOWERCASE_A: 'a', /* a */
  CHAR_UPPERCASE_Z: 'Z', /* Z */
  CHAR_LOWERCASE_Z: 'z', /* z */

  CHAR_LEFT_PARENTHESES: '(', /* ( */
  CHAR_RIGHT_PARENTHESES: ')', /* ) */

  CHAR_ASTERISK: '*', /* * */

  // Non-alphabetic chars.
  CHAR_AMPERSAND: '&', /* & */
  CHAR_AT: '@', /* @ */
  CHAR_BACKSLASH: '\\', /* \ */
  CHAR_BACKTICK: '`', /* ` */
  CHAR_CARRIAGE_RETURN: '\r', /* \r */
  CHAR_CIRCUMFLEX_ACCENT: '^', /* ^ */
  CHAR_COLON: ':', /* : */
  CHAR_COMMA: ',', /* , */
  CHAR_DOLLAR: '$', /* . */
  CHAR_DOT: '.', /* . */
  CHAR_DOUBLE_QUOTE: '"', /* " */
  CHAR_EQUAL: '=', /* = */
  CHAR_EXCLAMATION_MARK: '!', /* ! */
  CHAR_FORM_FEED: '\f', /* \f */
  CHAR_FORWARD_SLASH: '/', /* / */
  CHAR_HASH: '#', /* # */
  CHAR_HYPHEN_MINUS: '-', /* - */
  CHAR_LEFT_ANGLE_BRACKET: '<', /* < */
  CHAR_LEFT_CURLY_BRACE: '{', /* { */
  CHAR_LEFT_SQUARE_BRACKET: '[', /* [ */
  CHAR_LINE_FEED: '\n', /* \n */
  CHAR_NO_BREAK_SPACE: '\u00A0', /* \u00A0 */
  CHAR_PERCENT: '%', /* % */
  CHAR_PLUS: '+', /* + */
  CHAR_QUESTION_MARK: '?', /* ? */
  CHAR_RIGHT_ANGLE_BRACKET: '>', /* > */
  CHAR_RIGHT_CURLY_BRACE: '}', /* } */
  CHAR_RIGHT_SQUARE_BRACKET: ']', /* ] */
  CHAR_SEMICOLON: ';', /* ; */
  CHAR_SINGLE_QUOTE: '\'', /* ' */
  CHAR_SPACE: ' ', /*   */
  CHAR_TAB: '\t', /* \t */
  CHAR_UNDERSCORE: '_', /* _ */
  CHAR_VERTICAL_LINE: '|', /* | */
  CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
};


code:
'use strict';

const fill = require('fill-range');
const stringify = require('./stringify');
const utils = require('./utils');

const append = (queue = '', stash = '', enclose = false) => {
  const result = [];

  queue = [].concat(queue);
  stash = [].concat(stash);

  if (!stash.length) return queue;
  if (!queue.length) {
    return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash;
  }

  for (const item of queue) {
    if (Array.isArray(item)) {
      for (const value of item) {
        result.push(append(value, stash, enclose));
      }
    } else {
      for (let ele of stash) {
        if (enclose === true && typeof ele === 'string') ele = `{${ele}}`;
        result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele);
      }
    }
  }
  return utils.flatten(result);
};

const expand = (ast, options = {}) => {
  const rangeLimit = options.rangeLimit === undefined ? 1000 : options.rangeLimit;

  const walk = (node, parent = {}) => {
    node.queue = [];

    let p = parent;
    let q = parent.queue;

    while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
      p = p.parent;
      q = p.queue;
    }

    if (node.invalid || node.dollar) {
      q.push(append(q.pop(), stringify(node, options)));
      return;
    }

    if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
      q.push(append(q.pop(), ['{}']));
      return;
    }

    if (node.nodes && node.ranges > 0) {
      const args = utils.reduce(node.nodes);

      if (utils.exceedsLimit(...args, options.step, rangeLimit)) {
        throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
      }

      let range = fill(...args, options);
      if (range.length === 0) {
        range = stringify(node, options);
      }

      q.push(append(q.pop(), range));
      node.nodes = [];
      return;
    }

    const enclose = utils.encloseBrace(node);
    let queue = node.queue;
    let block = node;

    while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
      block = block.parent;
      queue = block.queue;
    }

    for (let i = 0; i < node.nodes.length; i++) {
      const child = node.nodes[i];

      if (child.type === 'comma' && node.type === 'brace') {
        if (i === 1) queue.push('');
        queue.push('');
        continue;
      }

      if (child.type === 'close') {
        q.push(append(q.pop(), queue, enclose));
        continue;
      }

      if (child.value && child.type !== 'open') {
        queue.push(append(queue.pop(), child.value));
        continue;
      }

      if (child.nodes) {
        walk(child, node);
      }
    }

    return queue;
  };

  return utils.flatten(walk(ast));
};

module.exports = expand;


code:
'use strict';

const stringify = require('./stringify');

/**
 * Constants
 */

const {
  MAX_LENGTH,
  CHAR_BACKSLASH, /* \ */
  CHAR_BACKTICK, /* ` */
  CHAR_COMMA, /* , */
  CHAR_DOT, /* . */
  CHAR_LEFT_PARENTHESES, /* ( */
  CHAR_RIGHT_PARENTHESES, /* ) */
  CHAR_LEFT_CURLY_BRACE, /* { */
  CHAR_RIGHT_CURLY_BRACE, /* } */
  CHAR_LEFT_SQUARE_BRACKET, /* [ */
  CHAR_RIGHT_SQUARE_BRACKET, /* ] */
  CHAR_DOUBLE_QUOTE, /* " */
  CHAR_SINGLE_QUOTE, /* ' */
  CHAR_NO_BREAK_SPACE,
  CHAR_ZERO_WIDTH_NOBREAK_SPACE
} = require('./constants');

/**
 * parse
 */

const parse = (input, options = {}) => {
  if (typeof input !== 'string') {
    throw new TypeError('Expected a string');
  }

  const opts = options || {};
  const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
  if (input.length > max) {
    throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
  }

  const ast = { type: 'root', input, nodes: [] };
  const stack = [ast];
  let block = ast;
  let prev = ast;
  let brackets = 0;
  const length = input.length;
  let index = 0;
  let depth = 0;
  let value;

  /**
   * Helpers
   */

  const advance = () => input[index++];
  const push = node => {
    if (node.type === 'text' && prev.type === 'dot') {
      prev.type = 'text';
    }

    if (prev && prev.type === 'text' && node.type === 'text') {
      prev.value += node.value;
      return;
    }

    block.nodes.push(node);
    node.parent = block;
    node.prev = prev;
    prev = node;
    return node;
  };

  push({ type: 'bos' });

  while (index < length) {
    block = stack[stack.length - 1];
    value = advance();

    /**
     * Invalid chars
     */

    if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
      continue;
    }

    /**
     * Escaped chars
     */

    if (value === CHAR_BACKSLASH) {
      push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
      continue;
    }

    /**
     * Right square bracket (literal): ']'
     */

    if (value === CHAR_RIGHT_SQUARE_BRACKET) {
      push({ type: 'text', value: '\\' + value });
      continue;
    }

    /**
     * Left square bracket: '['
     */

    if (value === CHAR_LEFT_SQUARE_BRACKET) {
      brackets++;

      let next;

      while (index < length && (next = advance())) {
        value += next;

        if (next === CHAR_LEFT_SQUARE_BRACKET) {
          brackets++;
          continue;
        }

        if (next === CHAR_BACKSLASH) {
          value += advance();
          continue;
        }

        if (next === CHAR_RIGHT_SQUARE_BRACKET) {
          brackets--;

          if (brackets === 0) {
            break;
          }
        }
      }

      push({ type: 'text', value });
      continue;
    }

    /**
     * Parentheses
     */

    if (value === CHAR_LEFT_PARENTHESES) {
      block = push({ type: 'paren', nodes: [] });
      stack.push(block);
      push({ type: 'text', value });
      continue;
    }

    if (value === CHAR_RIGHT_PARENTHESES) {
      if (block.type !== 'paren') {
        push({ type: 'text', value });
        continue;
      }
      block = stack.pop();
      push({ type: 'text', value });
      block = stack[stack.length - 1];
      continue;
    }

    /**
     * Quotes: '|"|`
     */

    if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
      const open = value;
      let next;

      if (options.keepQuotes !== true) {
        value = '';
      }

      while (index < length && (next = advance())) {
        if (next === CHAR_BACKSLASH) {
          value += next + advance();
          continue;
        }

        if (next === open) {
          if (options.keepQuotes === true) value += next;
          break;
        }

        value += next;
      }

      push({ type: 'text', value });
      continue;
    }

    /**
     * Left curly brace: '{'
     */

    if (value === CHAR_LEFT_CURLY_BRACE) {
      depth++;

      const dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
      const brace = {
        type: 'brace',
        open: true,
        close: false,
        dollar,
        depth,
        commas: 0,
        ranges: 0,
        nodes: []
      };

      block = push(brace);
      stack.push(block);
      push({ type: 'open', value });
      continue;
    }

    /**
     * Right curly brace: '}'
     */

    if (value === CHAR_RIGHT_CURLY_BRACE) {
      if (block.type !== 'brace') {
        push({ type: 'text', value });
        continue;
      }

      const type = 'close';
      block = stack.pop();
      block.close = true;

      push({ type, value });
      depth--;

      block = stack[stack.length - 1];
      continue;
    }

    /**
     * Comma: ','
     */

    if (value === CHAR_COMMA && depth > 0) {
      if (block.ranges > 0) {
        block.ranges = 0;
        const open = block.nodes.shift();
        block.nodes = [open, { type: 'text', value: stringify(block) }];
      }

      push({ type: 'comma', value });
      block.commas++;
      continue;
    }

    /**
     * Dot: '.'
     */

    if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
      const siblings = block.nodes;

      if (depth === 0 || siblings.length === 0) {
        push({ type: 'text', value });
        continue;
      }

      if (prev.type === 'dot') {
        block.range = [];
        prev.value += value;
        prev.type = 'range';

        if (block.nodes.length !== 3 && block.nodes.length !== 5) {
          block.invalid = true;
          block.ranges = 0;
          prev.type = 'text';
          continue;
        }

        block.ranges++;
        block.args = [];
        continue;
      }

      if (prev.type === 'range') {
        siblings.pop();

        const before = siblings[siblings.length - 1];
        before.value += prev.value + value;
        prev = before;
        block.ranges--;
        continue;
      }

      push({ type: 'dot', value });
      continue;
    }

    /**
     * Text
     */

    push({ type: 'text', value });
  }

  // Mark imbalanced braces and brackets as invalid
  do {
    block = stack.pop();

    if (block.type !== 'root') {
      block.nodes.forEach(node => {
        if (!node.nodes) {
          if (node.type === 'open') node.isOpen = true;
          if (node.type === 'close') node.isClose = true;
          if (!node.nodes) node.type = 'text';
          node.invalid = true;
        }
      });

      // get the location of the block on parent.nodes (block's siblings)
      const parent = stack[stack.length - 1];
      const index = parent.nodes.indexOf(block);
      // replace the (invalid) block with it's nodes
      parent.nodes.splice(index, 1, ...block.nodes);
    }
  } while (stack.length > 0);

  push({ type: 'eos' });
  return ast;
};

module.exports = parse;


code:
'use strict';

const utils = require('./utils');

module.exports = (ast, options = {}) => {
  const stringify = (node, parent = {}) => {
    const invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent);
    const invalidNode = node.invalid === true && options.escapeInvalid === true;
    let output = '';

    if (node.value) {
      if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) {
        return '\\' + node.value;
      }
      return node.value;
    }

    if (node.value) {
      return node.value;
    }

    if (node.nodes) {
      for (const child of node.nodes) {
        output += stringify(child);
      }
    }
    return output;
  };

  return stringify(ast);
};


code:
'use strict';

exports.isInteger = num => {
  if (typeof num === 'number') {
    return Number.isInteger(num);
  }
  if (typeof num === 'string' && num.trim() !== '') {
    return Number.isInteger(Number(num));
  }
  return false;
};

/**
 * Find a node of the given type
 */

exports.find = (node, type) => node.nodes.find(node => node.type === type);

/**
 * Find a node of the given type
 */

exports.exceedsLimit = (min, max, step = 1, limit) => {
  if (limit === false) return false;
  if (!exports.isInteger(min) || !exports.isInteger(max)) return false;
  return ((Number(max) - Number(min)) / Number(step)) >= limit;
};

/**
 * Escape the given node with '\\' before node.value
 */

exports.escapeNode = (block, n = 0, type) => {
  const node = block.nodes[n];
  if (!node) return;

  if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
    if (node.escaped !== true) {
      node.value = '\\' + node.value;
      node.escaped = true;
    }
  }
};

/**
 * Returns true if the given brace node should be enclosed in literal braces
 */

exports.encloseBrace = node => {
  if (node.type !== 'brace') return false;
  if ((node.commas >> 0 + node.ranges >> 0) === 0) {
    node.invalid = true;
    return true;
  }
  return false;
};

/**
 * Returns true if a brace node is invalid.
 */

exports.isInvalidBrace = block => {
  if (block.type !== 'brace') return false;
  if (block.invalid === true || block.dollar) return true;
  if ((block.commas >> 0 + block.ranges >> 0) === 0) {
    block.invalid = true;
    return true;
  }
  if (block.open !== true || block.close !== true) {
    block.invalid = true;
    return true;
  }
  return false;
};

/**
 * Returns true if a node is an open or close node
 */

exports.isOpenOrClose = node => {
  if (node.type === 'open' || node.type === 'close') {
    return true;
  }
  return node.open === true || node.close === true;
};

/**
 * Reduce an array of text nodes.
 */

exports.reduce = nodes => nodes.reduce((acc, node) => {
  if (node.type === 'text') acc.push(node.value);
  if (node.type === 'range') node.type = 'text';
  return acc;
}, []);

/**
 * Flatten an array
 */

exports.flatten = (...args) => {
  const result = [];

  const flat = arr => {
    for (let i = 0; i < arr.length; i++) {
      const ele = arr[i];

      if (Array.isArray(ele)) {
        flat(ele);
        continue;
      }

      if (ele !== undefined) {
        result.push(ele);
      }
    }
    return result;
  };

  flat(args);
  return result;
};


braces

description: Bash-like brace expansion, implemented in JavaScript. Safer than other brace expansion libs, with complete support for the Bash 4.3 braces specification, without sacrificing speed.

repository: micromatch/braces

test: mocha

benchmark: node benchmark

keywords: alpha alphabetical bash brace braces expand expansion filepath fill fs glob globbing letter match matches matching number numerical path range ranges sh

layout: default


code:
# Browserslist [![Cult Of Martians][cult-img]][cult]

The config to share target browsers and Node.js versions between different
front-end tools. It is used in:

* [Autoprefixer]
* [Babel]
* [postcss-preset-env]
* [eslint-plugin-compat]
* [stylelint-no-unsupported-browser-features]
* [postcss-normalize]
* [obsolete-webpack-plugin]

All tools will find target browsers automatically,
when you add the following to `package.json`:

```json
  "browserslist": [
    "defaults and fully supports es6-module",
    "maintained node versions"
  ]
```

Or in `.browserslistrc` config:

```yaml
# Browsers that we support

defaults and fully supports es6-module
maintained node versions
```

Developers set their version lists using queries like `last 2 versions`
to be free from updating versions manually.
Browserslist will use [`caniuse-lite`] with [Can I Use] data for this queries.

You can check how config works at our playground: [`browsersl.ist`](https://browsersl.ist/)

[stylelint-no-unsupported-browser-features]: https://github.com/ismay/stylelint-no-unsupported-browser-features
[obsolete-webpack-plugin]:                   https://github.com/ElemeFE/obsolete-webpack-plugin
[eslint-plugin-compat]:                      https://github.com/amilajack/eslint-plugin-compat
[Browserslist Example]:                      https://github.com/browserslist/browserslist-example
[postcss-preset-env]:                        https://github.com/csstools/postcss-plugins/tree/main/plugin-packs/postcss-preset-env
[postcss-normalize]:                         https://github.com/csstools/postcss-normalize
[`browsersl.ist`]:                           https://browsersl.ist/
[`caniuse-lite`]:                            https://github.com/ben-eb/caniuse-lite
[Autoprefixer]:                              https://github.com/postcss/autoprefixer
[Can I Use]:                                 https://caniuse.com/
[Babel]:                                     https://github.com/babel/babel/tree/master/packages/babel-preset-env
[cult-img]: https://cultofmartians.com/assets/badges/badge.svg
[cult]: https://cultofmartians.com/done.html

## Docs
Read full docs **[here](https://github.com/browserslist/browserslist#readme)**.


code:
var BrowserslistError = require('./error')

function noop() {}

module.exports = {
  loadQueries: function loadQueries() {
    throw new BrowserslistError(
      'Sharable configs are not supported in client-side build of Browserslist'
    )
  },

  getStat: function getStat(opts) {
    return opts.stats
  },

  loadConfig: function loadConfig(opts) {
    if (opts.config) {
      throw new BrowserslistError(
        'Browserslist config are not supported in client-side build'
      )
    }
  },

  loadCountry: function loadCountry() {
    throw new BrowserslistError(
      'Country statistics are not supported ' +
        'in client-side build of Browserslist'
    )
  },

  loadFeature: function loadFeature() {
    throw new BrowserslistError(
      'Supports queries are not available in client-side build of Browserslist'
    )
  },

  currentNode: function currentNode(resolve, context) {
    return resolve(['maintained node versions'], context)[0]
  },

  parseConfig: noop,

  readConfig: noop,

  findConfig: noop,

  findConfigFile: noop,

  clearCaches: noop,

  oldDataWarning: noop,

  env: {}
}


code:
#!/usr/bin/env node

var fs = require('fs')
var updateDb = require('update-browserslist-db')

var browserslist = require('./')
var pkg = require('./package.json')

var args = process.argv.slice(2)

var USAGE =
  'Usage:\n' +
  '  npx browserslist\n' +
  '  npx browserslist "QUERIES"\n' +
  '  npx browserslist --json "QUERIES"\n' +
  '  npx browserslist --config="path/to/browserlist/file"\n' +
  '  npx browserslist --coverage "QUERIES"\n' +
  '  npx browserslist --coverage=US "QUERIES"\n' +
  '  npx browserslist --coverage=US,RU,global "QUERIES"\n' +
  '  npx browserslist --env="environment name defined in config"\n' +
  '  npx browserslist --stats="path/to/browserlist/stats/file"\n' +
  '  npx browserslist --mobile-to-desktop\n' +
  '  npx browserslist --ignore-unknown-versions\n'

function isArg(arg) {
  return args.some(function (str) {
    return str === arg || str.indexOf(arg + '=') === 0
  })
}

function error(msg) {
  process.stderr.write('browserslist: ' + msg + '\n')
  process.exit(1)
}

if (isArg('--help') || isArg('-h')) {
  process.stdout.write(pkg.description + '.\n\n' + USAGE + '\n')
} else if (isArg('--version') || isArg('-v')) {
  process.stdout.write('browserslist ' + pkg.version + '\n')
} else if (isArg('--update-db')) {
  /* c8 ignore next 8 */
  process.stdout.write(
    'The --update-db command is deprecated.\n' +
      'Please use npx update-browserslist-db@latest instead.\n'
  )
  process.stdout.write('Browserslist DB update will still be made.\n')
  updateDb(function (str) {
    process.stdout.write(str)
  })
} else {
  var mode = 'browsers'
  var opts = {}
  var queries
  var areas

  for (var i = 0; i < args.length; i++) {
    if (args[i][0] !== '-') {
      queries = args[i].replace(/^["']|["']$/g, '')
      continue
    }

    var arg = args[i].split('=')
    var name = arg[0]
    var value = arg[1]

    if (value) value = value.replace(/^["']|["']$/g, '')

    if (name === '--config' || name === '-b') {
      opts.config = value
    } else if (name === '--env' || name === '-e') {
      opts.env = value
    } else if (name === '--stats' || name === '-s') {
      opts.stats = value
    } else if (name === '--coverage' || name === '-c') {
      if (mode !== 'json') mode = 'coverage'
      if (value) {
        areas = value.split(',')
      } else {
        areas = ['global']
      }
    } else if (name === '--json') {
      mode = 'json'
    } else if (name === '--mobile-to-desktop') {
      /* c8 ignore next */
      opts.mobileToDesktop = true
    } else if (name === '--ignore-unknown-versions') {
      /* c8 ignore next */
      opts.ignoreUnknownVersions = true
    } else {
      error('Unknown arguments ' + args[i] + '.\n\n' + USAGE)
    }
  }

  var browsers
  try {
    browsers = browserslist(queries, opts)
  } catch (e) {
    if (e.name === 'BrowserslistError') {
      error(e.message)
    } /* c8 ignore start */ else {
      throw e
    } /* c8 ignore end */
  }

  var coverage
  if (mode === 'browsers') {
    browsers.forEach(function (browser) {
      process.stdout.write(browser + '\n')
    })
  } else if (areas) {
    coverage = areas.map(function (area) {
      var stats
      if (area !== 'global') {
        stats = area
      } else if (opts.stats) {
        stats = JSON.parse(fs.readFileSync(opts.stats))
      }
      var result = browserslist.coverage(browsers, stats)
      var round = Math.round(result * 100) / 100.0

      return [area, round]
    })

    if (mode === 'coverage') {
      var prefix = 'These browsers account for '
      process.stdout.write(prefix)
      coverage.forEach(function (data, index) {
        var area = data[0]
        var round = data[1]
        var end = 'globally'
        if (area && area !== 'global') {
          end = 'in the ' + area.toUpperCase()
        } else if (opts.stats) {
          end = 'in custom statistics'
        }

        if (index !== 0) {
          process.stdout.write(prefix.replace(/./g, ' '))
        }

        process.stdout.write(round + '% of all users ' + end + '\n')
      })
    }
  }

  if (mode === 'json') {
    var data = { browsers: browsers }
    if (coverage) {
      data.coverage = coverage.reduce(function (object, j) {
        object[j[0]] = j[1]
        return object
      }, {})
    }
    process.stdout.write(JSON.stringify(data, null, '  ') + '\n')
  }
}


code:
declare class BrowserslistError extends Error {
  constructor(message: any)
  name: 'BrowserslistError'
  browserslist: true
}

export = BrowserslistError


code:
function BrowserslistError(message) {
  this.name = 'BrowserslistError'
  this.message = message
  this.browserslist = true
  if (Error.captureStackTrace) {
    Error.captureStackTrace(this, BrowserslistError)
  }
}

BrowserslistError.prototype = Error.prototype

module.exports = BrowserslistError


code:
/**
 * Return array of browsers by selection queries.
 *
 * ```js
 * browserslist('IE >= 10, IE 8') //=> ['ie 11', 'ie 10', 'ie 8']
 * ```
 *
 * @param queries Browser queries.
 * @param opts Options.
 * @returns Array with browser names in Can I Use.
 */
declare function browserslist(
  queries?: string | readonly string[] | null,
  opts?: browserslist.Options
): string[]

declare namespace browserslist {
  interface Query {
    compose: 'or' | 'and'
    type: string
    query: string
    not?: true
  }

  interface Options {
    /**
     * Path to processed file. It will be used to find config files.
     */
    path?: string | false
    /**
     * Processing environment. It will be used to take right queries
     * from config file.
     */
    env?: string
    /**
     * Custom browser usage statistics for "> 1% in my stats" query.
     */
    stats?: Stats | string
    /**
     * Path to config file with queries.
     */
    config?: string
    /**
     * Do not throw on unknown version in direct query.
     */
    ignoreUnknownVersions?: boolean
    /**
     * Throw an error if env is not found.
     */
    throwOnMissing?: boolean
    /**
     * Disable security checks for extend query.
     */
    dangerousExtend?: boolean
    /**
     * Alias mobile browsers to the desktop version when Can I Use
     * doesn’t have data about the specified version.
     */
    mobileToDesktop?: boolean
  }

  type Config = {
    defaults: string[]
    [section: string]: string[] | undefined
  }

  interface Stats {
    [browser: string]: {
      [version: string]: number
    }
  }

  /**
   * Browser names aliases.
   */
  let aliases: {
    [alias: string]: string | undefined
  }

  /**
   * Aliases to work with joined versions like `ios_saf 7.0-7.1`.
   */
  let versionAliases: {
    [browser: string]:
      | {
          [version: string]: string | undefined
        }
      | undefined
  }

  /**
   * Can I Use only provides a few versions for some browsers (e.g. `and_chr`).
   *
   * Fallback to a similar browser for unknown versions.
   */
  let desktopNames: {
    [browser: string]: string | undefined
  }

  let data: {
    [browser: string]:
      | {
          name: string
          versions: string[]
          released: string[]
          releaseDate: {
            [version: string]: number | undefined | null
          }
        }
      | undefined
  }

  let nodeVersions: string[]

  interface Usage {
    [version: string]: number
  }

  let usage: {
    global?: Usage
    custom?: Usage | null
    [country: string]: Usage | undefined | null
  }

  let cache: {
    [feature: string]: {
      [name: string]: {
        [version: string]: string
      }
    }
  }

  /**
   * Default browsers query
   */
  let defaults: readonly string[]

  /**
   * Which statistics should be used. Country code or custom statistics.
   * Pass `"my stats"` to load statistics from `Browserslist` files.
   */
  type StatsOptions = string | 'my stats' | Stats | { dataByBrowser: Stats }

  /**
   * Return browsers market coverage.
   *
   * ```js
   * browserslist.coverage(browserslist('> 1% in US'), 'US') //=> 83.1
   * ```
   *
   * @param browsers Browsers names in Can I Use.
   * @param stats Which statistics should be used.
   * @returns Total market coverage for all selected browsers.
   */
  function coverage(browsers: readonly string[], stats?: StatsOptions): number

  /**
   * Get queries AST to analyze the config content.
   *
   * @param queries Browser queries.
   * @param opts Options.
   * @returns An array of the data of each query in the config.
   */
  function parse(
    queries?: string | readonly string[] | null,
    opts?: browserslist.Options
  ): Query[]

  /**
   * Return queries for specific file inside the project.
   *
   * ```js
   * browserslist.loadConfig({
   *   file: process.cwd()
   * }) ?? browserslist.defaults
   * ```
   */
  function loadConfig(options: LoadConfigOptions): string[] | undefined

  function clearCaches(): void

  function parseConfig(string: string): Config

  function readConfig(file: string): Config

  function findConfig(...pathSegments: string[]): Config | undefined

  function findConfigFile(...pathSegments: string[]): string | undefined

  interface LoadConfigOptions {
    /**
     * Path to config file
     * */
    config?: string

    /**
     * Path to file inside the project to find Browserslist config
     * in closest folder
     */
    path?: string

    /**
     * Environment to choose part of config.
     */
    env?: string
  }
}

declare global {
  namespace NodeJS {
    interface ProcessEnv {
      BROWSERSLIST?: string
      BROWSERSLIST_CONFIG?: string
      BROWSERSLIST_DANGEROUS_EXTEND?: string
      BROWSERSLIST_DISABLE_CACHE?: string
      BROWSERSLIST_ENV?: string
      BROWSERSLIST_IGNORE_OLD_DATA?: string
      BROWSERSLIST_STATS?: string
      BROWSERSLIST_ROOT_PATH?: string
    }
  }
}

export = browserslist