util.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.getWriteSyncArgs = exports.getWriteArgs = exports.bufToUint8 = void 0;
  4. exports.promisify = promisify;
  5. exports.validateCallback = validateCallback;
  6. exports.modeToNumber = modeToNumber;
  7. exports.nullCheck = nullCheck;
  8. exports.pathToFilename = pathToFilename;
  9. exports.createError = createError;
  10. exports.createStatError = createStatError;
  11. exports.genRndStr6 = genRndStr6;
  12. exports.flagsToNumber = flagsToNumber;
  13. exports.streamToBuffer = streamToBuffer;
  14. exports.bufferToEncoding = bufferToEncoding;
  15. exports.isReadableStream = isReadableStream;
  16. const fs_node_utils_1 = require("@jsonjoy.com/fs-node-utils");
  17. const errors = require("@jsonjoy.com/fs-node-builtins/lib/internal/errors");
  18. const buffer_1 = require("@jsonjoy.com/fs-node-builtins/lib/internal/buffer");
  19. const fs_core_1 = require("@jsonjoy.com/fs-core");
  20. const util_1 = require("@jsonjoy.com/fs-core/lib/util");
  21. function promisify(fs, fn, getResult = input => input) {
  22. return (...args) => new Promise((resolve, reject) => {
  23. fs[fn].bind(fs)(...args, (error, result) => {
  24. if (error)
  25. return reject(error);
  26. return resolve(getResult(result));
  27. });
  28. });
  29. }
  30. function validateCallback(callback) {
  31. if (typeof callback !== 'function')
  32. throw TypeError(fs_node_utils_1.ERRSTR.CB);
  33. return callback;
  34. }
  35. function _modeToNumber(mode, def) {
  36. if (typeof mode === 'number')
  37. return mode;
  38. if (typeof mode === 'string')
  39. return parseInt(mode, 8);
  40. if (def)
  41. return modeToNumber(def);
  42. return undefined;
  43. }
  44. function modeToNumber(mode, def) {
  45. const result = _modeToNumber(mode, def);
  46. if (typeof result !== 'number' || isNaN(result))
  47. throw new TypeError(fs_node_utils_1.ERRSTR.MODE_INT);
  48. return result;
  49. }
  50. function nullCheck(path, callback) {
  51. if (('' + path).indexOf('\u0000') !== -1) {
  52. const er = new Error('Path must be a string without null bytes');
  53. er.code = 'ENOENT';
  54. if (typeof callback !== 'function')
  55. throw er;
  56. queueMicrotask(() => {
  57. callback(er);
  58. });
  59. return false;
  60. }
  61. return true;
  62. }
  63. function getPathFromURLPosix(url) {
  64. if (url.hostname !== '') {
  65. throw new errors.TypeError('ERR_INVALID_FILE_URL_HOST', process.platform);
  66. }
  67. const pathname = url.pathname;
  68. for (let n = 0; n < pathname.length; n++) {
  69. if (pathname[n] === '%') {
  70. const third = pathname.codePointAt(n + 2) | 0x20;
  71. if (pathname[n + 1] === '2' && third === 102) {
  72. throw new errors.TypeError('ERR_INVALID_FILE_URL_PATH', 'must not include encoded / characters');
  73. }
  74. }
  75. }
  76. const filepath = decodeURIComponent(pathname);
  77. // On Windows `pathToFileURL` puts a slash before the drive letter
  78. // (`file:///C:/dir` -> pathname `/C:/dir`) and `fileURLToPath` strips it back
  79. // off. On POSIX Node keeps the slash, so `/C:/dir` stays absolute there —
  80. // stripping it unconditionally would make the path cwd-relative instead.
  81. return util_1.isWin ? filepath.replace(/^\/([a-zA-Z]:)/, '$1') : filepath;
  82. }
  83. function pathToFilename(path) {
  84. if (path instanceof Uint8Array) {
  85. path = (0, buffer_1.bufferFrom)(path);
  86. }
  87. if (typeof path !== 'string' && !buffer_1.Buffer.isBuffer(path)) {
  88. try {
  89. if (!(path instanceof require('url').URL))
  90. throw new TypeError(fs_node_utils_1.ERRSTR.PATH_STR);
  91. }
  92. catch (err) {
  93. throw new TypeError(fs_node_utils_1.ERRSTR.PATH_STR);
  94. }
  95. path = getPathFromURLPosix(path);
  96. }
  97. const pathString = String(path);
  98. nullCheck(pathString);
  99. // return slash(pathString);
  100. return pathString;
  101. }
  102. const ENOENT = 'ENOENT';
  103. const EBADF = 'EBADF';
  104. const EINVAL = 'EINVAL';
  105. const EPERM = 'EPERM';
  106. const EPROTO = 'EPROTO';
  107. const EEXIST = 'EEXIST';
  108. const ENOTDIR = 'ENOTDIR';
  109. const EMFILE = 'EMFILE';
  110. const EACCES = 'EACCES';
  111. const EISDIR = 'EISDIR';
  112. const ENOTEMPTY = 'ENOTEMPTY';
  113. const ENOSYS = 'ENOSYS';
  114. const ERR_FS_EISDIR = 'ERR_FS_EISDIR';
  115. const ERR_OUT_OF_RANGE = 'ERR_OUT_OF_RANGE';
  116. function formatError(errorCode, func = '', path = '', path2 = '') {
  117. let pathFormatted = '';
  118. if (path)
  119. pathFormatted = ` '${path}'`;
  120. if (path2)
  121. pathFormatted += ` -> '${path2}'`;
  122. switch (errorCode) {
  123. case ENOENT:
  124. return `ENOENT: no such file or directory, ${func}${pathFormatted}`;
  125. case EBADF:
  126. return `EBADF: bad file descriptor, ${func}${pathFormatted}`;
  127. case EINVAL:
  128. return `EINVAL: invalid argument, ${func}${pathFormatted}`;
  129. case EPERM:
  130. return `EPERM: operation not permitted, ${func}${pathFormatted}`;
  131. case EPROTO:
  132. return `EPROTO: protocol error, ${func}${pathFormatted}`;
  133. case EEXIST:
  134. return `EEXIST: file already exists, ${func}${pathFormatted}`;
  135. case ENOTDIR:
  136. return `ENOTDIR: not a directory, ${func}${pathFormatted}`;
  137. case EISDIR:
  138. return `EISDIR: illegal operation on a directory, ${func}${pathFormatted}`;
  139. case EACCES:
  140. return `EACCES: permission denied, ${func}${pathFormatted}`;
  141. case ENOTEMPTY:
  142. return `ENOTEMPTY: directory not empty, ${func}${pathFormatted}`;
  143. case EMFILE:
  144. return `EMFILE: too many open files, ${func}${pathFormatted}`;
  145. case ENOSYS:
  146. return `ENOSYS: function not implemented, ${func}${pathFormatted}`;
  147. case ERR_FS_EISDIR:
  148. return `[ERR_FS_EISDIR]: Path is a directory: ${func} returned EISDIR (is a directory) ${path}`;
  149. case ERR_OUT_OF_RANGE:
  150. return `[ERR_OUT_OF_RANGE]: value out of range, ${func}${pathFormatted}`;
  151. default:
  152. return `${errorCode}: error occurred, ${func}${pathFormatted}`;
  153. }
  154. }
  155. function createError(errorCode, func = '', path = '', path2 = '', Constructor = Error) {
  156. const error = new Constructor(formatError(errorCode, func, path, path2));
  157. error.code = errorCode;
  158. if (path) {
  159. error.path = path;
  160. }
  161. return error;
  162. }
  163. function createStatError(errorCode, func = '', path = '', path2 = '') {
  164. return {
  165. code: errorCode,
  166. message: formatError(errorCode, func, path, path2),
  167. path,
  168. toError() {
  169. const error = new Error(this.message);
  170. error.code = this.code;
  171. if (this.path) {
  172. error.path = this.path;
  173. }
  174. return error;
  175. },
  176. };
  177. }
  178. function genRndStr6() {
  179. return Math.random().toString(36).slice(2, 8).padEnd(6, '0');
  180. }
  181. function flagsToNumber(flags) {
  182. if (typeof flags === 'number')
  183. return flags;
  184. if (typeof flags === 'string') {
  185. const flagsNum = fs_node_utils_1.FLAGS[flags];
  186. if (typeof flagsNum !== 'undefined')
  187. return flagsNum;
  188. }
  189. // throw new TypeError(formatError(ERRSTR_FLAG(flags)));
  190. throw new errors.TypeError('ERR_INVALID_OPT_VALUE', 'flags', flags);
  191. }
  192. function streamToBuffer(stream) {
  193. const chunks = [];
  194. return new Promise((resolve, reject) => {
  195. stream.on('data', chunk => chunks.push(chunk));
  196. stream.on('end', () => resolve(buffer_1.Buffer.concat(chunks)));
  197. stream.on('error', reject);
  198. });
  199. }
  200. const bufToUint8 = (buf) => new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
  201. exports.bufToUint8 = bufToUint8;
  202. const getWriteArgs = (fd, a, b, c, d, e) => {
  203. (0, fs_core_1.validateFd)(fd);
  204. let offset = 0;
  205. let length;
  206. let position = null;
  207. let encoding;
  208. let callback;
  209. const tipa = typeof a;
  210. const tipb = typeof b;
  211. const tipc = typeof c;
  212. const tipd = typeof d;
  213. if (tipa !== 'string') {
  214. if (tipb === 'function') {
  215. callback = b;
  216. }
  217. else if (tipc === 'function') {
  218. offset = b | 0;
  219. callback = c;
  220. }
  221. else if (tipd === 'function') {
  222. offset = b | 0;
  223. length = c;
  224. callback = d;
  225. }
  226. else {
  227. offset = b | 0;
  228. length = c;
  229. position = d;
  230. callback = e;
  231. }
  232. }
  233. else {
  234. if (tipb === 'function') {
  235. callback = b;
  236. }
  237. else if (tipc === 'function') {
  238. position = b;
  239. callback = c;
  240. }
  241. else if (tipd === 'function') {
  242. position = b;
  243. encoding = c;
  244. callback = d;
  245. }
  246. }
  247. const buf = (0, fs_core_1.dataToBuffer)(a, encoding);
  248. if (tipa !== 'string') {
  249. if (typeof length === 'undefined')
  250. length = buf.length;
  251. }
  252. else {
  253. offset = 0;
  254. length = buf.length;
  255. }
  256. const cb = validateCallback(callback);
  257. return [fd, tipa === 'string', buf, offset, length, position, cb];
  258. };
  259. exports.getWriteArgs = getWriteArgs;
  260. const getWriteSyncArgs = (fd, a, b, c, d) => {
  261. (0, fs_core_1.validateFd)(fd);
  262. let encoding;
  263. let offset;
  264. let length;
  265. let position;
  266. const isBuffer = typeof a !== 'string';
  267. if (isBuffer) {
  268. offset = (b || 0) | 0;
  269. length = c;
  270. position = d;
  271. }
  272. else {
  273. position = b;
  274. encoding = c;
  275. }
  276. const buf = (0, fs_core_1.dataToBuffer)(a, encoding);
  277. if (isBuffer) {
  278. if (typeof length === 'undefined') {
  279. length = buf.length;
  280. }
  281. }
  282. else {
  283. offset = 0;
  284. length = buf.length;
  285. }
  286. return [fd, buf, offset || 0, length, position];
  287. };
  288. exports.getWriteSyncArgs = getWriteSyncArgs;
  289. function bufferToEncoding(buffer, encoding) {
  290. if (!encoding || encoding === 'buffer')
  291. return buffer;
  292. else
  293. return buffer.toString(encoding);
  294. }
  295. function isReadableStream(stream) {
  296. return (stream !== null &&
  297. typeof stream === 'object' &&
  298. typeof stream.pipe === 'function' &&
  299. typeof stream.on === 'function' &&
  300. stream.readable === true);
  301. }
  302. //# sourceMappingURL=util.js.map