@eduardo191labs/watcher 0.0.0-stage → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CMakeLists.txt +82 -0
  2. package/LICENSE +21 -0
  3. package/README.md +135 -2
  4. package/binding.gyp +125 -0
  5. package/index.d.ts +49 -0
  6. package/index.js +55 -0
  7. package/index.js.flow +45 -0
  8. package/package.json +61 -3
  9. package/scripts/build-from-source.js +16 -0
  10. package/src/Backend.cc +186 -0
  11. package/src/Backend.hh +37 -0
  12. package/src/Debounce.cc +113 -0
  13. package/src/Debounce.hh +49 -0
  14. package/src/DirTree.cc +164 -0
  15. package/src/DirTree.hh +50 -0
  16. package/src/Event.hh +109 -0
  17. package/src/Glob.cc +22 -0
  18. package/src/Glob.hh +34 -0
  19. package/src/PromiseRunner.hh +101 -0
  20. package/src/Signal.hh +46 -0
  21. package/src/Watcher.cc +241 -0
  22. package/src/Watcher.hh +73 -0
  23. package/src/binding.cc +268 -0
  24. package/src/kqueue/KqueueBackend.cc +306 -0
  25. package/src/kqueue/KqueueBackend.hh +35 -0
  26. package/src/linux/InotifyBackend.cc +236 -0
  27. package/src/linux/InotifyBackend.hh +34 -0
  28. package/src/macos/FSEventsBackend.cc +338 -0
  29. package/src/macos/FSEventsBackend.hh +20 -0
  30. package/src/shared/BruteForceBackend.cc +41 -0
  31. package/src/shared/BruteForceBackend.hh +25 -0
  32. package/src/unix/fts.cc +50 -0
  33. package/src/unix/legacy.cc +77 -0
  34. package/src/wasm/WasmBackend.cc +132 -0
  35. package/src/wasm/WasmBackend.hh +34 -0
  36. package/src/wasm/include.h +74 -0
  37. package/src/watchman/BSER.cc +302 -0
  38. package/src/watchman/BSER.hh +69 -0
  39. package/src/watchman/IPC.hh +175 -0
  40. package/src/watchman/WatchmanBackend.cc +342 -0
  41. package/src/watchman/WatchmanBackend.hh +35 -0
  42. package/src/windows/WindowsBackend.cc +282 -0
  43. package/src/windows/WindowsBackend.hh +18 -0
  44. package/src/windows/win_utils.cc +44 -0
  45. package/src/windows/win_utils.hh +11 -0
  46. package/wrapper.js +88 -0
@@ -0,0 +1,282 @@
1
+ #include <string>
2
+ #include <stack>
3
+ #include "../DirTree.hh"
4
+ #include "../shared/BruteForceBackend.hh"
5
+ #include "./WindowsBackend.hh"
6
+ #include "./win_utils.hh"
7
+
8
+ #define DEFAULT_BUF_SIZE 1024 * 1024
9
+ #define NETWORK_BUF_SIZE 64 * 1024
10
+ #define CONVERT_TIME(ft) ULARGE_INTEGER{ft.dwLowDateTime, ft.dwHighDateTime}.QuadPart
11
+
12
+ void BruteForceBackend::readTree(WatcherRef watcher, std::shared_ptr<DirTree> tree) {
13
+ std::stack<std::string> directories;
14
+
15
+ directories.push(watcher->mDir);
16
+
17
+ while (!directories.empty()) {
18
+ HANDLE hFind = INVALID_HANDLE_VALUE;
19
+
20
+ std::string path = directories.top();
21
+ std::string spec = path + "\\*";
22
+ directories.pop();
23
+
24
+ WIN32_FIND_DATA ffd;
25
+ hFind = FindFirstFile(spec.c_str(), &ffd);
26
+
27
+ if (hFind == INVALID_HANDLE_VALUE) {
28
+ if (path == watcher->mDir) {
29
+ FindClose(hFind);
30
+ throw WatcherError("Error opening directory", watcher);
31
+ }
32
+
33
+ tree->remove(path);
34
+ continue;
35
+ }
36
+
37
+ do {
38
+ if (strcmp(ffd.cFileName, ".") != 0 && strcmp(ffd.cFileName, "..") != 0) {
39
+ std::string fullPath = path + "\\" + ffd.cFileName;
40
+ if (watcher->isIgnored(fullPath)) {
41
+ continue;
42
+ }
43
+
44
+ tree->add(fullPath, CONVERT_TIME(ffd.ftLastWriteTime), ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
45
+ if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
46
+ directories.push(fullPath);
47
+ }
48
+ }
49
+ } while (FindNextFile(hFind, &ffd) != 0);
50
+
51
+ FindClose(hFind);
52
+ }
53
+ }
54
+
55
+ void WindowsBackend::start() {
56
+ mRunning = true;
57
+ notifyStarted();
58
+
59
+ while (mRunning) {
60
+ SleepEx(INFINITE, true);
61
+ }
62
+ }
63
+
64
+ WindowsBackend::~WindowsBackend() {
65
+ // Mark as stopped, and queue a noop function in the thread to break the loop
66
+ mRunning = false;
67
+ QueueUserAPC([](__in ULONG_PTR) {}, mThread.native_handle(), (ULONG_PTR)this);
68
+ }
69
+
70
+ class Subscription: public WatcherState {
71
+ public:
72
+ Subscription(WindowsBackend *backend, WatcherRef watcher, std::shared_ptr<DirTree> tree) {
73
+ mRunning = true;
74
+ mBackend = backend;
75
+ mWatcher = watcher;
76
+ mTree = tree;
77
+ ZeroMemory(&mOverlapped, sizeof(OVERLAPPED));
78
+ mOverlapped.hEvent = this;
79
+ mReadBuffer.resize(DEFAULT_BUF_SIZE);
80
+ mWriteBuffer.resize(DEFAULT_BUF_SIZE);
81
+
82
+ mDirectoryHandle = CreateFileW(
83
+ utf8ToUtf16(watcher->mDir).data(),
84
+ FILE_LIST_DIRECTORY,
85
+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
86
+ NULL,
87
+ OPEN_EXISTING,
88
+ FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
89
+ NULL
90
+ );
91
+
92
+ if (mDirectoryHandle == INVALID_HANDLE_VALUE) {
93
+ throw WatcherError("Invalid handle", mWatcher);
94
+ }
95
+
96
+ // Ensure that the path is a directory
97
+ BY_HANDLE_FILE_INFORMATION info;
98
+ bool success = GetFileInformationByHandle(
99
+ mDirectoryHandle,
100
+ &info
101
+ );
102
+
103
+ if (!success) {
104
+ throw WatcherError("Could not get file information", mWatcher);
105
+ }
106
+
107
+ if (!(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
108
+ throw WatcherError("Not a directory", mWatcher);
109
+ }
110
+ }
111
+
112
+ virtual ~Subscription() {
113
+ stop();
114
+ }
115
+
116
+ void run() {
117
+ try {
118
+ poll();
119
+ } catch (WatcherError &err) {
120
+ mBackend->handleWatcherError(err);
121
+ }
122
+ }
123
+
124
+ void stop() {
125
+ if (mRunning) {
126
+ mRunning = false;
127
+ CancelIo(mDirectoryHandle);
128
+ CloseHandle(mDirectoryHandle);
129
+ }
130
+ }
131
+
132
+ void poll() {
133
+ if (!mRunning) {
134
+ return;
135
+ }
136
+
137
+ // Asynchronously wait for changes.
138
+ int success = ReadDirectoryChangesW(
139
+ mDirectoryHandle,
140
+ mWriteBuffer.data(),
141
+ static_cast<DWORD>(mWriteBuffer.size()),
142
+ TRUE, // recursive
143
+ FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_ATTRIBUTES
144
+ | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE,
145
+ NULL,
146
+ &mOverlapped,
147
+ [](DWORD errorCode, DWORD numBytes, LPOVERLAPPED overlapped) {
148
+ auto subscription = reinterpret_cast<Subscription *>(overlapped->hEvent);
149
+ try {
150
+ subscription->processEvents(errorCode);
151
+ } catch (WatcherError &err) {
152
+ subscription->mBackend->handleWatcherError(err);
153
+ }
154
+ }
155
+ );
156
+
157
+ if (!success) {
158
+ throw WatcherError("Failed to read changes", mWatcher);
159
+ }
160
+ }
161
+
162
+ void processEvents(DWORD errorCode) {
163
+ if (!mRunning) {
164
+ return;
165
+ }
166
+
167
+ switch (errorCode) {
168
+ case ERROR_OPERATION_ABORTED:
169
+ return;
170
+ case ERROR_INVALID_PARAMETER:
171
+ // resize buffers to network size (64kb), and try again
172
+ mReadBuffer.resize(NETWORK_BUF_SIZE);
173
+ mWriteBuffer.resize(NETWORK_BUF_SIZE);
174
+ poll();
175
+ return;
176
+ case ERROR_NOTIFY_ENUM_DIR:
177
+ throw WatcherError("Buffer overflow. Some events may have been lost.", mWatcher);
178
+ case ERROR_ACCESS_DENIED: {
179
+ // This can happen if the watched directory is deleted. Check if that is the case,
180
+ // and if so emit a delete event. Otherwise, fall through to default error case.
181
+ DWORD attrs = GetFileAttributesW(utf8ToUtf16(mWatcher->mDir).data());
182
+ bool isDir = attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY);
183
+ if (!isDir) {
184
+ mWatcher->mEvents.remove(mWatcher->mDir);
185
+ mTree->remove(mWatcher->mDir);
186
+ mWatcher->notify();
187
+ stop();
188
+ return;
189
+ }
190
+ }
191
+ default:
192
+ if (errorCode != ERROR_SUCCESS) {
193
+ throw WatcherError("Unknown error", mWatcher);
194
+ }
195
+ }
196
+
197
+ // Swap read and write buffers, and poll again
198
+ std::swap(mWriteBuffer, mReadBuffer);
199
+ poll();
200
+
201
+ // Read change events
202
+ BYTE *base = mReadBuffer.data();
203
+ while (true) {
204
+ PFILE_NOTIFY_INFORMATION info = (PFILE_NOTIFY_INFORMATION)base;
205
+ processEvent(info);
206
+
207
+ if (info->NextEntryOffset == 0) {
208
+ break;
209
+ }
210
+
211
+ base += info->NextEntryOffset;
212
+ }
213
+
214
+ mWatcher->notify();
215
+ }
216
+
217
+ void processEvent(PFILE_NOTIFY_INFORMATION info) {
218
+ std::string path = mWatcher->mDir + "\\" + utf16ToUtf8(info->FileName, info->FileNameLength / sizeof(WCHAR));
219
+ if (mWatcher->isIgnored(path)) {
220
+ return;
221
+ }
222
+
223
+ switch (info->Action) {
224
+ case FILE_ACTION_ADDED:
225
+ case FILE_ACTION_RENAMED_NEW_NAME: {
226
+ WIN32_FILE_ATTRIBUTE_DATA data;
227
+ if (GetFileAttributesExW(utf8ToUtf16(path).data(), GetFileExInfoStandard, &data)) {
228
+ mWatcher->mEvents.create(path);
229
+ mTree->add(path, CONVERT_TIME(data.ftLastWriteTime), data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
230
+ }
231
+ break;
232
+ }
233
+ case FILE_ACTION_MODIFIED: {
234
+ WIN32_FILE_ATTRIBUTE_DATA data;
235
+ if (GetFileAttributesExW(utf8ToUtf16(path).data(), GetFileExInfoStandard, &data)) {
236
+ mTree->update(path, CONVERT_TIME(data.ftLastWriteTime));
237
+ if (!(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
238
+ mWatcher->mEvents.update(path);
239
+ }
240
+ }
241
+ break;
242
+ }
243
+ case FILE_ACTION_REMOVED:
244
+ case FILE_ACTION_RENAMED_OLD_NAME:
245
+ mWatcher->mEvents.remove(path);
246
+ mTree->remove(path);
247
+ break;
248
+ }
249
+ }
250
+
251
+ private:
252
+ WindowsBackend *mBackend;
253
+ std::shared_ptr<Watcher> mWatcher;
254
+ std::shared_ptr<DirTree> mTree;
255
+ bool mRunning;
256
+ HANDLE mDirectoryHandle;
257
+ std::vector<BYTE> mReadBuffer;
258
+ std::vector<BYTE> mWriteBuffer;
259
+ OVERLAPPED mOverlapped;
260
+ };
261
+
262
+ // This function is called by Backend::watch which takes a lock on mMutex
263
+ void WindowsBackend::subscribe(WatcherRef watcher) {
264
+ // Create a subscription for this watcher
265
+ auto sub = std::make_shared<Subscription>(this, watcher, getTree(watcher, false));
266
+ watcher->state = sub;
267
+
268
+ // Queue polling for this subscription in the correct thread.
269
+ bool success = QueueUserAPC([](__in ULONG_PTR ptr) {
270
+ Subscription *sub = (Subscription *)ptr;
271
+ sub->run();
272
+ }, mThread.native_handle(), (ULONG_PTR)sub.get());
273
+
274
+ if (!success) {
275
+ throw std::runtime_error("Unable to queue APC");
276
+ }
277
+ }
278
+
279
+ // This function is called by Backend::unwatch which takes a lock on mMutex
280
+ void WindowsBackend::unsubscribe(WatcherRef watcher) {
281
+ watcher->state = nullptr;
282
+ }
@@ -0,0 +1,18 @@
1
+ #ifndef WINDOWS_H
2
+ #define WINDOWS_H
3
+
4
+ #include <winsock2.h>
5
+ #include <windows.h>
6
+ #include "../shared/BruteForceBackend.hh"
7
+
8
+ class WindowsBackend : public BruteForceBackend {
9
+ public:
10
+ void start() override;
11
+ ~WindowsBackend();
12
+ void subscribe(WatcherRef watcher) override;
13
+ void unsubscribe(WatcherRef watcher) override;
14
+ private:
15
+ bool mRunning;
16
+ };
17
+
18
+ #endif
@@ -0,0 +1,44 @@
1
+ #include "./win_utils.hh"
2
+
3
+ std::wstring utf8ToUtf16(std::string input) {
4
+ unsigned int len = MultiByteToWideChar(CP_UTF8, 0, input.c_str(), -1, NULL, 0);
5
+ WCHAR *output = new WCHAR[len];
6
+ MultiByteToWideChar(CP_UTF8, 0, input.c_str(), -1, output, len);
7
+ std::wstring res(output);
8
+ delete[] output;
9
+ return res;
10
+ }
11
+
12
+ std::string utf16ToUtf8(const WCHAR *input, DWORD length) {
13
+ unsigned int len = WideCharToMultiByte(CP_UTF8, 0, input, length, NULL, 0, NULL, NULL);
14
+ char *output = new char[len + 1];
15
+ WideCharToMultiByte(CP_UTF8, 0, input, length, output, len, NULL, NULL);
16
+ output[len] = '\0';
17
+ std::string res(output);
18
+ delete[] output;
19
+ return res;
20
+ }
21
+
22
+ std::string normalizePath(std::string path) {
23
+ // Prevent truncation to MAX_PATH characters by adding the \\?\ prefix
24
+ std::wstring p = utf8ToUtf16("\\\\?\\" + path);
25
+
26
+ // Get the required length for the output
27
+ DWORD len = GetLongPathNameW(p.data(), NULL, 0);
28
+ if (!len) {
29
+ return path;
30
+ }
31
+
32
+ // Allocate output array and get long path
33
+ WCHAR *output = new WCHAR[len];
34
+ len = GetLongPathNameW(p.data(), output, len);
35
+ if (!len) {
36
+ delete[] output;
37
+ return path;
38
+ }
39
+
40
+ // Convert back to utf8
41
+ std::string res = utf16ToUtf8(output + 4, len - 4);
42
+ delete[] output;
43
+ return res;
44
+ }
@@ -0,0 +1,11 @@
1
+ #ifndef WIN_UTILS_H
2
+ #define WIN_UTILS_H
3
+
4
+ #include <string>
5
+ #include <windows.h>
6
+
7
+ std::wstring utf8ToUtf16(std::string input);
8
+ std::string utf16ToUtf8(const WCHAR *input, DWORD length);
9
+ std::string normalizePath(std::string path);
10
+
11
+ #endif
package/wrapper.js ADDED
@@ -0,0 +1,88 @@
1
+ const path = require('path');
2
+ const picomatch = require('picomatch');
3
+ const isGlob = require('is-glob');
4
+
5
+ function normalizeOptions(dir, opts = {}) {
6
+ const {ignore, ...rest} = opts;
7
+
8
+ if (Array.isArray(ignore)) {
9
+ opts = {...rest};
10
+
11
+ for (const value of ignore) {
12
+ if (value instanceof RegExp) {
13
+ if (value.flags !== '') {
14
+ throw new Error(
15
+ `RegExp ignore patterns must not have flags (got /${value.source}/${value.flags}). Flags are not supported by the native matcher.`,
16
+ );
17
+ }
18
+ if (!opts.ignoreGlobs) {
19
+ opts.ignoreGlobs = [];
20
+ }
21
+ // The native backend uses std::regex_match (full-string match), but
22
+ // callers expect JS .test() semantics (substring search). Wrapping the
23
+ // source in ^[\\s\\S]*(?:…)[\\s\\S]*$ achieves that. The (?:…) group
24
+ // isolates the source so leading/trailing | in the source stays contained.
25
+ opts.ignoreGlobs.push(`^[\\s\\S]*(?:${value.source})[\\s\\S]*$`);
26
+ } else if (isGlob(value)) {
27
+ if (!opts.ignoreGlobs) {
28
+ opts.ignoreGlobs = [];
29
+ }
30
+
31
+ const regex = picomatch.makeRe(value, {
32
+ // We set `dot: true` to workaround an issue with the
33
+ // regular expression on Linux where the resulting
34
+ // negative lookahead `(?!(\\/|^)` was never matching
35
+ // in some cases. See also https://bit.ly/3UZlQDm
36
+ dot: true,
37
+ windows: process.platform === 'win32',
38
+ });
39
+ opts.ignoreGlobs.push(regex.source);
40
+ } else {
41
+ if (!opts.ignorePaths) {
42
+ opts.ignorePaths = [];
43
+ }
44
+
45
+ opts.ignorePaths.push(path.resolve(dir, value));
46
+ }
47
+ }
48
+ }
49
+
50
+ return opts;
51
+ }
52
+
53
+ exports.createWrapper = (binding) => {
54
+ return {
55
+ writeSnapshot(dir, snapshot, opts) {
56
+ return binding.writeSnapshot(
57
+ path.resolve(dir),
58
+ path.resolve(snapshot),
59
+ normalizeOptions(dir, opts),
60
+ );
61
+ },
62
+ getEventsSince(dir, snapshot, opts) {
63
+ return binding.getEventsSince(
64
+ path.resolve(dir),
65
+ path.resolve(snapshot),
66
+ normalizeOptions(dir, opts),
67
+ );
68
+ },
69
+ async subscribe(dir, fn, opts) {
70
+ dir = path.resolve(dir);
71
+ opts = normalizeOptions(dir, opts);
72
+ await binding.subscribe(dir, fn, opts);
73
+
74
+ return {
75
+ unsubscribe() {
76
+ return binding.unsubscribe(dir, fn, opts);
77
+ },
78
+ };
79
+ },
80
+ unsubscribe(dir, fn, opts) {
81
+ return binding.unsubscribe(
82
+ path.resolve(dir),
83
+ fn,
84
+ normalizeOptions(dir, opts),
85
+ );
86
+ },
87
+ };
88
+ };