volume.js 86 KB

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