help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
ruby-calculator
/
node_modules
/
chokidar
/
esm
RSK World
ruby-calculator
Ruby Calculator Pro - Interactive Calculator with 8 Types + Mathematical Functions + Rails MVC + Modern Web Interface + API Integration + Educational Design
esm
  • handler.d.ts3.8 KB
  • handler.js24.2 KB
  • index.d.ts7.9 KB
  • index.js28.5 KB
  • package.json43 B
index.jsmain.d.ts
node_modules/chokidar/index.js
Raw Download
Find: Go to:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FSWatcher = exports.WatchHelper = void 0;
exports.watch = watch;
/*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */
const fs_1 = require("fs");
const promises_1 = require("fs/promises");
const events_1 = require("events");
const sysPath = require("path");
const readdirp_1 = require("readdirp");
const handler_js_1 = require("./handler.js");
const SLASH = '/';
const SLASH_SLASH = '//';
const ONE_DOT = '.';
const TWO_DOTS = '..';
const STRING_TYPE = 'string';
const BACK_SLASH_RE = /\\/g;
const DOUBLE_SLASH_RE = /\/\//;
const DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
const REPLACER_RE = /^\.[/\\]/;
function arrify(item) {
    return Array.isArray(item) ? item : [item];
}
const isMatcherObject = (matcher) => typeof matcher === 'object' && matcher !== null && !(matcher instanceof RegExp);
function createPattern(matcher) {
    if (typeof matcher === 'function')
        return matcher;
    if (typeof matcher === 'string')
        return (string) => matcher === string;
    if (matcher instanceof RegExp)
        return (string) => matcher.test(string);
    if (typeof matcher === 'object' && matcher !== null) {
        return (string) => {
            if (matcher.path === string)
                return true;
            if (matcher.recursive) {
                const relative = sysPath.relative(matcher.path, string);
                if (!relative) {
                    return false;
                }
                return !relative.startsWith('..') && !sysPath.isAbsolute(relative);
            }
            return false;
        };
    }
    return () => false;
}
function normalizePath(path) {
    if (typeof path !== 'string')
        throw new Error('string expected');
    path = sysPath.normalize(path);
    path = path.replace(/\\/g, '/');
    let prepend = false;
    if (path.startsWith('//'))
        prepend = true;
    const DOUBLE_SLASH_RE = /\/\//;
    while (path.match(DOUBLE_SLASH_RE))
        path = path.replace(DOUBLE_SLASH_RE, '/');
    if (prepend)
        path = '/' + path;
    return path;
}
function matchPatterns(patterns, testString, stats) {
    const path = normalizePath(testString);
    for (let index = 0; index < patterns.length; index++) {
        const pattern = patterns[index];
        if (pattern(path, stats)) {
            return true;
        }
    }
    return false;
}
function anymatch(matchers, testString) {
    if (matchers == null) {
        throw new TypeError('anymatch: specify first argument');
    }
    // Early cache for matchers.
    const matchersArray = arrify(matchers);
    const patterns = matchersArray.map((matcher) => createPattern(matcher));
    if (testString == null) {
        return (testString, stats) => {
            return matchPatterns(patterns, testString, stats);
        };
    }
    return matchPatterns(patterns, testString);
}
const unifyPaths = (paths_) => {
    const paths = arrify(paths_).flat();
    if (!paths.every((p) => typeof p === STRING_TYPE)) {
        throw new TypeError(`Non-string provided as watch path: ${paths}`);
    }
    return paths.map(normalizePathToUnix);
};
// If SLASH_SLASH occurs at the beginning of path, it is not replaced
//     because "//StoragePC/DrivePool/Movies" is a valid network path
const toUnix = (string) => {
    let str = string.replace(BACK_SLASH_RE, SLASH);
    let prepend = false;
    if (str.startsWith(SLASH_SLASH)) {
        prepend = true;
    }
    while (str.match(DOUBLE_SLASH_RE)) {
        str = str.replace(DOUBLE_SLASH_RE, SLASH);
    }
    if (prepend) {
        str = SLASH + str;
    }
    return str;
};
// Our version of upath.normalize
// TODO: this is not equal to path-normalize module - investigate why
const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
// TODO: refactor
const normalizeIgnored = (cwd = '') => (path) => {
    if (typeof path === 'string') {
        return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
    }
    else {
        return path;
    }
};
const getAbsolutePath = (path, cwd) => {
    if (sysPath.isAbsolute(path)) {
        return path;
    }
    return sysPath.join(cwd, path);
};
const EMPTY_SET = Object.freeze(new Set());
/**
 * Directory entry.
 */
class DirEntry {
    constructor(dir, removeWatcher) {
        this.path = dir;
        this._removeWatcher = removeWatcher;
        this.items = new Set();
    }
    add(item) {
        const { items } = this;
        if (!items)
            return;
        if (item !== ONE_DOT && item !== TWO_DOTS)
            items.add(item);
    }
    async remove(item) {
        const { items } = this;
        if (!items)
            return;
        items.delete(item);
        if (items.size > 0)
            return;
        const dir = this.path;
        try {
            await (0, promises_1.readdir)(dir);
        }
        catch (err) {
            if (this._removeWatcher) {
                this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
            }
        }
    }
    has(item) {
        const { items } = this;
        if (!items)
            return;
        return items.has(item);
    }
    getChildren() {
        const { items } = this;
        if (!items)
            return [];
        return [...items.values()];
    }
    dispose() {
        this.items.clear();
        this.path = '';
        this._removeWatcher = handler_js_1.EMPTY_FN;
        this.items = EMPTY_SET;
        Object.freeze(this);
    }
}
const STAT_METHOD_F = 'stat';
const STAT_METHOD_L = 'lstat';
class WatchHelper {
    constructor(path, follow, fsw) {
        this.fsw = fsw;
        const watchPath = path;
        this.path = path = path.replace(REPLACER_RE, '');
        this.watchPath = watchPath;
        this.fullWatchPath = sysPath.resolve(watchPath);
        this.dirParts = [];
        this.dirParts.forEach((parts) => {
            if (parts.length > 1)
                parts.pop();
        });
        this.followSymlinks = follow;
        this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
    }
    entryPath(entry) {
        return sysPath.join(this.watchPath, sysPath.relative(this.watchPath, entry.fullPath));
    }
    filterPath(entry) {
        const { stats } = entry;
        if (stats && stats.isSymbolicLink())
            return this.filterDir(entry);
        const resolvedPath = this.entryPath(entry);
        // TODO: what if stats is undefined? remove !
        return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
    }
    filterDir(entry) {
        return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
    }
}
exports.WatchHelper = WatchHelper;
/**
 * Watches files & directories for changes. Emitted events:
 * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
 *
 *     new FSWatcher()
 *       .add(directories)
 *       .on('add', path => log('File', path, 'was added'))
 */
class FSWatcher extends events_1.EventEmitter {
    // Not indenting methods for history sake; for now.
    constructor(_opts = {}) {
        super();
        this.closed = false;
        this._closers = new Map();
        this._ignoredPaths = new Set();
        this._throttled = new Map();
        this._streams = new Set();
        this._symlinkPaths = new Map();
        this._watched = new Map();
        this._pendingWrites = new Map();
        this._pendingUnlinks = new Map();
        this._readyCount = 0;
        this._readyEmitted = false;
        const awf = _opts.awaitWriteFinish;
        const DEF_AWF = { stabilityThreshold: 2000, pollInterval: 100 };
        const opts = {
            // Defaults
            persistent: true,
            ignoreInitial: false,
            ignorePermissionErrors: false,
            interval: 100,
            binaryInterval: 300,
            followSymlinks: true,
            usePolling: false,
            // useAsync: false,
            atomic: true, // NOTE: overwritten later (depends on usePolling)
            ..._opts,
            // Change format
            ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
            awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === 'object' ? { ...DEF_AWF, ...awf } : false,
        };
        // Always default to polling on IBM i because fs.watch() is not available on IBM i.
        if (handler_js_1.isIBMi)
            opts.usePolling = true;
        // Editor atomic write normalization enabled by default with fs.watch
        if (opts.atomic === undefined)
            opts.atomic = !opts.usePolling;
        // opts.atomic = typeof _opts.atomic === 'number' ? _opts.atomic : 100;
        // Global override. Useful for developers, who need to force polling for all
        // instances of chokidar, regardless of usage / dependency depth
        const envPoll = process.env.CHOKIDAR_USEPOLLING;
        if (envPoll !== undefined) {
            const envLower = envPoll.toLowerCase();
            if (envLower === 'false' || envLower === '0')
                opts.usePolling = false;
            else if (envLower === 'true' || envLower === '1')
                opts.usePolling = true;
            else
                opts.usePolling = !!envLower;
        }
        const envInterval = process.env.CHOKIDAR_INTERVAL;
        if (envInterval)
            opts.interval = Number.parseInt(envInterval, 10);
        // This is done to emit ready only once, but each 'add' will increase that?
        let readyCalls = 0;
        this._emitReady = () => {
            readyCalls++;
            if (readyCalls >= this._readyCount) {
                this._emitReady = handler_js_1.EMPTY_FN;
                this._readyEmitted = true;
                // use process.nextTick to allow time for listener to be bound
                process.nextTick(() => this.emit(handler_js_1.EVENTS.READY));
            }
        };
        this._emitRaw = (...args) => this.emit(handler_js_1.EVENTS.RAW, ...args);
        this._boundRemove = this._remove.bind(this);
        this.options = opts;
        this._nodeFsHandler = new handler_js_1.NodeFsHandler(this);
        // You’re frozen when your heart’s not open.
        Object.freeze(opts);
    }
    _addIgnoredPath(matcher) {
        if (isMatcherObject(matcher)) {
            // return early if we already have a deeply equal matcher object
            for (const ignored of this._ignoredPaths) {
                if (isMatcherObject(ignored) &&
                    ignored.path === matcher.path &&
                    ignored.recursive === matcher.recursive) {
                    return;
                }
            }
        }
        this._ignoredPaths.add(matcher);
    }
    _removeIgnoredPath(matcher) {
        this._ignoredPaths.delete(matcher);
        // now find any matcher objects with the matcher as path
        if (typeof matcher === 'string') {
            for (const ignored of this._ignoredPaths) {
                // TODO (43081j): make this more efficient.
                // probably just make a `this._ignoredDirectories` or some
                // such thing.
                if (isMatcherObject(ignored) && ignored.path === matcher) {
                    this._ignoredPaths.delete(ignored);
                }
            }
        }
    }
    // Public methods
    /**
     * Adds paths to be watched on an existing FSWatcher instance.
     * @param paths_ file or file list. Other arguments are unused
     */
    add(paths_, _origAdd, _internal) {
        const { cwd } = this.options;
        this.closed = false;
        this._closePromise = undefined;
        let paths = unifyPaths(paths_);
        if (cwd) {
            paths = paths.map((path) => {
                const absPath = getAbsolutePath(path, cwd);
                // Check `path` instead of `absPath` because the cwd portion can't be a glob
                return absPath;
            });
        }
        paths.forEach((path) => {
            this._removeIgnoredPath(path);
        });
        this._userIgnored = undefined;
        if (!this._readyCount)
            this._readyCount = 0;
        this._readyCount += paths.length;
        Promise.all(paths.map(async (path) => {
            const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, undefined, 0, _origAdd);
            if (res)
                this._emitReady();
            return res;
        })).then((results) => {
            if (this.closed)
                return;
            results.forEach((item) => {
                if (item)
                    this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
            });
        });
        return this;
    }
    /**
     * Close watchers or start ignoring events from specified paths.
     */
    unwatch(paths_) {
        if (this.closed)
            return this;
        const paths = unifyPaths(paths_);
        const { cwd } = this.options;
        paths.forEach((path) => {
            // convert to absolute path unless relative path already matches
            if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
                if (cwd)
                    path = sysPath.join(cwd, path);
                path = sysPath.resolve(path);
            }
            this._closePath(path);
            this._addIgnoredPath(path);
            if (this._watched.has(path)) {
                this._addIgnoredPath({
                    path,
                    recursive: true,
                });
            }
            // reset the cached userIgnored anymatch fn
            // to make ignoredPaths changes effective
            this._userIgnored = undefined;
        });
        return this;
    }
    /**
     * Close watchers and remove all listeners from watched paths.
     */
    close() {
        if (this._closePromise) {
            return this._closePromise;
        }
        this.closed = true;
        // Memory management.
        this.removeAllListeners();
        const closers = [];
        this._closers.forEach((closerList) => closerList.forEach((closer) => {
            const promise = closer();
            if (promise instanceof Promise)
                closers.push(promise);
        }));
        this._streams.forEach((stream) => stream.destroy());
        this._userIgnored = undefined;
        this._readyCount = 0;
        this._readyEmitted = false;
        this._watched.forEach((dirent) => dirent.dispose());
        this._closers.clear();
        this._watched.clear();
        this._streams.clear();
        this._symlinkPaths.clear();
        this._throttled.clear();
        this._closePromise = closers.length
            ? Promise.all(closers).then(() => undefined)
            : Promise.resolve();
        return this._closePromise;
    }
    /**
     * Expose list of watched paths
     * @returns for chaining
     */
    getWatched() {
        const watchList = {};
        this._watched.forEach((entry, dir) => {
            const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
            const index = key || ONE_DOT;
            watchList[index] = entry.getChildren().sort();
        });
        return watchList;
    }
    emitWithAll(event, args) {
        this.emit(event, ...args);
        if (event !== handler_js_1.EVENTS.ERROR)
            this.emit(handler_js_1.EVENTS.ALL, event, ...args);
    }
    // Common helpers
    // --------------
    /**
     * Normalize and emit events.
     * Calling _emit DOES NOT MEAN emit() would be called!
     * @param event Type of event
     * @param path File or directory path
     * @param stats arguments to be passed with event
     * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
     */
    async _emit(event, path, stats) {
        if (this.closed)
            return;
        const opts = this.options;
        if (handler_js_1.isWindows)
            path = sysPath.normalize(path);
        if (opts.cwd)
            path = sysPath.relative(opts.cwd, path);
        const args = [path];
        if (stats != null)
            args.push(stats);
        const awf = opts.awaitWriteFinish;
        let pw;
        if (awf && (pw = this._pendingWrites.get(path))) {
            pw.lastChange = new Date();
            return this;
        }
        if (opts.atomic) {
            if (event === handler_js_1.EVENTS.UNLINK) {
                this._pendingUnlinks.set(path, [event, ...args]);
                setTimeout(() => {
                    this._pendingUnlinks.forEach((entry, path) => {
                        this.emit(...entry);
                        this.emit(handler_js_1.EVENTS.ALL, ...entry);
                        this._pendingUnlinks.delete(path);
                    });
                }, typeof opts.atomic === 'number' ? opts.atomic : 100);
                return this;
            }
            if (event === handler_js_1.EVENTS.ADD && this._pendingUnlinks.has(path)) {
                event = handler_js_1.EVENTS.CHANGE;
                this._pendingUnlinks.delete(path);
            }
        }
        if (awf && (event === handler_js_1.EVENTS.ADD || event === handler_js_1.EVENTS.CHANGE) && this._readyEmitted) {
            const awfEmit = (err, stats) => {
                if (err) {
                    event = handler_js_1.EVENTS.ERROR;
                    args[0] = err;
                    this.emitWithAll(event, args);
                }
                else if (stats) {
                    // if stats doesn't exist the file must have been deleted
                    if (args.length > 1) {
                        args[1] = stats;
                    }
                    else {
                        args.push(stats);
                    }
                    this.emitWithAll(event, args);
                }
            };
            this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
            return this;
        }
        if (event === handler_js_1.EVENTS.CHANGE) {
            const isThrottled = !this._throttle(handler_js_1.EVENTS.CHANGE, path, 50);
            if (isThrottled)
                return this;
        }
        if (opts.alwaysStat &&
            stats === undefined &&
            (event === handler_js_1.EVENTS.ADD || event === handler_js_1.EVENTS.ADD_DIR || event === handler_js_1.EVENTS.CHANGE)) {
            const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
            let stats;
            try {
                stats = await (0, promises_1.stat)(fullPath);
            }
            catch (err) {
                // do nothing
            }
            // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
            if (!stats || this.closed)
                return;
            args.push(stats);
        }
        this.emitWithAll(event, args);
        return this;
    }
    /**
     * Common handler for errors
     * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
     */
    _handleError(error) {
        const code = error && error.code;
        if (error &&
            code !== 'ENOENT' &&
            code !== 'ENOTDIR' &&
            (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))) {
            this.emit(handler_js_1.EVENTS.ERROR, error);
        }
        return error || this.closed;
    }
    /**
     * Helper utility for throttling
     * @param actionType type being throttled
     * @param path being acted upon
     * @param timeout duration of time to suppress duplicate actions
     * @returns tracking object or false if action should be suppressed
     */
    _throttle(actionType, path, timeout) {
        if (!this._throttled.has(actionType)) {
            this._throttled.set(actionType, new Map());
        }
        const action = this._throttled.get(actionType);
        if (!action)
            throw new Error('invalid throttle');
        const actionPath = action.get(path);
        if (actionPath) {
            actionPath.count++;
            return false;
        }
        // eslint-disable-next-line prefer-const
        let timeoutObject;
        const clear = () => {
            const item = action.get(path);
            const count = item ? item.count : 0;
            action.delete(path);
            clearTimeout(timeoutObject);
            if (item)
                clearTimeout(item.timeoutObject);
            return count;
        };
        timeoutObject = setTimeout(clear, timeout);
        const thr = { timeoutObject, clear, count: 0 };
        action.set(path, thr);
        return thr;
    }
    _incrReadyCount() {
        return this._readyCount++;
    }
    /**
     * Awaits write operation to finish.
     * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
     * @param path being acted upon
     * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
     * @param event
     * @param awfEmit Callback to be called when ready for event to be emitted.
     */
    _awaitWriteFinish(path, threshold, event, awfEmit) {
        const awf = this.options.awaitWriteFinish;
        if (typeof awf !== 'object')
            return;
        const pollInterval = awf.pollInterval;
        let timeoutHandler;
        let fullPath = path;
        if (this.options.cwd && !sysPath.isAbsolute(path)) {
            fullPath = sysPath.join(this.options.cwd, path);
        }
        const now = new Date();
        const writes = this._pendingWrites;
        function awaitWriteFinishFn(prevStat) {
            (0, fs_1.stat)(fullPath, (err, curStat) => {
                if (err || !writes.has(path)) {
                    if (err && err.code !== 'ENOENT')
                        awfEmit(err);
                    return;
                }
                const now = Number(new Date());
                if (prevStat && curStat.size !== prevStat.size) {
                    writes.get(path).lastChange = now;
                }
                const pw = writes.get(path);
                const df = now - pw.lastChange;
                if (df >= threshold) {
                    writes.delete(path);
                    awfEmit(undefined, curStat);
                }
                else {
                    timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
                }
            });
        }
        if (!writes.has(path)) {
            writes.set(path, {
                lastChange: now,
                cancelWait: () => {
                    writes.delete(path);
                    clearTimeout(timeoutHandler);
                    return event;
                },
            });
            timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
        }
    }
    /**
     * Determines whether user has asked to ignore this path.
     */
    _isIgnored(path, stats) {
        if (this.options.atomic && DOT_RE.test(path))
            return true;
        if (!this._userIgnored) {
            const { cwd } = this.options;
            const ign = this.options.ignored;
            const ignored = (ign || []).map(normalizeIgnored(cwd));
            const ignoredPaths = [...this._ignoredPaths];
            const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored];
            this._userIgnored = anymatch(list, undefined);
        }
        return this._userIgnored(path, stats);
    }
    _isntIgnored(path, stat) {
        return !this._isIgnored(path, stat);
    }
    /**
     * Provides a set of common helpers and properties relating to symlink handling.
     * @param path file or directory pattern being watched
     */
    _getWatchHelpers(path) {
        return new WatchHelper(path, this.options.followSymlinks, this);
    }
    // Directory helpers
    // -----------------
    /**
     * Provides directory tracking objects
     * @param directory path of the directory
     */
    _getWatchedDir(directory) {
        const dir = sysPath.resolve(directory);
        if (!this._watched.has(dir))
            this._watched.set(dir, new DirEntry(dir, this._boundRemove));
        return this._watched.get(dir);
    }
    // File helpers
    // ------------
    /**
     * Check for read permissions: https://stackoverflow.com/a/11781404/1358405
     */
    _hasReadPermissions(stats) {
        if (this.options.ignorePermissionErrors)
            return true;
        return Boolean(Number(stats.mode) & 0o400);
    }
    /**
     * Handles emitting unlink events for
     * files and directories, and via recursion, for
     * files and directories within directories that are unlinked
     * @param directory within which the following item is located
     * @param item      base path of item/directory
     */
    _remove(directory, item, isDirectory) {
        // if what is being deleted is a directory, get that directory's paths
        // for recursive deleting and cleaning of watched object
        // if it is not a directory, nestedDirectoryChildren will be empty array
        const path = sysPath.join(directory, item);
        const fullPath = sysPath.resolve(path);
        isDirectory =
            isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);
        // prevent duplicate handling in case of arriving here nearly simultaneously
        // via multiple paths (such as _handleFile and _handleDir)
        if (!this._throttle('remove', path, 100))
            return;
        // if the only watched file is removed, watch for its return
        if (!isDirectory && this._watched.size === 1) {
            this.add(directory, item, true);
        }
        // This will create a new entry in the watched object in either case
        // so we got to do the directory check beforehand
        const wp = this._getWatchedDir(path);
        const nestedDirectoryChildren = wp.getChildren();
        // Recursively remove children directories / files.
        nestedDirectoryChildren.forEach((nested) => this._remove(path, nested));
        // Check if item was on the watched list and remove it
        const parent = this._getWatchedDir(directory);
        const wasTracked = parent.has(item);
        parent.remove(item);
        // Fixes issue #1042 -> Relative paths were detected and added as symlinks
        // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
        // but never removed from the map in case the path was deleted.
        // This leads to an incorrect state if the path was recreated:
        // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
        if (this._symlinkPaths.has(fullPath)) {
            this._symlinkPaths.delete(fullPath);
        }
        // If we wait for this file to be fully written, cancel the wait.
        let relPath = path;
        if (this.options.cwd)
            relPath = sysPath.relative(this.options.cwd, path);
        if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
            const event = this._pendingWrites.get(relPath).cancelWait();
            if (event === handler_js_1.EVENTS.ADD)
                return;
        }
        // The Entry will either be a directory that just got removed
        // or a bogus entry to a file, in either case we have to remove it
        this._watched.delete(path);
        this._watched.delete(fullPath);
        const eventName = isDirectory ? handler_js_1.EVENTS.UNLINK_DIR : handler_js_1.EVENTS.UNLINK;
        if (wasTracked && !this._isIgnored(path))
            this._emit(eventName, path);
        // Avoid conflicts if we later create another file with the same name
        this._closePath(path);
    }
    /**
     * Closes all watchers for a path
     */
    _closePath(path) {
        this._closeFile(path);
        const dir = sysPath.dirname(path);
        this._getWatchedDir(dir).remove(sysPath.basename(path));
    }
    /**
     * Closes only file-specific watchers
     */
    _closeFile(path) {
        const closers = this._closers.get(path);
        if (!closers)
            return;
        closers.forEach((closer) => closer());
        this._closers.delete(path);
    }
    _addPathCloser(path, closer) {
        if (!closer)
            return;
        let list = this._closers.get(path);
        if (!list) {
            list = [];
            this._closers.set(path, list);
        }
        list.push(closer);
    }
    _readdirp(root, opts) {
        if (this.closed)
            return;
        const options = { type: handler_js_1.EVENTS.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 };
        let stream = (0, readdirp_1.readdirp)(root, options);
        this._streams.add(stream);
        stream.once(handler_js_1.STR_CLOSE, () => {
            stream = undefined;
        });
        stream.once(handler_js_1.STR_END, () => {
            if (stream) {
                this._streams.delete(stream);
                stream = undefined;
            }
        });
        return stream;
    }
}
exports.FSWatcher = FSWatcher;
/**
 * Instantiates watcher with paths to be tracked.
 * @param paths file / directory paths
 * @param options opts, such as `atomic`, `awaitWriteFinish`, `ignored`, and others
 * @returns an instance of FSWatcher for chaining.
 * @example
 * const watcher = watch('.').on('all', (event, path) => { console.log(event, path); });
 * watch('.', { atomic: true, awaitWriteFinish: true, ignored: (f, stats) => stats?.isFile() && !f.endsWith('.js') })
 */
function watch(paths, options = {}) {
    const watcher = new FSWatcher(options);
    watcher.add(paths);
    return watcher;
}
exports.default = { watch, FSWatcher };
805 lines•29.2 KB
javascript
node_modules/esbuild/lib/main.d.ts
Raw Download
Find: Go to:
export type Platform = 'browser' | 'node' | 'neutral';
export type Format = 'iife' | 'cjs' | 'esm';
export type Loader = 'js' | 'jsx' | 'ts' | 'tsx' | 'css' | 'json' | 'text' | 'base64' | 'file' | 'dataurl' | 'binary' | 'copy' | 'default';
export type LogLevel = 'verbose' | 'debug' | 'info' | 'warning' | 'error' | 'silent';
export type Charset = 'ascii' | 'utf8';
export type Drop = 'console' | 'debugger';

interface CommonOptions {
  /** Documentation: https://esbuild.github.io/api/#sourcemap */
  sourcemap?: boolean | 'linked' | 'inline' | 'external' | 'both';
  /** Documentation: https://esbuild.github.io/api/#legal-comments */
  legalComments?: 'none' | 'inline' | 'eof' | 'linked' | 'external';
  /** Documentation: https://esbuild.github.io/api/#source-root */
  sourceRoot?: string;
  /** Documentation: https://esbuild.github.io/api/#sources-content */
  sourcesContent?: boolean;

  /** Documentation: https://esbuild.github.io/api/#format */
  format?: Format;
  /** Documentation: https://esbuild.github.io/api/#global-name */
  globalName?: string;
  /** Documentation: https://esbuild.github.io/api/#target */
  target?: string | string[];
  /** Documentation: https://esbuild.github.io/api/#supported */
  supported?: Record<string, boolean>;
  /** Documentation: https://esbuild.github.io/api/#platform */
  platform?: Platform;

  /** Documentation: https://esbuild.github.io/api/#mangle-props */
  mangleProps?: RegExp;
  /** Documentation: https://esbuild.github.io/api/#mangle-props */
  reserveProps?: RegExp;
  /** Documentation: https://esbuild.github.io/api/#mangle-props */
  mangleQuoted?: boolean;
  /** Documentation: https://esbuild.github.io/api/#mangle-props */
  mangleCache?: Record<string, string | false>;
  /** Documentation: https://esbuild.github.io/api/#drop */
  drop?: Drop[];
  /** Documentation: https://esbuild.github.io/api/#minify */
  minify?: boolean;
  /** Documentation: https://esbuild.github.io/api/#minify */
  minifyWhitespace?: boolean;
  /** Documentation: https://esbuild.github.io/api/#minify */
  minifyIdentifiers?: boolean;
  /** Documentation: https://esbuild.github.io/api/#minify */
  minifySyntax?: boolean;
  /** Documentation: https://esbuild.github.io/api/#charset */
  charset?: Charset;
  /** Documentation: https://esbuild.github.io/api/#tree-shaking */
  treeShaking?: boolean;
  /** Documentation: https://esbuild.github.io/api/#ignore-annotations */
  ignoreAnnotations?: boolean;

  /** Documentation: https://esbuild.github.io/api/#jsx */
  jsx?: 'transform' | 'preserve' | 'automatic';
  /** Documentation: https://esbuild.github.io/api/#jsx-factory */
  jsxFactory?: string;
  /** Documentation: https://esbuild.github.io/api/#jsx-fragment */
  jsxFragment?: string;
  /** Documentation: https://esbuild.github.io/api/#jsx-import-source */
  jsxImportSource?: string;
  /** Documentation: https://esbuild.github.io/api/#jsx-development */
  jsxDev?: boolean;

  /** Documentation: https://esbuild.github.io/api/#define */
  define?: { [key: string]: string };
  /** Documentation: https://esbuild.github.io/api/#pure */
  pure?: string[];
  /** Documentation: https://esbuild.github.io/api/#keep-names */
  keepNames?: boolean;

  /** Documentation: https://esbuild.github.io/api/#color */
  color?: boolean;
  /** Documentation: https://esbuild.github.io/api/#log-level */
  logLevel?: LogLevel;
  /** Documentation: https://esbuild.github.io/api/#log-limit */
  logLimit?: number;
  /** Documentation: https://esbuild.github.io/api/#log-override */
  logOverride?: Record<string, LogLevel>;
}

export interface BuildOptions extends CommonOptions {
  /** Documentation: https://esbuild.github.io/api/#bundle */
  bundle?: boolean;
  /** Documentation: https://esbuild.github.io/api/#splitting */
  splitting?: boolean;
  /** Documentation: https://esbuild.github.io/api/#preserve-symlinks */
  preserveSymlinks?: boolean;
  /** Documentation: https://esbuild.github.io/api/#outfile */
  outfile?: string;
  /** Documentation: https://esbuild.github.io/api/#metafile */
  metafile?: boolean;
  /** Documentation: https://esbuild.github.io/api/#outdir */
  outdir?: string;
  /** Documentation: https://esbuild.github.io/api/#outbase */
  outbase?: string;
  /** Documentation: https://esbuild.github.io/api/#external */
  external?: string[];
  /** Documentation: https://esbuild.github.io/api/#loader */
  loader?: { [ext: string]: Loader };
  /** Documentation: https://esbuild.github.io/api/#resolve-extensions */
  resolveExtensions?: string[];
  /** Documentation: https://esbuild.github.io/api/#main-fields */
  mainFields?: string[];
  /** Documentation: https://esbuild.github.io/api/#conditions */
  conditions?: string[];
  /** Documentation: https://esbuild.github.io/api/#write */
  write?: boolean;
  /** Documentation: https://esbuild.github.io/api/#allow-overwrite */
  allowOverwrite?: boolean;
  /** Documentation: https://esbuild.github.io/api/#tsconfig */
  tsconfig?: string;
  /** Documentation: https://esbuild.github.io/api/#out-extension */
  outExtension?: { [ext: string]: string };
  /** Documentation: https://esbuild.github.io/api/#public-path */
  publicPath?: string;
  /** Documentation: https://esbuild.github.io/api/#entry-names */
  entryNames?: string;
  /** Documentation: https://esbuild.github.io/api/#chunk-names */
  chunkNames?: string;
  /** Documentation: https://esbuild.github.io/api/#asset-names */
  assetNames?: string;
  /** Documentation: https://esbuild.github.io/api/#inject */
  inject?: string[];
  /** Documentation: https://esbuild.github.io/api/#banner */
  banner?: { [type: string]: string };
  /** Documentation: https://esbuild.github.io/api/#footer */
  footer?: { [type: string]: string };
  /** Documentation: https://esbuild.github.io/api/#incremental */
  incremental?: boolean;
  /** Documentation: https://esbuild.github.io/api/#entry-points */
  entryPoints?: string[] | Record<string, string>;
  /** Documentation: https://esbuild.github.io/api/#stdin */
  stdin?: StdinOptions;
  /** Documentation: https://esbuild.github.io/plugins/ */
  plugins?: Plugin[];
  /** Documentation: https://esbuild.github.io/api/#working-directory */
  absWorkingDir?: string;
  /** Documentation: https://esbuild.github.io/api/#node-paths */
  nodePaths?: string[]; // The "NODE_PATH" variable from Node.js
  /** Documentation: https://esbuild.github.io/api/#watch */
  watch?: boolean | WatchMode;
}

export interface WatchMode {
  onRebuild?: (error: BuildFailure | null, result: BuildResult | null) => void;
}

export interface StdinOptions {
  contents: string | Uint8Array;
  resolveDir?: string;
  sourcefile?: string;
  loader?: Loader;
}

export interface Message {
  id: string;
  pluginName: string;
  text: string;
  location: Location | null;
  notes: Note[];

  /**
   * Optional user-specified data that is passed through unmodified. You can
   * use this to stash the original error, for example.
   */
  detail: any;
}

export interface Note {
  text: string;
  location: Location | null;
}

export interface Location {
  file: string;
  namespace: string;
  /** 1-based */
  line: number;
  /** 0-based, in bytes */
  column: number;
  /** in bytes */
  length: number;
  lineText: string;
  suggestion: string;
}

export interface OutputFile {
  path: string;
  /** "text" as bytes */
  contents: Uint8Array;
  /** "contents" as text */
  text: string;
}

export interface BuildInvalidate {
  (): Promise<BuildIncremental>;
  dispose(): void;
}

export interface BuildIncremental extends BuildResult {
  rebuild: BuildInvalidate;
}

export interface BuildResult {
  errors: Message[];
  warnings: Message[];
  /** Only when "write: false" */
  outputFiles?: OutputFile[];
  /** Only when "incremental: true" */
  rebuild?: BuildInvalidate;
  /** Only when "watch: true" */
  stop?: () => void;
  /** Only when "metafile: true" */
  metafile?: Metafile;
  /** Only when "mangleCache" is present */
  mangleCache?: Record<string, string | false>;
}

export interface BuildFailure extends Error {
  errors: Message[];
  warnings: Message[];
}

/** Documentation: https://esbuild.github.io/api/#serve-arguments */
export interface ServeOptions {
  port?: number;
  host?: string;
  servedir?: string;
  onRequest?: (args: ServeOnRequestArgs) => void;
}

export interface ServeOnRequestArgs {
  remoteAddress: string;
  method: string;
  path: string;
  status: number;
  /** The time to generate the response, not to send it */
  timeInMS: number;
}

/** Documentation: https://esbuild.github.io/api/#serve-return-values */
export interface ServeResult {
  port: number;
  host: string;
  wait: Promise<void>;
  stop: () => void;
}

export interface TransformOptions extends CommonOptions {
  tsconfigRaw?: string | {
    compilerOptions?: {
      jsxFactory?: string,
      jsxFragmentFactory?: string,
      useDefineForClassFields?: boolean,
      importsNotUsedAsValues?: 'remove' | 'preserve' | 'error',
      preserveValueImports?: boolean,
    },
  };

  sourcefile?: string;
  loader?: Loader;
  banner?: string;
  footer?: string;
}

export interface TransformResult {
  code: string;
  map: string;
  warnings: Message[];
  /** Only when "mangleCache" is present */
  mangleCache?: Record<string, string | false>;
}

export interface TransformFailure extends Error {
  errors: Message[];
  warnings: Message[];
}

export interface Plugin {
  name: string;
  setup: (build: PluginBuild) => (void | Promise<void>);
}

export interface PluginBuild {
  initialOptions: BuildOptions;
  resolve(path: string, options?: ResolveOptions): Promise<ResolveResult>;

  onStart(callback: () =>
    (OnStartResult | null | void | Promise<OnStartResult | null | void>)): void;
  onEnd(callback: (result: BuildResult) =>
    (void | Promise<void>)): void;
  onResolve(options: OnResolveOptions, callback: (args: OnResolveArgs) =>
    (OnResolveResult | null | undefined | Promise<OnResolveResult | null | undefined>)): void;
  onLoad(options: OnLoadOptions, callback: (args: OnLoadArgs) =>
    (OnLoadResult | null | undefined | Promise<OnLoadResult | null | undefined>)): void;

  // This is a full copy of the esbuild library in case you need it
  esbuild: {
    serve: typeof serve,
    build: typeof build,
    buildSync: typeof buildSync,
    transform: typeof transform,
    transformSync: typeof transformSync,
    formatMessages: typeof formatMessages,
    formatMessagesSync: typeof formatMessagesSync,
    analyzeMetafile: typeof analyzeMetafile,
    analyzeMetafileSync: typeof analyzeMetafileSync,
    initialize: typeof initialize,
    version: typeof version,
  };
}

export interface ResolveOptions {
  pluginName?: string;
  importer?: string;
  namespace?: string;
  resolveDir?: string;
  kind?: ImportKind;
  pluginData?: any;
}

export interface ResolveResult {
  errors: Message[];
  warnings: Message[];

  path: string;
  external: boolean;
  sideEffects: boolean;
  namespace: string;
  suffix: string;
  pluginData: any;
}

export interface OnStartResult {
  errors?: PartialMessage[];
  warnings?: PartialMessage[];
}

export interface OnResolveOptions {
  filter: RegExp;
  namespace?: string;
}

export interface OnResolveArgs {
  path: string;
  importer: string;
  namespace: string;
  resolveDir: string;
  kind: ImportKind;
  pluginData: any;
}

export type ImportKind =
  | 'entry-point'

  // JS
  | 'import-statement'
  | 'require-call'
  | 'dynamic-import'
  | 'require-resolve'

  // CSS
  | 'import-rule'
  | 'url-token'

export interface OnResolveResult {
  pluginName?: string;

  errors?: PartialMessage[];
  warnings?: PartialMessage[];

  path?: string;
  external?: boolean;
  sideEffects?: boolean;
  namespace?: string;
  suffix?: string;
  pluginData?: any;

  watchFiles?: string[];
  watchDirs?: string[];
}

export interface OnLoadOptions {
  filter: RegExp;
  namespace?: string;
}

export interface OnLoadArgs {
  path: string;
  namespace: string;
  suffix: string;
  pluginData: any;
}

export interface OnLoadResult {
  pluginName?: string;

  errors?: PartialMessage[];
  warnings?: PartialMessage[];

  contents?: string | Uint8Array;
  resolveDir?: string;
  loader?: Loader;
  pluginData?: any;

  watchFiles?: string[];
  watchDirs?: string[];
}

export interface PartialMessage {
  id?: string;
  pluginName?: string;
  text?: string;
  location?: Partial<Location> | null;
  notes?: PartialNote[];
  detail?: any;
}

export interface PartialNote {
  text?: string;
  location?: Partial<Location> | null;
}

export interface Metafile {
  inputs: {
    [path: string]: {
      bytes: number
      imports: {
        path: string
        kind: ImportKind
      }[]
    }
  }
  outputs: {
    [path: string]: {
      bytes: number
      inputs: {
        [path: string]: {
          bytesInOutput: number
        }
      }
      imports: {
        path: string
        kind: ImportKind
      }[]
      exports: string[]
      entryPoint?: string
    }
  }
}

export interface FormatMessagesOptions {
  kind: 'error' | 'warning';
  color?: boolean;
  terminalWidth?: number;
}

export interface AnalyzeMetafileOptions {
  color?: boolean;
  verbose?: boolean;
}

/**
 * This function invokes the "esbuild" command-line tool for you. It returns a
 * promise that either resolves with a "BuildResult" object or rejects with a
 * "BuildFailure" object.
 *
 * - Works in node: yes
 * - Works in browser: yes
 *
 * Documentation: https://esbuild.github.io/api/#build-api
 */
export declare function build(options: BuildOptions & { write: false }): Promise<BuildResult & { outputFiles: OutputFile[] }>;
export declare function build(options: BuildOptions & { incremental: true, metafile: true }): Promise<BuildIncremental & { metafile: Metafile }>;
export declare function build(options: BuildOptions & { incremental: true }): Promise<BuildIncremental>;
export declare function build(options: BuildOptions & { metafile: true }): Promise<BuildResult & { metafile: Metafile }>;
export declare function build(options: BuildOptions): Promise<BuildResult>;

/**
 * This function is similar to "build" but it serves the resulting files over
 * HTTP on a localhost address with the specified port.
 *
 * - Works in node: yes
 * - Works in browser: no
 *
 * Documentation: https://esbuild.github.io/api/#serve
 */
export declare function serve(serveOptions: ServeOptions, buildOptions: BuildOptions): Promise<ServeResult>;

/**
 * This function transforms a single JavaScript file. It can be used to minify
 * JavaScript, convert TypeScript/JSX to JavaScript, or convert newer JavaScript
 * to older JavaScript. It returns a promise that is either resolved with a
 * "TransformResult" object or rejected with a "TransformFailure" object.
 *
 * - Works in node: yes
 * - Works in browser: yes
 *
 * Documentation: https://esbuild.github.io/api/#transform-api
 */
export declare function transform(input: string | Uint8Array, options?: TransformOptions): Promise<TransformResult>;

/**
 * Converts log messages to formatted message strings suitable for printing in
 * the terminal. This allows you to reuse the built-in behavior of esbuild's
 * log message formatter. This is a batch-oriented API for efficiency.
 *
 * - Works in node: yes
 * - Works in browser: yes
 */
export declare function formatMessages(messages: PartialMessage[], options: FormatMessagesOptions): Promise<string[]>;

/**
 * Pretty-prints an analysis of the metafile JSON to a string. This is just for
 * convenience to be able to match esbuild's pretty-printing exactly. If you want
 * to customize it, you can just inspect the data in the metafile yourself.
 *
 * - Works in node: yes
 * - Works in browser: yes
 *
 * Documentation: https://esbuild.github.io/api/#analyze
 */
export declare function analyzeMetafile(metafile: Metafile | string, options?: AnalyzeMetafileOptions): Promise<string>;

/**
 * A synchronous version of "build".
 *
 * - Works in node: yes
 * - Works in browser: no
 *
 * Documentation: https://esbuild.github.io/api/#build-api
 */
export declare function buildSync(options: BuildOptions & { write: false }): BuildResult & { outputFiles: OutputFile[] };
export declare function buildSync(options: BuildOptions): BuildResult;

/**
 * A synchronous version of "transform".
 *
 * - Works in node: yes
 * - Works in browser: no
 *
 * Documentation: https://esbuild.github.io/api/#transform-api
 */
export declare function transformSync(input: string, options?: TransformOptions): TransformResult;

/**
 * A synchronous version of "formatMessages".
 *
 * - Works in node: yes
 * - Works in browser: no
 */
export declare function formatMessagesSync(messages: PartialMessage[], options: FormatMessagesOptions): string[];

/**
 * A synchronous version of "analyzeMetafile".
 *
 * - Works in node: yes
 * - Works in browser: no
 *
 * Documentation: https://esbuild.github.io/api/#analyze
 */
export declare function analyzeMetafileSync(metafile: Metafile | string, options?: AnalyzeMetafileOptions): string;

/**
 * This configures the browser-based version of esbuild. It is necessary to
 * call this first and wait for the returned promise to be resolved before
 * making other API calls when using esbuild in the browser.
 *
 * - Works in node: yes
 * - Works in browser: yes ("options" is required)
 *
 * Documentation: https://esbuild.github.io/api/#running-in-the-browser
 */
export declare function initialize(options: InitializeOptions): Promise<void>;

export interface InitializeOptions {
  /**
   * The URL of the "esbuild.wasm" file. This must be provided when running
   * esbuild in the browser.
   */
  wasmURL?: string

  /**
   * The result of calling "new WebAssembly.Module(buffer)" where "buffer"
   * is a typed array or ArrayBuffer containing the binary code of the
   * "esbuild.wasm" file.
   *
   * You can use this as an alternative to "wasmURL" for environments where it's
   * not possible to download the WebAssembly module.
   */
  wasmModule?: WebAssembly.Module

  /**
   * By default esbuild runs the WebAssembly-based browser API in a web worker
   * to avoid blocking the UI thread. This can be disabled by setting "worker"
   * to false.
   */
  worker?: boolean
}

export let version: string;
603 lines•17.8 KB
typescript
🚀 Support RSK World

Subscribe to our YouTube channel for latest tutorials & updates!



Click subscribe & support our work ❤️

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer