volume.js 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375
  1. "use strict";
  2. var __extends = (this && this.__extends) || (function () {
  3. var extendStatics = function (d, b) {
  4. extendStatics = Object.setPrototypeOf ||
  5. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  6. function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
  7. return extendStatics(d, b);
  8. };
  9. return function (d, b) {
  10. if (typeof b !== "function" && b !== null)
  11. throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
  18. if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
  19. if (ar || !(i in from)) {
  20. if (!ar) ar = Array.prototype.slice.call(from, 0, i);
  21. ar[i] = from[i];
  22. }
  23. }
  24. return to.concat(ar || Array.prototype.slice.call(from));
  25. };
  26. Object.defineProperty(exports, "__esModule", { value: true });
  27. exports.FSWatcher = exports.StatWatcher = exports.Volume = exports.toUnixTimestamp = exports.bufferToEncoding = exports.dataToBuffer = exports.dataToStr = exports.pathToSteps = exports.filenameToSteps = exports.pathToFilename = exports.flagsToNumber = exports.FLAGS = void 0;
  28. var pathModule = require("path");
  29. var node_1 = require("./node");
  30. var Stats_1 = require("./Stats");
  31. var Dirent_1 = require("./Dirent");
  32. var buffer_1 = require("./internal/buffer");
  33. var setImmediate_1 = require("./setImmediate");
  34. var process_1 = require("./process");
  35. var setTimeoutUnref_1 = require("./setTimeoutUnref");
  36. var stream_1 = require("stream");
  37. var constants_1 = require("./constants");
  38. var events_1 = require("events");
  39. var encoding_1 = require("./encoding");
  40. var errors = require("./internal/errors");
  41. var util = require("util");
  42. var promises_1 = require("./promises");
  43. var resolveCrossPlatform = pathModule.resolve;
  44. var O_RDONLY = constants_1.constants.O_RDONLY, O_WRONLY = constants_1.constants.O_WRONLY, O_RDWR = constants_1.constants.O_RDWR, O_CREAT = constants_1.constants.O_CREAT, O_EXCL = constants_1.constants.O_EXCL, O_TRUNC = constants_1.constants.O_TRUNC, O_APPEND = constants_1.constants.O_APPEND, O_SYNC = constants_1.constants.O_SYNC, O_DIRECTORY = constants_1.constants.O_DIRECTORY, F_OK = constants_1.constants.F_OK, COPYFILE_EXCL = constants_1.constants.COPYFILE_EXCL, COPYFILE_FICLONE_FORCE = constants_1.constants.COPYFILE_FICLONE_FORCE;
  45. var _a = pathModule.posix ? pathModule.posix : pathModule, sep = _a.sep, relative = _a.relative, join = _a.join, dirname = _a.dirname;
  46. var isWin = process_1.default.platform === 'win32';
  47. var kMinPoolSpace = 128;
  48. // const kMaxLength = require('buffer').kMaxLength;
  49. // ---------------------------------------- Error messages
  50. // TODO: Use `internal/errors.js` in the future.
  51. var ERRSTR = {
  52. PATH_STR: 'path must be a string or Buffer',
  53. // FD: 'file descriptor must be a unsigned 32-bit integer',
  54. FD: 'fd must be a file descriptor',
  55. MODE_INT: 'mode must be an int',
  56. CB: 'callback must be a function',
  57. UID: 'uid must be an unsigned int',
  58. GID: 'gid must be an unsigned int',
  59. LEN: 'len must be an integer',
  60. ATIME: 'atime must be an integer',
  61. MTIME: 'mtime must be an integer',
  62. PREFIX: 'filename prefix is required',
  63. BUFFER: 'buffer must be an instance of Buffer or StaticBuffer',
  64. OFFSET: 'offset must be an integer',
  65. LENGTH: 'length must be an integer',
  66. POSITION: 'position must be an integer',
  67. };
  68. var ERRSTR_OPTS = function (tipeof) { return "Expected options to be either an object or a string, but got ".concat(tipeof, " instead"); };
  69. // const ERRSTR_FLAG = flag => `Unknown file open flag: ${flag}`;
  70. var ENOENT = 'ENOENT';
  71. var EBADF = 'EBADF';
  72. var EINVAL = 'EINVAL';
  73. var EPERM = 'EPERM';
  74. var EPROTO = 'EPROTO';
  75. var EEXIST = 'EEXIST';
  76. var ENOTDIR = 'ENOTDIR';
  77. var EMFILE = 'EMFILE';
  78. var EACCES = 'EACCES';
  79. var EISDIR = 'EISDIR';
  80. var ENOTEMPTY = 'ENOTEMPTY';
  81. var ENOSYS = 'ENOSYS';
  82. var ERR_FS_EISDIR = 'ERR_FS_EISDIR';
  83. function formatError(errorCode, func, path, path2) {
  84. if (func === void 0) { func = ''; }
  85. if (path === void 0) { path = ''; }
  86. if (path2 === void 0) { path2 = ''; }
  87. var pathFormatted = '';
  88. if (path)
  89. pathFormatted = " '".concat(path, "'");
  90. if (path2)
  91. pathFormatted += " -> '".concat(path2, "'");
  92. switch (errorCode) {
  93. case ENOENT:
  94. return "ENOENT: no such file or directory, ".concat(func).concat(pathFormatted);
  95. case EBADF:
  96. return "EBADF: bad file descriptor, ".concat(func).concat(pathFormatted);
  97. case EINVAL:
  98. return "EINVAL: invalid argument, ".concat(func).concat(pathFormatted);
  99. case EPERM:
  100. return "EPERM: operation not permitted, ".concat(func).concat(pathFormatted);
  101. case EPROTO:
  102. return "EPROTO: protocol error, ".concat(func).concat(pathFormatted);
  103. case EEXIST:
  104. return "EEXIST: file already exists, ".concat(func).concat(pathFormatted);
  105. case ENOTDIR:
  106. return "ENOTDIR: not a directory, ".concat(func).concat(pathFormatted);
  107. case EISDIR:
  108. return "EISDIR: illegal operation on a directory, ".concat(func).concat(pathFormatted);
  109. case EACCES:
  110. return "EACCES: permission denied, ".concat(func).concat(pathFormatted);
  111. case ENOTEMPTY:
  112. return "ENOTEMPTY: directory not empty, ".concat(func).concat(pathFormatted);
  113. case EMFILE:
  114. return "EMFILE: too many open files, ".concat(func).concat(pathFormatted);
  115. case ENOSYS:
  116. return "ENOSYS: function not implemented, ".concat(func).concat(pathFormatted);
  117. case ERR_FS_EISDIR:
  118. return "[ERR_FS_EISDIR]: Path is a directory: ".concat(func, " returned EISDIR (is a directory) ").concat(path);
  119. default:
  120. return "".concat(errorCode, ": error occurred, ").concat(func).concat(pathFormatted);
  121. }
  122. }
  123. function createError(errorCode, func, path, path2, Constructor) {
  124. if (func === void 0) { func = ''; }
  125. if (path === void 0) { path = ''; }
  126. if (path2 === void 0) { path2 = ''; }
  127. if (Constructor === void 0) { Constructor = Error; }
  128. var error = new Constructor(formatError(errorCode, func, path, path2));
  129. error.code = errorCode;
  130. if (path) {
  131. error.path = path;
  132. }
  133. return error;
  134. }
  135. // ---------------------------------------- Flags
  136. // List of file `flags` as defined by Node.
  137. var FLAGS;
  138. (function (FLAGS) {
  139. // Open file for reading. An exception occurs if the file does not exist.
  140. FLAGS[FLAGS["r"] = O_RDONLY] = "r";
  141. // Open file for reading and writing. An exception occurs if the file does not exist.
  142. FLAGS[FLAGS["r+"] = O_RDWR] = "r+";
  143. // Open file for reading in synchronous mode. Instructs the operating system to bypass the local file system cache.
  144. FLAGS[FLAGS["rs"] = O_RDONLY | O_SYNC] = "rs";
  145. FLAGS[FLAGS["sr"] = FLAGS.rs] = "sr";
  146. // Open file for reading and writing, telling the OS to open it synchronously. See notes for 'rs' about using this with caution.
  147. FLAGS[FLAGS["rs+"] = O_RDWR | O_SYNC] = "rs+";
  148. FLAGS[FLAGS["sr+"] = FLAGS['rs+']] = "sr+";
  149. // Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
  150. FLAGS[FLAGS["w"] = O_WRONLY | O_CREAT | O_TRUNC] = "w";
  151. // Like 'w' but fails if path exists.
  152. FLAGS[FLAGS["wx"] = O_WRONLY | O_CREAT | O_TRUNC | O_EXCL] = "wx";
  153. FLAGS[FLAGS["xw"] = FLAGS.wx] = "xw";
  154. // Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
  155. FLAGS[FLAGS["w+"] = O_RDWR | O_CREAT | O_TRUNC] = "w+";
  156. // Like 'w+' but fails if path exists.
  157. FLAGS[FLAGS["wx+"] = O_RDWR | O_CREAT | O_TRUNC | O_EXCL] = "wx+";
  158. FLAGS[FLAGS["xw+"] = FLAGS['wx+']] = "xw+";
  159. // Open file for appending. The file is created if it does not exist.
  160. FLAGS[FLAGS["a"] = O_WRONLY | O_APPEND | O_CREAT] = "a";
  161. // Like 'a' but fails if path exists.
  162. FLAGS[FLAGS["ax"] = O_WRONLY | O_APPEND | O_CREAT | O_EXCL] = "ax";
  163. FLAGS[FLAGS["xa"] = FLAGS.ax] = "xa";
  164. // Open file for reading and appending. The file is created if it does not exist.
  165. FLAGS[FLAGS["a+"] = O_RDWR | O_APPEND | O_CREAT] = "a+";
  166. // Like 'a+' but fails if path exists.
  167. FLAGS[FLAGS["ax+"] = O_RDWR | O_APPEND | O_CREAT | O_EXCL] = "ax+";
  168. FLAGS[FLAGS["xa+"] = FLAGS['ax+']] = "xa+";
  169. })(FLAGS = exports.FLAGS || (exports.FLAGS = {}));
  170. function flagsToNumber(flags) {
  171. if (typeof flags === 'number')
  172. return flags;
  173. if (typeof flags === 'string') {
  174. var flagsNum = FLAGS[flags];
  175. if (typeof flagsNum !== 'undefined')
  176. return flagsNum;
  177. }
  178. // throw new TypeError(formatError(ERRSTR_FLAG(flags)));
  179. throw new errors.TypeError('ERR_INVALID_OPT_VALUE', 'flags', flags);
  180. }
  181. exports.flagsToNumber = flagsToNumber;
  182. // ---------------------------------------- Options
  183. function getOptions(defaults, options) {
  184. var opts;
  185. if (!options)
  186. return defaults;
  187. else {
  188. var tipeof = typeof options;
  189. switch (tipeof) {
  190. case 'string':
  191. opts = Object.assign({}, defaults, { encoding: options });
  192. break;
  193. case 'object':
  194. opts = Object.assign({}, defaults, options);
  195. break;
  196. default:
  197. throw TypeError(ERRSTR_OPTS(tipeof));
  198. }
  199. }
  200. if (opts.encoding !== 'buffer')
  201. (0, encoding_1.assertEncoding)(opts.encoding);
  202. return opts;
  203. }
  204. function optsGenerator(defaults) {
  205. return function (options) { return getOptions(defaults, options); };
  206. }
  207. function validateCallback(callback) {
  208. if (typeof callback !== 'function')
  209. throw TypeError(ERRSTR.CB);
  210. return callback;
  211. }
  212. function optsAndCbGenerator(getOpts) {
  213. return function (options, callback) {
  214. return typeof options === 'function' ? [getOpts(), options] : [getOpts(options), validateCallback(callback)];
  215. };
  216. }
  217. var optsDefaults = {
  218. encoding: 'utf8',
  219. };
  220. var getDefaultOpts = optsGenerator(optsDefaults);
  221. var getDefaultOptsAndCb = optsAndCbGenerator(getDefaultOpts);
  222. var readFileOptsDefaults = {
  223. flag: 'r',
  224. };
  225. var getReadFileOptions = optsGenerator(readFileOptsDefaults);
  226. var writeFileDefaults = {
  227. encoding: 'utf8',
  228. mode: 438 /* MODE.DEFAULT */,
  229. flag: FLAGS[FLAGS.w],
  230. };
  231. var getWriteFileOptions = optsGenerator(writeFileDefaults);
  232. var appendFileDefaults = {
  233. encoding: 'utf8',
  234. mode: 438 /* MODE.DEFAULT */,
  235. flag: FLAGS[FLAGS.a],
  236. };
  237. var getAppendFileOpts = optsGenerator(appendFileDefaults);
  238. var getAppendFileOptsAndCb = optsAndCbGenerator(getAppendFileOpts);
  239. var realpathDefaults = optsDefaults;
  240. var getRealpathOptions = optsGenerator(realpathDefaults);
  241. var getRealpathOptsAndCb = optsAndCbGenerator(getRealpathOptions);
  242. var mkdirDefaults = {
  243. mode: 511 /* MODE.DIR */,
  244. recursive: false,
  245. };
  246. var getMkdirOptions = function (options) {
  247. if (typeof options === 'number')
  248. return Object.assign({}, mkdirDefaults, { mode: options });
  249. return Object.assign({}, mkdirDefaults, options);
  250. };
  251. var rmdirDefaults = {
  252. recursive: false,
  253. };
  254. var getRmdirOptions = function (options) {
  255. return Object.assign({}, rmdirDefaults, options);
  256. };
  257. var getRmOpts = optsGenerator(optsDefaults);
  258. var getRmOptsAndCb = optsAndCbGenerator(getRmOpts);
  259. var readdirDefaults = {
  260. encoding: 'utf8',
  261. withFileTypes: false,
  262. };
  263. var getReaddirOptions = optsGenerator(readdirDefaults);
  264. var getReaddirOptsAndCb = optsAndCbGenerator(getReaddirOptions);
  265. var statDefaults = {
  266. bigint: false,
  267. };
  268. var getStatOptions = function (options) {
  269. if (options === void 0) { options = {}; }
  270. return Object.assign({}, statDefaults, options);
  271. };
  272. var getStatOptsAndCb = function (options, callback) {
  273. return typeof options === 'function' ? [getStatOptions(), options] : [getStatOptions(options), validateCallback(callback)];
  274. };
  275. // ---------------------------------------- Utility functions
  276. function getPathFromURLPosix(url) {
  277. if (url.hostname !== '') {
  278. throw new errors.TypeError('ERR_INVALID_FILE_URL_HOST', process_1.default.platform);
  279. }
  280. var pathname = url.pathname;
  281. for (var n = 0; n < pathname.length; n++) {
  282. if (pathname[n] === '%') {
  283. var third = pathname.codePointAt(n + 2) | 0x20;
  284. if (pathname[n + 1] === '2' && third === 102) {
  285. throw new errors.TypeError('ERR_INVALID_FILE_URL_PATH', 'must not include encoded / characters');
  286. }
  287. }
  288. }
  289. return decodeURIComponent(pathname);
  290. }
  291. function pathToFilename(path) {
  292. if (typeof path !== 'string' && !buffer_1.Buffer.isBuffer(path)) {
  293. try {
  294. if (!(path instanceof require('url').URL))
  295. throw new TypeError(ERRSTR.PATH_STR);
  296. }
  297. catch (err) {
  298. throw new TypeError(ERRSTR.PATH_STR);
  299. }
  300. path = getPathFromURLPosix(path);
  301. }
  302. var pathString = String(path);
  303. nullCheck(pathString);
  304. // return slash(pathString);
  305. return pathString;
  306. }
  307. exports.pathToFilename = pathToFilename;
  308. var resolve = function (filename, base) {
  309. if (base === void 0) { base = process_1.default.cwd(); }
  310. return resolveCrossPlatform(base, filename);
  311. };
  312. if (isWin) {
  313. var _resolve_1 = resolve;
  314. var unixify_1 = require('fs-monkey/lib/correctPath').unixify;
  315. resolve = function (filename, base) { return unixify_1(_resolve_1(filename, base)); };
  316. }
  317. function filenameToSteps(filename, base) {
  318. var fullPath = resolve(filename, base);
  319. var fullPathSansSlash = fullPath.substring(1);
  320. if (!fullPathSansSlash)
  321. return [];
  322. return fullPathSansSlash.split(sep);
  323. }
  324. exports.filenameToSteps = filenameToSteps;
  325. function pathToSteps(path) {
  326. return filenameToSteps(pathToFilename(path));
  327. }
  328. exports.pathToSteps = pathToSteps;
  329. function dataToStr(data, encoding) {
  330. if (encoding === void 0) { encoding = encoding_1.ENCODING_UTF8; }
  331. if (buffer_1.Buffer.isBuffer(data))
  332. return data.toString(encoding);
  333. else if (data instanceof Uint8Array)
  334. return (0, buffer_1.bufferFrom)(data).toString(encoding);
  335. else
  336. return String(data);
  337. }
  338. exports.dataToStr = dataToStr;
  339. function dataToBuffer(data, encoding) {
  340. if (encoding === void 0) { encoding = encoding_1.ENCODING_UTF8; }
  341. if (buffer_1.Buffer.isBuffer(data))
  342. return data;
  343. else if (data instanceof Uint8Array)
  344. return (0, buffer_1.bufferFrom)(data);
  345. else
  346. return (0, buffer_1.bufferFrom)(String(data), encoding);
  347. }
  348. exports.dataToBuffer = dataToBuffer;
  349. function bufferToEncoding(buffer, encoding) {
  350. if (!encoding || encoding === 'buffer')
  351. return buffer;
  352. else
  353. return buffer.toString(encoding);
  354. }
  355. exports.bufferToEncoding = bufferToEncoding;
  356. function nullCheck(path, callback) {
  357. if (('' + path).indexOf('\u0000') !== -1) {
  358. var er = new Error('Path must be a string without null bytes');
  359. er.code = ENOENT;
  360. if (typeof callback !== 'function')
  361. throw er;
  362. process_1.default.nextTick(callback, er);
  363. return false;
  364. }
  365. return true;
  366. }
  367. function _modeToNumber(mode, def) {
  368. if (typeof mode === 'number')
  369. return mode;
  370. if (typeof mode === 'string')
  371. return parseInt(mode, 8);
  372. if (def)
  373. return modeToNumber(def);
  374. return undefined;
  375. }
  376. function modeToNumber(mode, def) {
  377. var result = _modeToNumber(mode, def);
  378. if (typeof result !== 'number' || isNaN(result))
  379. throw new TypeError(ERRSTR.MODE_INT);
  380. return result;
  381. }
  382. function isFd(path) {
  383. return path >>> 0 === path;
  384. }
  385. function validateFd(fd) {
  386. if (!isFd(fd))
  387. throw TypeError(ERRSTR.FD);
  388. }
  389. // converts Date or number to a fractional UNIX timestamp
  390. function toUnixTimestamp(time) {
  391. // tslint:disable-next-line triple-equals
  392. if (typeof time === 'string' && +time == time) {
  393. return +time;
  394. }
  395. if (time instanceof Date) {
  396. return time.getTime() / 1000;
  397. }
  398. if (isFinite(time)) {
  399. if (time < 0) {
  400. return Date.now() / 1000;
  401. }
  402. return time;
  403. }
  404. throw new Error('Cannot parse time: ' + time);
  405. }
  406. exports.toUnixTimestamp = toUnixTimestamp;
  407. function validateUid(uid) {
  408. if (typeof uid !== 'number')
  409. throw TypeError(ERRSTR.UID);
  410. }
  411. function validateGid(gid) {
  412. if (typeof gid !== 'number')
  413. throw TypeError(ERRSTR.GID);
  414. }
  415. function flattenJSON(nestedJSON) {
  416. var flatJSON = {};
  417. function flatten(pathPrefix, node) {
  418. for (var path in node) {
  419. var contentOrNode = node[path];
  420. var joinedPath = join(pathPrefix, path);
  421. if (typeof contentOrNode === 'string') {
  422. flatJSON[joinedPath] = contentOrNode;
  423. }
  424. else if (typeof contentOrNode === 'object' && contentOrNode !== null && Object.keys(contentOrNode).length > 0) {
  425. // empty directories need an explicit entry and therefore get handled in `else`, non-empty ones are implicitly considered
  426. flatten(joinedPath, contentOrNode);
  427. }
  428. else {
  429. // without this branch null, empty-object or non-object entries would not be handled in the same way
  430. // by both fromJSON() and fromNestedJSON()
  431. flatJSON[joinedPath] = null;
  432. }
  433. }
  434. }
  435. flatten('', nestedJSON);
  436. return flatJSON;
  437. }
  438. /**
  439. * `Volume` represents a file system.
  440. */
  441. var Volume = /** @class */ (function () {
  442. function Volume(props) {
  443. if (props === void 0) { props = {}; }
  444. // I-node number counter.
  445. this.ino = 0;
  446. // A mapping for i-node numbers to i-nodes (`Node`);
  447. this.inodes = {};
  448. // List of released i-node numbers, for reuse.
  449. this.releasedInos = [];
  450. // A mapping for file descriptors to `File`s.
  451. this.fds = {};
  452. // A list of reusable (opened and closed) file descriptors, that should be
  453. // used first before creating a new file descriptor.
  454. this.releasedFds = [];
  455. // Max number of open files.
  456. this.maxFiles = 10000;
  457. // Current number of open files.
  458. this.openFiles = 0;
  459. this.promisesApi = (0, promises_1.default)(this);
  460. this.statWatchers = {};
  461. this.props = Object.assign({ Node: node_1.Node, Link: node_1.Link, File: node_1.File }, props);
  462. var root = this.createLink();
  463. root.setNode(this.createNode(true));
  464. var self = this; // tslint:disable-line no-this-assignment
  465. this.StatWatcher = /** @class */ (function (_super) {
  466. __extends(StatWatcher, _super);
  467. function StatWatcher() {
  468. return _super.call(this, self) || this;
  469. }
  470. return StatWatcher;
  471. }(StatWatcher));
  472. var _ReadStream = FsReadStream;
  473. this.ReadStream = /** @class */ (function (_super) {
  474. __extends(class_1, _super);
  475. function class_1() {
  476. var args = [];
  477. for (var _i = 0; _i < arguments.length; _i++) {
  478. args[_i] = arguments[_i];
  479. }
  480. return _super.apply(this, __spreadArray([self], args, false)) || this;
  481. }
  482. return class_1;
  483. }(_ReadStream));
  484. var _WriteStream = FsWriteStream;
  485. this.WriteStream = /** @class */ (function (_super) {
  486. __extends(class_2, _super);
  487. function class_2() {
  488. var args = [];
  489. for (var _i = 0; _i < arguments.length; _i++) {
  490. args[_i] = arguments[_i];
  491. }
  492. return _super.apply(this, __spreadArray([self], args, false)) || this;
  493. }
  494. return class_2;
  495. }(_WriteStream));
  496. this.FSWatcher = /** @class */ (function (_super) {
  497. __extends(FSWatcher, _super);
  498. function FSWatcher() {
  499. return _super.call(this, self) || this;
  500. }
  501. return FSWatcher;
  502. }(FSWatcher));
  503. root.setChild('.', root);
  504. root.getNode().nlink++;
  505. root.setChild('..', root);
  506. root.getNode().nlink++;
  507. this.root = root;
  508. }
  509. Volume.fromJSON = function (json, cwd) {
  510. var vol = new Volume();
  511. vol.fromJSON(json, cwd);
  512. return vol;
  513. };
  514. Volume.fromNestedJSON = function (json, cwd) {
  515. var vol = new Volume();
  516. vol.fromNestedJSON(json, cwd);
  517. return vol;
  518. };
  519. Object.defineProperty(Volume.prototype, "promises", {
  520. get: function () {
  521. if (this.promisesApi === null)
  522. throw new Error('Promise is not supported in this environment.');
  523. return this.promisesApi;
  524. },
  525. enumerable: false,
  526. configurable: true
  527. });
  528. Volume.prototype.createLink = function (parent, name, isDirectory, perm) {
  529. if (isDirectory === void 0) { isDirectory = false; }
  530. if (!parent) {
  531. return new this.props.Link(this, null, '');
  532. }
  533. if (!name) {
  534. throw new Error('createLink: name cannot be empty');
  535. }
  536. return parent.createChild(name, this.createNode(isDirectory, perm));
  537. };
  538. Volume.prototype.deleteLink = function (link) {
  539. var parent = link.parent;
  540. if (parent) {
  541. parent.deleteChild(link);
  542. return true;
  543. }
  544. return false;
  545. };
  546. Volume.prototype.newInoNumber = function () {
  547. var releasedFd = this.releasedInos.pop();
  548. if (releasedFd)
  549. return releasedFd;
  550. else {
  551. this.ino = (this.ino + 1) % 0xffffffff;
  552. return this.ino;
  553. }
  554. };
  555. Volume.prototype.newFdNumber = function () {
  556. var releasedFd = this.releasedFds.pop();
  557. return typeof releasedFd === 'number' ? releasedFd : Volume.fd--;
  558. };
  559. Volume.prototype.createNode = function (isDirectory, perm) {
  560. if (isDirectory === void 0) { isDirectory = false; }
  561. var node = new this.props.Node(this.newInoNumber(), perm);
  562. if (isDirectory)
  563. node.setIsDirectory();
  564. this.inodes[node.ino] = node;
  565. return node;
  566. };
  567. Volume.prototype.getNode = function (ino) {
  568. return this.inodes[ino];
  569. };
  570. Volume.prototype.deleteNode = function (node) {
  571. node.del();
  572. delete this.inodes[node.ino];
  573. this.releasedInos.push(node.ino);
  574. };
  575. // Generates 6 character long random string, used by `mkdtemp`.
  576. Volume.prototype.genRndStr = function () {
  577. var str = (Math.random() + 1).toString(36).substring(2, 8);
  578. if (str.length === 6)
  579. return str;
  580. else
  581. return this.genRndStr();
  582. };
  583. // Returns a `Link` (hard link) referenced by path "split" into steps.
  584. Volume.prototype.getLink = function (steps) {
  585. return this.root.walk(steps);
  586. };
  587. // Just link `getLink`, but throws a correct user error, if link to found.
  588. Volume.prototype.getLinkOrThrow = function (filename, funcName) {
  589. var steps = filenameToSteps(filename);
  590. var link = this.getLink(steps);
  591. if (!link)
  592. throw createError(ENOENT, funcName, filename);
  593. return link;
  594. };
  595. // Just like `getLink`, but also dereference/resolves symbolic links.
  596. Volume.prototype.getResolvedLink = function (filenameOrSteps) {
  597. var steps = typeof filenameOrSteps === 'string' ? filenameToSteps(filenameOrSteps) : filenameOrSteps;
  598. var link = this.root;
  599. var i = 0;
  600. while (i < steps.length) {
  601. var step = steps[i];
  602. link = link.getChild(step);
  603. if (!link)
  604. return null;
  605. var node = link.getNode();
  606. if (node.isSymlink()) {
  607. steps = node.symlink.concat(steps.slice(i + 1));
  608. link = this.root;
  609. i = 0;
  610. continue;
  611. }
  612. i++;
  613. }
  614. return link;
  615. };
  616. // Just like `getLinkOrThrow`, but also dereference/resolves symbolic links.
  617. Volume.prototype.getResolvedLinkOrThrow = function (filename, funcName) {
  618. var link = this.getResolvedLink(filename);
  619. if (!link)
  620. throw createError(ENOENT, funcName, filename);
  621. return link;
  622. };
  623. Volume.prototype.resolveSymlinks = function (link) {
  624. // let node: Node = link.getNode();
  625. // while(link && node.isSymlink()) {
  626. // link = this.getLink(node.symlink);
  627. // if(!link) return null;
  628. // node = link.getNode();
  629. // }
  630. // return link;
  631. return this.getResolvedLink(link.steps.slice(1));
  632. };
  633. // Just like `getLinkOrThrow`, but also verifies that the link is a directory.
  634. Volume.prototype.getLinkAsDirOrThrow = function (filename, funcName) {
  635. var link = this.getLinkOrThrow(filename, funcName);
  636. if (!link.getNode().isDirectory())
  637. throw createError(ENOTDIR, funcName, filename);
  638. return link;
  639. };
  640. // Get the immediate parent directory of the link.
  641. Volume.prototype.getLinkParent = function (steps) {
  642. return this.root.walk(steps, steps.length - 1);
  643. };
  644. Volume.prototype.getLinkParentAsDirOrThrow = function (filenameOrSteps, funcName) {
  645. var steps = filenameOrSteps instanceof Array ? filenameOrSteps : filenameToSteps(filenameOrSteps);
  646. var link = this.getLinkParent(steps);
  647. if (!link)
  648. throw createError(ENOENT, funcName, sep + steps.join(sep));
  649. if (!link.getNode().isDirectory())
  650. throw createError(ENOTDIR, funcName, sep + steps.join(sep));
  651. return link;
  652. };
  653. Volume.prototype.getFileByFd = function (fd) {
  654. return this.fds[String(fd)];
  655. };
  656. Volume.prototype.getFileByFdOrThrow = function (fd, funcName) {
  657. if (!isFd(fd))
  658. throw TypeError(ERRSTR.FD);
  659. var file = this.getFileByFd(fd);
  660. if (!file)
  661. throw createError(EBADF, funcName);
  662. return file;
  663. };
  664. /**
  665. * @todo This is not used anymore. Remove.
  666. */
  667. /*
  668. private getNodeByIdOrCreate(id: TFileId, flags: number, perm: number): Node {
  669. if (typeof id === 'number') {
  670. const file = this.getFileByFd(id);
  671. if (!file) throw Error('File nto found');
  672. return file.node;
  673. } else {
  674. const steps = pathToSteps(id as PathLike);
  675. let link = this.getLink(steps);
  676. if (link) return link.getNode();
  677. // Try creating a node if not found.
  678. if (flags & O_CREAT) {
  679. const dirLink = this.getLinkParent(steps);
  680. if (dirLink) {
  681. const name = steps[steps.length - 1];
  682. link = this.createLink(dirLink, name, false, perm);
  683. return link.getNode();
  684. }
  685. }
  686. throw createError(ENOENT, 'getNodeByIdOrCreate', pathToFilename(id));
  687. }
  688. }
  689. */
  690. Volume.prototype.wrapAsync = function (method, args, callback) {
  691. var _this = this;
  692. validateCallback(callback);
  693. (0, setImmediate_1.default)(function () {
  694. var result;
  695. try {
  696. result = method.apply(_this, args);
  697. }
  698. catch (err) {
  699. callback(err);
  700. return;
  701. }
  702. callback(null, result);
  703. });
  704. };
  705. Volume.prototype._toJSON = function (link, json, path) {
  706. var _a;
  707. if (link === void 0) { link = this.root; }
  708. if (json === void 0) { json = {}; }
  709. var isEmpty = true;
  710. var children = link.children;
  711. if (link.getNode().isFile()) {
  712. children = (_a = {}, _a[link.getName()] = link.parent.getChild(link.getName()), _a);
  713. link = link.parent;
  714. }
  715. for (var name_1 in children) {
  716. if (name_1 === '.' || name_1 === '..') {
  717. continue;
  718. }
  719. isEmpty = false;
  720. var child = link.getChild(name_1);
  721. if (!child) {
  722. throw new Error('_toJSON: unexpected undefined');
  723. }
  724. var node = child.getNode();
  725. if (node.isFile()) {
  726. var filename = child.getPath();
  727. if (path)
  728. filename = relative(path, filename);
  729. json[filename] = node.getString();
  730. }
  731. else if (node.isDirectory()) {
  732. this._toJSON(child, json, path);
  733. }
  734. }
  735. var dirPath = link.getPath();
  736. if (path)
  737. dirPath = relative(path, dirPath);
  738. if (dirPath && isEmpty) {
  739. json[dirPath] = null;
  740. }
  741. return json;
  742. };
  743. Volume.prototype.toJSON = function (paths, json, isRelative) {
  744. if (json === void 0) { json = {}; }
  745. if (isRelative === void 0) { isRelative = false; }
  746. var links = [];
  747. if (paths) {
  748. if (!(paths instanceof Array))
  749. paths = [paths];
  750. for (var _i = 0, paths_1 = paths; _i < paths_1.length; _i++) {
  751. var path = paths_1[_i];
  752. var filename = pathToFilename(path);
  753. var link = this.getResolvedLink(filename);
  754. if (!link)
  755. continue;
  756. links.push(link);
  757. }
  758. }
  759. else {
  760. links.push(this.root);
  761. }
  762. if (!links.length)
  763. return json;
  764. for (var _a = 0, links_1 = links; _a < links_1.length; _a++) {
  765. var link = links_1[_a];
  766. this._toJSON(link, json, isRelative ? link.getPath() : '');
  767. }
  768. return json;
  769. };
  770. Volume.prototype.fromJSON = function (json, cwd) {
  771. if (cwd === void 0) { cwd = process_1.default.cwd(); }
  772. for (var filename in json) {
  773. var data = json[filename];
  774. filename = resolve(filename, cwd);
  775. if (typeof data === 'string') {
  776. var dir = dirname(filename);
  777. this.mkdirpBase(dir, 511 /* MODE.DIR */);
  778. this.writeFileSync(filename, data);
  779. }
  780. else {
  781. this.mkdirpBase(filename, 511 /* MODE.DIR */);
  782. }
  783. }
  784. };
  785. Volume.prototype.fromNestedJSON = function (json, cwd) {
  786. this.fromJSON(flattenJSON(json), cwd);
  787. };
  788. Volume.prototype.reset = function () {
  789. this.ino = 0;
  790. this.inodes = {};
  791. this.releasedInos = [];
  792. this.fds = {};
  793. this.releasedFds = [];
  794. this.openFiles = 0;
  795. this.root = this.createLink();
  796. this.root.setNode(this.createNode(true));
  797. };
  798. // Legacy interface
  799. Volume.prototype.mountSync = function (mountpoint, json) {
  800. this.fromJSON(json, mountpoint);
  801. };
  802. Volume.prototype.openLink = function (link, flagsNum, resolveSymlinks) {
  803. if (resolveSymlinks === void 0) { resolveSymlinks = true; }
  804. if (this.openFiles >= this.maxFiles) {
  805. // Too many open files.
  806. throw createError(EMFILE, 'open', link.getPath());
  807. }
  808. // Resolve symlinks.
  809. var realLink = link;
  810. if (resolveSymlinks)
  811. realLink = this.resolveSymlinks(link);
  812. if (!realLink)
  813. throw createError(ENOENT, 'open', link.getPath());
  814. var node = realLink.getNode();
  815. // Check whether node is a directory
  816. if (node.isDirectory()) {
  817. if ((flagsNum & (O_RDONLY | O_RDWR | O_WRONLY)) !== O_RDONLY)
  818. throw createError(EISDIR, 'open', link.getPath());
  819. }
  820. else {
  821. if (flagsNum & O_DIRECTORY)
  822. throw createError(ENOTDIR, 'open', link.getPath());
  823. }
  824. // Check node permissions
  825. if (!(flagsNum & O_WRONLY)) {
  826. if (!node.canRead()) {
  827. throw createError(EACCES, 'open', link.getPath());
  828. }
  829. }
  830. if (flagsNum & O_RDWR) {
  831. }
  832. var file = new this.props.File(link, node, flagsNum, this.newFdNumber());
  833. this.fds[file.fd] = file;
  834. this.openFiles++;
  835. if (flagsNum & O_TRUNC)
  836. file.truncate();
  837. return file;
  838. };
  839. Volume.prototype.openFile = function (filename, flagsNum, modeNum, resolveSymlinks) {
  840. if (resolveSymlinks === void 0) { resolveSymlinks = true; }
  841. var steps = filenameToSteps(filename);
  842. var link = resolveSymlinks ? this.getResolvedLink(steps) : this.getLink(steps);
  843. if (link && flagsNum & O_EXCL)
  844. throw createError(EEXIST, 'open', filename);
  845. // Try creating a new file, if it does not exist.
  846. if (!link && flagsNum & O_CREAT) {
  847. // const dirLink: Link = this.getLinkParent(steps);
  848. var dirLink = this.getResolvedLink(steps.slice(0, steps.length - 1));
  849. // if(!dirLink) throw createError(ENOENT, 'open', filename);
  850. if (!dirLink)
  851. throw createError(ENOENT, 'open', sep + steps.join(sep));
  852. if (flagsNum & O_CREAT && typeof modeNum === 'number') {
  853. link = this.createLink(dirLink, steps[steps.length - 1], false, modeNum);
  854. }
  855. }
  856. if (link)
  857. return this.openLink(link, flagsNum, resolveSymlinks);
  858. throw createError(ENOENT, 'open', filename);
  859. };
  860. Volume.prototype.openBase = function (filename, flagsNum, modeNum, resolveSymlinks) {
  861. if (resolveSymlinks === void 0) { resolveSymlinks = true; }
  862. var file = this.openFile(filename, flagsNum, modeNum, resolveSymlinks);
  863. if (!file)
  864. throw createError(ENOENT, 'open', filename);
  865. return file.fd;
  866. };
  867. Volume.prototype.openSync = function (path, flags, mode) {
  868. if (mode === void 0) { mode = 438 /* MODE.DEFAULT */; }
  869. // Validate (1) mode; (2) path; (3) flags - in that order.
  870. var modeNum = modeToNumber(mode);
  871. var fileName = pathToFilename(path);
  872. var flagsNum = flagsToNumber(flags);
  873. return this.openBase(fileName, flagsNum, modeNum);
  874. };
  875. Volume.prototype.open = function (path, flags, a, b) {
  876. var mode = a;
  877. var callback = b;
  878. if (typeof a === 'function') {
  879. mode = 438 /* MODE.DEFAULT */;
  880. callback = a;
  881. }
  882. mode = mode || 438 /* MODE.DEFAULT */;
  883. var modeNum = modeToNumber(mode);
  884. var fileName = pathToFilename(path);
  885. var flagsNum = flagsToNumber(flags);
  886. this.wrapAsync(this.openBase, [fileName, flagsNum, modeNum], callback);
  887. };
  888. Volume.prototype.closeFile = function (file) {
  889. if (!this.fds[file.fd])
  890. return;
  891. this.openFiles--;
  892. delete this.fds[file.fd];
  893. this.releasedFds.push(file.fd);
  894. };
  895. Volume.prototype.closeSync = function (fd) {
  896. validateFd(fd);
  897. var file = this.getFileByFdOrThrow(fd, 'close');
  898. this.closeFile(file);
  899. };
  900. Volume.prototype.close = function (fd, callback) {
  901. validateFd(fd);
  902. this.wrapAsync(this.closeSync, [fd], callback);
  903. };
  904. Volume.prototype.openFileOrGetById = function (id, flagsNum, modeNum) {
  905. if (typeof id === 'number') {
  906. var file = this.fds[id];
  907. if (!file)
  908. throw createError(ENOENT);
  909. return file;
  910. }
  911. else {
  912. return this.openFile(pathToFilename(id), flagsNum, modeNum);
  913. }
  914. };
  915. Volume.prototype.readBase = function (fd, buffer, offset, length, position) {
  916. var file = this.getFileByFdOrThrow(fd);
  917. return file.read(buffer, Number(offset), Number(length), position);
  918. };
  919. Volume.prototype.readSync = function (fd, buffer, offset, length, position) {
  920. validateFd(fd);
  921. return this.readBase(fd, buffer, offset, length, position);
  922. };
  923. Volume.prototype.read = function (fd, buffer, offset, length, position, callback) {
  924. var _this = this;
  925. validateCallback(callback);
  926. // This `if` branch is from Node.js
  927. if (length === 0) {
  928. return process_1.default.nextTick(function () {
  929. if (callback)
  930. callback(null, 0, buffer);
  931. });
  932. }
  933. (0, setImmediate_1.default)(function () {
  934. try {
  935. var bytes = _this.readBase(fd, buffer, offset, length, position);
  936. callback(null, bytes, buffer);
  937. }
  938. catch (err) {
  939. callback(err);
  940. }
  941. });
  942. };
  943. Volume.prototype.readFileBase = function (id, flagsNum, encoding) {
  944. var result;
  945. var isUserFd = typeof id === 'number';
  946. var userOwnsFd = isUserFd && isFd(id);
  947. var fd;
  948. if (userOwnsFd)
  949. fd = id;
  950. else {
  951. var filename = pathToFilename(id);
  952. var steps = filenameToSteps(filename);
  953. var link = this.getResolvedLink(steps);
  954. if (link) {
  955. var node = link.getNode();
  956. if (node.isDirectory())
  957. throw createError(EISDIR, 'open', link.getPath());
  958. }
  959. fd = this.openSync(id, flagsNum);
  960. }
  961. try {
  962. result = bufferToEncoding(this.getFileByFdOrThrow(fd).getBuffer(), encoding);
  963. }
  964. finally {
  965. if (!userOwnsFd) {
  966. this.closeSync(fd);
  967. }
  968. }
  969. return result;
  970. };
  971. Volume.prototype.readFileSync = function (file, options) {
  972. var opts = getReadFileOptions(options);
  973. var flagsNum = flagsToNumber(opts.flag);
  974. return this.readFileBase(file, flagsNum, opts.encoding);
  975. };
  976. Volume.prototype.readFile = function (id, a, b) {
  977. var _a = optsAndCbGenerator(getReadFileOptions)(a, b), opts = _a[0], callback = _a[1];
  978. var flagsNum = flagsToNumber(opts.flag);
  979. this.wrapAsync(this.readFileBase, [id, flagsNum, opts.encoding], callback);
  980. };
  981. Volume.prototype.writeBase = function (fd, buf, offset, length, position) {
  982. var file = this.getFileByFdOrThrow(fd, 'write');
  983. return file.write(buf, offset, length, position);
  984. };
  985. Volume.prototype.writeSync = function (fd, a, b, c, d) {
  986. validateFd(fd);
  987. var encoding;
  988. var offset;
  989. var length;
  990. var position;
  991. var isBuffer = typeof a !== 'string';
  992. if (isBuffer) {
  993. offset = (b || 0) | 0;
  994. length = c;
  995. position = d;
  996. }
  997. else {
  998. position = b;
  999. encoding = c;
  1000. }
  1001. var buf = dataToBuffer(a, encoding);
  1002. if (isBuffer) {
  1003. if (typeof length === 'undefined') {
  1004. length = buf.length;
  1005. }
  1006. }
  1007. else {
  1008. offset = 0;
  1009. length = buf.length;
  1010. }
  1011. return this.writeBase(fd, buf, offset, length, position);
  1012. };
  1013. Volume.prototype.write = function (fd, a, b, c, d, e) {
  1014. var _this = this;
  1015. validateFd(fd);
  1016. var offset;
  1017. var length;
  1018. var position;
  1019. var encoding;
  1020. var callback;
  1021. var tipa = typeof a;
  1022. var tipb = typeof b;
  1023. var tipc = typeof c;
  1024. var tipd = typeof d;
  1025. if (tipa !== 'string') {
  1026. if (tipb === 'function') {
  1027. callback = b;
  1028. }
  1029. else if (tipc === 'function') {
  1030. offset = b | 0;
  1031. callback = c;
  1032. }
  1033. else if (tipd === 'function') {
  1034. offset = b | 0;
  1035. length = c;
  1036. callback = d;
  1037. }
  1038. else {
  1039. offset = b | 0;
  1040. length = c;
  1041. position = d;
  1042. callback = e;
  1043. }
  1044. }
  1045. else {
  1046. if (tipb === 'function') {
  1047. callback = b;
  1048. }
  1049. else if (tipc === 'function') {
  1050. position = b;
  1051. callback = c;
  1052. }
  1053. else if (tipd === 'function') {
  1054. position = b;
  1055. encoding = c;
  1056. callback = d;
  1057. }
  1058. }
  1059. var buf = dataToBuffer(a, encoding);
  1060. if (tipa !== 'string') {
  1061. if (typeof length === 'undefined')
  1062. length = buf.length;
  1063. }
  1064. else {
  1065. offset = 0;
  1066. length = buf.length;
  1067. }
  1068. var cb = validateCallback(callback);
  1069. (0, setImmediate_1.default)(function () {
  1070. try {
  1071. var bytes = _this.writeBase(fd, buf, offset, length, position);
  1072. if (tipa !== 'string') {
  1073. cb(null, bytes, buf);
  1074. }
  1075. else {
  1076. cb(null, bytes, a);
  1077. }
  1078. }
  1079. catch (err) {
  1080. cb(err);
  1081. }
  1082. });
  1083. };
  1084. Volume.prototype.writeFileBase = function (id, buf, flagsNum, modeNum) {
  1085. // console.log('writeFileBase', id, buf, flagsNum, modeNum);
  1086. // const node = this.getNodeByIdOrCreate(id, flagsNum, modeNum);
  1087. // node.setBuffer(buf);
  1088. var isUserFd = typeof id === 'number';
  1089. var fd;
  1090. if (isUserFd)
  1091. fd = id;
  1092. else {
  1093. fd = this.openBase(pathToFilename(id), flagsNum, modeNum);
  1094. // fd = this.openSync(id as PathLike, flagsNum, modeNum);
  1095. }
  1096. var offset = 0;
  1097. var length = buf.length;
  1098. var position = flagsNum & O_APPEND ? undefined : 0;
  1099. try {
  1100. while (length > 0) {
  1101. var written = this.writeSync(fd, buf, offset, length, position);
  1102. offset += written;
  1103. length -= written;
  1104. if (position !== undefined)
  1105. position += written;
  1106. }
  1107. }
  1108. finally {
  1109. if (!isUserFd)
  1110. this.closeSync(fd);
  1111. }
  1112. };
  1113. Volume.prototype.writeFileSync = function (id, data, options) {
  1114. var opts = getWriteFileOptions(options);
  1115. var flagsNum = flagsToNumber(opts.flag);
  1116. var modeNum = modeToNumber(opts.mode);
  1117. var buf = dataToBuffer(data, opts.encoding);
  1118. this.writeFileBase(id, buf, flagsNum, modeNum);
  1119. };
  1120. Volume.prototype.writeFile = function (id, data, a, b) {
  1121. var options = a;
  1122. var callback = b;
  1123. if (typeof a === 'function') {
  1124. options = writeFileDefaults;
  1125. callback = a;
  1126. }
  1127. var cb = validateCallback(callback);
  1128. var opts = getWriteFileOptions(options);
  1129. var flagsNum = flagsToNumber(opts.flag);
  1130. var modeNum = modeToNumber(opts.mode);
  1131. var buf = dataToBuffer(data, opts.encoding);
  1132. this.wrapAsync(this.writeFileBase, [id, buf, flagsNum, modeNum], cb);
  1133. };
  1134. Volume.prototype.linkBase = function (filename1, filename2) {
  1135. var steps1 = filenameToSteps(filename1);
  1136. var link1 = this.getLink(steps1);
  1137. if (!link1)
  1138. throw createError(ENOENT, 'link', filename1, filename2);
  1139. var steps2 = filenameToSteps(filename2);
  1140. // Check new link directory exists.
  1141. var dir2 = this.getLinkParent(steps2);
  1142. if (!dir2)
  1143. throw createError(ENOENT, 'link', filename1, filename2);
  1144. var name = steps2[steps2.length - 1];
  1145. // Check if new file already exists.
  1146. if (dir2.getChild(name))
  1147. throw createError(EEXIST, 'link', filename1, filename2);
  1148. var node = link1.getNode();
  1149. node.nlink++;
  1150. dir2.createChild(name, node);
  1151. };
  1152. Volume.prototype.copyFileBase = function (src, dest, flags) {
  1153. var buf = this.readFileSync(src);
  1154. if (flags & COPYFILE_EXCL) {
  1155. if (this.existsSync(dest)) {
  1156. throw createError(EEXIST, 'copyFile', src, dest);
  1157. }
  1158. }
  1159. if (flags & COPYFILE_FICLONE_FORCE) {
  1160. throw createError(ENOSYS, 'copyFile', src, dest);
  1161. }
  1162. this.writeFileBase(dest, buf, FLAGS.w, 438 /* MODE.DEFAULT */);
  1163. };
  1164. Volume.prototype.copyFileSync = function (src, dest, flags) {
  1165. var srcFilename = pathToFilename(src);
  1166. var destFilename = pathToFilename(dest);
  1167. return this.copyFileBase(srcFilename, destFilename, (flags || 0) | 0);
  1168. };
  1169. Volume.prototype.copyFile = function (src, dest, a, b) {
  1170. var srcFilename = pathToFilename(src);
  1171. var destFilename = pathToFilename(dest);
  1172. var flags;
  1173. var callback;
  1174. if (typeof a === 'function') {
  1175. flags = 0;
  1176. callback = a;
  1177. }
  1178. else {
  1179. flags = a;
  1180. callback = b;
  1181. }
  1182. validateCallback(callback);
  1183. this.wrapAsync(this.copyFileBase, [srcFilename, destFilename, flags], callback);
  1184. };
  1185. Volume.prototype.linkSync = function (existingPath, newPath) {
  1186. var existingPathFilename = pathToFilename(existingPath);
  1187. var newPathFilename = pathToFilename(newPath);
  1188. this.linkBase(existingPathFilename, newPathFilename);
  1189. };
  1190. Volume.prototype.link = function (existingPath, newPath, callback) {
  1191. var existingPathFilename = pathToFilename(existingPath);
  1192. var newPathFilename = pathToFilename(newPath);
  1193. this.wrapAsync(this.linkBase, [existingPathFilename, newPathFilename], callback);
  1194. };
  1195. Volume.prototype.unlinkBase = function (filename) {
  1196. var steps = filenameToSteps(filename);
  1197. var link = this.getLink(steps);
  1198. if (!link)
  1199. throw createError(ENOENT, 'unlink', filename);
  1200. // TODO: Check if it is file, dir, other...
  1201. if (link.length)
  1202. throw Error('Dir not empty...');
  1203. this.deleteLink(link);
  1204. var node = link.getNode();
  1205. node.nlink--;
  1206. // When all hard links to i-node are deleted, remove the i-node, too.
  1207. if (node.nlink <= 0) {
  1208. this.deleteNode(node);
  1209. }
  1210. };
  1211. Volume.prototype.unlinkSync = function (path) {
  1212. var filename = pathToFilename(path);
  1213. this.unlinkBase(filename);
  1214. };
  1215. Volume.prototype.unlink = function (path, callback) {
  1216. var filename = pathToFilename(path);
  1217. this.wrapAsync(this.unlinkBase, [filename], callback);
  1218. };
  1219. Volume.prototype.symlinkBase = function (targetFilename, pathFilename) {
  1220. var pathSteps = filenameToSteps(pathFilename);
  1221. // Check if directory exists, where we about to create a symlink.
  1222. var dirLink = this.getLinkParent(pathSteps);
  1223. if (!dirLink)
  1224. throw createError(ENOENT, 'symlink', targetFilename, pathFilename);
  1225. var name = pathSteps[pathSteps.length - 1];
  1226. // Check if new file already exists.
  1227. if (dirLink.getChild(name))
  1228. throw createError(EEXIST, 'symlink', targetFilename, pathFilename);
  1229. // Create symlink.
  1230. var symlink = dirLink.createChild(name);
  1231. symlink.getNode().makeSymlink(filenameToSteps(targetFilename));
  1232. return symlink;
  1233. };
  1234. // `type` argument works only on Windows.
  1235. Volume.prototype.symlinkSync = function (target, path, type) {
  1236. var targetFilename = pathToFilename(target);
  1237. var pathFilename = pathToFilename(path);
  1238. this.symlinkBase(targetFilename, pathFilename);
  1239. };
  1240. Volume.prototype.symlink = function (target, path, a, b) {
  1241. var callback = validateCallback(typeof a === 'function' ? a : b);
  1242. var targetFilename = pathToFilename(target);
  1243. var pathFilename = pathToFilename(path);
  1244. this.wrapAsync(this.symlinkBase, [targetFilename, pathFilename], callback);
  1245. };
  1246. Volume.prototype.realpathBase = function (filename, encoding) {
  1247. var steps = filenameToSteps(filename);
  1248. var realLink = this.getResolvedLink(steps);
  1249. if (!realLink)
  1250. throw createError(ENOENT, 'realpath', filename);
  1251. return (0, encoding_1.strToEncoding)(realLink.getPath() || '/', encoding);
  1252. };
  1253. Volume.prototype.realpathSync = function (path, options) {
  1254. return this.realpathBase(pathToFilename(path), getRealpathOptions(options).encoding);
  1255. };
  1256. Volume.prototype.realpath = function (path, a, b) {
  1257. var _a = getRealpathOptsAndCb(a, b), opts = _a[0], callback = _a[1];
  1258. var pathFilename = pathToFilename(path);
  1259. this.wrapAsync(this.realpathBase, [pathFilename, opts.encoding], callback);
  1260. };
  1261. Volume.prototype.lstatBase = function (filename, bigint, throwIfNoEntry) {
  1262. if (bigint === void 0) { bigint = false; }
  1263. if (throwIfNoEntry === void 0) { throwIfNoEntry = false; }
  1264. var link = this.getLink(filenameToSteps(filename));
  1265. if (link) {
  1266. return Stats_1.default.build(link.getNode(), bigint);
  1267. }
  1268. else if (!throwIfNoEntry) {
  1269. return undefined;
  1270. }
  1271. else {
  1272. throw createError(ENOENT, 'lstat', filename);
  1273. }
  1274. };
  1275. Volume.prototype.lstatSync = function (path, options) {
  1276. var _a = getStatOptions(options), _b = _a.throwIfNoEntry, throwIfNoEntry = _b === void 0 ? true : _b, _c = _a.bigint, bigint = _c === void 0 ? false : _c;
  1277. return this.lstatBase(pathToFilename(path), bigint, throwIfNoEntry);
  1278. };
  1279. Volume.prototype.lstat = function (path, a, b) {
  1280. var _a = getStatOptsAndCb(a, b), _b = _a[0], _c = _b.throwIfNoEntry, throwIfNoEntry = _c === void 0 ? true : _c, _d = _b.bigint, bigint = _d === void 0 ? false : _d, callback = _a[1];
  1281. this.wrapAsync(this.lstatBase, [pathToFilename(path), bigint, throwIfNoEntry], callback);
  1282. };
  1283. Volume.prototype.statBase = function (filename, bigint, throwIfNoEntry) {
  1284. if (bigint === void 0) { bigint = false; }
  1285. if (throwIfNoEntry === void 0) { throwIfNoEntry = true; }
  1286. var link = this.getResolvedLink(filenameToSteps(filename));
  1287. if (link) {
  1288. return Stats_1.default.build(link.getNode(), bigint);
  1289. }
  1290. else if (!throwIfNoEntry) {
  1291. return undefined;
  1292. }
  1293. else {
  1294. throw createError(ENOENT, 'stat', filename);
  1295. }
  1296. };
  1297. Volume.prototype.statSync = function (path, options) {
  1298. var _a = getStatOptions(options), _b = _a.bigint, bigint = _b === void 0 ? true : _b, _c = _a.throwIfNoEntry, throwIfNoEntry = _c === void 0 ? true : _c;
  1299. return this.statBase(pathToFilename(path), bigint, throwIfNoEntry);
  1300. };
  1301. Volume.prototype.stat = function (path, a, b) {
  1302. var _a = getStatOptsAndCb(a, b), _b = _a[0], _c = _b.bigint, bigint = _c === void 0 ? false : _c, _d = _b.throwIfNoEntry, throwIfNoEntry = _d === void 0 ? true : _d, callback = _a[1];
  1303. this.wrapAsync(this.statBase, [pathToFilename(path), bigint, throwIfNoEntry], callback);
  1304. };
  1305. Volume.prototype.fstatBase = function (fd, bigint) {
  1306. if (bigint === void 0) { bigint = false; }
  1307. var file = this.getFileByFd(fd);
  1308. if (!file)
  1309. throw createError(EBADF, 'fstat');
  1310. return Stats_1.default.build(file.node, bigint);
  1311. };
  1312. Volume.prototype.fstatSync = function (fd, options) {
  1313. return this.fstatBase(fd, getStatOptions(options).bigint);
  1314. };
  1315. Volume.prototype.fstat = function (fd, a, b) {
  1316. var _a = getStatOptsAndCb(a, b), opts = _a[0], callback = _a[1];
  1317. this.wrapAsync(this.fstatBase, [fd, opts.bigint], callback);
  1318. };
  1319. Volume.prototype.renameBase = function (oldPathFilename, newPathFilename) {
  1320. var link = this.getLink(filenameToSteps(oldPathFilename));
  1321. if (!link)
  1322. throw createError(ENOENT, 'rename', oldPathFilename, newPathFilename);
  1323. // TODO: Check if it is directory, if non-empty, we cannot move it, right?
  1324. var newPathSteps = filenameToSteps(newPathFilename);
  1325. // Check directory exists for the new location.
  1326. var newPathDirLink = this.getLinkParent(newPathSteps);
  1327. if (!newPathDirLink)
  1328. throw createError(ENOENT, 'rename', oldPathFilename, newPathFilename);
  1329. // TODO: Also treat cases with directories and symbolic links.
  1330. // TODO: See: http://man7.org/linux/man-pages/man2/rename.2.html
  1331. // Remove hard link from old folder.
  1332. var oldLinkParent = link.parent;
  1333. if (oldLinkParent) {
  1334. oldLinkParent.deleteChild(link);
  1335. }
  1336. // Rename should overwrite the new path, if that exists.
  1337. var name = newPathSteps[newPathSteps.length - 1];
  1338. link.name = name;
  1339. link.steps = __spreadArray(__spreadArray([], newPathDirLink.steps, true), [name], false);
  1340. newPathDirLink.setChild(link.getName(), link);
  1341. };
  1342. Volume.prototype.renameSync = function (oldPath, newPath) {
  1343. var oldPathFilename = pathToFilename(oldPath);
  1344. var newPathFilename = pathToFilename(newPath);
  1345. this.renameBase(oldPathFilename, newPathFilename);
  1346. };
  1347. Volume.prototype.rename = function (oldPath, newPath, callback) {
  1348. var oldPathFilename = pathToFilename(oldPath);
  1349. var newPathFilename = pathToFilename(newPath);
  1350. this.wrapAsync(this.renameBase, [oldPathFilename, newPathFilename], callback);
  1351. };
  1352. Volume.prototype.existsBase = function (filename) {
  1353. return !!this.statBase(filename);
  1354. };
  1355. Volume.prototype.existsSync = function (path) {
  1356. try {
  1357. return this.existsBase(pathToFilename(path));
  1358. }
  1359. catch (err) {
  1360. return false;
  1361. }
  1362. };
  1363. Volume.prototype.exists = function (path, callback) {
  1364. var _this = this;
  1365. var filename = pathToFilename(path);
  1366. if (typeof callback !== 'function')
  1367. throw Error(ERRSTR.CB);
  1368. (0, setImmediate_1.default)(function () {
  1369. try {
  1370. callback(_this.existsBase(filename));
  1371. }
  1372. catch (err) {
  1373. callback(false);
  1374. }
  1375. });
  1376. };
  1377. Volume.prototype.accessBase = function (filename, mode) {
  1378. var link = this.getLinkOrThrow(filename, 'access');
  1379. // TODO: Verify permissions
  1380. };
  1381. Volume.prototype.accessSync = function (path, mode) {
  1382. if (mode === void 0) { mode = F_OK; }
  1383. var filename = pathToFilename(path);
  1384. mode = mode | 0;
  1385. this.accessBase(filename, mode);
  1386. };
  1387. Volume.prototype.access = function (path, a, b) {
  1388. var mode = F_OK;
  1389. var callback;
  1390. if (typeof a !== 'function') {
  1391. mode = a | 0; // cast to number
  1392. callback = validateCallback(b);
  1393. }
  1394. else {
  1395. callback = a;
  1396. }
  1397. var filename = pathToFilename(path);
  1398. this.wrapAsync(this.accessBase, [filename, mode], callback);
  1399. };
  1400. Volume.prototype.appendFileSync = function (id, data, options) {
  1401. if (options === void 0) { options = appendFileDefaults; }
  1402. var opts = getAppendFileOpts(options);
  1403. // force append behavior when using a supplied file descriptor
  1404. if (!opts.flag || isFd(id))
  1405. opts.flag = 'a';
  1406. this.writeFileSync(id, data, opts);
  1407. };
  1408. Volume.prototype.appendFile = function (id, data, a, b) {
  1409. var _a = getAppendFileOptsAndCb(a, b), opts = _a[0], callback = _a[1];
  1410. // force append behavior when using a supplied file descriptor
  1411. if (!opts.flag || isFd(id))
  1412. opts.flag = 'a';
  1413. this.writeFile(id, data, opts, callback);
  1414. };
  1415. Volume.prototype.readdirBase = function (filename, options) {
  1416. var steps = filenameToSteps(filename);
  1417. var link = this.getResolvedLink(steps);
  1418. if (!link)
  1419. throw createError(ENOENT, 'readdir', filename);
  1420. var node = link.getNode();
  1421. if (!node.isDirectory())
  1422. throw createError(ENOTDIR, 'scandir', filename);
  1423. if (options.withFileTypes) {
  1424. var list_1 = [];
  1425. for (var name_2 in link.children) {
  1426. var child = link.getChild(name_2);
  1427. if (!child || name_2 === '.' || name_2 === '..') {
  1428. continue;
  1429. }
  1430. list_1.push(Dirent_1.default.build(child, options.encoding));
  1431. }
  1432. if (!isWin && options.encoding !== 'buffer')
  1433. list_1.sort(function (a, b) {
  1434. if (a.name < b.name)
  1435. return -1;
  1436. if (a.name > b.name)
  1437. return 1;
  1438. return 0;
  1439. });
  1440. return list_1;
  1441. }
  1442. var list = [];
  1443. for (var name_3 in link.children) {
  1444. if (name_3 === '.' || name_3 === '..') {
  1445. continue;
  1446. }
  1447. list.push((0, encoding_1.strToEncoding)(name_3, options.encoding));
  1448. }
  1449. if (!isWin && options.encoding !== 'buffer')
  1450. list.sort();
  1451. return list;
  1452. };
  1453. Volume.prototype.readdirSync = function (path, options) {
  1454. var opts = getReaddirOptions(options);
  1455. var filename = pathToFilename(path);
  1456. return this.readdirBase(filename, opts);
  1457. };
  1458. Volume.prototype.readdir = function (path, a, b) {
  1459. var _a = getReaddirOptsAndCb(a, b), options = _a[0], callback = _a[1];
  1460. var filename = pathToFilename(path);
  1461. this.wrapAsync(this.readdirBase, [filename, options], callback);
  1462. };
  1463. Volume.prototype.readlinkBase = function (filename, encoding) {
  1464. var link = this.getLinkOrThrow(filename, 'readlink');
  1465. var node = link.getNode();
  1466. if (!node.isSymlink())
  1467. throw createError(EINVAL, 'readlink', filename);
  1468. var str = sep + node.symlink.join(sep);
  1469. return (0, encoding_1.strToEncoding)(str, encoding);
  1470. };
  1471. Volume.prototype.readlinkSync = function (path, options) {
  1472. var opts = getDefaultOpts(options);
  1473. var filename = pathToFilename(path);
  1474. return this.readlinkBase(filename, opts.encoding);
  1475. };
  1476. Volume.prototype.readlink = function (path, a, b) {
  1477. var _a = getDefaultOptsAndCb(a, b), opts = _a[0], callback = _a[1];
  1478. var filename = pathToFilename(path);
  1479. this.wrapAsync(this.readlinkBase, [filename, opts.encoding], callback);
  1480. };
  1481. Volume.prototype.fsyncBase = function (fd) {
  1482. this.getFileByFdOrThrow(fd, 'fsync');
  1483. };
  1484. Volume.prototype.fsyncSync = function (fd) {
  1485. this.fsyncBase(fd);
  1486. };
  1487. Volume.prototype.fsync = function (fd, callback) {
  1488. this.wrapAsync(this.fsyncBase, [fd], callback);
  1489. };
  1490. Volume.prototype.fdatasyncBase = function (fd) {
  1491. this.getFileByFdOrThrow(fd, 'fdatasync');
  1492. };
  1493. Volume.prototype.fdatasyncSync = function (fd) {
  1494. this.fdatasyncBase(fd);
  1495. };
  1496. Volume.prototype.fdatasync = function (fd, callback) {
  1497. this.wrapAsync(this.fdatasyncBase, [fd], callback);
  1498. };
  1499. Volume.prototype.ftruncateBase = function (fd, len) {
  1500. var file = this.getFileByFdOrThrow(fd, 'ftruncate');
  1501. file.truncate(len);
  1502. };
  1503. Volume.prototype.ftruncateSync = function (fd, len) {
  1504. this.ftruncateBase(fd, len);
  1505. };
  1506. Volume.prototype.ftruncate = function (fd, a, b) {
  1507. var len = typeof a === 'number' ? a : 0;
  1508. var callback = validateCallback(typeof a === 'number' ? b : a);
  1509. this.wrapAsync(this.ftruncateBase, [fd, len], callback);
  1510. };
  1511. Volume.prototype.truncateBase = function (path, len) {
  1512. var fd = this.openSync(path, 'r+');
  1513. try {
  1514. this.ftruncateSync(fd, len);
  1515. }
  1516. finally {
  1517. this.closeSync(fd);
  1518. }
  1519. };
  1520. Volume.prototype.truncateSync = function (id, len) {
  1521. if (isFd(id))
  1522. return this.ftruncateSync(id, len);
  1523. this.truncateBase(id, len);
  1524. };
  1525. Volume.prototype.truncate = function (id, a, b) {
  1526. var len = typeof a === 'number' ? a : 0;
  1527. var callback = validateCallback(typeof a === 'number' ? b : a);
  1528. if (isFd(id))
  1529. return this.ftruncate(id, len, callback);
  1530. this.wrapAsync(this.truncateBase, [id, len], callback);
  1531. };
  1532. Volume.prototype.futimesBase = function (fd, atime, mtime) {
  1533. var file = this.getFileByFdOrThrow(fd, 'futimes');
  1534. var node = file.node;
  1535. node.atime = new Date(atime * 1000);
  1536. node.mtime = new Date(mtime * 1000);
  1537. };
  1538. Volume.prototype.futimesSync = function (fd, atime, mtime) {
  1539. this.futimesBase(fd, toUnixTimestamp(atime), toUnixTimestamp(mtime));
  1540. };
  1541. Volume.prototype.futimes = function (fd, atime, mtime, callback) {
  1542. this.wrapAsync(this.futimesBase, [fd, toUnixTimestamp(atime), toUnixTimestamp(mtime)], callback);
  1543. };
  1544. Volume.prototype.utimesBase = function (filename, atime, mtime) {
  1545. var fd = this.openSync(filename, 'r');
  1546. try {
  1547. this.futimesBase(fd, atime, mtime);
  1548. }
  1549. finally {
  1550. this.closeSync(fd);
  1551. }
  1552. };
  1553. Volume.prototype.utimesSync = function (path, atime, mtime) {
  1554. this.utimesBase(pathToFilename(path), toUnixTimestamp(atime), toUnixTimestamp(mtime));
  1555. };
  1556. Volume.prototype.utimes = function (path, atime, mtime, callback) {
  1557. this.wrapAsync(this.utimesBase, [pathToFilename(path), toUnixTimestamp(atime), toUnixTimestamp(mtime)], callback);
  1558. };
  1559. Volume.prototype.mkdirBase = function (filename, modeNum) {
  1560. var steps = filenameToSteps(filename);
  1561. // This will throw if user tries to create root dir `fs.mkdirSync('/')`.
  1562. if (!steps.length) {
  1563. throw createError(EEXIST, 'mkdir', filename);
  1564. }
  1565. var dir = this.getLinkParentAsDirOrThrow(filename, 'mkdir');
  1566. // Check path already exists.
  1567. var name = steps[steps.length - 1];
  1568. if (dir.getChild(name))
  1569. throw createError(EEXIST, 'mkdir', filename);
  1570. dir.createChild(name, this.createNode(true, modeNum));
  1571. };
  1572. /**
  1573. * Creates directory tree recursively.
  1574. * @param filename
  1575. * @param modeNum
  1576. */
  1577. Volume.prototype.mkdirpBase = function (filename, modeNum) {
  1578. var fullPath = resolve(filename);
  1579. var fullPathSansSlash = fullPath.substring(1);
  1580. var steps = !fullPathSansSlash ? [] : fullPathSansSlash.split(sep);
  1581. var link = this.root;
  1582. var created = false;
  1583. for (var i = 0; i < steps.length; i++) {
  1584. var step = steps[i];
  1585. if (!link.getNode().isDirectory())
  1586. throw createError(ENOTDIR, 'mkdir', link.getPath());
  1587. var child = link.getChild(step);
  1588. if (child) {
  1589. if (child.getNode().isDirectory())
  1590. link = child;
  1591. else
  1592. throw createError(ENOTDIR, 'mkdir', child.getPath());
  1593. }
  1594. else {
  1595. link = link.createChild(step, this.createNode(true, modeNum));
  1596. created = true;
  1597. }
  1598. }
  1599. return created ? fullPath : undefined;
  1600. };
  1601. Volume.prototype.mkdirSync = function (path, options) {
  1602. var opts = getMkdirOptions(options);
  1603. var modeNum = modeToNumber(opts.mode, 511);
  1604. var filename = pathToFilename(path);
  1605. if (opts.recursive)
  1606. return this.mkdirpBase(filename, modeNum);
  1607. this.mkdirBase(filename, modeNum);
  1608. };
  1609. Volume.prototype.mkdir = function (path, a, b) {
  1610. var opts = getMkdirOptions(a);
  1611. var callback = validateCallback(typeof a === 'function' ? a : b);
  1612. var modeNum = modeToNumber(opts.mode, 511);
  1613. var filename = pathToFilename(path);
  1614. if (opts.recursive)
  1615. this.wrapAsync(this.mkdirpBase, [filename, modeNum], callback);
  1616. else
  1617. this.wrapAsync(this.mkdirBase, [filename, modeNum], callback);
  1618. };
  1619. // legacy interface
  1620. Volume.prototype.mkdirpSync = function (path, mode) {
  1621. return this.mkdirSync(path, { mode: mode, recursive: true });
  1622. };
  1623. Volume.prototype.mkdirp = function (path, a, b) {
  1624. var mode = typeof a === 'function' ? undefined : a;
  1625. var callback = validateCallback(typeof a === 'function' ? a : b);
  1626. this.mkdir(path, { mode: mode, recursive: true }, callback);
  1627. };
  1628. Volume.prototype.mkdtempBase = function (prefix, encoding, retry) {
  1629. if (retry === void 0) { retry = 5; }
  1630. var filename = prefix + this.genRndStr();
  1631. try {
  1632. this.mkdirBase(filename, 511 /* MODE.DIR */);
  1633. return (0, encoding_1.strToEncoding)(filename, encoding);
  1634. }
  1635. catch (err) {
  1636. if (err.code === EEXIST) {
  1637. if (retry > 1)
  1638. return this.mkdtempBase(prefix, encoding, retry - 1);
  1639. else
  1640. throw Error('Could not create temp dir.');
  1641. }
  1642. else
  1643. throw err;
  1644. }
  1645. };
  1646. Volume.prototype.mkdtempSync = function (prefix, options) {
  1647. var encoding = getDefaultOpts(options).encoding;
  1648. if (!prefix || typeof prefix !== 'string')
  1649. throw new TypeError('filename prefix is required');
  1650. nullCheck(prefix);
  1651. return this.mkdtempBase(prefix, encoding);
  1652. };
  1653. Volume.prototype.mkdtemp = function (prefix, a, b) {
  1654. var _a = getDefaultOptsAndCb(a, b), encoding = _a[0].encoding, callback = _a[1];
  1655. if (!prefix || typeof prefix !== 'string')
  1656. throw new TypeError('filename prefix is required');
  1657. if (!nullCheck(prefix))
  1658. return;
  1659. this.wrapAsync(this.mkdtempBase, [prefix, encoding], callback);
  1660. };
  1661. Volume.prototype.rmdirBase = function (filename, options) {
  1662. var opts = getRmdirOptions(options);
  1663. var link = this.getLinkAsDirOrThrow(filename, 'rmdir');
  1664. // Check directory is empty.
  1665. if (link.length && !opts.recursive)
  1666. throw createError(ENOTEMPTY, 'rmdir', filename);
  1667. this.deleteLink(link);
  1668. };
  1669. Volume.prototype.rmdirSync = function (path, options) {
  1670. this.rmdirBase(pathToFilename(path), options);
  1671. };
  1672. Volume.prototype.rmdir = function (path, a, b) {
  1673. var opts = getRmdirOptions(a);
  1674. var callback = validateCallback(typeof a === 'function' ? a : b);
  1675. this.wrapAsync(this.rmdirBase, [pathToFilename(path), opts], callback);
  1676. };
  1677. Volume.prototype.rmBase = function (filename, options) {
  1678. if (options === void 0) { options = {}; }
  1679. var link = this.getResolvedLink(filename);
  1680. if (!link) {
  1681. // "stat" is used to match Node's native error message.
  1682. if (!options.force)
  1683. throw createError(ENOENT, 'stat', filename);
  1684. return;
  1685. }
  1686. if (link.getNode().isDirectory()) {
  1687. if (!options.recursive) {
  1688. throw createError(ERR_FS_EISDIR, 'rm', filename);
  1689. }
  1690. }
  1691. this.deleteLink(link);
  1692. };
  1693. Volume.prototype.rmSync = function (path, options) {
  1694. this.rmBase(pathToFilename(path), options);
  1695. };
  1696. Volume.prototype.rm = function (path, a, b) {
  1697. var _a = getRmOptsAndCb(a, b), opts = _a[0], callback = _a[1];
  1698. this.wrapAsync(this.rmBase, [pathToFilename(path), opts], callback);
  1699. };
  1700. Volume.prototype.fchmodBase = function (fd, modeNum) {
  1701. var file = this.getFileByFdOrThrow(fd, 'fchmod');
  1702. file.chmod(modeNum);
  1703. };
  1704. Volume.prototype.fchmodSync = function (fd, mode) {
  1705. this.fchmodBase(fd, modeToNumber(mode));
  1706. };
  1707. Volume.prototype.fchmod = function (fd, mode, callback) {
  1708. this.wrapAsync(this.fchmodBase, [fd, modeToNumber(mode)], callback);
  1709. };
  1710. Volume.prototype.chmodBase = function (filename, modeNum) {
  1711. var fd = this.openSync(filename, 'r');
  1712. try {
  1713. this.fchmodBase(fd, modeNum);
  1714. }
  1715. finally {
  1716. this.closeSync(fd);
  1717. }
  1718. };
  1719. Volume.prototype.chmodSync = function (path, mode) {
  1720. var modeNum = modeToNumber(mode);
  1721. var filename = pathToFilename(path);
  1722. this.chmodBase(filename, modeNum);
  1723. };
  1724. Volume.prototype.chmod = function (path, mode, callback) {
  1725. var modeNum = modeToNumber(mode);
  1726. var filename = pathToFilename(path);
  1727. this.wrapAsync(this.chmodBase, [filename, modeNum], callback);
  1728. };
  1729. Volume.prototype.lchmodBase = function (filename, modeNum) {
  1730. var fd = this.openBase(filename, O_RDWR, 0, false);
  1731. try {
  1732. this.fchmodBase(fd, modeNum);
  1733. }
  1734. finally {
  1735. this.closeSync(fd);
  1736. }
  1737. };
  1738. Volume.prototype.lchmodSync = function (path, mode) {
  1739. var modeNum = modeToNumber(mode);
  1740. var filename = pathToFilename(path);
  1741. this.lchmodBase(filename, modeNum);
  1742. };
  1743. Volume.prototype.lchmod = function (path, mode, callback) {
  1744. var modeNum = modeToNumber(mode);
  1745. var filename = pathToFilename(path);
  1746. this.wrapAsync(this.lchmodBase, [filename, modeNum], callback);
  1747. };
  1748. Volume.prototype.fchownBase = function (fd, uid, gid) {
  1749. this.getFileByFdOrThrow(fd, 'fchown').chown(uid, gid);
  1750. };
  1751. Volume.prototype.fchownSync = function (fd, uid, gid) {
  1752. validateUid(uid);
  1753. validateGid(gid);
  1754. this.fchownBase(fd, uid, gid);
  1755. };
  1756. Volume.prototype.fchown = function (fd, uid, gid, callback) {
  1757. validateUid(uid);
  1758. validateGid(gid);
  1759. this.wrapAsync(this.fchownBase, [fd, uid, gid], callback);
  1760. };
  1761. Volume.prototype.chownBase = function (filename, uid, gid) {
  1762. var link = this.getResolvedLinkOrThrow(filename, 'chown');
  1763. var node = link.getNode();
  1764. node.chown(uid, gid);
  1765. // if(node.isFile() || node.isSymlink()) {
  1766. //
  1767. // } else if(node.isDirectory()) {
  1768. //
  1769. // } else {
  1770. // TODO: What do we do here?
  1771. // }
  1772. };
  1773. Volume.prototype.chownSync = function (path, uid, gid) {
  1774. validateUid(uid);
  1775. validateGid(gid);
  1776. this.chownBase(pathToFilename(path), uid, gid);
  1777. };
  1778. Volume.prototype.chown = function (path, uid, gid, callback) {
  1779. validateUid(uid);
  1780. validateGid(gid);
  1781. this.wrapAsync(this.chownBase, [pathToFilename(path), uid, gid], callback);
  1782. };
  1783. Volume.prototype.lchownBase = function (filename, uid, gid) {
  1784. this.getLinkOrThrow(filename, 'lchown').getNode().chown(uid, gid);
  1785. };
  1786. Volume.prototype.lchownSync = function (path, uid, gid) {
  1787. validateUid(uid);
  1788. validateGid(gid);
  1789. this.lchownBase(pathToFilename(path), uid, gid);
  1790. };
  1791. Volume.prototype.lchown = function (path, uid, gid, callback) {
  1792. validateUid(uid);
  1793. validateGid(gid);
  1794. this.wrapAsync(this.lchownBase, [pathToFilename(path), uid, gid], callback);
  1795. };
  1796. Volume.prototype.watchFile = function (path, a, b) {
  1797. var filename = pathToFilename(path);
  1798. var options = a;
  1799. var listener = b;
  1800. if (typeof options === 'function') {
  1801. listener = a;
  1802. options = null;
  1803. }
  1804. if (typeof listener !== 'function') {
  1805. throw Error('"watchFile()" requires a listener function');
  1806. }
  1807. var interval = 5007;
  1808. var persistent = true;
  1809. if (options && typeof options === 'object') {
  1810. if (typeof options.interval === 'number')
  1811. interval = options.interval;
  1812. if (typeof options.persistent === 'boolean')
  1813. persistent = options.persistent;
  1814. }
  1815. var watcher = this.statWatchers[filename];
  1816. if (!watcher) {
  1817. watcher = new this.StatWatcher();
  1818. watcher.start(filename, persistent, interval);
  1819. this.statWatchers[filename] = watcher;
  1820. }
  1821. watcher.addListener('change', listener);
  1822. return watcher;
  1823. };
  1824. Volume.prototype.unwatchFile = function (path, listener) {
  1825. var filename = pathToFilename(path);
  1826. var watcher = this.statWatchers[filename];
  1827. if (!watcher)
  1828. return;
  1829. if (typeof listener === 'function') {
  1830. watcher.removeListener('change', listener);
  1831. }
  1832. else {
  1833. watcher.removeAllListeners('change');
  1834. }
  1835. if (watcher.listenerCount('change') === 0) {
  1836. watcher.stop();
  1837. delete this.statWatchers[filename];
  1838. }
  1839. };
  1840. Volume.prototype.createReadStream = function (path, options) {
  1841. return new this.ReadStream(path, options);
  1842. };
  1843. Volume.prototype.createWriteStream = function (path, options) {
  1844. return new this.WriteStream(path, options);
  1845. };
  1846. // watch(path: PathLike): FSWatcher;
  1847. // watch(path: PathLike, options?: IWatchOptions | string): FSWatcher;
  1848. Volume.prototype.watch = function (path, options, listener) {
  1849. var filename = pathToFilename(path);
  1850. var givenOptions = options;
  1851. if (typeof options === 'function') {
  1852. listener = options;
  1853. givenOptions = null;
  1854. }
  1855. // tslint:disable-next-line prefer-const
  1856. var _a = getDefaultOpts(givenOptions), persistent = _a.persistent, recursive = _a.recursive, encoding = _a.encoding;
  1857. if (persistent === undefined)
  1858. persistent = true;
  1859. if (recursive === undefined)
  1860. recursive = false;
  1861. var watcher = new this.FSWatcher();
  1862. watcher.start(filename, persistent, recursive, encoding);
  1863. if (listener) {
  1864. watcher.addListener('change', listener);
  1865. }
  1866. return watcher;
  1867. };
  1868. /**
  1869. * Global file descriptor counter. UNIX file descriptors start from 0 and go sequentially
  1870. * up, so here, in order not to conflict with them, we choose some big number and descrease
  1871. * the file descriptor of every new opened file.
  1872. * @type {number}
  1873. * @todo This should not be static, right?
  1874. */
  1875. Volume.fd = 0x7fffffff;
  1876. return Volume;
  1877. }());
  1878. exports.Volume = Volume;
  1879. function emitStop(self) {
  1880. self.emit('stop');
  1881. }
  1882. var StatWatcher = /** @class */ (function (_super) {
  1883. __extends(StatWatcher, _super);
  1884. function StatWatcher(vol) {
  1885. var _this = _super.call(this) || this;
  1886. _this.onInterval = function () {
  1887. try {
  1888. var stats = _this.vol.statSync(_this.filename);
  1889. if (_this.hasChanged(stats)) {
  1890. _this.emit('change', stats, _this.prev);
  1891. _this.prev = stats;
  1892. }
  1893. }
  1894. finally {
  1895. _this.loop();
  1896. }
  1897. };
  1898. _this.vol = vol;
  1899. return _this;
  1900. }
  1901. StatWatcher.prototype.loop = function () {
  1902. this.timeoutRef = this.setTimeout(this.onInterval, this.interval);
  1903. };
  1904. StatWatcher.prototype.hasChanged = function (stats) {
  1905. // if(!this.prev) return false;
  1906. if (stats.mtimeMs > this.prev.mtimeMs)
  1907. return true;
  1908. if (stats.nlink !== this.prev.nlink)
  1909. return true;
  1910. return false;
  1911. };
  1912. StatWatcher.prototype.start = function (path, persistent, interval) {
  1913. if (persistent === void 0) { persistent = true; }
  1914. if (interval === void 0) { interval = 5007; }
  1915. this.filename = pathToFilename(path);
  1916. this.setTimeout = persistent
  1917. ? setTimeout.bind(typeof globalThis !== 'undefined' ? globalThis : global)
  1918. : setTimeoutUnref_1.default;
  1919. this.interval = interval;
  1920. this.prev = this.vol.statSync(this.filename);
  1921. this.loop();
  1922. };
  1923. StatWatcher.prototype.stop = function () {
  1924. clearTimeout(this.timeoutRef);
  1925. process_1.default.nextTick(emitStop, this);
  1926. };
  1927. return StatWatcher;
  1928. }(events_1.EventEmitter));
  1929. exports.StatWatcher = StatWatcher;
  1930. var pool;
  1931. function allocNewPool(poolSize) {
  1932. pool = (0, buffer_1.bufferAllocUnsafe)(poolSize);
  1933. pool.used = 0;
  1934. }
  1935. util.inherits(FsReadStream, stream_1.Readable);
  1936. exports.ReadStream = FsReadStream;
  1937. function FsReadStream(vol, path, options) {
  1938. if (!(this instanceof FsReadStream))
  1939. return new FsReadStream(vol, path, options);
  1940. this._vol = vol;
  1941. // a little bit bigger buffer and water marks by default
  1942. options = Object.assign({}, getOptions(options, {}));
  1943. if (options.highWaterMark === undefined)
  1944. options.highWaterMark = 64 * 1024;
  1945. stream_1.Readable.call(this, options);
  1946. this.path = pathToFilename(path);
  1947. this.fd = options.fd === undefined ? null : options.fd;
  1948. this.flags = options.flags === undefined ? 'r' : options.flags;
  1949. this.mode = options.mode === undefined ? 438 : options.mode;
  1950. this.start = options.start;
  1951. this.end = options.end;
  1952. this.autoClose = options.autoClose === undefined ? true : options.autoClose;
  1953. this.pos = undefined;
  1954. this.bytesRead = 0;
  1955. if (this.start !== undefined) {
  1956. if (typeof this.start !== 'number') {
  1957. throw new TypeError('"start" option must be a Number');
  1958. }
  1959. if (this.end === undefined) {
  1960. this.end = Infinity;
  1961. }
  1962. else if (typeof this.end !== 'number') {
  1963. throw new TypeError('"end" option must be a Number');
  1964. }
  1965. if (this.start > this.end) {
  1966. throw new Error('"start" option must be <= "end" option');
  1967. }
  1968. this.pos = this.start;
  1969. }
  1970. if (typeof this.fd !== 'number')
  1971. this.open();
  1972. this.on('end', function () {
  1973. if (this.autoClose) {
  1974. if (this.destroy)
  1975. this.destroy();
  1976. }
  1977. });
  1978. }
  1979. FsReadStream.prototype.open = function () {
  1980. var self = this; // tslint:disable-line no-this-assignment
  1981. this._vol.open(this.path, this.flags, this.mode, function (er, fd) {
  1982. if (er) {
  1983. if (self.autoClose) {
  1984. if (self.destroy)
  1985. self.destroy();
  1986. }
  1987. self.emit('error', er);
  1988. return;
  1989. }
  1990. self.fd = fd;
  1991. self.emit('open', fd);
  1992. // start the flow of data.
  1993. self.read();
  1994. });
  1995. };
  1996. FsReadStream.prototype._read = function (n) {
  1997. if (typeof this.fd !== 'number') {
  1998. return this.once('open', function () {
  1999. this._read(n);
  2000. });
  2001. }
  2002. if (this.destroyed)
  2003. return;
  2004. if (!pool || pool.length - pool.used < kMinPoolSpace) {
  2005. // discard the old pool.
  2006. allocNewPool(this._readableState.highWaterMark);
  2007. }
  2008. // Grab another reference to the pool in the case that while we're
  2009. // in the thread pool another read() finishes up the pool, and
  2010. // allocates a new one.
  2011. var thisPool = pool;
  2012. var toRead = Math.min(pool.length - pool.used, n);
  2013. var start = pool.used;
  2014. if (this.pos !== undefined)
  2015. toRead = Math.min(this.end - this.pos + 1, toRead);
  2016. // already read everything we were supposed to read!
  2017. // treat as EOF.
  2018. if (toRead <= 0)
  2019. return this.push(null);
  2020. // the actual read.
  2021. var self = this; // tslint:disable-line no-this-assignment
  2022. this._vol.read(this.fd, pool, pool.used, toRead, this.pos, onread);
  2023. // move the pool positions, and internal position for reading.
  2024. if (this.pos !== undefined)
  2025. this.pos += toRead;
  2026. pool.used += toRead;
  2027. function onread(er, bytesRead) {
  2028. if (er) {
  2029. if (self.autoClose && self.destroy) {
  2030. self.destroy();
  2031. }
  2032. self.emit('error', er);
  2033. }
  2034. else {
  2035. var b = null;
  2036. if (bytesRead > 0) {
  2037. self.bytesRead += bytesRead;
  2038. b = thisPool.slice(start, start + bytesRead);
  2039. }
  2040. self.push(b);
  2041. }
  2042. }
  2043. };
  2044. FsReadStream.prototype._destroy = function (err, cb) {
  2045. this.close(function (err2) {
  2046. cb(err || err2);
  2047. });
  2048. };
  2049. FsReadStream.prototype.close = function (cb) {
  2050. var _this = this;
  2051. var _a;
  2052. if (cb)
  2053. this.once('close', cb);
  2054. if (this.closed || typeof this.fd !== 'number') {
  2055. if (typeof this.fd !== 'number') {
  2056. this.once('open', closeOnOpen);
  2057. return;
  2058. }
  2059. return process_1.default.nextTick(function () { return _this.emit('close'); });
  2060. }
  2061. // Since Node 18, there is only a getter for '.closed'.
  2062. // The first branch mimics other setters from Readable.
  2063. // See https://github.com/nodejs/node/blob/v18.0.0/lib/internal/streams/readable.js#L1243
  2064. if (typeof ((_a = this._readableState) === null || _a === void 0 ? void 0 : _a.closed) === 'boolean') {
  2065. this._readableState.closed = true;
  2066. }
  2067. else {
  2068. this.closed = true;
  2069. }
  2070. this._vol.close(this.fd, function (er) {
  2071. if (er)
  2072. _this.emit('error', er);
  2073. else
  2074. _this.emit('close');
  2075. });
  2076. this.fd = null;
  2077. };
  2078. // needed because as it will be called with arguments
  2079. // that does not match this.close() signature
  2080. function closeOnOpen(fd) {
  2081. this.close();
  2082. }
  2083. util.inherits(FsWriteStream, stream_1.Writable);
  2084. exports.WriteStream = FsWriteStream;
  2085. function FsWriteStream(vol, path, options) {
  2086. if (!(this instanceof FsWriteStream))
  2087. return new FsWriteStream(vol, path, options);
  2088. this._vol = vol;
  2089. options = Object.assign({}, getOptions(options, {}));
  2090. stream_1.Writable.call(this, options);
  2091. this.path = pathToFilename(path);
  2092. this.fd = options.fd === undefined ? null : options.fd;
  2093. this.flags = options.flags === undefined ? 'w' : options.flags;
  2094. this.mode = options.mode === undefined ? 438 : options.mode;
  2095. this.start = options.start;
  2096. this.autoClose = options.autoClose === undefined ? true : !!options.autoClose;
  2097. this.pos = undefined;
  2098. this.bytesWritten = 0;
  2099. if (this.start !== undefined) {
  2100. if (typeof this.start !== 'number') {
  2101. throw new TypeError('"start" option must be a Number');
  2102. }
  2103. if (this.start < 0) {
  2104. throw new Error('"start" must be >= zero');
  2105. }
  2106. this.pos = this.start;
  2107. }
  2108. if (options.encoding)
  2109. this.setDefaultEncoding(options.encoding);
  2110. if (typeof this.fd !== 'number')
  2111. this.open();
  2112. // dispose on finish.
  2113. this.once('finish', function () {
  2114. if (this.autoClose) {
  2115. this.close();
  2116. }
  2117. });
  2118. }
  2119. FsWriteStream.prototype.open = function () {
  2120. this._vol.open(this.path, this.flags, this.mode, function (er, fd) {
  2121. if (er) {
  2122. if (this.autoClose && this.destroy) {
  2123. this.destroy();
  2124. }
  2125. this.emit('error', er);
  2126. return;
  2127. }
  2128. this.fd = fd;
  2129. this.emit('open', fd);
  2130. }.bind(this));
  2131. };
  2132. FsWriteStream.prototype._write = function (data, encoding, cb) {
  2133. if (!(data instanceof buffer_1.Buffer || data instanceof Uint8Array))
  2134. return this.emit('error', new Error('Invalid data'));
  2135. if (typeof this.fd !== 'number') {
  2136. return this.once('open', function () {
  2137. this._write(data, encoding, cb);
  2138. });
  2139. }
  2140. var self = this; // tslint:disable-line no-this-assignment
  2141. this._vol.write(this.fd, data, 0, data.length, this.pos, function (er, bytes) {
  2142. if (er) {
  2143. if (self.autoClose && self.destroy) {
  2144. self.destroy();
  2145. }
  2146. return cb(er);
  2147. }
  2148. self.bytesWritten += bytes;
  2149. cb();
  2150. });
  2151. if (this.pos !== undefined)
  2152. this.pos += data.length;
  2153. };
  2154. FsWriteStream.prototype._writev = function (data, cb) {
  2155. if (typeof this.fd !== 'number') {
  2156. return this.once('open', function () {
  2157. this._writev(data, cb);
  2158. });
  2159. }
  2160. var self = this; // tslint:disable-line no-this-assignment
  2161. var len = data.length;
  2162. var chunks = new Array(len);
  2163. var size = 0;
  2164. for (var i = 0; i < len; i++) {
  2165. var chunk = data[i].chunk;
  2166. chunks[i] = chunk;
  2167. size += chunk.length;
  2168. }
  2169. var buf = buffer_1.Buffer.concat(chunks);
  2170. this._vol.write(this.fd, buf, 0, buf.length, this.pos, function (er, bytes) {
  2171. if (er) {
  2172. if (self.destroy)
  2173. self.destroy();
  2174. return cb(er);
  2175. }
  2176. self.bytesWritten += bytes;
  2177. cb();
  2178. });
  2179. if (this.pos !== undefined)
  2180. this.pos += size;
  2181. };
  2182. FsWriteStream.prototype.close = function (cb) {
  2183. var _this = this;
  2184. var _a;
  2185. if (cb)
  2186. this.once('close', cb);
  2187. if (this.closed || typeof this.fd !== 'number') {
  2188. if (typeof this.fd !== 'number') {
  2189. this.once('open', closeOnOpen);
  2190. return;
  2191. }
  2192. return process_1.default.nextTick(function () { return _this.emit('close'); });
  2193. }
  2194. // Since Node 18, there is only a getter for '.closed'.
  2195. // The first branch mimics other setters from Writable.
  2196. // See https://github.com/nodejs/node/blob/v18.0.0/lib/internal/streams/writable.js#L766
  2197. if (typeof ((_a = this._writableState) === null || _a === void 0 ? void 0 : _a.closed) === 'boolean') {
  2198. this._writableState.closed = true;
  2199. }
  2200. else {
  2201. this.closed = true;
  2202. }
  2203. this._vol.close(this.fd, function (er) {
  2204. if (er)
  2205. _this.emit('error', er);
  2206. else
  2207. _this.emit('close');
  2208. });
  2209. this.fd = null;
  2210. };
  2211. FsWriteStream.prototype._destroy = FsReadStream.prototype._destroy;
  2212. // There is no shutdown() for files.
  2213. FsWriteStream.prototype.destroySoon = FsWriteStream.prototype.end;
  2214. // ---------------------------------------- FSWatcher
  2215. var FSWatcher = /** @class */ (function (_super) {
  2216. __extends(FSWatcher, _super);
  2217. function FSWatcher(vol) {
  2218. var _this = _super.call(this) || this;
  2219. _this._filename = '';
  2220. _this._filenameEncoded = '';
  2221. // _persistent: boolean = true;
  2222. _this._recursive = false;
  2223. _this._encoding = encoding_1.ENCODING_UTF8;
  2224. // inode -> removers
  2225. _this._listenerRemovers = new Map();
  2226. _this._onParentChild = function (link) {
  2227. if (link.getName() === _this._getName()) {
  2228. _this._emit('rename');
  2229. }
  2230. };
  2231. _this._emit = function (type) {
  2232. _this.emit('change', type, _this._filenameEncoded);
  2233. };
  2234. _this._persist = function () {
  2235. _this._timer = setTimeout(_this._persist, 1e6);
  2236. };
  2237. _this._vol = vol;
  2238. return _this;
  2239. // TODO: Emit "error" messages when watching.
  2240. // this._handle.onchange = function(status, eventType, filename) {
  2241. // if (status < 0) {
  2242. // self._handle.close();
  2243. // const error = !filename ?
  2244. // errnoException(status, 'Error watching file for changes:') :
  2245. // errnoException(status, `Error watching file ${filename} for changes:`);
  2246. // error.filename = filename;
  2247. // self.emit('error', error);
  2248. // } else {
  2249. // self.emit('change', eventType, filename);
  2250. // }
  2251. // };
  2252. }
  2253. FSWatcher.prototype._getName = function () {
  2254. return this._steps[this._steps.length - 1];
  2255. };
  2256. FSWatcher.prototype.start = function (path, persistent, recursive, encoding) {
  2257. var _this = this;
  2258. if (persistent === void 0) { persistent = true; }
  2259. if (recursive === void 0) { recursive = false; }
  2260. if (encoding === void 0) { encoding = encoding_1.ENCODING_UTF8; }
  2261. this._filename = pathToFilename(path);
  2262. this._steps = filenameToSteps(this._filename);
  2263. this._filenameEncoded = (0, encoding_1.strToEncoding)(this._filename);
  2264. // this._persistent = persistent;
  2265. this._recursive = recursive;
  2266. this._encoding = encoding;
  2267. try {
  2268. this._link = this._vol.getLinkOrThrow(this._filename, 'FSWatcher');
  2269. }
  2270. catch (err) {
  2271. var error = new Error("watch ".concat(this._filename, " ").concat(err.code));
  2272. error.code = err.code;
  2273. error.errno = err.code;
  2274. throw error;
  2275. }
  2276. var watchLinkNodeChanged = function (link) {
  2277. var _a;
  2278. var filepath = link.getPath();
  2279. var node = link.getNode();
  2280. var onNodeChange = function () {
  2281. var filename = relative(_this._filename, filepath);
  2282. if (!filename) {
  2283. filename = _this._getName();
  2284. }
  2285. return _this.emit('change', 'change', filename);
  2286. };
  2287. node.on('change', onNodeChange);
  2288. var removers = (_a = _this._listenerRemovers.get(node.ino)) !== null && _a !== void 0 ? _a : [];
  2289. removers.push(function () { return node.removeListener('change', onNodeChange); });
  2290. _this._listenerRemovers.set(node.ino, removers);
  2291. };
  2292. var watchLinkChildrenChanged = function (link) {
  2293. var _a;
  2294. var node = link.getNode();
  2295. // when a new link added
  2296. var onLinkChildAdd = function (l) {
  2297. _this.emit('change', 'rename', relative(_this._filename, l.getPath()));
  2298. setTimeout(function () {
  2299. // 1. watch changes of the new link-node
  2300. watchLinkNodeChanged(l);
  2301. // 2. watch changes of the new link-node's children
  2302. watchLinkChildrenChanged(l);
  2303. });
  2304. };
  2305. // when a new link deleted
  2306. var onLinkChildDelete = function (l) {
  2307. // remove the listeners of the children nodes
  2308. var removeLinkNodeListeners = function (curLink) {
  2309. var ino = curLink.getNode().ino;
  2310. var removers = _this._listenerRemovers.get(ino);
  2311. if (removers) {
  2312. removers.forEach(function (r) { return r(); });
  2313. _this._listenerRemovers.delete(ino);
  2314. }
  2315. Object.values(curLink.children).forEach(function (childLink) {
  2316. if (childLink) {
  2317. removeLinkNodeListeners(childLink);
  2318. }
  2319. });
  2320. };
  2321. removeLinkNodeListeners(l);
  2322. _this.emit('change', 'rename', relative(_this._filename, l.getPath()));
  2323. };
  2324. // children nodes changed
  2325. Object.entries(link.children).forEach(function (_a) {
  2326. var name = _a[0], childLink = _a[1];
  2327. if (childLink && name !== '.' && name !== '..') {
  2328. watchLinkNodeChanged(childLink);
  2329. }
  2330. });
  2331. // link children add/remove
  2332. link.on('child:add', onLinkChildAdd);
  2333. link.on('child:delete', onLinkChildDelete);
  2334. var removers = (_a = _this._listenerRemovers.get(node.ino)) !== null && _a !== void 0 ? _a : [];
  2335. removers.push(function () {
  2336. link.removeListener('child:add', onLinkChildAdd);
  2337. link.removeListener('child:delete', onLinkChildDelete);
  2338. });
  2339. if (recursive) {
  2340. Object.entries(link.children).forEach(function (_a) {
  2341. var name = _a[0], childLink = _a[1];
  2342. if (childLink && name !== '.' && name !== '..') {
  2343. watchLinkChildrenChanged(childLink);
  2344. }
  2345. });
  2346. }
  2347. };
  2348. watchLinkNodeChanged(this._link);
  2349. watchLinkChildrenChanged(this._link);
  2350. var parent = this._link.parent;
  2351. if (parent) {
  2352. // parent.on('child:add', this._onParentChild);
  2353. parent.setMaxListeners(parent.getMaxListeners() + 1);
  2354. parent.on('child:delete', this._onParentChild);
  2355. }
  2356. if (persistent)
  2357. this._persist();
  2358. };
  2359. FSWatcher.prototype.close = function () {
  2360. clearTimeout(this._timer);
  2361. this._listenerRemovers.forEach(function (removers) {
  2362. removers.forEach(function (r) { return r(); });
  2363. });
  2364. this._listenerRemovers.clear();
  2365. var parent = this._link.parent;
  2366. if (parent) {
  2367. // parent.removeListener('child:add', this._onParentChild);
  2368. parent.removeListener('child:delete', this._onParentChild);
  2369. }
  2370. };
  2371. return FSWatcher;
  2372. }(events_1.EventEmitter));
  2373. exports.FSWatcher = FSWatcher;