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
/
@parcel
/
watcher
/
src
RSK World
ruby-calculator
Ruby Calculator Pro - Interactive Calculator with 8 Types + Mathematical Functions + Rails MVC + Modern Web Interface + API Integration + Educational Design
src
  • kqueue
  • linux
  • macos
  • shared
  • unix
  • wasm
  • watchman
  • windows
  • Backend.cc4.3 KB
  • Backend.hh874 B
  • Debounce.cc2.5 KB
  • Debounce.hh883 B
  • DirTree.cc4.2 KB
  • DirTree.hh1.1 KB
  • Event.hh2.5 KB
  • Glob.cc539 B
  • Glob.hh509 B
  • PromiseRunner.hh2.5 KB
  • Signal.hh816 B
  • Watcher.cc6.2 KB
  • Watcher.hh1.8 KB
  • binding.cc6.8 KB
binding.ccDirTree.hhBackend.cc
node_modules/@parcel/watcher/src/binding.cc
Raw Download
Find: Go to:
#include <unordered_set>
#include <node_api.h>
#include "wasm/include.h"
#include <napi.h>
#include "Glob.hh"
#include "Event.hh"
#include "Backend.hh"
#include "Watcher.hh"
#include "PromiseRunner.hh"

using namespace Napi;

std::unordered_set<std::string> getIgnorePaths(Env env, Value opts) {
  std::unordered_set<std::string> result;

  if (opts.IsObject()) {
    Value v = opts.As<Object>().Get(String::New(env, "ignorePaths"));
    if (v.IsArray()) {
      Array items = v.As<Array>();
      for (size_t i = 0; i < items.Length(); i++) {
        Value item = items.Get(Number::New(env, static_cast<double>(i)));
        if (item.IsString()) {
          result.insert(std::string(item.As<String>().Utf8Value().c_str()));
        }
      }
    }
  }

  return result;
}

std::unordered_set<Glob> getIgnoreGlobs(Env env, Value opts) {
  std::unordered_set<Glob> result;

  if (opts.IsObject()) {
    Value v = opts.As<Object>().Get(String::New(env, "ignoreGlobs"));
    if (v.IsArray()) {
      Array items = v.As<Array>();
      for (size_t i = 0; i < items.Length(); i++) {
        Value item = items.Get(Number::New(env, static_cast<double>(i)));
        if (item.IsString()) {
          auto key = item.As<String>().Utf8Value();
          try {
            result.emplace(key);
          } catch (const std::regex_error& e) {
            Error::New(env, e.what()).ThrowAsJavaScriptException();
          }
        }
      }
    }
  }

  return result;
}

std::shared_ptr<Backend> getBackend(Env env, Value opts) {
  Value b = opts.As<Object>().Get(String::New(env, "backend"));
  std::string backendName;
  if (b.IsString()) {
    backendName = std::string(b.As<String>().Utf8Value().c_str());
  }

  return Backend::getShared(backendName);
}

class WriteSnapshotRunner : public PromiseRunner {
public:
  WriteSnapshotRunner(Env env, Value dir, Value snap, Value opts)
    : PromiseRunner(env),
      snapshotPath(std::string(snap.As<String>().Utf8Value().c_str())) {
    watcher = Watcher::getShared(
      std::string(dir.As<String>().Utf8Value().c_str()),
      getIgnorePaths(env, opts),
      getIgnoreGlobs(env, opts)
    );

    backend = getBackend(env, opts);
  }

  ~WriteSnapshotRunner() {
    watcher->unref();
    backend->unref();
  }
private:
  std::shared_ptr<Backend> backend;
  WatcherRef watcher;
  std::string snapshotPath;

  void execute() override {
    backend->writeSnapshot(watcher, &snapshotPath);
  }
};

class GetEventsSinceRunner : public PromiseRunner {
public:
  GetEventsSinceRunner(Env env, Value dir, Value snap, Value opts)
    : PromiseRunner(env),
      snapshotPath(std::string(snap.As<String>().Utf8Value().c_str())) {
    watcher = std::make_shared<Watcher>(
      std::string(dir.As<String>().Utf8Value().c_str()),
      getIgnorePaths(env, opts),
      getIgnoreGlobs(env, opts)
    );

    backend = getBackend(env, opts);
  }

  ~GetEventsSinceRunner() {
    watcher->unref();
    backend->unref();
  }
private:
  std::shared_ptr<Backend> backend;
  WatcherRef watcher;
  std::string snapshotPath;

  void execute() override {
    backend->getEventsSince(watcher, &snapshotPath);
    if (watcher->mEvents.hasError()) {
      throw std::runtime_error(watcher->mEvents.getError());
    }
  }

  Value getResult() override {
    std::vector<Event> events = watcher->mEvents.getEvents();
    Array eventsArray = Array::New(env, events.size());
    uint32_t i = 0;
    for (auto it = events.begin(); it != events.end(); it++) {
      eventsArray.Set(i++, it->toJS(env));
    }
    return eventsArray;
  }
};

template<class Runner>
Value queueSnapshotWork(const CallbackInfo& info) {
  Env env = info.Env();
  if (info.Length() < 1 || !info[0].IsString()) {
    TypeError::New(env, "Expected a string").ThrowAsJavaScriptException();
    return env.Null();
  }

  if (info.Length() < 2 || !info[1].IsString()) {
    TypeError::New(env, "Expected a string").ThrowAsJavaScriptException();
    return env.Null();
  }

  if (info.Length() >= 3 && !info[2].IsObject()) {
    TypeError::New(env, "Expected an object").ThrowAsJavaScriptException();
    return env.Null();
  }

  Runner *runner = new Runner(info.Env(), info[0], info[1], info[2]);
  return runner->queue();
}

Value writeSnapshot(const CallbackInfo& info) {
  return queueSnapshotWork<WriteSnapshotRunner>(info);
}

Value getEventsSince(const CallbackInfo& info) {
  return queueSnapshotWork<GetEventsSinceRunner>(info);
}

class SubscribeRunner : public PromiseRunner {
public:
  SubscribeRunner(Env env, Value dir, Value fn, Value opts) : PromiseRunner(env) {
    watcher = Watcher::getShared(
      std::string(dir.As<String>().Utf8Value().c_str()),
      getIgnorePaths(env, opts),
      getIgnoreGlobs(env, opts)
    );

    backend = getBackend(env, opts);
    watcher->watch(fn.As<Function>());
  }

private:
  WatcherRef watcher;
  std::shared_ptr<Backend> backend;
  FunctionReference callback;

  void execute() override {
    try {
      backend->watch(watcher);
    } catch (std::exception&) {
      watcher->destroy();
      throw;
    }
  }
};

class UnsubscribeRunner : public PromiseRunner {
public:
  UnsubscribeRunner(Env env, Value dir, Value fn, Value opts) : PromiseRunner(env) {
    watcher = Watcher::getShared(
      std::string(dir.As<String>().Utf8Value().c_str()),
      getIgnorePaths(env, opts),
      getIgnoreGlobs(env, opts)
    );

    backend = getBackend(env, opts);
    shouldUnwatch = watcher->unwatch(fn.As<Function>());
  }

private:
  WatcherRef watcher;
  std::shared_ptr<Backend> backend;
  bool shouldUnwatch;

  void execute() override {
    if (shouldUnwatch) {
      backend->unwatch(watcher);
    }
  }
};

template<class Runner>
Value queueSubscriptionWork(const CallbackInfo& info) {
  Env env = info.Env();
  if (info.Length() < 1 || !info[0].IsString()) {
    TypeError::New(env, "Expected a string").ThrowAsJavaScriptException();
    return env.Null();
  }

  if (info.Length() < 2 || !info[1].IsFunction()) {
    TypeError::New(env, "Expected a function").ThrowAsJavaScriptException();
    return env.Null();
  }

  if (info.Length() >= 3 && !info[2].IsObject()) {
    TypeError::New(env, "Expected an object").ThrowAsJavaScriptException();
    return env.Null();
  }

  Runner *runner = new Runner(info.Env(), info[0], info[1], info[2]);
  return runner->queue();
}

Value subscribe(const CallbackInfo& info) {
  return queueSubscriptionWork<SubscribeRunner>(info);
}

Value unsubscribe(const CallbackInfo& info) {
  return queueSubscriptionWork<UnsubscribeRunner>(info);
}

Object Init(Env env, Object exports) {
  exports.Set(
    String::New(env, "writeSnapshot"),
    Function::New(env, writeSnapshot)
  );
  exports.Set(
    String::New(env, "getEventsSince"),
    Function::New(env, getEventsSince)
  );
  exports.Set(
    String::New(env, "subscribe"),
    Function::New(env, subscribe)
  );
  exports.Set(
    String::New(env, "unsubscribe"),
    Function::New(env, unsubscribe)
  );
  return exports;
}

NODE_API_MODULE(watcher, Init)
269 lines•6.8 KB
cpp
DirTree.hh

This file cannot be displayed in the browser.

Download File
node_modules/@parcel/watcher/src/Backend.cc
Raw Download
Find: Go to:
#ifdef FS_EVENTS
#include "macos/FSEventsBackend.hh"
#endif
#ifdef WATCHMAN
#include "watchman/WatchmanBackend.hh"
#endif
#ifdef WINDOWS
#include "windows/WindowsBackend.hh"
#endif
#ifdef INOTIFY
#include "linux/InotifyBackend.hh"
#endif
#ifdef KQUEUE
#include "kqueue/KqueueBackend.hh"
#endif
#ifdef __wasm32__
#include "wasm/WasmBackend.hh"
#endif
#include "shared/BruteForceBackend.hh"

#include "Backend.hh"
#include <unordered_map>

static std::unordered_map<std::string, std::shared_ptr<Backend>>& getSharedBackends() {
  static std::unordered_map<std::string, std::shared_ptr<Backend>>* sharedBackends = 
    new std::unordered_map<std::string, std::shared_ptr<Backend>>();
  return *sharedBackends;
}

std::shared_ptr<Backend> getBackend(std::string backend) {
  // Use FSEvents on macOS by default.
  // Use watchman by default if available on other platforms.
  // Fall back to brute force.
  #ifdef FS_EVENTS
    if (backend == "fs-events" || backend == "default") {
      return std::make_shared<FSEventsBackend>();
    }
  #endif
  #ifdef WATCHMAN
    if ((backend == "watchman" || backend == "default") && WatchmanBackend::checkAvailable()) {
      return std::make_shared<WatchmanBackend>();
    }
  #endif
  #ifdef WINDOWS
    if (backend == "windows" || backend == "default") {
      return std::make_shared<WindowsBackend>();
    }
  #endif
  #ifdef INOTIFY
    if (backend == "inotify" || backend == "default") {
      return std::make_shared<InotifyBackend>();
    }
  #endif
  #ifdef KQUEUE
    if (backend == "kqueue" || backend == "default") {
      return std::make_shared<KqueueBackend>();
    }
  #endif
  #ifdef __wasm32__
    if (backend == "wasm" || backend == "default") {
      return std::make_shared<WasmBackend>();
    }
  #endif
  if (backend == "brute-force" || backend == "default") {
    return std::make_shared<BruteForceBackend>();
  }

  return nullptr;
}

std::shared_ptr<Backend> Backend::getShared(std::string backend) {
  auto found = getSharedBackends().find(backend);
  if (found != getSharedBackends().end()) {
    return found->second;
  }

  auto result = getBackend(backend);
  if (!result) {
    return getShared("default");
  }

  result->run();
  getSharedBackends().emplace(backend, result);
  return result;
}

void removeShared(Backend *backend) {
  for (auto it = getSharedBackends().begin(); it != getSharedBackends().end(); it++) {
    if (it->second.get() == backend) {
      getSharedBackends().erase(it);
      break;
    }
  }

  // Free up memory.
  if (getSharedBackends().size() == 0) {
    getSharedBackends().rehash(0);
  }
}

void Backend::run() {
  #ifndef __wasm32__
    mThread = std::thread([this] () {
      try {
        start();
      } catch (std::exception &err) {
        handleError(err);
      }
    });

    if (mThread.joinable()) {
      mStartedSignal.wait();
    }
  #else
    try {
      start();
    } catch (std::exception &err) {
      handleError(err);
    }
  #endif
}

void Backend::notifyStarted() {
  mStartedSignal.notify();
}

void Backend::start() {
  notifyStarted();
}

Backend::~Backend() {
  #ifndef __wasm32__
    // Wait for thread to stop
    if (mThread.joinable()) {
      // If the backend is being destroyed from the thread itself, detach, otherwise join.
      if (mThread.get_id() == std::this_thread::get_id()) {
        mThread.detach();
      } else {
        mThread.join();
      }
    }
  #endif
}

void Backend::watch(WatcherRef watcher) {
  std::unique_lock<std::mutex> lock(mMutex);
  auto res = mSubscriptions.find(watcher);
  if (res == mSubscriptions.end()) {
    try {
      this->subscribe(watcher);
      mSubscriptions.insert(watcher);
    } catch (std::exception&) {
      unref();
      throw;
    }
  }
}

void Backend::unwatch(WatcherRef watcher) {
  std::unique_lock<std::mutex> lock(mMutex);
  size_t deleted = mSubscriptions.erase(watcher);
  if (deleted > 0) {
    this->unsubscribe(watcher);
    unref();
  }
}

void Backend::unref() {
  if (mSubscriptions.size() == 0) {
    removeShared(this);
  }
}

void Backend::handleWatcherError(WatcherError &err) {
  unwatch(err.mWatcher);
  err.mWatcher->notifyError(err);
}

void Backend::handleError(std::exception &err) {
  std::unique_lock<std::mutex> lock(mMutex);
  for (auto it = mSubscriptions.begin(); it != mSubscriptions.end(); it++) {
    (*it)->notifyError(err);
  }

  removeShared(this);
}
187 lines•4.3 KB
cpp
🚀 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