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
/
@hotwired
/
stimulus
/
dist
/
types
RSK World
ruby-calculator
Ruby Calculator Pro - Interactive Calculator with 8 Types + Mathematical Functions + Rails MVC + Modern Web Interface + API Integration + Educational Design
types
  • core
  • multimap
  • mutation-observers
  • tests
  • index.d.ts90 B
binding.ccDirTree.hhBackend.ccWatcher.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
node_modules/@parcel/watcher/src/Watcher.cc
Raw Download
Find: Go to:
#include "Watcher.hh"
#include <unordered_set>

using namespace Napi;

struct WatcherHash {
  std::size_t operator() (WatcherRef const &k) const {
    return std::hash<std::string>()(k->mDir);
  }
};

struct WatcherCompare {
  size_t operator() (WatcherRef const &a, WatcherRef const &b) const {
    return *a == *b;
  }
};

static std::unordered_set<WatcherRef , WatcherHash, WatcherCompare>& getSharedWatchers() {
  static std::unordered_set<WatcherRef , WatcherHash, WatcherCompare>* sharedWatchers = 
    new std::unordered_set<WatcherRef , WatcherHash, WatcherCompare>();
  return *sharedWatchers;
}

WatcherRef Watcher::getShared(std::string dir, std::unordered_set<std::string> ignorePaths, std::unordered_set<Glob> ignoreGlobs) {
  WatcherRef watcher = std::make_shared<Watcher>(dir, ignorePaths, ignoreGlobs);
  auto found = getSharedWatchers().find(watcher);
  if (found != getSharedWatchers().end()) {
    return *found;
  }

  getSharedWatchers().insert(watcher);
  return watcher;
}

void removeShared(Watcher *watcher) {
  for (auto it = getSharedWatchers().begin(); it != getSharedWatchers().end(); it++) {
    if (it->get() == watcher) {
      getSharedWatchers().erase(it);
      break;
    }
  }

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

Watcher::Watcher(std::string dir, std::unordered_set<std::string> ignorePaths, std::unordered_set<Glob> ignoreGlobs)
  : mDir(dir),
    mIgnorePaths(ignorePaths),
    mIgnoreGlobs(ignoreGlobs) {
      mDebounce = Debounce::getShared();
      mDebounce->add(this, [this] () {
        triggerCallbacks();
      });
    }

Watcher::~Watcher() {
  mDebounce->remove(this);
}

void Watcher::wait() {
  std::unique_lock<std::mutex> lk(mMutex);
  mCond.wait(lk);
}

void Watcher::notify() {
  std::unique_lock<std::mutex> lk(mMutex);
  mCond.notify_all();

  if (mCallbacks.size() > 0 && mEvents.size() > 0) {
    // We must release our lock before calling into the debouncer
    // to avoid a deadlock: the debouncer thread itself will require
    // our lock from its thread when calling into `triggerCallbacks`
    // while holding its own debouncer lock.
    lk.unlock();
    mDebounce->trigger();
  }
}

struct CallbackData {
  std::string error;
  std::vector<Event> events;
  CallbackData(std::string error, std::vector<Event> events) : error(error), events(events) {}
};

Value callbackEventsToJS(const Env &env, std::vector<Event> &events) {
  EscapableHandleScope scope(env);
  Array arr = Array::New(env, events.size());
  uint32_t currentEventIndex = 0;
  for (auto eventIterator = events.begin(); eventIterator != events.end(); eventIterator++) {
    arr.Set(currentEventIndex++, eventIterator->toJS(env));
  }
  return scope.Escape(arr);
}

void callJSFunction(Napi::Env env, Function jsCallback, CallbackData *data) {
  HandleScope scope(env);
  auto err = data->error.size() > 0 ? Error::New(env, data->error).Value() : env.Null();
  auto events = callbackEventsToJS(env, data->events);
  jsCallback.Call({err, events});
  delete data;

  // Throw errors from the callback as fatal exceptions
  // If we don't handle these node segfaults...
  if (env.IsExceptionPending()) {
    Napi::Error err = env.GetAndClearPendingException();
    napi_fatal_exception(env, err.Value());
  }
}

void Watcher::notifyError(std::exception &err) {
  std::unique_lock<std::mutex> lk(mMutex);
  for (auto it = mCallbacks.begin(); it != mCallbacks.end(); it++) {
    CallbackData *data = new CallbackData(err.what(), {});
    it->tsfn.BlockingCall(data, callJSFunction);
  }

  clearCallbacks();
}

// This function is called from the debounce thread.
void Watcher::triggerCallbacks() {
  std::unique_lock<std::mutex> lk(mMutex);
  if (mCallbacks.size() > 0 && (mEvents.size() > 0 || mEvents.hasError())) {
    auto error = mEvents.getError();
    auto events = mEvents.getEvents();
    mEvents.clear();

    for (auto it = mCallbacks.begin(); it != mCallbacks.end(); it++) {
      it->tsfn.BlockingCall(new CallbackData(error, events), callJSFunction);
    }
  }
}

// This should be called from the JavaScript thread.
bool Watcher::watch(Function callback) {
  std::unique_lock<std::mutex> lk(mMutex);

  auto it = findCallback(callback);
  if (it != mCallbacks.end()) {
    return false;
  }

  auto tsfn = ThreadSafeFunction::New(
    callback.Env(),
    callback,
    "Watcher callback",
    0, // Unlimited queue
    1 // Initial thread count
  );

  mCallbacks.push_back(Callback {
    tsfn,
    Napi::Persistent(callback),
    std::this_thread::get_id()
  });

  return true;
}

// This should be called from the JavaScript thread.
std::vector<Callback>::iterator Watcher::findCallback(Function callback) {
  for (auto it = mCallbacks.begin(); it != mCallbacks.end(); it++) {
    // Only consider callbacks created by the same thread, or V8 will panic.
    if (it->threadId == std::this_thread::get_id() && it->ref.Value() == callback) {
      return it;
    }
  }

  return mCallbacks.end();
}

// This should be called from the JavaScript thread.
bool Watcher::unwatch(Function callback) {
  std::unique_lock<std::mutex> lk(mMutex);

  bool removed = false;
  auto it = findCallback(callback);
  if (it != mCallbacks.end()) {
    it->tsfn.Release();
    it->ref.Unref();
    mCallbacks.erase(it);
    removed = true;
  }

  if (removed && mCallbacks.size() == 0) {
    unref();
    return true;
  }

  return false;
}

void Watcher::unref() {
  if (mCallbacks.size() == 0) {
    removeShared(this);
  }
}

void Watcher::destroy() {
  std::unique_lock<std::mutex> lk(mMutex);
  clearCallbacks();
}

// Private because it doesn't lock.
void Watcher::clearCallbacks() {
  for (auto it = mCallbacks.begin(); it != mCallbacks.end(); it++) {
    it->tsfn.Release();
    it->ref.Unref();
  }

  mCallbacks.clear();
  unref();
}

bool Watcher::isIgnored(std::string path) {
  for (auto it = mIgnorePaths.begin(); it != mIgnorePaths.end(); it++) {
    auto dir = *it + DIR_SEP;
    if (*it == path || path.compare(0, dir.size(), dir) == 0) {
      return true;
    }
  }

  auto basePath = mDir + DIR_SEP;

  if (path.rfind(basePath, 0) != 0) {
    return false;
  }

  auto relativePath = path.substr(basePath.size());

  for (auto it = mIgnoreGlobs.begin(); it != mIgnoreGlobs.end(); it++) {
    if (it->isIgnored(relativePath)) {
      return true;
    }
  }

  return false;
}
242 lines•6.2 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