volume.js 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.FSWatcher = exports.StatWatcher = exports.Volume = void 0;
  4. exports.pathToSteps = pathToSteps;
  5. exports.dataToStr = dataToStr;
  6. exports.toUnixTimestamp = toUnixTimestamp;
  7. const path_1 = require("@jsonjoy.com/fs-node-builtins/lib/path");
  8. const fs_core_1 = require("@jsonjoy.com/fs-core");
  9. const util_1 = require("@jsonjoy.com/fs-core/lib/util");
  10. const Stats_1 = require("./Stats");
  11. const Dirent_1 = require("./Dirent");
  12. const StatFs_1 = require("./StatFs");
  13. const buffer_1 = require("@jsonjoy.com/fs-node-builtins/lib/internal/buffer");
  14. const setTimeoutUnref_1 = require("@jsonjoy.com/fs-node-utils/lib/setTimeoutUnref");
  15. const stream_1 = require("@jsonjoy.com/fs-node-builtins/lib/stream");
  16. const fs_node_utils_1 = require("@jsonjoy.com/fs-node-utils");
  17. const events_1 = require("@jsonjoy.com/fs-node-builtins/lib/events");
  18. const FileHandle_1 = require("./FileHandle");
  19. const util_2 = require("@jsonjoy.com/fs-node-builtins/lib/util");
  20. const FsPromises_1 = require("./FsPromises");
  21. const fs_print_1 = require("@jsonjoy.com/fs-print");
  22. const fsSnapshot = require("@jsonjoy.com/fs-snapshot");
  23. const fs_node_utils_2 = require("@jsonjoy.com/fs-node-utils");
  24. const errors = require("@jsonjoy.com/fs-node-builtins/lib/internal/errors");
  25. const options_1 = require("./options");
  26. const util_3 = require("./util");
  27. const Dir_1 = require("./Dir");
  28. const resolveCrossPlatform = path_1.resolve;
  29. const { O_SYMLINK, F_OK, R_OK, W_OK, X_OK, COPYFILE_EXCL, COPYFILE_FICLONE_FORCE } = fs_node_utils_1.constants;
  30. const pathSep = path_1.posix ? path_1.posix.sep : path_1.sep;
  31. const pathRelative = path_1.posix ? path_1.posix.relative : path_1.relative;
  32. const pathJoin = path_1.posix ? path_1.posix.join : path_1.join;
  33. const pathDirname = path_1.posix ? path_1.posix.dirname : path_1.dirname;
  34. const pathNormalize = path_1.posix ? path_1.posix.normalize : path_1.normalize;
  35. // ------------------------------------------------------------------ Constants
  36. const kMinPoolSpace = 128;
  37. // ---------------------------------------------------------- Utility functions
  38. function pathToSteps(path) {
  39. return (0, fs_core_1.filenameToSteps)((0, util_3.pathToFilename)(path));
  40. }
  41. function dataToStr(data, encoding = fs_node_utils_1.ENCODING_UTF8) {
  42. if (buffer_1.Buffer.isBuffer(data))
  43. return data.toString(encoding);
  44. else if (data instanceof Uint8Array)
  45. return (0, buffer_1.bufferFrom)(data).toString(encoding);
  46. else
  47. return String(data);
  48. }
  49. // converts Date or number to a fractional UNIX timestamp
  50. function toUnixTimestamp(time) {
  51. // tslint:disable-next-line triple-equals
  52. if (typeof time === 'string' && +time == time) {
  53. return +time;
  54. }
  55. if (time instanceof Date) {
  56. return time.getTime() / 1000;
  57. }
  58. if (isFinite(time)) {
  59. if (time < 0) {
  60. return Date.now() / 1000;
  61. }
  62. return time;
  63. }
  64. throw new Error('Cannot parse time: ' + time);
  65. }
  66. function validateUid(uid) {
  67. if (typeof uid !== 'number')
  68. throw TypeError(fs_node_utils_2.ERRSTR.UID);
  69. }
  70. function validateGid(gid) {
  71. if (typeof gid !== 'number')
  72. throw TypeError(fs_node_utils_2.ERRSTR.GID);
  73. }
  74. /**
  75. * `Volume` represents a file system.
  76. */
  77. class Volume {
  78. get promises() {
  79. if (this.promisesApi === null)
  80. throw new Error('Promise is not supported in this environment.');
  81. return this.promisesApi;
  82. }
  83. constructor(_core = new fs_core_1.Superblock()) {
  84. this._core = _core;
  85. this.promisesApi = new FsPromises_1.FsPromises(this, FileHandle_1.FileHandle);
  86. this.openSync = (path, flags, mode = 438 /* MODE.DEFAULT */) => {
  87. // Validate (1) mode; (2) path; (3) flags - in that order.
  88. const modeNum = (0, util_3.modeToNumber)(mode);
  89. const fileName = (0, util_3.pathToFilename)(path);
  90. const flagsNum = (0, util_3.flagsToNumber)(flags);
  91. return this._core.open(fileName, flagsNum, modeNum, !(flagsNum & O_SYMLINK));
  92. };
  93. this.open = (path, flags, a, b) => {
  94. let mode = a;
  95. let callback = b;
  96. if (typeof a === 'function') {
  97. mode = 438 /* MODE.DEFAULT */;
  98. callback = a;
  99. }
  100. mode = mode || 438 /* MODE.DEFAULT */;
  101. const modeNum = (0, util_3.modeToNumber)(mode);
  102. const fileName = (0, util_3.pathToFilename)(path);
  103. const flagsNum = (0, util_3.flagsToNumber)(flags);
  104. this.wrapAsync(this._core.open, [fileName, flagsNum, modeNum, !(flagsNum & O_SYMLINK)], callback);
  105. };
  106. this.closeSync = (fd) => {
  107. this._core.close(fd);
  108. };
  109. this.close = (fd, callback) => {
  110. (0, fs_core_1.validateFd)(fd);
  111. const file = this._core.getFileByFdOrThrow(fd, 'close');
  112. this.wrapAsync(this._core.close, [file.fd], callback);
  113. };
  114. this.readSync = (fd, buffer, offset, length, position) => {
  115. (0, fs_core_1.validateFd)(fd);
  116. return this._core.read(fd, buffer, offset, length, position);
  117. };
  118. this.read = (fd, buffer, offset, length, position, callback) => {
  119. (0, util_3.validateCallback)(callback);
  120. if (length === 0) {
  121. // This `if` branch is from Node.js
  122. return queueMicrotask(() => {
  123. if (callback)
  124. callback(null, 0, buffer);
  125. });
  126. }
  127. Promise.resolve().then(() => {
  128. try {
  129. const bytes = this._core.read(fd, buffer, offset, length, position);
  130. callback(null, bytes, buffer);
  131. }
  132. catch (err) {
  133. callback(err);
  134. }
  135. });
  136. };
  137. this.readv = (fd, buffers, a, b) => {
  138. let position = a;
  139. let callback = b;
  140. if (typeof a === 'function')
  141. [position, callback] = [null, a];
  142. (0, util_3.validateCallback)(callback);
  143. Promise.resolve().then(() => {
  144. try {
  145. const bytes = this._core.readv(fd, buffers, position);
  146. callback(null, bytes, buffers);
  147. }
  148. catch (err) {
  149. callback(err);
  150. }
  151. });
  152. };
  153. this.readvSync = (fd, buffers, position) => {
  154. (0, fs_core_1.validateFd)(fd);
  155. return this._core.readv(fd, buffers, position ?? null);
  156. };
  157. this._readfile = (id, flagsNum, encoding) => {
  158. let result;
  159. const isUserFd = typeof id === 'number';
  160. const userOwnsFd = isUserFd && (0, fs_core_1.isFd)(id);
  161. let fd;
  162. if (userOwnsFd)
  163. fd = id;
  164. else {
  165. const filename = (0, util_3.pathToFilename)(id);
  166. // Check if original path had trailing slash (indicates directory intent)
  167. const originalPath = String(id);
  168. const hasTrailingSlash = originalPath.length > 1 && originalPath.endsWith('/');
  169. const link = this._core.getResolvedLinkOrThrow(filename, 'open');
  170. const node = link.getNode();
  171. if (node.isDirectory())
  172. throw (0, util_3.createError)("EISDIR" /* ERROR_CODE.EISDIR */, 'open', link.getPath());
  173. // If path had trailing slash but resolved to a file, throw ENOTDIR
  174. if (hasTrailingSlash && node.isFile()) {
  175. throw (0, util_3.createError)("ENOTDIR" /* ERROR_CODE.ENOTDIR */, 'open', originalPath);
  176. }
  177. fd = this.openSync(id, flagsNum);
  178. }
  179. try {
  180. result = (0, util_3.bufferToEncoding)(this._core.getFileByFdOrThrow(fd).getBuffer(), encoding);
  181. }
  182. finally {
  183. if (!userOwnsFd) {
  184. this.closeSync(fd);
  185. }
  186. }
  187. return result;
  188. };
  189. this.readFileSync = (file, options) => {
  190. const opts = (0, options_1.getReadFileOptions)(options);
  191. const flagsNum = (0, util_3.flagsToNumber)(opts.flag);
  192. return this._readfile(file, flagsNum, opts.encoding);
  193. };
  194. this.readFile = (id, a, b) => {
  195. const [opts, callback] = (0, options_1.optsAndCbGenerator)(options_1.getReadFileOptions)(a, b);
  196. const flagsNum = (0, util_3.flagsToNumber)(opts.flag);
  197. this.wrapAsync(this._readfile, [id, flagsNum, opts.encoding], callback);
  198. };
  199. this.writeSync = (fd, a, b, c, d) => {
  200. const [, buf, offset, length, position] = (0, util_3.getWriteSyncArgs)(fd, a, b, c, d);
  201. return this._write(fd, buf, offset, length, position);
  202. };
  203. this.write = (fd, a, b, c, d, e) => {
  204. const [, asStr, buf, offset, length, position, cb] = (0, util_3.getWriteArgs)(fd, a, b, c, d, e);
  205. Promise.resolve().then(() => {
  206. try {
  207. const bytes = this._write(fd, buf, offset, length, position);
  208. if (!asStr) {
  209. cb(null, bytes, buf);
  210. }
  211. else {
  212. cb(null, bytes, a);
  213. }
  214. }
  215. catch (err) {
  216. cb(err);
  217. }
  218. });
  219. };
  220. this.writev = (fd, buffers, a, b) => {
  221. let position = a;
  222. let callback = b;
  223. if (typeof a === 'function')
  224. [position, callback] = [null, a];
  225. (0, util_3.validateCallback)(callback);
  226. Promise.resolve().then(() => {
  227. try {
  228. const bytes = this.writevBase(fd, buffers, position);
  229. callback(null, bytes, buffers);
  230. }
  231. catch (err) {
  232. callback(err);
  233. }
  234. });
  235. };
  236. this.writevSync = (fd, buffers, position) => {
  237. (0, fs_core_1.validateFd)(fd);
  238. return this.writevBase(fd, buffers, position ?? null);
  239. };
  240. this.writeFileSync = (id, data, options) => {
  241. const opts = (0, options_1.getWriteFileOptions)(options);
  242. const flagsNum = (0, util_3.flagsToNumber)(opts.flag);
  243. const modeNum = (0, util_3.modeToNumber)(opts.mode);
  244. const buf = (0, fs_core_1.dataToBuffer)(data, opts.encoding);
  245. this._core.writeFile(id, buf, flagsNum, modeNum);
  246. };
  247. this.writeFile = (id, data, a, b) => {
  248. let options = a;
  249. let callback = b;
  250. if (typeof a === 'function')
  251. [options, callback] = [options_1.writeFileDefaults, a];
  252. const cb = (0, util_3.validateCallback)(callback);
  253. const opts = (0, options_1.getWriteFileOptions)(options);
  254. const flagsNum = (0, util_3.flagsToNumber)(opts.flag);
  255. const modeNum = (0, util_3.modeToNumber)(opts.mode);
  256. const buf = (0, fs_core_1.dataToBuffer)(data, opts.encoding);
  257. this.wrapAsync(this._core.writeFile, [id, buf, flagsNum, modeNum], cb);
  258. };
  259. this.copyFileSync = (src, dest, flags) => {
  260. const srcFilename = (0, util_3.pathToFilename)(src);
  261. const destFilename = (0, util_3.pathToFilename)(dest);
  262. return this._copyFile(srcFilename, destFilename, (flags || 0) | 0);
  263. };
  264. this.copyFile = (src, dest, a, b) => {
  265. const srcFilename = (0, util_3.pathToFilename)(src);
  266. const destFilename = (0, util_3.pathToFilename)(dest);
  267. let flags;
  268. let callback;
  269. if (typeof a === 'function')
  270. [flags, callback] = [0, a];
  271. else
  272. [flags, callback] = [a, b];
  273. (0, util_3.validateCallback)(callback);
  274. this.wrapAsync(this._copyFile, [srcFilename, destFilename, flags], callback);
  275. };
  276. this._cp = (src, dest, options) => {
  277. if (options.filter && !options.filter(src, dest))
  278. return;
  279. const srcStat = options.dereference ? this.statSync(src) : this.lstatSync(src);
  280. let destStat = null;
  281. try {
  282. destStat = this.lstatSync(dest);
  283. }
  284. catch (err) {
  285. if (err.code !== 'ENOENT') {
  286. throw err;
  287. }
  288. }
  289. // Check if src and dest are the same (both exist and have same inode)
  290. if (destStat && srcStat.ino === destStat.ino && srcStat.dev === destStat.dev)
  291. throw (0, util_3.createError)("EINVAL" /* ERROR_CODE.EINVAL */, 'cp', src, dest);
  292. // Check type compatibility
  293. if (destStat) {
  294. if (srcStat.isDirectory() && !destStat.isDirectory())
  295. throw (0, util_3.createError)("EISDIR" /* ERROR_CODE.EISDIR */, 'cp', src, dest);
  296. if (!srcStat.isDirectory() && destStat.isDirectory())
  297. throw (0, util_3.createError)("ENOTDIR" /* ERROR_CODE.ENOTDIR */, 'cp', src, dest);
  298. }
  299. // Check if trying to copy directory to subdirectory of itself
  300. if (srcStat.isDirectory() && this.isSrcSubdir(src, dest))
  301. throw (0, util_3.createError)("EINVAL" /* ERROR_CODE.EINVAL */, 'cp', src, dest);
  302. ENDURE_PARENT_DIR_EXISTS: {
  303. const parent = pathDirname(dest);
  304. if (!this.existsSync(parent))
  305. this.mkdirSync(parent, { recursive: true });
  306. }
  307. // Handle different file types
  308. if (srcStat.isDirectory()) {
  309. if (!options.recursive)
  310. throw (0, util_3.createError)("EISDIR" /* ERROR_CODE.EISDIR */, 'cp', src);
  311. this.cpDirSync(srcStat, destStat, src, dest, options);
  312. }
  313. else if (srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice()) {
  314. this.cpFileSync(srcStat, destStat, src, dest, options);
  315. }
  316. else if (srcStat.isSymbolicLink() && !options.dereference) {
  317. // Only handle as symlink if not dereferencing
  318. this.cpSymlinkSync(destStat, src, dest, options);
  319. }
  320. else {
  321. throw (0, util_3.createError)("EINVAL" /* ERROR_CODE.EINVAL */, 'cp', src);
  322. }
  323. };
  324. this.linkSync = (existingPath, newPath) => {
  325. const existingPathFilename = (0, util_3.pathToFilename)(existingPath);
  326. const newPathFilename = (0, util_3.pathToFilename)(newPath);
  327. this._core.link(existingPathFilename, newPathFilename);
  328. };
  329. this.link = (existingPath, newPath, callback) => {
  330. const existingPathFilename = (0, util_3.pathToFilename)(existingPath);
  331. const newPathFilename = (0, util_3.pathToFilename)(newPath);
  332. this.wrapAsync(this._core.link, [existingPathFilename, newPathFilename], callback);
  333. };
  334. this.unlinkSync = (path) => {
  335. const filename = (0, util_3.pathToFilename)(path);
  336. this._core.unlink(filename);
  337. };
  338. this.unlink = (path, callback) => {
  339. const filename = (0, util_3.pathToFilename)(path);
  340. this.wrapAsync(this._core.unlink, [filename], callback);
  341. };
  342. /**
  343. * `type` argument works only on Windows.
  344. * @param target
  345. * @param path
  346. * @param type
  347. */
  348. this.symlinkSync = (target, path, type) => {
  349. const targetFilename = (0, util_3.pathToFilename)(target);
  350. const pathFilename = (0, util_3.pathToFilename)(path);
  351. this._core.symlink(targetFilename, pathFilename);
  352. };
  353. this.symlink = (target, path, a, b) => {
  354. const callback = (0, util_3.validateCallback)(typeof a === 'function' ? a : b);
  355. const targetFilename = (0, util_3.pathToFilename)(target);
  356. const pathFilename = (0, util_3.pathToFilename)(path);
  357. this.wrapAsync(this._core.symlink, [targetFilename, pathFilename], callback);
  358. };
  359. this._lstat = (filename, bigint = false, throwIfNoEntry = false) => {
  360. let link;
  361. try {
  362. link = this._core.getLinkOrThrow(filename, 'lstat');
  363. }
  364. catch (err) {
  365. if (err.code === "ENOENT" /* ERROR_CODE.ENOENT */ && !throwIfNoEntry)
  366. return undefined;
  367. else
  368. throw err;
  369. }
  370. return Stats_1.default.build(link.getNode(), bigint);
  371. };
  372. this.lstatSync = (path, options) => {
  373. const { throwIfNoEntry = true, bigint = false } = (0, options_1.getStatOptions)(options);
  374. return this._lstat((0, util_3.pathToFilename)(path), bigint, throwIfNoEntry);
  375. };
  376. this.renameSync = (oldPath, newPath) => {
  377. const oldPathFilename = (0, util_3.pathToFilename)(oldPath);
  378. const newPathFilename = (0, util_3.pathToFilename)(newPath);
  379. this._core.rename(oldPathFilename, newPathFilename);
  380. };
  381. this.rename = (oldPath, newPath, callback) => {
  382. const oldPathFilename = (0, util_3.pathToFilename)(oldPath);
  383. const newPathFilename = (0, util_3.pathToFilename)(newPath);
  384. this.wrapAsync(this._core.rename, [oldPathFilename, newPathFilename], callback);
  385. };
  386. this.existsSync = (path) => {
  387. try {
  388. return this._exists((0, util_3.pathToFilename)(path)).ok;
  389. }
  390. catch (err) {
  391. return false;
  392. }
  393. };
  394. this.exists = (path, callback) => {
  395. const filename = (0, util_3.pathToFilename)(path);
  396. if (typeof callback !== 'function')
  397. throw Error(fs_node_utils_2.ERRSTR.CB);
  398. Promise.resolve().then(() => {
  399. try {
  400. callback(this._exists(filename).ok);
  401. }
  402. catch (err) {
  403. callback(false);
  404. }
  405. });
  406. };
  407. this.accessSync = (path, mode = F_OK) => {
  408. const filename = (0, util_3.pathToFilename)(path);
  409. mode = mode | 0;
  410. this._access(filename, mode);
  411. };
  412. this.access = (path, a, b) => {
  413. let mode = F_OK;
  414. let callback;
  415. if (typeof a !== 'function')
  416. [mode, callback] = [a | 0, (0, util_3.validateCallback)(b)];
  417. else
  418. callback = a;
  419. const filename = (0, util_3.pathToFilename)(path);
  420. this.wrapAsync(this._access, [filename, mode], callback);
  421. };
  422. this.appendFileSync = (id, data, options) => {
  423. const opts = (0, options_1.getAppendFileOpts)(options);
  424. // Force append behavior when using a supplied file descriptor.
  425. if (!opts.flag || (0, fs_core_1.isFd)(id))
  426. opts.flag = 'a';
  427. this.writeFileSync(id, data, opts);
  428. };
  429. this.appendFile = (id, data, a, b) => {
  430. const [opts, callback] = (0, options_1.getAppendFileOptsAndCb)(a, b);
  431. // Force append behavior when using a supplied file descriptor.
  432. if (!opts.flag || (0, fs_core_1.isFd)(id))
  433. opts.flag = 'a';
  434. this.writeFile(id, data, opts, callback);
  435. };
  436. this._readdir = (filename, options) => {
  437. const steps = (0, fs_core_1.filenameToSteps)(filename);
  438. const link = this._core.getResolvedLinkOrThrow(filename, 'scandir');
  439. const node = link.getNode();
  440. if (!node.isDirectory())
  441. throw (0, util_3.createError)("ENOTDIR" /* ERROR_CODE.ENOTDIR */, 'scandir', filename);
  442. // Check we have permissions
  443. if (!node.canRead())
  444. throw (0, util_3.createError)("EACCES" /* ERROR_CODE.EACCES */, 'scandir', filename);
  445. const list = []; // output list
  446. for (const name of link.children.keys()) {
  447. const child = link.getChild(name);
  448. if (!child || name === '.' || name === '..')
  449. continue;
  450. list.push(Dirent_1.default.build(child, options.encoding));
  451. // recursion
  452. if (options.recursive && child.children.size) {
  453. const recurseOptions = { ...options, recursive: true, withFileTypes: true };
  454. const childList = this._readdir(child.getPath(), recurseOptions);
  455. list.push(...childList);
  456. }
  457. }
  458. if (!util_1.isWin && options.encoding !== 'buffer')
  459. list.sort((a, b) => {
  460. if (a.name < b.name)
  461. return -1;
  462. if (a.name > b.name)
  463. return 1;
  464. return 0;
  465. });
  466. if (options.withFileTypes)
  467. return list;
  468. let filename2 = filename;
  469. if (util_1.isWin)
  470. filename2 = filename2.replace(/\\/g, '/');
  471. return list.map(dirent => {
  472. if (options.recursive) {
  473. let fullPath = pathJoin(dirent.parentPath, dirent.name.toString());
  474. if (util_1.isWin) {
  475. fullPath = fullPath.replace(/\\/g, '/');
  476. }
  477. return fullPath.replace(filename2 + path_1.posix.sep, '');
  478. }
  479. return dirent.name;
  480. });
  481. };
  482. this.readdirSync = (path, options) => {
  483. const opts = (0, options_1.getReaddirOptions)(options);
  484. const filename = (0, util_3.pathToFilename)(path);
  485. return this._readdir(filename, opts);
  486. };
  487. this.readdir = (path, a, b) => {
  488. const [options, callback] = (0, options_1.getReaddirOptsAndCb)(a, b);
  489. const filename = (0, util_3.pathToFilename)(path);
  490. this.wrapAsync(this._readdir, [filename, options], callback);
  491. };
  492. this._readlink = (filename, encoding) => {
  493. const link = this._core.getLinkOrThrow(filename, 'readlink');
  494. const node = link.getNode();
  495. if (!node.isSymlink())
  496. throw (0, util_3.createError)("EINVAL" /* ERROR_CODE.EINVAL */, 'readlink', filename);
  497. return (0, fs_node_utils_1.strToEncoding)(node.symlink, encoding);
  498. };
  499. this.readlinkSync = (path, options) => {
  500. const opts = (0, options_1.getDefaultOpts)(options);
  501. const filename = (0, util_3.pathToFilename)(path);
  502. return this._readlink(filename, opts.encoding);
  503. };
  504. this.readlink = (path, a, b) => {
  505. const [opts, callback] = (0, options_1.getDefaultOptsAndCb)(a, b);
  506. const filename = (0, util_3.pathToFilename)(path);
  507. this.wrapAsync(this._readlink, [filename, opts.encoding], callback);
  508. };
  509. this._fsync = (fd) => {
  510. this._core.getFileByFdOrThrow(fd, 'fsync');
  511. };
  512. this.fsyncSync = (fd) => {
  513. this._fsync(fd);
  514. };
  515. this.fsync = (fd, callback) => {
  516. this.wrapAsync(this._fsync, [fd], callback);
  517. };
  518. this._fdatasync = (fd) => {
  519. this._core.getFileByFdOrThrow(fd, 'fdatasync');
  520. };
  521. this.fdatasyncSync = (fd) => {
  522. this._fdatasync(fd);
  523. };
  524. this.fdatasync = (fd, callback) => {
  525. this.wrapAsync(this._fdatasync, [fd], callback);
  526. };
  527. this._ftruncate = (fd, len) => {
  528. const file = this._core.getFileByFdOrThrow(fd, 'ftruncate');
  529. file.truncate(len);
  530. };
  531. this.ftruncateSync = (fd, len) => {
  532. this._ftruncate(fd, len);
  533. };
  534. this.ftruncate = (fd, a, b) => {
  535. const len = typeof a === 'number' ? a : 0;
  536. const callback = (0, util_3.validateCallback)(typeof a === 'number' ? b : a);
  537. this.wrapAsync(this._ftruncate, [fd, len], callback);
  538. };
  539. this._truncate = (path, len) => {
  540. const fd = this.openSync(path, 'r+');
  541. try {
  542. this.ftruncateSync(fd, len);
  543. }
  544. finally {
  545. this.closeSync(fd);
  546. }
  547. };
  548. /**
  549. * `id` should be a file descriptor or a path. `id` as file descriptor will
  550. * not be supported soon.
  551. */
  552. this.truncateSync = (id, len) => {
  553. if ((0, fs_core_1.isFd)(id))
  554. return this.ftruncateSync(id, len);
  555. this._truncate(id, len);
  556. };
  557. this.truncate = (id, a, b) => {
  558. const len = typeof a === 'number' ? a : 0;
  559. const callback = (0, util_3.validateCallback)(typeof a === 'number' ? b : a);
  560. if ((0, fs_core_1.isFd)(id))
  561. return this.ftruncate(id, len, callback);
  562. this.wrapAsync(this._truncate, [id, len], callback);
  563. };
  564. this._futimes = (fd, atime, mtime) => {
  565. const file = this._core.getFileByFdOrThrow(fd, 'futimes');
  566. const node = file.node;
  567. node.atime = new Date(atime * 1000);
  568. node.mtime = new Date(mtime * 1000);
  569. };
  570. this.futimesSync = (fd, atime, mtime) => {
  571. this._futimes(fd, toUnixTimestamp(atime), toUnixTimestamp(mtime));
  572. };
  573. this.futimes = (fd, atime, mtime, callback) => {
  574. this.wrapAsync(this._futimes, [fd, toUnixTimestamp(atime), toUnixTimestamp(mtime)], callback);
  575. };
  576. this._utimes = (filename, atime, mtime, followSymlinks = true) => {
  577. const core = this._core;
  578. const link = followSymlinks
  579. ? core.getResolvedLinkOrThrow(filename, 'utimes')
  580. : core.getLinkOrThrow(filename, 'lutimes');
  581. const node = link.getNode();
  582. node.atime = new Date(atime * 1000);
  583. node.mtime = new Date(mtime * 1000);
  584. };
  585. this.utimesSync = (path, atime, mtime) => {
  586. this._utimes((0, util_3.pathToFilename)(path), toUnixTimestamp(atime), toUnixTimestamp(mtime), true);
  587. };
  588. this.utimes = (path, atime, mtime, callback) => {
  589. this.wrapAsync(this._utimes, [(0, util_3.pathToFilename)(path), toUnixTimestamp(atime), toUnixTimestamp(mtime), true], callback);
  590. };
  591. this.lutimesSync = (path, atime, mtime) => {
  592. this._utimes((0, util_3.pathToFilename)(path), toUnixTimestamp(atime), toUnixTimestamp(mtime), false);
  593. };
  594. this.lutimes = (path, atime, mtime, callback) => {
  595. this.wrapAsync(this._utimes, [(0, util_3.pathToFilename)(path), toUnixTimestamp(atime), toUnixTimestamp(mtime), false], callback);
  596. };
  597. this.mkdirSync = (path, options) => {
  598. const opts = (0, options_1.getMkdirOptions)(options);
  599. const modeNum = (0, util_3.modeToNumber)(opts.mode, 0o777);
  600. const filename = (0, util_3.pathToFilename)(path);
  601. if (opts.recursive)
  602. return this._core.mkdirp(filename, modeNum);
  603. this._core.mkdir(filename, modeNum);
  604. };
  605. this.mkdir = (path, a, b) => {
  606. const opts = (0, options_1.getMkdirOptions)(a);
  607. const callback = (0, util_3.validateCallback)(typeof a === 'function' ? a : b);
  608. const modeNum = (0, util_3.modeToNumber)(opts.mode, 0o777);
  609. const filename = (0, util_3.pathToFilename)(path);
  610. if (opts.recursive)
  611. this.wrapAsync(this._core.mkdirp, [filename, modeNum], callback);
  612. else
  613. this.wrapAsync(this._core.mkdir, [filename, modeNum], callback);
  614. };
  615. this._mkdtemp = (prefix, encoding, retry = 5) => {
  616. const filename = prefix + (0, util_3.genRndStr6)();
  617. try {
  618. this._core.mkdir(filename, 511 /* MODE.DIR */);
  619. return (0, fs_node_utils_1.strToEncoding)(filename, encoding);
  620. }
  621. catch (err) {
  622. if (err.code === "EEXIST" /* ERROR_CODE.EEXIST */) {
  623. if (retry > 1)
  624. return this._mkdtemp(prefix, encoding, retry - 1);
  625. else
  626. throw Error('Could not create temp dir.');
  627. }
  628. else
  629. throw err;
  630. }
  631. };
  632. this.mkdtempSync = (prefix, options) => {
  633. const { encoding } = (0, options_1.getDefaultOpts)(options);
  634. if (!prefix || typeof prefix !== 'string')
  635. throw new TypeError('filename prefix is required');
  636. (0, util_3.nullCheck)(prefix);
  637. return this._mkdtemp(prefix, encoding);
  638. };
  639. this.mkdtemp = (prefix, a, b) => {
  640. const [{ encoding }, callback] = (0, options_1.getDefaultOptsAndCb)(a, b);
  641. if (!prefix || typeof prefix !== 'string')
  642. throw new TypeError('filename prefix is required');
  643. if (!(0, util_3.nullCheck)(prefix))
  644. return;
  645. this.wrapAsync(this._mkdtemp, [prefix, encoding], callback);
  646. };
  647. this.rmdirSync = (path, options) => {
  648. const opts = (0, options_1.getRmdirOptions)(options);
  649. this._core.rmdir((0, util_3.pathToFilename)(path), opts.recursive);
  650. };
  651. this.rmdir = (path, a, b) => {
  652. const opts = (0, options_1.getRmdirOptions)(a);
  653. const callback = (0, util_3.validateCallback)(typeof a === 'function' ? a : b);
  654. this.wrapAsync(this._core.rmdir, [(0, util_3.pathToFilename)(path), opts.recursive], callback);
  655. };
  656. this.rmSync = (path, options) => {
  657. this._core.rm((0, util_3.pathToFilename)(path), options?.force, options?.recursive);
  658. };
  659. this.rm = (path, a, b) => {
  660. const [opts, callback] = (0, options_1.getRmOptsAndCb)(a, b);
  661. this.wrapAsync(this._core.rm, [(0, util_3.pathToFilename)(path), opts?.force, opts?.recursive], callback);
  662. };
  663. this._fchmod = (fd, modeNum) => {
  664. const file = this._core.getFileByFdOrThrow(fd, 'fchmod');
  665. file.chmod(modeNum);
  666. };
  667. this.fchmodSync = (fd, mode) => {
  668. this._fchmod(fd, (0, util_3.modeToNumber)(mode));
  669. };
  670. this.fchmod = (fd, mode, callback) => {
  671. this.wrapAsync(this._fchmod, [fd, (0, util_3.modeToNumber)(mode)], callback);
  672. };
  673. this._chmod = (filename, modeNum, followSymlinks = true) => {
  674. const link = followSymlinks
  675. ? this._core.getResolvedLinkOrThrow(filename, 'chmod')
  676. : this._core.getLinkOrThrow(filename, 'chmod');
  677. const node = link.getNode();
  678. node.chmod(modeNum);
  679. };
  680. this.chmodSync = (path, mode) => {
  681. const modeNum = (0, util_3.modeToNumber)(mode);
  682. const filename = (0, util_3.pathToFilename)(path);
  683. this._chmod(filename, modeNum, true);
  684. };
  685. this.chmod = (path, mode, callback) => {
  686. const modeNum = (0, util_3.modeToNumber)(mode);
  687. const filename = (0, util_3.pathToFilename)(path);
  688. this.wrapAsync(this._chmod, [filename, modeNum], callback);
  689. };
  690. this._lchmod = (filename, modeNum) => {
  691. this._chmod(filename, modeNum, false);
  692. };
  693. this.lchmodSync = (path, mode) => {
  694. const modeNum = (0, util_3.modeToNumber)(mode);
  695. const filename = (0, util_3.pathToFilename)(path);
  696. this._lchmod(filename, modeNum);
  697. };
  698. this.lchmod = (path, mode, callback) => {
  699. const modeNum = (0, util_3.modeToNumber)(mode);
  700. const filename = (0, util_3.pathToFilename)(path);
  701. this.wrapAsync(this._lchmod, [filename, modeNum], callback);
  702. };
  703. this._fchown = (fd, uid, gid) => {
  704. this._core.getFileByFdOrThrow(fd, 'fchown').chown(uid, gid);
  705. };
  706. this.fchownSync = (fd, uid, gid) => {
  707. validateUid(uid);
  708. validateGid(gid);
  709. this._fchown(fd, uid, gid);
  710. };
  711. this.fchown = (fd, uid, gid, callback) => {
  712. validateUid(uid);
  713. validateGid(gid);
  714. this.wrapAsync(this._fchown, [fd, uid, gid], callback);
  715. };
  716. this._chown = (filename, uid, gid) => {
  717. const link = this._core.getResolvedLinkOrThrow(filename, 'chown');
  718. const node = link.getNode();
  719. node.chown(uid, gid);
  720. };
  721. this.chownSync = (path, uid, gid) => {
  722. validateUid(uid);
  723. validateGid(gid);
  724. this._chown((0, util_3.pathToFilename)(path), uid, gid);
  725. };
  726. this.chown = (path, uid, gid, callback) => {
  727. validateUid(uid);
  728. validateGid(gid);
  729. this.wrapAsync(this._chown, [(0, util_3.pathToFilename)(path), uid, gid], callback);
  730. };
  731. this._lchown = (filename, uid, gid) => {
  732. this._core.getLinkOrThrow(filename, 'lchown').getNode().chown(uid, gid);
  733. };
  734. this.lchownSync = (path, uid, gid) => {
  735. validateUid(uid);
  736. validateGid(gid);
  737. this._lchown((0, util_3.pathToFilename)(path), uid, gid);
  738. };
  739. this.lchown = (path, uid, gid, callback) => {
  740. validateUid(uid);
  741. validateGid(gid);
  742. this.wrapAsync(this._lchown, [(0, util_3.pathToFilename)(path), uid, gid], callback);
  743. };
  744. this.statWatchers = {};
  745. this.cpSync = (src, dest, options) => {
  746. const srcFilename = (0, util_3.pathToFilename)(src);
  747. const destFilename = (0, util_3.pathToFilename)(dest);
  748. const opts_ = {
  749. dereference: options?.dereference ?? false,
  750. errorOnExist: options?.errorOnExist ?? false,
  751. filter: options?.filter,
  752. force: options?.force ?? true,
  753. mode: options?.mode ?? 0,
  754. preserveTimestamps: options?.preserveTimestamps ?? false,
  755. recursive: options?.recursive ?? false,
  756. verbatimSymlinks: options?.verbatimSymlinks ?? false,
  757. };
  758. return this._cp(srcFilename, destFilename, opts_);
  759. };
  760. this.cp = (src, dest, a, b) => {
  761. const srcFilename = (0, util_3.pathToFilename)(src);
  762. const destFilename = (0, util_3.pathToFilename)(dest);
  763. let options;
  764. let callback;
  765. if (typeof a === 'function')
  766. [options, callback] = [{}, a];
  767. else
  768. [options, callback] = [a || {}, b];
  769. (0, util_3.validateCallback)(callback);
  770. const opts_ = {
  771. dereference: options?.dereference ?? false,
  772. errorOnExist: options?.errorOnExist ?? false,
  773. filter: options?.filter,
  774. force: options?.force ?? true,
  775. mode: options?.mode ?? 0,
  776. preserveTimestamps: options?.preserveTimestamps ?? false,
  777. recursive: options?.recursive ?? false,
  778. verbatimSymlinks: options?.verbatimSymlinks ?? false,
  779. };
  780. this.wrapAsync(this._cp, [srcFilename, destFilename, opts_], callback);
  781. };
  782. this.openAsBlob = async (path, options) => {
  783. const filename = (0, util_3.pathToFilename)(path);
  784. let link;
  785. try {
  786. link = this._core.getResolvedLinkOrThrow(filename, 'open');
  787. }
  788. catch (error) {
  789. // Convert ENOENT to Node.js-compatible error for openAsBlob
  790. if (error && typeof error === 'object' && error.code === 'ENOENT') {
  791. const nodeError = new errors.TypeError('ERR_INVALID_ARG_VALUE');
  792. throw nodeError;
  793. }
  794. throw error;
  795. }
  796. const node = link.getNode();
  797. // Note: Node.js allows opening directories as blobs, so we don't throw EISDIR
  798. const buffer = node.getBuffer();
  799. const type = options?.type || '';
  800. return new Blob([buffer], { type });
  801. };
  802. this.glob = (pattern, ...args) => {
  803. const [options, callback] = args.length === 1 ? [{}, args[0]] : [args[0], args[1]];
  804. this.wrapAsync(this._globSync, [pattern, options || {}], callback);
  805. };
  806. this.globSync = (pattern, options = {}) => {
  807. return this._globSync(pattern, options);
  808. };
  809. this._globSync = (pattern, options = {}) => {
  810. const { globSync } = require('./glob');
  811. return globSync(this, pattern, options);
  812. };
  813. this._opendir = (filename, options) => {
  814. const link = this._core.getResolvedLinkOrThrow(filename, 'scandir');
  815. const node = link.getNode();
  816. if (!node.isDirectory())
  817. throw (0, util_3.createError)("ENOTDIR" /* ERROR_CODE.ENOTDIR */, 'scandir', filename);
  818. return new Dir_1.Dir(link, options);
  819. };
  820. this.opendirSync = (path, options) => {
  821. const opts = (0, options_1.getOpendirOptions)(options);
  822. const filename = (0, util_3.pathToFilename)(path);
  823. return this._opendir(filename, opts);
  824. };
  825. this.opendir = (path, a, b) => {
  826. const [options, callback] = (0, options_1.getOpendirOptsAndCb)(a, b);
  827. const filename = (0, util_3.pathToFilename)(path);
  828. this.wrapAsync(this._opendir, [filename, options], callback);
  829. };
  830. const self = this; // tslint:disable-line no-this-assignment
  831. this.StatWatcher = class extends StatWatcher {
  832. constructor() {
  833. super(self);
  834. }
  835. };
  836. const _ReadStream = FsReadStream;
  837. this.ReadStream = class extends _ReadStream {
  838. constructor(...args) {
  839. super(self, ...args);
  840. }
  841. };
  842. const _WriteStream = FsWriteStream;
  843. this.WriteStream = class extends _WriteStream {
  844. constructor(...args) {
  845. super(self, ...args);
  846. }
  847. };
  848. this.FSWatcher = class extends FSWatcher {
  849. constructor() {
  850. super(self);
  851. }
  852. };
  853. const _realpath = (filename, encoding) => {
  854. const realLink = this._core.getResolvedLinkOrThrow(filename, 'realpath');
  855. return (0, fs_node_utils_1.strToEncoding)(realLink.getPath() || '/', encoding);
  856. };
  857. const realpathImpl = (path, a, b) => {
  858. const [opts, callback] = (0, options_1.getRealpathOptsAndCb)(a, b);
  859. const pathFilename = (0, util_3.pathToFilename)(path);
  860. self.wrapAsync(_realpath, [pathFilename, opts.encoding], callback);
  861. };
  862. const realpathSyncImpl = (path, options) => _realpath((0, util_3.pathToFilename)(path), (0, options_1.getRealpathOptions)(options).encoding);
  863. this.realpath = realpathImpl;
  864. this.realpath.native = realpathImpl;
  865. this.realpathSync = realpathSyncImpl;
  866. this.realpathSync.native = realpathSyncImpl;
  867. }
  868. wrapAsync(method, args, callback) {
  869. (0, util_3.validateCallback)(callback);
  870. Promise.resolve().then(() => {
  871. let result;
  872. try {
  873. result = method.apply(this, args);
  874. }
  875. catch (err) {
  876. callback(err);
  877. return;
  878. }
  879. callback(null, result);
  880. });
  881. }
  882. reset() {
  883. this._core.reset();
  884. }
  885. toJSON(paths, json = {}, isRelative = false, asBuffer = false) {
  886. return this._core.toJSON(paths, json, isRelative, asBuffer);
  887. }
  888. fromJSON(json, cwd) {
  889. return this._core.fromJSON(json, cwd);
  890. }
  891. fromNestedJSON(json, cwd) {
  892. return this._core.fromNestedJSON(json, cwd);
  893. }
  894. // Legacy interface
  895. mountSync(mountpoint, json) {
  896. this._core.fromJSON(json, mountpoint);
  897. }
  898. _write(fd, buf, offset, length, position) {
  899. const file = this._core.getFileByFdOrThrow(fd, 'write');
  900. if (file.node.isSymlink()) {
  901. throw (0, util_3.createError)("EBADF" /* ERROR_CODE.EBADF */, 'write', file.link.getPath());
  902. }
  903. return file.write(buf, offset, length, position === -1 || typeof position !== 'number' ? undefined : position);
  904. }
  905. writevBase(fd, buffers, position) {
  906. const file = this._core.getFileByFdOrThrow(fd);
  907. let p = position ?? undefined;
  908. if (p === -1) {
  909. p = undefined;
  910. }
  911. let bytesWritten = 0;
  912. for (const buffer of buffers) {
  913. const nodeBuf = buffer_1.Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  914. const bytes = file.write(nodeBuf, 0, nodeBuf.byteLength, p);
  915. p = undefined;
  916. bytesWritten += bytes;
  917. if (bytes < nodeBuf.byteLength)
  918. break;
  919. }
  920. return bytesWritten;
  921. }
  922. _copyFile(src, dest, flags) {
  923. const buf = this.readFileSync(src);
  924. if (flags & COPYFILE_EXCL && this.existsSync(dest))
  925. throw (0, util_3.createError)("EEXIST" /* ERROR_CODE.EEXIST */, 'copyFile', src, dest);
  926. if (flags & COPYFILE_FICLONE_FORCE)
  927. throw (0, util_3.createError)("ENOSYS" /* ERROR_CODE.ENOSYS */, 'copyFile', src, dest);
  928. this._core.writeFile(dest, buf, fs_node_utils_2.FLAGS.w, 438 /* MODE.DEFAULT */);
  929. }
  930. isSrcSubdir(src, dest) {
  931. try {
  932. const normalizedSrc = pathNormalize(src.startsWith('/') ? src : '/' + src);
  933. const normalizedDest = pathNormalize(dest.startsWith('/') ? dest : '/' + dest);
  934. if (normalizedSrc === normalizedDest)
  935. return true;
  936. // Check if dest is under src by using relative path
  937. // If dest is under src, the relative path from src to dest won't start with '..'
  938. const relativePath = pathRelative(normalizedSrc, normalizedDest);
  939. // If relative path is empty or doesn't start with '..', dest is under src
  940. return relativePath === '' || (!relativePath.startsWith('..') && !(0, path_1.isAbsolute)(relativePath));
  941. }
  942. catch (error) {
  943. // If path operations fail, assume it's safe (don't block the copy)
  944. return false;
  945. }
  946. }
  947. cpFileSync(srcStat, destStat, src, dest, options) {
  948. if (destStat) {
  949. if (options.errorOnExist)
  950. throw (0, util_3.createError)("EEXIST" /* ERROR_CODE.EEXIST */, 'cp', dest);
  951. if (!options.force)
  952. return;
  953. this.unlinkSync(dest);
  954. }
  955. // Copy the file
  956. this.copyFileSync(src, dest, options.mode);
  957. // Preserve timestamps if requested
  958. if (options.preserveTimestamps)
  959. this.utimesSync(dest, srcStat.atime, srcStat.mtime);
  960. // Set file mode
  961. this.chmodSync(dest, Number(srcStat.mode));
  962. }
  963. cpDirSync(srcStat, destStat, src, dest, options) {
  964. if (!destStat) {
  965. this.mkdirSync(dest);
  966. }
  967. // Read directory contents
  968. const entries = this.readdirSync(src);
  969. for (const entry of entries) {
  970. const srcItem = pathJoin(src, String(entry));
  971. const destItem = pathJoin(dest, String(entry));
  972. // Apply filter to each item
  973. if (options.filter && !options.filter(srcItem, destItem)) {
  974. continue;
  975. }
  976. this._cp(srcItem, destItem, options);
  977. }
  978. // Set directory mode
  979. this.chmodSync(dest, Number(srcStat.mode));
  980. }
  981. cpSymlinkSync(destStat, src, dest, options) {
  982. let linkTarget = String(this.readlinkSync(src));
  983. if (!options.verbatimSymlinks && !(0, path_1.isAbsolute)(linkTarget))
  984. linkTarget = resolveCrossPlatform(pathDirname(src), linkTarget);
  985. if (destStat)
  986. this.unlinkSync(dest);
  987. this.symlinkSync(linkTarget, dest);
  988. }
  989. lstat(path, a, b) {
  990. const [{ throwIfNoEntry = true, bigint = false }, callback] = (0, options_1.getStatOptsAndCb)(a, b);
  991. this.wrapAsync(this._lstat, [(0, util_3.pathToFilename)(path), bigint, throwIfNoEntry], callback);
  992. }
  993. _stat(filename, bigint = false, throwIfNoEntry = true) {
  994. const result = this._core.getResolvedLinkResult(filename, 'stat');
  995. if (result.ok) {
  996. return (0, fs_core_1.Ok)(Stats_1.default.build(result.value.getNode(), bigint));
  997. }
  998. if (result.err.code === "ENOENT" /* ERROR_CODE.ENOENT */ && !throwIfNoEntry) {
  999. return (0, fs_core_1.Ok)(undefined);
  1000. }
  1001. else {
  1002. return result;
  1003. }
  1004. }
  1005. _statOrThrow(filename, bigint = false, throwIfNoEntry = true) {
  1006. const result = this._stat(filename, bigint, throwIfNoEntry);
  1007. if (result.ok) {
  1008. return result.value;
  1009. }
  1010. else {
  1011. throw result.err.toError();
  1012. }
  1013. }
  1014. statSync(path, options) {
  1015. const { bigint = true, throwIfNoEntry = true } = (0, options_1.getStatOptions)(options);
  1016. const result = this._stat((0, util_3.pathToFilename)(path), bigint, throwIfNoEntry);
  1017. if (result.ok) {
  1018. return result.value;
  1019. }
  1020. else {
  1021. throw result.err.toError();
  1022. }
  1023. }
  1024. stat(path, a, b) {
  1025. const [{ bigint = false, throwIfNoEntry = true }, callback] = (0, options_1.getStatOptsAndCb)(a, b);
  1026. this.wrapAsync(this._statOrThrow, [(0, util_3.pathToFilename)(path), bigint, throwIfNoEntry], callback);
  1027. }
  1028. fstatBase(fd, bigint = false) {
  1029. const file = this._core.getFileByFd(fd);
  1030. if (!file)
  1031. throw (0, util_3.createError)("EBADF" /* ERROR_CODE.EBADF */, 'fstat');
  1032. return Stats_1.default.build(file.node, bigint);
  1033. }
  1034. fstatSync(fd, options) {
  1035. return this.fstatBase(fd, (0, options_1.getStatOptions)(options).bigint);
  1036. }
  1037. fstat(fd, a, b) {
  1038. const [opts, callback] = (0, options_1.getStatOptsAndCb)(a, b);
  1039. this.wrapAsync(this.fstatBase, [fd, opts.bigint], callback);
  1040. }
  1041. _exists(filename) {
  1042. const result = this._stat(filename);
  1043. return result.ok ? (0, fs_core_1.Ok)(true) : result;
  1044. }
  1045. _access(filename, mode) {
  1046. const link = this._core.getLinkOrThrow(filename, 'access');
  1047. const node = link.getNode();
  1048. // F_OK (0) just checks for existence, which we already confirmed above
  1049. if (mode === F_OK) {
  1050. return;
  1051. }
  1052. // Check read permission
  1053. if (mode & R_OK && !node.canRead()) {
  1054. throw (0, util_3.createError)("EACCES" /* ERROR_CODE.EACCES */, 'access', filename);
  1055. }
  1056. // Check write permission
  1057. if (mode & W_OK && !node.canWrite()) {
  1058. throw (0, util_3.createError)("EACCES" /* ERROR_CODE.EACCES */, 'access', filename);
  1059. }
  1060. // Check execute permission
  1061. if (mode & X_OK && !node.canExecute()) {
  1062. throw (0, util_3.createError)("EACCES" /* ERROR_CODE.EACCES */, 'access', filename);
  1063. }
  1064. }
  1065. watchFile(path, a, b) {
  1066. const filename = (0, util_3.pathToFilename)(path);
  1067. let options = a;
  1068. let listener = b;
  1069. if (typeof options === 'function') {
  1070. listener = a;
  1071. options = null;
  1072. }
  1073. if (typeof listener !== 'function') {
  1074. throw Error('"watchFile()" requires a listener function');
  1075. }
  1076. let interval = 5007;
  1077. let persistent = true;
  1078. if (options && typeof options === 'object') {
  1079. if (typeof options.interval === 'number')
  1080. interval = options.interval;
  1081. if (typeof options.persistent === 'boolean')
  1082. persistent = options.persistent;
  1083. }
  1084. let watcher = this.statWatchers[filename];
  1085. if (!watcher) {
  1086. watcher = new this.StatWatcher();
  1087. watcher.start(filename, persistent, interval);
  1088. this.statWatchers[filename] = watcher;
  1089. }
  1090. watcher.addListener('change', listener);
  1091. return watcher;
  1092. }
  1093. unwatchFile(path, listener) {
  1094. const filename = (0, util_3.pathToFilename)(path);
  1095. const watcher = this.statWatchers[filename];
  1096. if (!watcher)
  1097. return;
  1098. if (typeof listener === 'function') {
  1099. watcher.removeListener('change', listener);
  1100. }
  1101. else {
  1102. watcher.removeAllListeners('change');
  1103. }
  1104. if (watcher.listenerCount('change') === 0) {
  1105. watcher.stop();
  1106. delete this.statWatchers[filename];
  1107. }
  1108. }
  1109. createReadStream(path, options) {
  1110. return new this.ReadStream(path, options);
  1111. }
  1112. createWriteStream(path, options) {
  1113. return new this.WriteStream(path, options);
  1114. }
  1115. // watch(path: PathLike): FSWatcher;
  1116. // watch(path: PathLike, options?: IWatchOptions | string): FSWatcher;
  1117. watch(path, options, listener) {
  1118. const filename = (0, util_3.pathToFilename)(path);
  1119. let givenOptions = options;
  1120. if (typeof options === 'function') {
  1121. listener = options;
  1122. givenOptions = null;
  1123. }
  1124. // tslint:disable-next-line prefer-const
  1125. let { persistent, recursive, encoding } = (0, options_1.getDefaultOpts)(givenOptions);
  1126. if (persistent === undefined)
  1127. persistent = true;
  1128. if (recursive === undefined)
  1129. recursive = false;
  1130. const watcher = new this.FSWatcher();
  1131. watcher.start(filename, persistent, recursive, encoding);
  1132. if (listener) {
  1133. watcher.addListener('change', listener);
  1134. }
  1135. return watcher;
  1136. }
  1137. _statfs(filename, bigint = false) {
  1138. // Verify the path exists to match Node.js behavior
  1139. this._core.getResolvedLinkOrThrow(filename, 'statfs');
  1140. return StatFs_1.default.build(this._core, bigint);
  1141. }
  1142. statfsSync(path, options) {
  1143. const { bigint = false } = (0, options_1.getStatfsOptions)(options);
  1144. return this._statfs((0, util_3.pathToFilename)(path), bigint);
  1145. }
  1146. statfs(path, a, b) {
  1147. const [{ bigint = false }, callback] = (0, options_1.getStatfsOptsAndCb)(a, b);
  1148. this.wrapAsync(this._statfs, [(0, util_3.pathToFilename)(path), bigint], callback);
  1149. }
  1150. // ---------------------------------------------------------------- Tree View
  1151. toTree(opts = { separator: path_1.sep }) {
  1152. return (0, fs_print_1.toTreeSync)(this, opts);
  1153. }
  1154. // ---------------------------------------------------------------- Snapshots
  1155. toSnapshot(path = '/') {
  1156. return fsSnapshot.toSnapshotSync({ fs: this, path });
  1157. }
  1158. fromSnapshot(snapshot, path = '/') {
  1159. return fsSnapshot.fromSnapshotSync(snapshot, { fs: this, path });
  1160. }
  1161. toBinarySnapshot(path = '/') {
  1162. return fsSnapshot.toBinarySnapshotSync({ fs: this, path });
  1163. }
  1164. fromBinarySnapshot(binary, path = '/') {
  1165. return fsSnapshot.fromBinarySnapshotSync(binary, { fs: this, path });
  1166. }
  1167. toJsonSnapshot(path = '/') {
  1168. const uint8 = fsSnapshot.toJsonSnapshotSync({ fs: this, path });
  1169. return buffer_1.Buffer.from(uint8).toString('utf8');
  1170. }
  1171. fromJsonSnapshot(json, path = '/') {
  1172. const uint8 = new Uint8Array(buffer_1.Buffer.from(json, 'utf8'));
  1173. return fsSnapshot.fromJsonSnapshotSync(uint8, { fs: this, path });
  1174. }
  1175. }
  1176. exports.Volume = Volume;
  1177. Volume.fromJSON = (json, cwd) => new Volume(fs_core_1.Superblock.fromJSON(json, cwd));
  1178. Volume.fromNestedJSON = (json, cwd) => new Volume(fs_core_1.Superblock.fromNestedJSON(json, cwd));
  1179. function emitStop(self) {
  1180. self.emit('stop');
  1181. }
  1182. class StatWatcher extends events_1.EventEmitter {
  1183. constructor(vol) {
  1184. super();
  1185. this.onInterval = () => {
  1186. try {
  1187. const stats = this.vol.statSync(this.filename);
  1188. if (this.hasChanged(stats)) {
  1189. this.emit('change', stats, this.prev);
  1190. this.prev = stats;
  1191. }
  1192. }
  1193. finally {
  1194. this.loop();
  1195. }
  1196. };
  1197. this.vol = vol;
  1198. }
  1199. loop() {
  1200. this.timeoutRef = this.setTimeout(this.onInterval, this.interval);
  1201. }
  1202. hasChanged(stats) {
  1203. // if(!this.prev) return false;
  1204. if (stats.mtimeMs > this.prev.mtimeMs)
  1205. return true;
  1206. if (stats.nlink !== this.prev.nlink)
  1207. return true;
  1208. return false;
  1209. }
  1210. start(path, persistent = true, interval = 5007) {
  1211. this.filename = (0, util_3.pathToFilename)(path);
  1212. this.setTimeout = persistent
  1213. ? setTimeout.bind(typeof globalThis !== 'undefined' ? globalThis : global)
  1214. : setTimeoutUnref_1.default;
  1215. this.interval = interval;
  1216. this.prev = this.vol.statSync(this.filename);
  1217. this.loop();
  1218. }
  1219. stop() {
  1220. clearTimeout(this.timeoutRef);
  1221. queueMicrotask(() => {
  1222. emitStop.call(this, this);
  1223. });
  1224. }
  1225. }
  1226. exports.StatWatcher = StatWatcher;
  1227. /* tslint:disable no-var-keyword prefer-const */
  1228. // ---------------------------------------- ReadStream
  1229. var pool;
  1230. function allocNewPool(poolSize) {
  1231. pool = (0, buffer_1.bufferAllocUnsafe)(poolSize);
  1232. pool.used = 0;
  1233. }
  1234. (0, util_2.inherits)(FsReadStream, stream_1.Readable);
  1235. exports.ReadStream = FsReadStream;
  1236. function FsReadStream(vol, path, options) {
  1237. if (!(this instanceof FsReadStream))
  1238. return new FsReadStream(vol, path, options);
  1239. this._vol = vol;
  1240. // a little bit bigger buffer and water marks by default
  1241. options = Object.assign({}, (0, options_1.getOptions)(options, {}));
  1242. if (options.highWaterMark === undefined)
  1243. options.highWaterMark = 64 * 1024;
  1244. stream_1.Readable.call(this, options);
  1245. this.path = (0, util_3.pathToFilename)(path);
  1246. this.fd = options.fd === undefined ? null : typeof options.fd !== 'number' ? options.fd.fd : options.fd;
  1247. this.flags = options.flags === undefined ? 'r' : options.flags;
  1248. this.mode = options.mode === undefined ? 0o666 : options.mode;
  1249. this.start = options.start;
  1250. this.end = options.end;
  1251. this.autoClose = options.autoClose === undefined ? true : options.autoClose;
  1252. this.pos = undefined;
  1253. this.bytesRead = 0;
  1254. if (this.start !== undefined) {
  1255. if (typeof this.start !== 'number') {
  1256. throw new TypeError('"start" option must be a Number');
  1257. }
  1258. if (this.end === undefined) {
  1259. this.end = Infinity;
  1260. }
  1261. else if (typeof this.end !== 'number') {
  1262. throw new TypeError('"end" option must be a Number');
  1263. }
  1264. if (this.start > this.end) {
  1265. throw new Error('"start" option must be <= "end" option');
  1266. }
  1267. this.pos = this.start;
  1268. }
  1269. if (typeof this.fd !== 'number')
  1270. this.open();
  1271. this.on('end', function () {
  1272. if (this.autoClose) {
  1273. if (this.destroy)
  1274. this.destroy();
  1275. }
  1276. });
  1277. }
  1278. FsReadStream.prototype.open = function () {
  1279. var self = this; // tslint:disable-line no-this-assignment
  1280. this._vol.open(this.path, this.flags, this.mode, (er, fd) => {
  1281. if (er) {
  1282. if (self.autoClose) {
  1283. if (self.destroy)
  1284. self.destroy();
  1285. }
  1286. self.emit('error', er);
  1287. return;
  1288. }
  1289. self.fd = fd;
  1290. self.emit('open', fd);
  1291. // start the flow of data.
  1292. self.read();
  1293. });
  1294. };
  1295. FsReadStream.prototype._read = function (n) {
  1296. if (typeof this.fd !== 'number') {
  1297. return this.once('open', function () {
  1298. this._read(n);
  1299. });
  1300. }
  1301. if (this.destroyed)
  1302. return;
  1303. if (!pool || pool.length - pool.used < kMinPoolSpace) {
  1304. // discard the old pool.
  1305. allocNewPool(this._readableState.highWaterMark);
  1306. }
  1307. // Grab another reference to the pool in the case that while we're
  1308. // in the thread pool another read() finishes up the pool, and
  1309. // allocates a new one.
  1310. var thisPool = pool;
  1311. var toRead = Math.min(pool.length - pool.used, n);
  1312. var start = pool.used;
  1313. if (this.pos !== undefined)
  1314. toRead = Math.min(this.end - this.pos + 1, toRead);
  1315. // already read everything we were supposed to read!
  1316. // treat as EOF.
  1317. if (toRead <= 0)
  1318. return this.push(null);
  1319. // the actual read.
  1320. var self = this; // tslint:disable-line no-this-assignment
  1321. this._vol.read(this.fd, pool, pool.used, toRead, this.pos, onread);
  1322. // move the pool positions, and internal position for reading.
  1323. if (this.pos !== undefined)
  1324. this.pos += toRead;
  1325. pool.used += toRead;
  1326. function onread(er, bytesRead) {
  1327. if (er) {
  1328. if (self.autoClose && self.destroy) {
  1329. self.destroy();
  1330. }
  1331. self.emit('error', er);
  1332. }
  1333. else {
  1334. var b = null;
  1335. if (bytesRead > 0) {
  1336. self.bytesRead += bytesRead;
  1337. b = thisPool.slice(start, start + bytesRead);
  1338. }
  1339. self.push(b);
  1340. }
  1341. }
  1342. };
  1343. FsReadStream.prototype._destroy = function (err, cb) {
  1344. this.close(err2 => {
  1345. cb(err || err2);
  1346. });
  1347. };
  1348. FsReadStream.prototype.close = function (cb) {
  1349. if (cb)
  1350. this.once('close', cb);
  1351. if (this.closed || typeof this.fd !== 'number') {
  1352. if (typeof this.fd !== 'number') {
  1353. this.once('open', closeOnOpen);
  1354. return;
  1355. }
  1356. return queueMicrotask(() => this.emit('close'));
  1357. }
  1358. // Since Node 18, there is only a getter for '.closed'.
  1359. // The first branch mimics other setters from Readable.
  1360. // See https://github.com/nodejs/node/blob/v18.0.0/lib/internal/streams/readable.js#L1243
  1361. if (typeof this._readableState?.closed === 'boolean') {
  1362. this._readableState.closed = true;
  1363. }
  1364. else {
  1365. this.closed = true;
  1366. }
  1367. this._vol.close(this.fd, er => {
  1368. if (er)
  1369. this.emit('error', er);
  1370. else
  1371. this.emit('close');
  1372. });
  1373. this.fd = null;
  1374. };
  1375. // needed because as it will be called with arguments
  1376. // that does not match this.close() signature
  1377. function closeOnOpen(fd) {
  1378. this.close();
  1379. }
  1380. (0, util_2.inherits)(FsWriteStream, stream_1.Writable);
  1381. exports.WriteStream = FsWriteStream;
  1382. function FsWriteStream(vol, path, options) {
  1383. if (!(this instanceof FsWriteStream))
  1384. return new FsWriteStream(vol, path, options);
  1385. this._vol = vol;
  1386. options = Object.assign({}, (0, options_1.getOptions)(options, {}));
  1387. stream_1.Writable.call(this, options);
  1388. this.path = (0, util_3.pathToFilename)(path);
  1389. this.fd = options.fd === undefined ? null : typeof options.fd !== 'number' ? options.fd.fd : options.fd;
  1390. this.flags = options.flags === undefined ? 'w' : options.flags;
  1391. this.mode = options.mode === undefined ? 0o666 : options.mode;
  1392. this.start = options.start;
  1393. this.autoClose = options.autoClose === undefined ? true : !!options.autoClose;
  1394. this.pos = undefined;
  1395. this.bytesWritten = 0;
  1396. this.pending = true;
  1397. if (this.start !== undefined) {
  1398. if (typeof this.start !== 'number') {
  1399. throw new TypeError('"start" option must be a Number');
  1400. }
  1401. if (this.start < 0) {
  1402. throw new Error('"start" must be >= zero');
  1403. }
  1404. this.pos = this.start;
  1405. }
  1406. if (options.encoding)
  1407. this.setDefaultEncoding(options.encoding);
  1408. if (typeof this.fd !== 'number')
  1409. this.open();
  1410. // dispose on finish.
  1411. this.once('finish', function () {
  1412. if (this.autoClose) {
  1413. this.close();
  1414. }
  1415. });
  1416. }
  1417. FsWriteStream.prototype.open = function () {
  1418. this._vol.open(this.path, this.flags, this.mode, function (er, fd) {
  1419. if (er) {
  1420. if (this.autoClose && this.destroy) {
  1421. this.destroy();
  1422. }
  1423. this.emit('error', er);
  1424. return;
  1425. }
  1426. this.fd = fd;
  1427. this.pending = false;
  1428. this.emit('open', fd);
  1429. }.bind(this));
  1430. };
  1431. FsWriteStream.prototype._write = function (data, encoding, cb) {
  1432. if (!(data instanceof buffer_1.Buffer || data instanceof Uint8Array))
  1433. return this.emit('error', new Error('Invalid data'));
  1434. if (typeof this.fd !== 'number') {
  1435. return this.once('open', function () {
  1436. this._write(data, encoding, cb);
  1437. });
  1438. }
  1439. var self = this; // tslint:disable-line no-this-assignment
  1440. this._vol.write(this.fd, data, 0, data.length, this.pos, (er, bytes) => {
  1441. if (er) {
  1442. if (self.autoClose && self.destroy) {
  1443. self.destroy();
  1444. }
  1445. return cb(er);
  1446. }
  1447. self.bytesWritten += bytes;
  1448. cb();
  1449. });
  1450. if (this.pos !== undefined)
  1451. this.pos += data.length;
  1452. };
  1453. FsWriteStream.prototype._writev = function (data, cb) {
  1454. if (typeof this.fd !== 'number') {
  1455. return this.once('open', function () {
  1456. this._writev(data, cb);
  1457. });
  1458. }
  1459. const self = this; // tslint:disable-line no-this-assignment
  1460. const len = data.length;
  1461. const chunks = new Array(len);
  1462. var size = 0;
  1463. for (var i = 0; i < len; i++) {
  1464. var chunk = data[i].chunk;
  1465. chunks[i] = chunk;
  1466. size += chunk.length;
  1467. }
  1468. const buf = buffer_1.Buffer.concat(chunks);
  1469. this._vol.write(this.fd, buf, 0, buf.length, this.pos, (er, bytes) => {
  1470. if (er) {
  1471. if (self.destroy)
  1472. self.destroy();
  1473. return cb(er);
  1474. }
  1475. self.bytesWritten += bytes;
  1476. cb();
  1477. });
  1478. if (this.pos !== undefined)
  1479. this.pos += size;
  1480. };
  1481. FsWriteStream.prototype.close = function (cb) {
  1482. if (cb)
  1483. this.once('close', cb);
  1484. if (this.closed || typeof this.fd !== 'number') {
  1485. if (typeof this.fd !== 'number') {
  1486. this.once('open', closeOnOpen);
  1487. return;
  1488. }
  1489. return queueMicrotask(() => this.emit('close'));
  1490. }
  1491. // Since Node 18, there is only a getter for '.closed'.
  1492. // The first branch mimics other setters from Writable.
  1493. // See https://github.com/nodejs/node/blob/v18.0.0/lib/internal/streams/writable.js#L766
  1494. if (typeof this._writableState?.closed === 'boolean') {
  1495. this._writableState.closed = true;
  1496. }
  1497. else {
  1498. this.closed = true;
  1499. }
  1500. this._vol.close(this.fd, er => {
  1501. if (er)
  1502. this.emit('error', er);
  1503. else
  1504. this.emit('close');
  1505. });
  1506. this.fd = null;
  1507. };
  1508. FsWriteStream.prototype._destroy = FsReadStream.prototype._destroy;
  1509. // There is no shutdown() for files.
  1510. FsWriteStream.prototype.destroySoon = FsWriteStream.prototype.end;
  1511. // ---------------------------------------- FSWatcher
  1512. class FSWatcher extends events_1.EventEmitter {
  1513. constructor(vol) {
  1514. super();
  1515. this._filename = '';
  1516. this._filenameEncoded = '';
  1517. // _persistent: boolean = true;
  1518. this._recursive = false;
  1519. this._encoding = fs_node_utils_1.ENCODING_UTF8;
  1520. // inode -> removers
  1521. this._listenerRemovers = new Map();
  1522. this._onParentChild = (link) => {
  1523. if (link.getName() === this._getName()) {
  1524. this._emit('rename');
  1525. }
  1526. };
  1527. this._emit = (type) => {
  1528. this.emit('change', type, this._filenameEncoded);
  1529. };
  1530. this._persist = () => {
  1531. this._timer = setTimeout(this._persist, 1e6);
  1532. };
  1533. this._vol = vol;
  1534. // TODO: Emit "error" messages when watching.
  1535. // this._handle.onchange = function(status, eventType, filename) {
  1536. // if (status < 0) {
  1537. // self._handle.close();
  1538. // const error = !filename ?
  1539. // errnoException(status, 'Error watching file for changes:') :
  1540. // errnoException(status, `Error watching file ${filename} for changes:`);
  1541. // error.filename = filename;
  1542. // self.emit('error', error);
  1543. // } else {
  1544. // self.emit('change', eventType, filename);
  1545. // }
  1546. // };
  1547. }
  1548. _getName() {
  1549. return this._steps[this._steps.length - 1];
  1550. }
  1551. start(path, persistent = true, recursive = false, encoding = fs_node_utils_1.ENCODING_UTF8) {
  1552. this._filename = (0, util_3.pathToFilename)(path);
  1553. this._steps = (0, fs_core_1.filenameToSteps)(this._filename);
  1554. this._filenameEncoded = (0, fs_node_utils_1.strToEncoding)(this._filename);
  1555. // this._persistent = persistent;
  1556. this._recursive = recursive;
  1557. this._encoding = encoding;
  1558. try {
  1559. this._link = this._vol._core.getLinkOrThrow(this._filename, 'FSWatcher');
  1560. }
  1561. catch (err) {
  1562. const error = new Error(`watch ${this._filename} ${err.code}`);
  1563. error.code = err.code;
  1564. error.errno = err.code;
  1565. throw error;
  1566. }
  1567. const watchLinkNodeChanged = (link) => {
  1568. const filepath = link.getPath();
  1569. const node = link.getNode();
  1570. const onNodeChange = () => {
  1571. let filename = pathRelative(this._filename, filepath);
  1572. if (!filename)
  1573. filename = this._getName();
  1574. return this.emit('change', 'change', filename);
  1575. };
  1576. const unsub = node.changes.listen(([type]) => {
  1577. if (type === 'modify')
  1578. onNodeChange();
  1579. });
  1580. const removers = this._listenerRemovers.get(node.ino) ?? [];
  1581. removers.push(() => unsub());
  1582. this._listenerRemovers.set(node.ino, removers);
  1583. };
  1584. const watchLinkChildrenChanged = (link) => {
  1585. const node = link.getNode();
  1586. // when a new link added
  1587. const onLinkChildAdd = (l) => {
  1588. this.emit('change', 'rename', pathRelative(this._filename, l.getPath()));
  1589. // 1. watch changes of the new link-node
  1590. watchLinkNodeChanged(l);
  1591. // 2. watch changes of the new link-node's children
  1592. watchLinkChildrenChanged(l);
  1593. };
  1594. // when a new link deleted
  1595. const onLinkChildDelete = (l) => {
  1596. // remove the listeners of the children nodes
  1597. const removeLinkNodeListeners = (curLink) => {
  1598. const ino = curLink.getNode().ino;
  1599. const removers = this._listenerRemovers.get(ino);
  1600. if (removers) {
  1601. removers.forEach(r => r());
  1602. this._listenerRemovers.delete(ino);
  1603. }
  1604. for (const [name, childLink] of curLink.children.entries()) {
  1605. if (childLink && name !== '.' && name !== '..') {
  1606. removeLinkNodeListeners(childLink);
  1607. }
  1608. }
  1609. };
  1610. removeLinkNodeListeners(l);
  1611. this.emit('change', 'rename', pathRelative(this._filename, l.getPath()));
  1612. };
  1613. // children nodes changed
  1614. for (const [name, childLink] of link.children.entries()) {
  1615. if (childLink && name !== '.' && name !== '..') {
  1616. watchLinkNodeChanged(childLink);
  1617. }
  1618. }
  1619. // link children add/remove
  1620. const unsubscribeLinkChanges = link.changes.listen(([type, link]) => {
  1621. if (type === 'child:add')
  1622. onLinkChildAdd(link);
  1623. else if (type === 'child:del')
  1624. onLinkChildDelete(link);
  1625. });
  1626. const removers = this._listenerRemovers.get(node.ino) ?? [];
  1627. removers.push(() => {
  1628. unsubscribeLinkChanges();
  1629. });
  1630. if (recursive) {
  1631. for (const [name, childLink] of link.children.entries()) {
  1632. if (childLink && name !== '.' && name !== '..') {
  1633. watchLinkChildrenChanged(childLink);
  1634. }
  1635. }
  1636. }
  1637. };
  1638. watchLinkNodeChanged(this._link);
  1639. watchLinkChildrenChanged(this._link);
  1640. const parent = this._link.parent;
  1641. if (parent) {
  1642. // parent.on('child:delete', this._onParentChild);
  1643. parent.changes.listen(([type, link]) => {
  1644. if (type === 'child:del')
  1645. this._onParentChild(link);
  1646. });
  1647. }
  1648. if (persistent)
  1649. this._persist();
  1650. }
  1651. close() {
  1652. clearTimeout(this._timer);
  1653. this._listenerRemovers.forEach(removers => {
  1654. removers.forEach(r => r());
  1655. });
  1656. this._listenerRemovers.clear();
  1657. this._parentChangesUnsub?.();
  1658. }
  1659. }
  1660. exports.FSWatcher = FSWatcher;
  1661. //# sourceMappingURL=volume.js.map