@ohos-ports/pm2 0.0.0-stage → 7.1.2-beta.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 (267) hide show
  1. package/CHANGELOG.md +2607 -0
  2. package/CONTRIBUTING.md +124 -0
  3. package/GNU-AGPL-3.0.txt +665 -0
  4. package/LICENSE +1 -0
  5. package/README.md +255 -2
  6. package/SECURITY.md +41 -0
  7. package/bin/pm2 +3 -0
  8. package/bin/pm2-dev +3 -0
  9. package/bin/pm2-docker +3 -0
  10. package/bin/pm2-runtime +3 -0
  11. package/bin/pm2.ps1 +3 -0
  12. package/constants.js +113 -0
  13. package/index.js +12 -0
  14. package/lib/API/Configuration.js +212 -0
  15. package/lib/API/Containerizer.js +335 -0
  16. package/lib/API/Dashboard.js +726 -0
  17. package/lib/API/Deploy.js +117 -0
  18. package/lib/API/Extra.js +798 -0
  19. package/lib/API/ExtraMgmt/Docker.js +30 -0
  20. package/lib/API/Log.js +388 -0
  21. package/lib/API/LogManagement.js +351 -0
  22. package/lib/API/Modules/LOCAL.js +122 -0
  23. package/lib/API/Modules/Modularizer.js +148 -0
  24. package/lib/API/Modules/NPM.js +443 -0
  25. package/lib/API/Modules/TAR.js +368 -0
  26. package/lib/API/Modules/flagExt.js +46 -0
  27. package/lib/API/Modules/index.js +120 -0
  28. package/lib/API/Monit.js +247 -0
  29. package/lib/API/Serve.js +497 -0
  30. package/lib/API/Startup.js +630 -0
  31. package/lib/API/UX/helpers.js +213 -0
  32. package/lib/API/UX/index.js +9 -0
  33. package/lib/API/UX/pm2-describe.js +197 -0
  34. package/lib/API/UX/pm2-ls-minimal.js +31 -0
  35. package/lib/API/UX/pm2-ls.js +581 -0
  36. package/lib/API/Version.js +383 -0
  37. package/lib/API/interpreter.json +12 -0
  38. package/lib/API/pm2-plus/PM2IO.js +381 -0
  39. package/lib/API/pm2-plus/auth-strategies/CliAuth.js +306 -0
  40. package/lib/API/pm2-plus/auth-strategies/WebAuth.js +195 -0
  41. package/lib/API/pm2-plus/helpers.js +97 -0
  42. package/lib/API/pm2-plus/link.js +126 -0
  43. package/lib/API/pm2-plus/pres/motd +16 -0
  44. package/lib/API/pm2-plus/pres/motd.update +26 -0
  45. package/lib/API/pm2-plus/pres/welcome +28 -0
  46. package/lib/API/pm2-plus/process-selector.js +52 -0
  47. package/lib/API/schema.json +375 -0
  48. package/lib/API.js +1980 -0
  49. package/lib/Client.js +793 -0
  50. package/lib/Common.js +949 -0
  51. package/lib/Configuration.js +309 -0
  52. package/lib/Daemon.js +468 -0
  53. package/lib/Event.js +37 -0
  54. package/lib/God/ActionMethods.js +955 -0
  55. package/lib/God/ClusterMode.js +192 -0
  56. package/lib/God/ForkMode.js +205 -0
  57. package/lib/God/Methods.js +292 -0
  58. package/lib/God/Reload.js +300 -0
  59. package/lib/God/StdioLogger.js +239 -0
  60. package/lib/God.js +653 -0
  61. package/lib/HttpInterface.js +75 -0
  62. package/lib/OtelManager.js +74 -0
  63. package/lib/ProcessContainer.js +321 -0
  64. package/lib/ProcessContainerBun.js +355 -0
  65. package/lib/ProcessContainerFork.js +42 -0
  66. package/lib/ProcessContainerForkBun.js +31 -0
  67. package/lib/ProcessUtils.js +74 -0
  68. package/lib/TreeKill.js +111 -0
  69. package/lib/Utility.js +304 -0
  70. package/lib/VersionCheck.js +46 -0
  71. package/lib/Watcher.js +117 -0
  72. package/lib/Worker.js +200 -0
  73. package/lib/binaries/CLI.js +1092 -0
  74. package/lib/binaries/DevCLI.js +183 -0
  75. package/lib/binaries/Runtime.js +101 -0
  76. package/lib/binaries/Runtime4Docker.js +192 -0
  77. package/lib/completion.js +229 -0
  78. package/lib/completion.sh +40 -0
  79. package/lib/motd +36 -0
  80. package/lib/templates/Dockerfiles/Dockerfile-nodejs.tpl +8 -0
  81. package/lib/templates/ecosystem-es.tpl +24 -0
  82. package/lib/templates/ecosystem-simple-es.tpl +8 -0
  83. package/lib/templates/ecosystem-simple.tpl +6 -0
  84. package/lib/templates/ecosystem.tpl +22 -0
  85. package/lib/templates/init-scripts/launchd.tpl +35 -0
  86. package/lib/templates/init-scripts/openrc.tpl +52 -0
  87. package/lib/templates/init-scripts/pm2-init-amazon.sh +86 -0
  88. package/lib/templates/init-scripts/rcd-openbsd.tpl +41 -0
  89. package/lib/templates/init-scripts/rcd.tpl +44 -0
  90. package/lib/templates/init-scripts/smf.tpl +43 -0
  91. package/lib/templates/init-scripts/systemd-online.tpl +22 -0
  92. package/lib/templates/init-scripts/systemd.tpl +22 -0
  93. package/lib/templates/init-scripts/upstart.tpl +103 -0
  94. package/lib/templates/logrotate.d/pm2 +10 -0
  95. package/lib/templates/sample-apps/http-server/README.md +14 -0
  96. package/lib/templates/sample-apps/http-server/api.js +9 -0
  97. package/lib/templates/sample-apps/http-server/ecosystem.config.js +14 -0
  98. package/lib/templates/sample-apps/http-server/package.json +11 -0
  99. package/lib/templates/sample-apps/pm2-plus-metrics-actions/README.md +45 -0
  100. package/lib/templates/sample-apps/pm2-plus-metrics-actions/custom-metrics.js +66 -0
  101. package/lib/templates/sample-apps/pm2-plus-metrics-actions/ecosystem.config.js +12 -0
  102. package/lib/templates/sample-apps/pm2-plus-metrics-actions/package.json +11 -0
  103. package/lib/templates/sample-apps/python-app/README.md +4 -0
  104. package/lib/templates/sample-apps/python-app/echo.py +7 -0
  105. package/lib/templates/sample-apps/python-app/ecosystem.config.js +12 -0
  106. package/lib/templates/sample-apps/python-app/package.json +11 -0
  107. package/lib/tools/Config.js +251 -0
  108. package/lib/tools/SysMetrics.js +375 -0
  109. package/lib/tools/copydirSync.js +101 -0
  110. package/lib/tools/deleteFolderRecursive.js +19 -0
  111. package/lib/tools/find-package-json.js +74 -0
  112. package/lib/tools/fmt.js +72 -0
  113. package/lib/tools/interpreter.js +88 -0
  114. package/lib/tools/isbinaryfile.js +94 -0
  115. package/lib/tools/json5.js +752 -0
  116. package/lib/tools/multimeter/bar.js +111 -0
  117. package/lib/tools/multimeter/charm/encode.js +18 -0
  118. package/lib/tools/multimeter/charm/index.js +305 -0
  119. package/lib/tools/multimeter/index.js +76 -0
  120. package/lib/tools/open.js +56 -0
  121. package/lib/tools/passwd.js +58 -0
  122. package/lib/tools/pm2-config-keys.js +165 -0
  123. package/lib/tools/prompt.js +76 -0
  124. package/lib/tools/serviceStop.js +149 -0
  125. package/lib/tools/sexec.js +55 -0
  126. package/lib/tools/treeify.js +113 -0
  127. package/lib/tools/typestrip.js +55 -0
  128. package/lib/tools/which.js +120 -0
  129. package/lib/tools/xdg-open +861 -0
  130. package/modules/blessed/LICENSE +20 -0
  131. package/modules/blessed/README.md +34 -0
  132. package/modules/blessed/index.js +1 -0
  133. package/modules/blessed/lib/alias.js +526 -0
  134. package/modules/blessed/lib/blessed.js +32 -0
  135. package/modules/blessed/lib/colors.js +530 -0
  136. package/modules/blessed/lib/events.js +189 -0
  137. package/modules/blessed/lib/gpmclient.js +221 -0
  138. package/modules/blessed/lib/helpers.js +165 -0
  139. package/modules/blessed/lib/keys.js +339 -0
  140. package/modules/blessed/lib/program.js +4297 -0
  141. package/modules/blessed/lib/tput.js +3022 -0
  142. package/modules/blessed/lib/unicode.js +885 -0
  143. package/modules/blessed/lib/widget.js +32 -0
  144. package/modules/blessed/lib/widgets/box.js +34 -0
  145. package/modules/blessed/lib/widgets/element.js +2570 -0
  146. package/modules/blessed/lib/widgets/list.js +599 -0
  147. package/modules/blessed/lib/widgets/log.js +83 -0
  148. package/modules/blessed/lib/widgets/node.js +282 -0
  149. package/modules/blessed/lib/widgets/screen.js +2298 -0
  150. package/modules/blessed/lib/widgets/scrollablebox.js +389 -0
  151. package/modules/blessed/lib/widgets/scrollabletext.js +35 -0
  152. package/modules/blessed/lib/widgets/text.js +35 -0
  153. package/modules/blessed/usr/linux +0 -0
  154. package/modules/blessed/usr/windows-ansi +0 -0
  155. package/modules/blessed/usr/xterm +0 -0
  156. package/modules/blessed/usr/xterm-256color +0 -0
  157. package/modules/blessed/usr/xterm.termcap +243 -0
  158. package/modules/chokidar/LICENSE +21 -0
  159. package/modules/chokidar/VENDORED.md +76 -0
  160. package/modules/chokidar/index.js +979 -0
  161. package/modules/chokidar/lib/brace-expand.js +180 -0
  162. package/modules/chokidar/lib/constants.js +66 -0
  163. package/modules/chokidar/lib/fsevents-handler.js +526 -0
  164. package/modules/chokidar/lib/nodefs-handler.js +654 -0
  165. package/modules/fclone.js +49 -0
  166. package/modules/pm2-axon/index.js +2 -0
  167. package/modules/pm2-axon/lib/configurable/History.md +5 -0
  168. package/modules/pm2-axon/lib/configurable/Makefile +7 -0
  169. package/modules/pm2-axon/lib/configurable/Readme.md +57 -0
  170. package/modules/pm2-axon/lib/configurable/index.js +2 -0
  171. package/modules/pm2-axon/lib/configurable/lib/configurable.js +47 -0
  172. package/modules/pm2-axon/lib/configurable/package.json +68 -0
  173. package/modules/pm2-axon/lib/index.js +44 -0
  174. package/modules/pm2-axon/lib/plugins/queue.js +71 -0
  175. package/modules/pm2-axon/lib/plugins/round-robin.js +55 -0
  176. package/modules/pm2-axon/lib/sockets/pub-emitter.js +26 -0
  177. package/modules/pm2-axon/lib/sockets/pub.js +77 -0
  178. package/modules/pm2-axon/lib/sockets/pull.js +37 -0
  179. package/modules/pm2-axon/lib/sockets/push.js +32 -0
  180. package/modules/pm2-axon/lib/sockets/rep.js +73 -0
  181. package/modules/pm2-axon/lib/sockets/req.js +101 -0
  182. package/modules/pm2-axon/lib/sockets/sock.js +430 -0
  183. package/modules/pm2-axon/lib/sockets/sub-emitter.js +92 -0
  184. package/modules/pm2-axon/lib/sockets/sub.js +147 -0
  185. package/modules/pm2-axon/lib/utils.js +19 -0
  186. package/modules/pm2-axon-rpc/index.js +3 -0
  187. package/modules/pm2-axon-rpc/lib/client.js +63 -0
  188. package/modules/pm2-axon-rpc/lib/server.js +139 -0
  189. package/modules/pm2-io-agent/LICENSE +661 -0
  190. package/modules/pm2-io-agent/README.md +62 -0
  191. package/modules/pm2-io-agent/config.js +30 -0
  192. package/modules/pm2-io-agent/constants.js +118 -0
  193. package/modules/pm2-io-agent/index.js +2 -0
  194. package/modules/pm2-io-agent/src/InteractorClient.js +513 -0
  195. package/modules/pm2-io-agent/src/InteractorDaemon.js +455 -0
  196. package/modules/pm2-io-agent/src/PM2Client.js +112 -0
  197. package/modules/pm2-io-agent/src/PM2Interface.js +180 -0
  198. package/modules/pm2-io-agent/src/TransporterInterface.js +173 -0
  199. package/modules/pm2-io-agent/src/Utility.js +392 -0
  200. package/modules/pm2-io-agent/src/WatchDog.js +70 -0
  201. package/modules/pm2-io-agent/src/push/DataRetriever.js +77 -0
  202. package/modules/pm2-io-agent/src/push/PushInteractor.js +206 -0
  203. package/modules/pm2-io-agent/src/push/TransactionAggregator.js +670 -0
  204. package/modules/pm2-io-agent/src/reverse/ReverseInteractor.js +128 -0
  205. package/modules/pm2-io-agent/src/transporters/Transporter.js +129 -0
  206. package/modules/pm2-io-agent/src/transporters/WebsocketTransport.js +202 -0
  207. package/modules/pm2-io-agent/src/utils/BinaryHeap.js +135 -0
  208. package/modules/pm2-io-agent/src/utils/EDS.js +111 -0
  209. package/modules/pm2-io-agent/src/utils/probes/Histogram.js +204 -0
  210. package/modules/pm2-io-agent/src/utils/units.js +10 -0
  211. package/modules/pm2-io-bpm/configuration.js +141 -0
  212. package/modules/pm2-io-bpm/constants.js +10 -0
  213. package/modules/pm2-io-bpm/featureManager.js +110 -0
  214. package/modules/pm2-io-bpm/features/dependencies.js +48 -0
  215. package/modules/pm2-io-bpm/features/events.js +50 -0
  216. package/modules/pm2-io-bpm/features/metrics.js +102 -0
  217. package/modules/pm2-io-bpm/features/notify.js +238 -0
  218. package/modules/pm2-io-bpm/features/profiling.js +70 -0
  219. package/modules/pm2-io-bpm/features/tracing.js +174 -0
  220. package/modules/pm2-io-bpm/index.js +11 -0
  221. package/modules/pm2-io-bpm/metrics/eventLoopMetrics.js +136 -0
  222. package/modules/pm2-io-bpm/metrics/httpMetrics.js +175 -0
  223. package/modules/pm2-io-bpm/metrics/network.js +132 -0
  224. package/modules/pm2-io-bpm/metrics/runtime.js +161 -0
  225. package/modules/pm2-io-bpm/metrics/v8.js +104 -0
  226. package/modules/pm2-io-bpm/otel/constants.js +7 -0
  227. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/platform/index.js +17 -0
  228. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/platform/node/index.js +17 -0
  229. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/platform/node/util.js +51 -0
  230. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/transform.js +137 -0
  231. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/types.js +24 -0
  232. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/utils.js +23 -0
  233. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/zipkin.js +149 -0
  234. package/modules/pm2-io-bpm/pmx.js +380 -0
  235. package/modules/pm2-io-bpm/profilers/addonProfiler.js +193 -0
  236. package/modules/pm2-io-bpm/profilers/inspectorProfiler.js +302 -0
  237. package/modules/pm2-io-bpm/serviceManager.js +21 -0
  238. package/modules/pm2-io-bpm/services/actions.js +159 -0
  239. package/modules/pm2-io-bpm/services/inspector.js +43 -0
  240. package/modules/pm2-io-bpm/services/metrics.js +186 -0
  241. package/modules/pm2-io-bpm/services/runtimeStats.js +54 -0
  242. package/modules/pm2-io-bpm/services/transport.js +11 -0
  243. package/modules/pm2-io-bpm/transports/IPCTransport.js +115 -0
  244. package/modules/pm2-io-bpm/utils/BinaryHeap.js +134 -0
  245. package/modules/pm2-io-bpm/utils/EDS.js +113 -0
  246. package/modules/pm2-io-bpm/utils/EWMA.js +32 -0
  247. package/modules/pm2-io-bpm/utils/autocast.js +61 -0
  248. package/modules/pm2-io-bpm/utils/metrics/counter.js +33 -0
  249. package/modules/pm2-io-bpm/utils/metrics/gauge.js +23 -0
  250. package/modules/pm2-io-bpm/utils/metrics/histogram.js +192 -0
  251. package/modules/pm2-io-bpm/utils/metrics/meter.js +46 -0
  252. package/modules/pm2-io-bpm/utils/miscellaneous.js +19 -0
  253. package/modules/pm2-io-bpm/utils/module.js +67 -0
  254. package/modules/pm2-io-bpm/utils/shimmer.js +19 -0
  255. package/modules/pm2-io-bpm/utils/stackParser.js +160 -0
  256. package/modules/pm2-io-bpm/utils/transactionAggregator.js +429 -0
  257. package/modules/pm2-io-bpm/utils/units.js +16 -0
  258. package/modules/vizion/LICENSE +13 -0
  259. package/modules/vizion/README.md +133 -0
  260. package/modules/vizion/index.js +1 -0
  261. package/modules/vizion/lib/git/git.js +247 -0
  262. package/modules/vizion/lib/vizion.js +52 -0
  263. package/package.json +170 -4
  264. package/paths.js +121 -0
  265. package/pm2 +11 -0
  266. package/types/index.d.ts +732 -0
  267. package/types/tsconfig.json +14 -0
@@ -0,0 +1,979 @@
1
+ // Vendored chokidar 3.6.0 (MIT, see LICENSE and VENDORED.md).
2
+ // Local change: braces.expand replaced by the bounded lib/brace-expand.js,
3
+ // null (unsupported/over limit) disables glob dir pruning instead of throwing.
4
+ 'use strict';
5
+
6
+ const { EventEmitter } = require('events');
7
+ const fs = require('fs');
8
+ const sysPath = require('path');
9
+ const { promisify } = require('util');
10
+ const readdirp = require('readdirp');
11
+ const anymatch = require('anymatch').default;
12
+ const globParent = require('glob-parent');
13
+ const isGlob = require('is-glob');
14
+ const expandBraces = require('./lib/brace-expand');
15
+ const normalizePath = require('normalize-path');
16
+
17
+ const NodeFsHandler = require('./lib/nodefs-handler');
18
+ const FsEventsHandler = require('./lib/fsevents-handler');
19
+ const {
20
+ EV_ALL,
21
+ EV_READY,
22
+ EV_ADD,
23
+ EV_CHANGE,
24
+ EV_UNLINK,
25
+ EV_ADD_DIR,
26
+ EV_UNLINK_DIR,
27
+ EV_RAW,
28
+ EV_ERROR,
29
+
30
+ STR_CLOSE,
31
+ STR_END,
32
+
33
+ BACK_SLASH_RE,
34
+ DOUBLE_SLASH_RE,
35
+ SLASH_OR_BACK_SLASH_RE,
36
+ DOT_RE,
37
+ REPLACER_RE,
38
+
39
+ SLASH,
40
+ SLASH_SLASH,
41
+ BRACE_START,
42
+ BANG,
43
+ ONE_DOT,
44
+ TWO_DOTS,
45
+ GLOBSTAR,
46
+ SLASH_GLOBSTAR,
47
+ ANYMATCH_OPTS,
48
+ STRING_TYPE,
49
+ FUNCTION_TYPE,
50
+ EMPTY_STR,
51
+ EMPTY_FN,
52
+
53
+ isWindows,
54
+ isMacos,
55
+ isIBMi
56
+ } = require('./lib/constants');
57
+
58
+ const stat = promisify(fs.stat);
59
+ const readdir = promisify(fs.readdir);
60
+
61
+ /**
62
+ * @typedef {String} Path
63
+ * @typedef {'all'|'add'|'addDir'|'change'|'unlink'|'unlinkDir'|'raw'|'error'|'ready'} EventName
64
+ * @typedef {'readdir'|'watch'|'add'|'remove'|'change'} ThrottleType
65
+ */
66
+
67
+ /**
68
+ *
69
+ * @typedef {Object} WatchHelpers
70
+ * @property {Boolean} followSymlinks
71
+ * @property {'stat'|'lstat'} statMethod
72
+ * @property {Path} path
73
+ * @property {Path} watchPath
74
+ * @property {Function} entryPath
75
+ * @property {Boolean} hasGlob
76
+ * @property {Object} globFilter
77
+ * @property {Function} filterPath
78
+ * @property {Function} filterDir
79
+ */
80
+
81
+ const arrify = (value = []) => Array.isArray(value) ? value : [value];
82
+ const flatten = (list, result = []) => {
83
+ list.forEach(item => {
84
+ if (Array.isArray(item)) {
85
+ flatten(item, result);
86
+ } else {
87
+ result.push(item);
88
+ }
89
+ });
90
+ return result;
91
+ };
92
+
93
+ const unifyPaths = (paths_) => {
94
+ /**
95
+ * @type {Array<String>}
96
+ */
97
+ const paths = flatten(arrify(paths_));
98
+ if (!paths.every(p => typeof p === STRING_TYPE)) {
99
+ throw new TypeError(`Non-string provided as watch path: ${paths}`);
100
+ }
101
+ return paths.map(normalizePathToUnix);
102
+ };
103
+
104
+ // If SLASH_SLASH occurs at the beginning of path, it is not replaced
105
+ // because "//StoragePC/DrivePool/Movies" is a valid network path
106
+ const toUnix = (string) => {
107
+ let str = string.replace(BACK_SLASH_RE, SLASH);
108
+ let prepend = false;
109
+ if (str.startsWith(SLASH_SLASH)) {
110
+ prepend = true;
111
+ }
112
+ while (str.match(DOUBLE_SLASH_RE)) {
113
+ str = str.replace(DOUBLE_SLASH_RE, SLASH);
114
+ }
115
+ if (prepend) {
116
+ str = SLASH + str;
117
+ }
118
+ return str;
119
+ };
120
+
121
+ // Our version of upath.normalize
122
+ // TODO: this is not equal to path-normalize module - investigate why
123
+ const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path)));
124
+
125
+ const normalizeIgnored = (cwd = EMPTY_STR) => (path) => {
126
+ if (typeof path !== STRING_TYPE) return path;
127
+ return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path));
128
+ };
129
+
130
+ const getAbsolutePath = (path, cwd) => {
131
+ if (sysPath.isAbsolute(path)) {
132
+ return path;
133
+ }
134
+ if (path.startsWith(BANG)) {
135
+ return BANG + sysPath.join(cwd, path.slice(1));
136
+ }
137
+ return sysPath.join(cwd, path);
138
+ };
139
+
140
+ const undef = (opts, key) => opts[key] === undefined;
141
+
142
+ /**
143
+ * Directory entry.
144
+ * @property {Path} path
145
+ * @property {Set<Path>} items
146
+ */
147
+ class DirEntry {
148
+ /**
149
+ * @param {Path} dir
150
+ * @param {Function} removeWatcher
151
+ */
152
+ constructor(dir, removeWatcher) {
153
+ this.path = dir;
154
+ this._removeWatcher = removeWatcher;
155
+ /** @type {Set<Path>} */
156
+ this.items = new Set();
157
+ }
158
+
159
+ add(item) {
160
+ const {items} = this;
161
+ if (!items) return;
162
+ if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
163
+ }
164
+
165
+ async remove(item) {
166
+ const {items} = this;
167
+ if (!items) return;
168
+ items.delete(item);
169
+ if (items.size > 0) return;
170
+
171
+ const dir = this.path;
172
+ try {
173
+ await readdir(dir);
174
+ } catch (err) {
175
+ if (this._removeWatcher) {
176
+ this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir));
177
+ }
178
+ }
179
+ }
180
+
181
+ has(item) {
182
+ const {items} = this;
183
+ if (!items) return;
184
+ return items.has(item);
185
+ }
186
+
187
+ /**
188
+ * @returns {Array<String>}
189
+ */
190
+ getChildren() {
191
+ const {items} = this;
192
+ if (!items) return;
193
+ return [...items.values()];
194
+ }
195
+
196
+ dispose() {
197
+ this.items.clear();
198
+ delete this.path;
199
+ delete this._removeWatcher;
200
+ delete this.items;
201
+ Object.freeze(this);
202
+ }
203
+ }
204
+
205
+ const STAT_METHOD_F = 'stat';
206
+ const STAT_METHOD_L = 'lstat';
207
+ class WatchHelper {
208
+ constructor(path, watchPath, follow, fsw) {
209
+ this.fsw = fsw;
210
+ this.path = path = path.replace(REPLACER_RE, EMPTY_STR);
211
+ this.watchPath = watchPath;
212
+ this.fullWatchPath = sysPath.resolve(watchPath);
213
+ this.hasGlob = watchPath !== path;
214
+ /** @type {object|boolean} */
215
+ if (path === EMPTY_STR) this.hasGlob = false;
216
+ this.globSymlink = this.hasGlob && follow ? undefined : false;
217
+ this.globFilter = this.hasGlob ? anymatch(path, undefined, ANYMATCH_OPTS) : false;
218
+ this.dirParts = this.getDirParts(path) || [[GLOBSTAR]];
219
+ this.dirParts.forEach((parts) => {
220
+ if (parts.length > 1) parts.pop();
221
+ });
222
+ this.followSymlinks = follow;
223
+ this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
224
+ }
225
+
226
+ checkGlobSymlink(entry) {
227
+ // only need to resolve once
228
+ // first entry should always have entry.parentDir === EMPTY_STR
229
+ if (this.globSymlink === undefined) {
230
+ this.globSymlink = entry.fullParentDir === this.fullWatchPath ?
231
+ false : {realPath: entry.fullParentDir, linkPath: this.fullWatchPath};
232
+ }
233
+
234
+ if (this.globSymlink) {
235
+ return entry.fullPath.replace(this.globSymlink.realPath, this.globSymlink.linkPath);
236
+ }
237
+
238
+ return entry.fullPath;
239
+ }
240
+
241
+ entryPath(entry) {
242
+ return sysPath.join(this.watchPath,
243
+ sysPath.relative(this.watchPath, this.checkGlobSymlink(entry))
244
+ );
245
+ }
246
+
247
+ filterPath(entry) {
248
+ const {stats} = entry;
249
+ if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
250
+ const resolvedPath = this.entryPath(entry);
251
+ const matchesGlob = this.hasGlob && typeof this.globFilter === FUNCTION_TYPE ?
252
+ this.globFilter(resolvedPath) : true;
253
+ return matchesGlob &&
254
+ this.fsw._isntIgnored(resolvedPath, stats) &&
255
+ this.fsw._hasReadPermissions(stats);
256
+ }
257
+
258
+ getDirParts(path) {
259
+ if (!this.hasGlob) return [];
260
+ const parts = [];
261
+ const expandedPath = path.includes(BRACE_START) ? expandBraces(path) : [path];
262
+ if (expandedPath === null) return null;
263
+ expandedPath.forEach((path) => {
264
+ parts.push(sysPath.relative(this.watchPath, path).split(SLASH_OR_BACK_SLASH_RE));
265
+ });
266
+ return parts;
267
+ }
268
+
269
+ filterDir(entry) {
270
+ if (this.hasGlob) {
271
+ const entryPath = this.checkGlobSymlink(entry);
272
+ const entryParts = this.getDirParts(entryPath) ||
273
+ [sysPath.relative(this.watchPath, entryPath).split(SLASH_OR_BACK_SLASH_RE)];
274
+ let globstar = false;
275
+ this.unmatchedGlob = !this.dirParts.some((parts) => {
276
+ return parts.every((part, i) => {
277
+ if (part === GLOBSTAR) globstar = true;
278
+ return globstar || !entryParts[0][i] || anymatch(part, entryParts[0][i], ANYMATCH_OPTS);
279
+ });
280
+ });
281
+ }
282
+ return !this.unmatchedGlob && this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
283
+ }
284
+ }
285
+
286
+ /**
287
+ * Watches files & directories for changes. Emitted events:
288
+ * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
289
+ *
290
+ * new FSWatcher()
291
+ * .add(directories)
292
+ * .on('add', path => log('File', path, 'was added'))
293
+ */
294
+ class FSWatcher extends EventEmitter {
295
+ // Not indenting methods for history sake; for now.
296
+ constructor(_opts) {
297
+ super();
298
+
299
+ const opts = {};
300
+ if (_opts) Object.assign(opts, _opts); // for frozen objects
301
+
302
+ /** @type {Map<String, DirEntry>} */
303
+ this._watched = new Map();
304
+ /** @type {Map<String, Array>} */
305
+ this._closers = new Map();
306
+ /** @type {Set<String>} */
307
+ this._ignoredPaths = new Set();
308
+
309
+ /** @type {Map<ThrottleType, Map>} */
310
+ this._throttled = new Map();
311
+
312
+ /** @type {Map<Path, String|Boolean>} */
313
+ this._symlinkPaths = new Map();
314
+
315
+ this._streams = new Set();
316
+ this.closed = false;
317
+
318
+ // Set up default options.
319
+ if (undef(opts, 'persistent')) opts.persistent = true;
320
+ if (undef(opts, 'ignoreInitial')) opts.ignoreInitial = false;
321
+ if (undef(opts, 'ignorePermissionErrors')) opts.ignorePermissionErrors = false;
322
+ if (undef(opts, 'interval')) opts.interval = 100;
323
+ if (undef(opts, 'binaryInterval')) opts.binaryInterval = 300;
324
+ if (undef(opts, 'disableGlobbing')) opts.disableGlobbing = false;
325
+ opts.enableBinaryInterval = opts.binaryInterval !== opts.interval;
326
+
327
+ // Enable fsevents on OS X when polling isn't explicitly enabled.
328
+ if (undef(opts, 'useFsEvents')) opts.useFsEvents = !opts.usePolling;
329
+
330
+ // If we can't use fsevents, ensure the options reflect it's disabled.
331
+ const canUseFsEvents = FsEventsHandler.canUse();
332
+ if (!canUseFsEvents) opts.useFsEvents = false;
333
+
334
+ // Use polling on Mac if not using fsevents.
335
+ // Other platforms use non-polling fs_watch.
336
+ if (undef(opts, 'usePolling') && !opts.useFsEvents) {
337
+ opts.usePolling = isMacos;
338
+ }
339
+
340
+ // Always default to polling on IBM i because fs.watch() is not available on IBM i.
341
+ if(isIBMi) {
342
+ opts.usePolling = true;
343
+ }
344
+
345
+ // Global override (useful for end-developers that need to force polling for all
346
+ // instances of chokidar, regardless of usage/dependency depth)
347
+ const envPoll = process.env.CHOKIDAR_USEPOLLING;
348
+ if (envPoll !== undefined) {
349
+ const envLower = envPoll.toLowerCase();
350
+
351
+ if (envLower === 'false' || envLower === '0') {
352
+ opts.usePolling = false;
353
+ } else if (envLower === 'true' || envLower === '1') {
354
+ opts.usePolling = true;
355
+ } else {
356
+ opts.usePolling = !!envLower;
357
+ }
358
+ }
359
+ const envInterval = process.env.CHOKIDAR_INTERVAL;
360
+ if (envInterval) {
361
+ opts.interval = Number.parseInt(envInterval, 10);
362
+ }
363
+
364
+ // Editor atomic write normalization enabled by default with fs.watch
365
+ if (undef(opts, 'atomic')) opts.atomic = !opts.usePolling && !opts.useFsEvents;
366
+ if (opts.atomic) this._pendingUnlinks = new Map();
367
+
368
+ if (undef(opts, 'followSymlinks')) opts.followSymlinks = true;
369
+
370
+ if (undef(opts, 'awaitWriteFinish')) opts.awaitWriteFinish = false;
371
+ if (opts.awaitWriteFinish === true) opts.awaitWriteFinish = {};
372
+ const awf = opts.awaitWriteFinish;
373
+ if (awf) {
374
+ if (!awf.stabilityThreshold) awf.stabilityThreshold = 2000;
375
+ if (!awf.pollInterval) awf.pollInterval = 100;
376
+ this._pendingWrites = new Map();
377
+ }
378
+ if (opts.ignored) opts.ignored = arrify(opts.ignored);
379
+
380
+ let readyCalls = 0;
381
+ this._emitReady = () => {
382
+ readyCalls++;
383
+ if (readyCalls >= this._readyCount) {
384
+ this._emitReady = EMPTY_FN;
385
+ this._readyEmitted = true;
386
+ // use process.nextTick to allow time for listener to be bound
387
+ process.nextTick(() => this.emit(EV_READY));
388
+ }
389
+ };
390
+ this._emitRaw = (...args) => this.emit(EV_RAW, ...args);
391
+ this._readyEmitted = false;
392
+ this.options = opts;
393
+
394
+ // Initialize with proper watcher.
395
+ if (opts.useFsEvents) {
396
+ this._fsEventsHandler = new FsEventsHandler(this);
397
+ } else {
398
+ this._nodeFsHandler = new NodeFsHandler(this);
399
+ }
400
+
401
+ // You’re frozen when your heart’s not open.
402
+ Object.freeze(opts);
403
+ }
404
+
405
+ // Public methods
406
+
407
+ /**
408
+ * Adds paths to be watched on an existing FSWatcher instance
409
+ * @param {Path|Array<Path>} paths_
410
+ * @param {String=} _origAdd private; for handling non-existent paths to be watched
411
+ * @param {Boolean=} _internal private; indicates a non-user add
412
+ * @returns {FSWatcher} for chaining
413
+ */
414
+ add(paths_, _origAdd, _internal) {
415
+ const {cwd, disableGlobbing} = this.options;
416
+ this.closed = false;
417
+ let paths = unifyPaths(paths_);
418
+ if (cwd) {
419
+ paths = paths.map((path) => {
420
+ const absPath = getAbsolutePath(path, cwd);
421
+
422
+ // Check `path` instead of `absPath` because the cwd portion can't be a glob
423
+ if (disableGlobbing || !isGlob(path)) {
424
+ return absPath;
425
+ }
426
+ return normalizePath(absPath);
427
+ });
428
+ }
429
+
430
+ // set aside negated glob strings
431
+ paths = paths.filter((path) => {
432
+ if (path.startsWith(BANG)) {
433
+ this._ignoredPaths.add(path.slice(1));
434
+ return false;
435
+ }
436
+
437
+ // if a path is being added that was previously ignored, stop ignoring it
438
+ this._ignoredPaths.delete(path);
439
+ this._ignoredPaths.delete(path + SLASH_GLOBSTAR);
440
+
441
+ // reset the cached userIgnored anymatch fn
442
+ // to make ignoredPaths changes effective
443
+ this._userIgnored = undefined;
444
+
445
+ return true;
446
+ });
447
+
448
+ if (this.options.useFsEvents && this._fsEventsHandler) {
449
+ if (!this._readyCount) this._readyCount = paths.length;
450
+ if (this.options.persistent) this._readyCount += paths.length;
451
+ paths.forEach((path) => this._fsEventsHandler._addToFsEvents(path));
452
+ } else {
453
+ if (!this._readyCount) this._readyCount = 0;
454
+ this._readyCount += paths.length;
455
+ Promise.all(
456
+ paths.map(async path => {
457
+ const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, 0, 0, _origAdd);
458
+ if (res) this._emitReady();
459
+ return res;
460
+ })
461
+ ).then(results => {
462
+ if (this.closed) return;
463
+ results.filter(item => item).forEach(item => {
464
+ this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item));
465
+ });
466
+ });
467
+ }
468
+
469
+ return this;
470
+ }
471
+
472
+ /**
473
+ * Close watchers or start ignoring events from specified paths.
474
+ * @param {Path|Array<Path>} paths_ - string or array of strings, file/directory paths and/or globs
475
+ * @returns {FSWatcher} for chaining
476
+ */
477
+ unwatch(paths_) {
478
+ if (this.closed) return this;
479
+ const paths = unifyPaths(paths_);
480
+ const {cwd} = this.options;
481
+
482
+ paths.forEach((path) => {
483
+ // convert to absolute path unless relative path already matches
484
+ if (!sysPath.isAbsolute(path) && !this._closers.has(path)) {
485
+ if (cwd) path = sysPath.join(cwd, path);
486
+ path = sysPath.resolve(path);
487
+ }
488
+
489
+ this._closePath(path);
490
+
491
+ this._ignoredPaths.add(path);
492
+ if (this._watched.has(path)) {
493
+ this._ignoredPaths.add(path + SLASH_GLOBSTAR);
494
+ }
495
+
496
+ // reset the cached userIgnored anymatch fn
497
+ // to make ignoredPaths changes effective
498
+ this._userIgnored = undefined;
499
+ });
500
+
501
+ return this;
502
+ }
503
+
504
+ /**
505
+ * Close watchers and remove all listeners from watched paths.
506
+ * @returns {Promise<void>}.
507
+ */
508
+ close() {
509
+ if (this.closed) return this._closePromise;
510
+ this.closed = true;
511
+
512
+ // Memory management.
513
+ this.removeAllListeners();
514
+ const closers = [];
515
+ this._closers.forEach(closerList => closerList.forEach(closer => {
516
+ const promise = closer();
517
+ if (promise instanceof Promise) closers.push(promise);
518
+ }));
519
+ this._streams.forEach(stream => stream.destroy());
520
+ this._userIgnored = undefined;
521
+ this._readyCount = 0;
522
+ this._readyEmitted = false;
523
+ this._watched.forEach(dirent => dirent.dispose());
524
+ ['closers', 'watched', 'streams', 'symlinkPaths', 'throttled'].forEach(key => {
525
+ this[`_${key}`].clear();
526
+ });
527
+
528
+ this._closePromise = closers.length ? Promise.all(closers).then(() => undefined) : Promise.resolve();
529
+ return this._closePromise;
530
+ }
531
+
532
+ /**
533
+ * Expose list of watched paths
534
+ * @returns {Object} for chaining
535
+ */
536
+ getWatched() {
537
+ const watchList = {};
538
+ this._watched.forEach((entry, dir) => {
539
+ const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir;
540
+ watchList[key || ONE_DOT] = entry.getChildren().sort();
541
+ });
542
+ return watchList;
543
+ }
544
+
545
+ emitWithAll(event, args) {
546
+ this.emit(...args);
547
+ if (event !== EV_ERROR) this.emit(EV_ALL, ...args);
548
+ }
549
+
550
+ // Common helpers
551
+ // --------------
552
+
553
+ /**
554
+ * Normalize and emit events.
555
+ * Calling _emit DOES NOT MEAN emit() would be called!
556
+ * @param {EventName} event Type of event
557
+ * @param {Path} path File or directory path
558
+ * @param {*=} val1 arguments to be passed with event
559
+ * @param {*=} val2
560
+ * @param {*=} val3
561
+ * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
562
+ */
563
+ async _emit(event, path, val1, val2, val3) {
564
+ if (this.closed) return;
565
+
566
+ const opts = this.options;
567
+ if (isWindows) path = sysPath.normalize(path);
568
+ if (opts.cwd) path = sysPath.relative(opts.cwd, path);
569
+ /** @type Array<any> */
570
+ const args = [event, path];
571
+ if (val3 !== undefined) args.push(val1, val2, val3);
572
+ else if (val2 !== undefined) args.push(val1, val2);
573
+ else if (val1 !== undefined) args.push(val1);
574
+
575
+ const awf = opts.awaitWriteFinish;
576
+ let pw;
577
+ if (awf && (pw = this._pendingWrites.get(path))) {
578
+ pw.lastChange = new Date();
579
+ return this;
580
+ }
581
+
582
+ if (opts.atomic) {
583
+ if (event === EV_UNLINK) {
584
+ this._pendingUnlinks.set(path, args);
585
+ setTimeout(() => {
586
+ this._pendingUnlinks.forEach((entry, path) => {
587
+ this.emit(...entry);
588
+ this.emit(EV_ALL, ...entry);
589
+ this._pendingUnlinks.delete(path);
590
+ });
591
+ }, typeof opts.atomic === 'number' ? opts.atomic : 100);
592
+ return this;
593
+ }
594
+ if (event === EV_ADD && this._pendingUnlinks.has(path)) {
595
+ event = args[0] = EV_CHANGE;
596
+ this._pendingUnlinks.delete(path);
597
+ }
598
+ }
599
+
600
+ if (awf && (event === EV_ADD || event === EV_CHANGE) && this._readyEmitted) {
601
+ const awfEmit = (err, stats) => {
602
+ if (err) {
603
+ event = args[0] = EV_ERROR;
604
+ args[1] = err;
605
+ this.emitWithAll(event, args);
606
+ } else if (stats) {
607
+ // if stats doesn't exist the file must have been deleted
608
+ if (args.length > 2) {
609
+ args[2] = stats;
610
+ } else {
611
+ args.push(stats);
612
+ }
613
+ this.emitWithAll(event, args);
614
+ }
615
+ };
616
+
617
+ this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
618
+ return this;
619
+ }
620
+
621
+ if (event === EV_CHANGE) {
622
+ const isThrottled = !this._throttle(EV_CHANGE, path, 50);
623
+ if (isThrottled) return this;
624
+ }
625
+
626
+ if (opts.alwaysStat && val1 === undefined &&
627
+ (event === EV_ADD || event === EV_ADD_DIR || event === EV_CHANGE)
628
+ ) {
629
+ const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path;
630
+ let stats;
631
+ try {
632
+ stats = await stat(fullPath);
633
+ } catch (err) {}
634
+ // Suppress event when fs_stat fails, to avoid sending undefined 'stat'
635
+ if (!stats || this.closed) return;
636
+ args.push(stats);
637
+ }
638
+ this.emitWithAll(event, args);
639
+
640
+ return this;
641
+ }
642
+
643
+ /**
644
+ * Common handler for errors
645
+ * @param {Error} error
646
+ * @returns {Error|Boolean} The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
647
+ */
648
+ _handleError(error) {
649
+ const code = error && error.code;
650
+ if (error && code !== 'ENOENT' && code !== 'ENOTDIR' &&
651
+ (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))
652
+ ) {
653
+ this.emit(EV_ERROR, error);
654
+ }
655
+ return error || this.closed;
656
+ }
657
+
658
+ /**
659
+ * Helper utility for throttling
660
+ * @param {ThrottleType} actionType type being throttled
661
+ * @param {Path} path being acted upon
662
+ * @param {Number} timeout duration of time to suppress duplicate actions
663
+ * @returns {Object|false} tracking object or false if action should be suppressed
664
+ */
665
+ _throttle(actionType, path, timeout) {
666
+ if (!this._throttled.has(actionType)) {
667
+ this._throttled.set(actionType, new Map());
668
+ }
669
+
670
+ /** @type {Map<Path, Object>} */
671
+ const action = this._throttled.get(actionType);
672
+ /** @type {Object} */
673
+ const actionPath = action.get(path);
674
+
675
+ if (actionPath) {
676
+ actionPath.count++;
677
+ return false;
678
+ }
679
+
680
+ let timeoutObject;
681
+ const clear = () => {
682
+ const item = action.get(path);
683
+ const count = item ? item.count : 0;
684
+ action.delete(path);
685
+ clearTimeout(timeoutObject);
686
+ if (item) clearTimeout(item.timeoutObject);
687
+ return count;
688
+ };
689
+ timeoutObject = setTimeout(clear, timeout);
690
+ const thr = {timeoutObject, clear, count: 0};
691
+ action.set(path, thr);
692
+ return thr;
693
+ }
694
+
695
+ _incrReadyCount() {
696
+ return this._readyCount++;
697
+ }
698
+
699
+ /**
700
+ * Awaits write operation to finish.
701
+ * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
702
+ * @param {Path} path being acted upon
703
+ * @param {Number} threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
704
+ * @param {EventName} event
705
+ * @param {Function} awfEmit Callback to be called when ready for event to be emitted.
706
+ */
707
+ _awaitWriteFinish(path, threshold, event, awfEmit) {
708
+ let timeoutHandler;
709
+
710
+ let fullPath = path;
711
+ if (this.options.cwd && !sysPath.isAbsolute(path)) {
712
+ fullPath = sysPath.join(this.options.cwd, path);
713
+ }
714
+
715
+ const now = new Date();
716
+
717
+ const awaitWriteFinish = (prevStat) => {
718
+ fs.stat(fullPath, (err, curStat) => {
719
+ if (err || !this._pendingWrites.has(path)) {
720
+ if (err && err.code !== 'ENOENT') awfEmit(err);
721
+ return;
722
+ }
723
+
724
+ const now = Number(new Date());
725
+
726
+ if (prevStat && curStat.size !== prevStat.size) {
727
+ this._pendingWrites.get(path).lastChange = now;
728
+ }
729
+ const pw = this._pendingWrites.get(path);
730
+ const df = now - pw.lastChange;
731
+
732
+ if (df >= threshold) {
733
+ this._pendingWrites.delete(path);
734
+ awfEmit(undefined, curStat);
735
+ } else {
736
+ timeoutHandler = setTimeout(
737
+ awaitWriteFinish,
738
+ this.options.awaitWriteFinish.pollInterval,
739
+ curStat
740
+ );
741
+ }
742
+ });
743
+ };
744
+
745
+ if (!this._pendingWrites.has(path)) {
746
+ this._pendingWrites.set(path, {
747
+ lastChange: now,
748
+ cancelWait: () => {
749
+ this._pendingWrites.delete(path);
750
+ clearTimeout(timeoutHandler);
751
+ return event;
752
+ }
753
+ });
754
+ timeoutHandler = setTimeout(
755
+ awaitWriteFinish,
756
+ this.options.awaitWriteFinish.pollInterval
757
+ );
758
+ }
759
+ }
760
+
761
+ _getGlobIgnored() {
762
+ return [...this._ignoredPaths.values()];
763
+ }
764
+
765
+ /**
766
+ * Determines whether user has asked to ignore this path.
767
+ * @param {Path} path filepath or dir
768
+ * @param {fs.Stats=} stats result of fs.stat
769
+ * @returns {Boolean}
770
+ */
771
+ _isIgnored(path, stats) {
772
+ if (this.options.atomic && DOT_RE.test(path)) return true;
773
+ if (!this._userIgnored) {
774
+ const {cwd} = this.options;
775
+ const ign = this.options.ignored;
776
+
777
+ const ignored = ign && ign.map(normalizeIgnored(cwd));
778
+ const paths = arrify(ignored)
779
+ .filter((path) => typeof path === STRING_TYPE && !isGlob(path))
780
+ .map((path) => path + SLASH_GLOBSTAR);
781
+ const list = this._getGlobIgnored().map(normalizeIgnored(cwd)).concat(ignored, paths);
782
+ this._userIgnored = anymatch(list, undefined, ANYMATCH_OPTS);
783
+ }
784
+
785
+ return this._userIgnored([path, stats]);
786
+ }
787
+
788
+ _isntIgnored(path, stat) {
789
+ return !this._isIgnored(path, stat);
790
+ }
791
+
792
+ /**
793
+ * Provides a set of common helpers and properties relating to symlink and glob handling.
794
+ * @param {Path} path file, directory, or glob pattern being watched
795
+ * @param {Number=} depth at any depth > 0, this isn't a glob
796
+ * @returns {WatchHelper} object containing helpers for this path
797
+ */
798
+ _getWatchHelpers(path, depth) {
799
+ const watchPath = depth || this.options.disableGlobbing || !isGlob(path) ? path : globParent(path);
800
+ const follow = this.options.followSymlinks;
801
+
802
+ return new WatchHelper(path, watchPath, follow, this);
803
+ }
804
+
805
+ // Directory helpers
806
+ // -----------------
807
+
808
+ /**
809
+ * Provides directory tracking objects
810
+ * @param {String} directory path of the directory
811
+ * @returns {DirEntry} the directory's tracking object
812
+ */
813
+ _getWatchedDir(directory) {
814
+ if (!this._boundRemove) this._boundRemove = this._remove.bind(this);
815
+ const dir = sysPath.resolve(directory);
816
+ if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
817
+ return this._watched.get(dir);
818
+ }
819
+
820
+ // File helpers
821
+ // ------------
822
+
823
+ /**
824
+ * Check for read permissions.
825
+ * Based on this answer on SO: https://stackoverflow.com/a/11781404/1358405
826
+ * @param {fs.Stats} stats - object, result of fs_stat
827
+ * @returns {Boolean} indicates whether the file can be read
828
+ */
829
+ _hasReadPermissions(stats) {
830
+ if (this.options.ignorePermissionErrors) return true;
831
+
832
+ // stats.mode may be bigint
833
+ const md = stats && Number.parseInt(stats.mode, 10);
834
+ const st = md & 0o777;
835
+ const it = Number.parseInt(st.toString(8)[0], 10);
836
+ return Boolean(4 & it);
837
+ }
838
+
839
+ /**
840
+ * Handles emitting unlink events for
841
+ * files and directories, and via recursion, for
842
+ * files and directories within directories that are unlinked
843
+ * @param {String} directory within which the following item is located
844
+ * @param {String} item base path of item/directory
845
+ * @returns {void}
846
+ */
847
+ _remove(directory, item, isDirectory) {
848
+ // if what is being deleted is a directory, get that directory's paths
849
+ // for recursive deleting and cleaning of watched object
850
+ // if it is not a directory, nestedDirectoryChildren will be empty array
851
+ const path = sysPath.join(directory, item);
852
+ const fullPath = sysPath.resolve(path);
853
+ isDirectory = isDirectory != null
854
+ ? isDirectory
855
+ : this._watched.has(path) || this._watched.has(fullPath);
856
+
857
+ // prevent duplicate handling in case of arriving here nearly simultaneously
858
+ // via multiple paths (such as _handleFile and _handleDir)
859
+ if (!this._throttle('remove', path, 100)) return;
860
+
861
+ // if the only watched file is removed, watch for its return
862
+ if (!isDirectory && !this.options.useFsEvents && this._watched.size === 1) {
863
+ this.add(directory, item, true);
864
+ }
865
+
866
+ // This will create a new entry in the watched object in either case
867
+ // so we got to do the directory check beforehand
868
+ const wp = this._getWatchedDir(path);
869
+ const nestedDirectoryChildren = wp.getChildren();
870
+
871
+ // Recursively remove children directories / files.
872
+ nestedDirectoryChildren.forEach(nested => this._remove(path, nested));
873
+
874
+ // Check if item was on the watched list and remove it
875
+ const parent = this._getWatchedDir(directory);
876
+ const wasTracked = parent.has(item);
877
+ parent.remove(item);
878
+
879
+ // Fixes issue #1042 -> Relative paths were detected and added as symlinks
880
+ // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612),
881
+ // but never removed from the map in case the path was deleted.
882
+ // This leads to an incorrect state if the path was recreated:
883
+ // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553
884
+ if (this._symlinkPaths.has(fullPath)) {
885
+ this._symlinkPaths.delete(fullPath);
886
+ }
887
+
888
+ // If we wait for this file to be fully written, cancel the wait.
889
+ let relPath = path;
890
+ if (this.options.cwd) relPath = sysPath.relative(this.options.cwd, path);
891
+ if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
892
+ const event = this._pendingWrites.get(relPath).cancelWait();
893
+ if (event === EV_ADD) return;
894
+ }
895
+
896
+ // The Entry will either be a directory that just got removed
897
+ // or a bogus entry to a file, in either case we have to remove it
898
+ this._watched.delete(path);
899
+ this._watched.delete(fullPath);
900
+ const eventName = isDirectory ? EV_UNLINK_DIR : EV_UNLINK;
901
+ if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
902
+
903
+ // Avoid conflicts if we later create another file with the same name
904
+ if (!this.options.useFsEvents) {
905
+ this._closePath(path);
906
+ }
907
+ }
908
+
909
+ /**
910
+ * Closes all watchers for a path
911
+ * @param {Path} path
912
+ */
913
+ _closePath(path) {
914
+ this._closeFile(path)
915
+ const dir = sysPath.dirname(path);
916
+ this._getWatchedDir(dir).remove(sysPath.basename(path));
917
+ }
918
+
919
+ /**
920
+ * Closes only file-specific watchers
921
+ * @param {Path} path
922
+ */
923
+ _closeFile(path) {
924
+ const closers = this._closers.get(path);
925
+ if (!closers) return;
926
+ closers.forEach(closer => closer());
927
+ this._closers.delete(path);
928
+ }
929
+
930
+ /**
931
+ *
932
+ * @param {Path} path
933
+ * @param {Function} closer
934
+ */
935
+ _addPathCloser(path, closer) {
936
+ if (!closer) return;
937
+ let list = this._closers.get(path);
938
+ if (!list) {
939
+ list = [];
940
+ this._closers.set(path, list);
941
+ }
942
+ list.push(closer);
943
+ }
944
+
945
+ _readdirp(root, opts) {
946
+ if (this.closed) return;
947
+ const options = {type: EV_ALL, alwaysStat: true, lstat: true, ...opts};
948
+ let stream = readdirp(root, options);
949
+ this._streams.add(stream);
950
+ stream.once(STR_CLOSE, () => {
951
+ stream = undefined;
952
+ });
953
+ stream.once(STR_END, () => {
954
+ if (stream) {
955
+ this._streams.delete(stream);
956
+ stream = undefined;
957
+ }
958
+ });
959
+ return stream;
960
+ }
961
+
962
+ }
963
+
964
+ // Export FSWatcher class
965
+ exports.FSWatcher = FSWatcher;
966
+
967
+ /**
968
+ * Instantiates watcher with paths to be tracked.
969
+ * @param {String|Array<String>} paths file/directory paths and/or globs
970
+ * @param {Object=} options chokidar opts
971
+ * @returns an instance of FSWatcher for chaining.
972
+ */
973
+ const watch = (paths, options) => {
974
+ const watcher = new FSWatcher(options);
975
+ watcher.add(paths);
976
+ return watcher;
977
+ };
978
+
979
+ exports.watch = watch;