tar 7.5.24 → 8.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (330) hide show
  1. package/README.md +1712 -1147
  2. package/dist/commonjs/bytes.d.ts +21 -0
  3. package/dist/commonjs/bytes.d.ts.map +1 -0
  4. package/dist/commonjs/bytes.js +83 -0
  5. package/dist/commonjs/bytes.js.map +1 -0
  6. package/dist/commonjs/codec.d.ts +53 -0
  7. package/dist/commonjs/codec.d.ts.map +1 -0
  8. package/dist/commonjs/codec.js +35 -0
  9. package/dist/commonjs/codec.js.map +1 -0
  10. package/dist/commonjs/concat.d.ts +3 -0
  11. package/dist/commonjs/concat.d.ts.map +1 -0
  12. package/dist/commonjs/concat.js +20 -0
  13. package/dist/commonjs/concat.js.map +1 -0
  14. package/dist/commonjs/create.d.ts +39 -2
  15. package/dist/commonjs/create.d.ts.map +1 -1
  16. package/dist/commonjs/create.js +150 -64
  17. package/dist/commonjs/create.js.map +1 -1
  18. package/dist/commonjs/dealias.d.ts +79 -0
  19. package/dist/commonjs/dealias.d.ts.map +1 -0
  20. package/dist/commonjs/dealias.js +50 -0
  21. package/dist/commonjs/dealias.js.map +1 -0
  22. package/dist/commonjs/delete.d.ts +19 -0
  23. package/dist/commonjs/delete.d.ts.map +1 -0
  24. package/dist/commonjs/delete.js +121 -0
  25. package/dist/commonjs/delete.js.map +1 -0
  26. package/dist/commonjs/entries.d.ts +82 -0
  27. package/dist/commonjs/entries.d.ts.map +1 -0
  28. package/dist/commonjs/entries.js +398 -0
  29. package/dist/commonjs/entries.js.map +1 -0
  30. package/dist/commonjs/extract.d.ts +14 -2
  31. package/dist/commonjs/extract.d.ts.map +1 -1
  32. package/dist/commonjs/extract.js +40 -81
  33. package/dist/commonjs/extract.js.map +1 -1
  34. package/dist/commonjs/fs.d.ts +201 -0
  35. package/dist/commonjs/fs.d.ts.map +1 -0
  36. package/dist/commonjs/fs.js +5 -0
  37. package/dist/commonjs/fs.js.map +1 -0
  38. package/dist/commonjs/header.d.ts +4 -4
  39. package/dist/commonjs/header.d.ts.map +1 -1
  40. package/dist/commonjs/header.js +38 -42
  41. package/dist/commonjs/header.js.map +1 -1
  42. package/dist/commonjs/index.d.ts +25 -18
  43. package/dist/commonjs/index.d.ts.map +1 -1
  44. package/dist/commonjs/index.js +46 -18
  45. package/dist/commonjs/index.js.map +1 -1
  46. package/dist/commonjs/index.min.js +2 -3
  47. package/dist/commonjs/index.min.js.map +4 -4
  48. package/dist/commonjs/large-numbers.d.ts +2 -2
  49. package/dist/commonjs/large-numbers.d.ts.map +1 -1
  50. package/dist/commonjs/large-numbers.js +4 -4
  51. package/dist/commonjs/large-numbers.js.map +1 -1
  52. package/dist/commonjs/list.d.ts +23 -6
  53. package/dist/commonjs/list.d.ts.map +1 -1
  54. package/dist/commonjs/list.js +99 -138
  55. package/dist/commonjs/list.js.map +1 -1
  56. package/dist/commonjs/mkdir.d.ts +16 -11
  57. package/dist/commonjs/mkdir.d.ts.map +1 -1
  58. package/dist/commonjs/mkdir.js +121 -159
  59. package/dist/commonjs/mkdir.js.map +1 -1
  60. package/dist/commonjs/options.d.ts +284 -513
  61. package/dist/commonjs/options.d.ts.map +1 -1
  62. package/dist/commonjs/options.js +20 -61
  63. package/dist/commonjs/options.js.map +1 -1
  64. package/dist/commonjs/pack.d.ts +150 -96
  65. package/dist/commonjs/pack.d.ts.map +1 -1
  66. package/dist/commonjs/pack.js +752 -445
  67. package/dist/commonjs/pack.js.map +1 -1
  68. package/dist/commonjs/parser.d.ts +94 -0
  69. package/dist/commonjs/parser.d.ts.map +1 -0
  70. package/dist/commonjs/parser.js +381 -0
  71. package/dist/commonjs/parser.js.map +1 -0
  72. package/dist/commonjs/path-reservations.d.ts +17 -7
  73. package/dist/commonjs/path-reservations.d.ts.map +1 -1
  74. package/dist/commonjs/path-reservations.js +96 -119
  75. package/dist/commonjs/path-reservations.js.map +1 -1
  76. package/dist/commonjs/path.d.ts +19 -0
  77. package/dist/commonjs/path.d.ts.map +1 -0
  78. package/dist/commonjs/path.js +90 -0
  79. package/dist/commonjs/path.js.map +1 -0
  80. package/dist/commonjs/pax.d.ts +3 -1
  81. package/dist/commonjs/pax.d.ts.map +1 -1
  82. package/dist/commonjs/pax.js +53 -43
  83. package/dist/commonjs/pax.js.map +1 -1
  84. package/dist/commonjs/read-entry.d.ts +97 -11
  85. package/dist/commonjs/read-entry.d.ts.map +1 -1
  86. package/dist/commonjs/read-entry.js +248 -97
  87. package/dist/commonjs/read-entry.js.map +1 -1
  88. package/dist/commonjs/read-file.d.ts +22 -0
  89. package/dist/commonjs/read-file.d.ts.map +1 -0
  90. package/dist/commonjs/read-file.js +104 -0
  91. package/dist/commonjs/read-file.js.map +1 -0
  92. package/dist/commonjs/replace.d.ts +45 -1
  93. package/dist/commonjs/replace.d.ts.map +1 -1
  94. package/dist/commonjs/replace.js +165 -211
  95. package/dist/commonjs/replace.js.map +1 -1
  96. package/dist/commonjs/server/codecs.d.ts +38 -0
  97. package/dist/commonjs/server/codecs.d.ts.map +1 -0
  98. package/dist/commonjs/server/codecs.js +252 -0
  99. package/dist/commonjs/server/codecs.js.map +1 -0
  100. package/dist/commonjs/server/index.d.ts +115 -0
  101. package/dist/commonjs/server/index.d.ts.map +1 -0
  102. package/dist/commonjs/server/index.js +166 -0
  103. package/dist/commonjs/server/index.js.map +1 -0
  104. package/dist/commonjs/server/index.min.js +3 -0
  105. package/dist/commonjs/server/index.min.js.map +7 -0
  106. package/dist/commonjs/strip-absolute-path.d.ts +8 -0
  107. package/dist/commonjs/strip-absolute-path.d.ts.map +1 -1
  108. package/dist/commonjs/strip-absolute-path.js +17 -20
  109. package/dist/commonjs/strip-absolute-path.js.map +1 -1
  110. package/dist/commonjs/to-stream.d.ts +7 -0
  111. package/dist/commonjs/to-stream.d.ts.map +1 -0
  112. package/dist/commonjs/to-stream.js +22 -0
  113. package/dist/commonjs/to-stream.js.map +1 -0
  114. package/dist/commonjs/types.d.ts +4 -3
  115. package/dist/commonjs/types.d.ts.map +1 -1
  116. package/dist/commonjs/types.js +4 -3
  117. package/dist/commonjs/types.js.map +1 -1
  118. package/dist/commonjs/unpack.d.ts +143 -89
  119. package/dist/commonjs/unpack.d.ts.map +1 -1
  120. package/dist/commonjs/unpack.js +782 -725
  121. package/dist/commonjs/unpack.js.map +1 -1
  122. package/dist/commonjs/update.d.ts +11 -1
  123. package/dist/commonjs/update.d.ts.map +1 -1
  124. package/dist/commonjs/update.js +37 -28
  125. package/dist/commonjs/update.js.map +1 -1
  126. package/dist/commonjs/warn.d.ts +27 -0
  127. package/dist/commonjs/warn.d.ts.map +1 -0
  128. package/dist/commonjs/warn.js +36 -0
  129. package/dist/commonjs/warn.js.map +1 -0
  130. package/dist/commonjs/win32-path.d.ts +16 -0
  131. package/dist/commonjs/win32-path.d.ts.map +1 -0
  132. package/dist/commonjs/win32-path.js +67 -0
  133. package/dist/commonjs/win32-path.js.map +1 -0
  134. package/dist/commonjs/write-entry.d.ts +64 -111
  135. package/dist/commonjs/write-entry.d.ts.map +1 -1
  136. package/dist/commonjs/write-entry.js +108 -672
  137. package/dist/commonjs/write-entry.js.map +1 -1
  138. package/dist/commonjs/write-flag.d.ts +18 -0
  139. package/dist/commonjs/write-flag.d.ts.map +1 -0
  140. package/dist/commonjs/write-flag.js +29 -0
  141. package/dist/commonjs/write-flag.js.map +1 -0
  142. package/dist/esm/bytes.d.ts +21 -0
  143. package/dist/esm/bytes.d.ts.map +1 -0
  144. package/dist/esm/bytes.js +72 -0
  145. package/dist/esm/bytes.js.map +1 -0
  146. package/dist/esm/codec.d.ts +53 -0
  147. package/dist/esm/codec.d.ts.map +1 -0
  148. package/dist/esm/codec.js +32 -0
  149. package/dist/esm/codec.js.map +1 -0
  150. package/dist/esm/concat.d.ts +3 -0
  151. package/dist/esm/concat.d.ts.map +1 -0
  152. package/dist/esm/concat.js +16 -0
  153. package/dist/esm/concat.js.map +1 -0
  154. package/dist/esm/create.d.ts +39 -2
  155. package/dist/esm/create.d.ts.map +1 -1
  156. package/dist/esm/create.js +144 -61
  157. package/dist/esm/create.js.map +1 -1
  158. package/dist/esm/dealias.d.ts +79 -0
  159. package/dist/esm/dealias.d.ts.map +1 -0
  160. package/dist/esm/dealias.js +46 -0
  161. package/dist/esm/dealias.js.map +1 -0
  162. package/dist/esm/delete.d.ts +19 -0
  163. package/dist/esm/delete.d.ts.map +1 -0
  164. package/dist/esm/delete.js +117 -0
  165. package/dist/esm/delete.js.map +1 -0
  166. package/dist/esm/entries.d.ts +82 -0
  167. package/dist/esm/entries.d.ts.map +1 -0
  168. package/dist/esm/entries.js +388 -0
  169. package/dist/esm/entries.js.map +1 -0
  170. package/dist/esm/extract.d.ts +14 -2
  171. package/dist/esm/extract.d.ts.map +1 -1
  172. package/dist/esm/extract.js +37 -44
  173. package/dist/esm/extract.js.map +1 -1
  174. package/dist/esm/fs.d.ts +201 -0
  175. package/dist/esm/fs.d.ts.map +1 -0
  176. package/dist/esm/fs.js +4 -0
  177. package/dist/esm/fs.js.map +1 -0
  178. package/dist/esm/header.d.ts +4 -4
  179. package/dist/esm/header.d.ts.map +1 -1
  180. package/dist/esm/header.js +38 -42
  181. package/dist/esm/header.js.map +1 -1
  182. package/dist/esm/index.d.ts +25 -18
  183. package/dist/esm/index.d.ts.map +1 -1
  184. package/dist/esm/index.js +23 -18
  185. package/dist/esm/index.js.map +1 -1
  186. package/dist/esm/index.min.js +2 -3
  187. package/dist/esm/index.min.js.map +4 -4
  188. package/dist/esm/large-numbers.d.ts +2 -2
  189. package/dist/esm/large-numbers.d.ts.map +1 -1
  190. package/dist/esm/large-numbers.js +4 -4
  191. package/dist/esm/large-numbers.js.map +1 -1
  192. package/dist/esm/list.d.ts +23 -6
  193. package/dist/esm/list.d.ts.map +1 -1
  194. package/dist/esm/list.js +96 -101
  195. package/dist/esm/list.js.map +1 -1
  196. package/dist/esm/mkdir.d.ts +16 -11
  197. package/dist/esm/mkdir.d.ts.map +1 -1
  198. package/dist/esm/mkdir.js +119 -154
  199. package/dist/esm/mkdir.js.map +1 -1
  200. package/dist/esm/options.d.ts +284 -513
  201. package/dist/esm/options.d.ts.map +1 -1
  202. package/dist/esm/options.js +17 -51
  203. package/dist/esm/options.js.map +1 -1
  204. package/dist/esm/pack.d.ts +150 -96
  205. package/dist/esm/pack.d.ts.map +1 -1
  206. package/dist/esm/pack.js +750 -441
  207. package/dist/esm/pack.js.map +1 -1
  208. package/dist/esm/parser.d.ts +94 -0
  209. package/dist/esm/parser.d.ts.map +1 -0
  210. package/dist/esm/parser.js +377 -0
  211. package/dist/esm/parser.js.map +1 -0
  212. package/dist/esm/path-reservations.d.ts +17 -7
  213. package/dist/esm/path-reservations.d.ts.map +1 -1
  214. package/dist/esm/path-reservations.js +96 -119
  215. package/dist/esm/path-reservations.js.map +1 -1
  216. package/dist/esm/path.d.ts +19 -0
  217. package/dist/esm/path.d.ts.map +1 -0
  218. package/dist/esm/path.js +80 -0
  219. package/dist/esm/path.js.map +1 -0
  220. package/dist/esm/pax.d.ts +3 -1
  221. package/dist/esm/pax.d.ts.map +1 -1
  222. package/dist/esm/pax.js +52 -42
  223. package/dist/esm/pax.js.map +1 -1
  224. package/dist/esm/read-entry.d.ts +97 -11
  225. package/dist/esm/read-entry.d.ts.map +1 -1
  226. package/dist/esm/read-entry.js +245 -96
  227. package/dist/esm/read-entry.js.map +1 -1
  228. package/dist/esm/read-file.d.ts +22 -0
  229. package/dist/esm/read-file.d.ts.map +1 -0
  230. package/dist/esm/read-file.js +99 -0
  231. package/dist/esm/read-file.js.map +1 -0
  232. package/dist/esm/replace.d.ts +45 -1
  233. package/dist/esm/replace.d.ts.map +1 -1
  234. package/dist/esm/replace.js +161 -207
  235. package/dist/esm/replace.js.map +1 -1
  236. package/dist/esm/server/codecs.d.ts +38 -0
  237. package/dist/esm/server/codecs.d.ts.map +1 -0
  238. package/dist/esm/server/codecs.js +214 -0
  239. package/dist/esm/server/codecs.js.map +1 -0
  240. package/dist/esm/server/index.d.ts +115 -0
  241. package/dist/esm/server/index.d.ts.map +1 -0
  242. package/dist/esm/server/index.js +102 -0
  243. package/dist/esm/server/index.js.map +1 -0
  244. package/dist/esm/server/index.min.js +3 -0
  245. package/dist/esm/server/index.min.js.map +7 -0
  246. package/dist/esm/strip-absolute-path.d.ts +8 -0
  247. package/dist/esm/strip-absolute-path.d.ts.map +1 -1
  248. package/dist/esm/strip-absolute-path.js +17 -20
  249. package/dist/esm/strip-absolute-path.js.map +1 -1
  250. package/dist/esm/to-stream.d.ts +7 -0
  251. package/dist/esm/to-stream.d.ts.map +1 -0
  252. package/dist/esm/to-stream.js +18 -0
  253. package/dist/esm/to-stream.js.map +1 -0
  254. package/dist/esm/types.d.ts +4 -3
  255. package/dist/esm/types.d.ts.map +1 -1
  256. package/dist/esm/types.js +4 -3
  257. package/dist/esm/types.js.map +1 -1
  258. package/dist/esm/unpack.d.ts +143 -89
  259. package/dist/esm/unpack.d.ts.map +1 -1
  260. package/dist/esm/unpack.js +778 -719
  261. package/dist/esm/unpack.js.map +1 -1
  262. package/dist/esm/update.d.ts +11 -1
  263. package/dist/esm/update.d.ts.map +1 -1
  264. package/dist/esm/update.js +35 -28
  265. package/dist/esm/update.js.map +1 -1
  266. package/dist/esm/warn.d.ts +27 -0
  267. package/dist/esm/warn.d.ts.map +1 -0
  268. package/dist/esm/warn.js +31 -0
  269. package/dist/esm/warn.js.map +1 -0
  270. package/dist/esm/win32-path.d.ts +16 -0
  271. package/dist/esm/win32-path.d.ts.map +1 -0
  272. package/dist/esm/win32-path.js +60 -0
  273. package/dist/esm/win32-path.js.map +1 -0
  274. package/dist/esm/write-entry.d.ts +64 -111
  275. package/dist/esm/write-entry.d.ts.map +1 -1
  276. package/dist/esm/write-entry.js +107 -633
  277. package/dist/esm/write-entry.js.map +1 -1
  278. package/dist/esm/write-flag.d.ts +18 -0
  279. package/dist/esm/write-flag.d.ts.map +1 -0
  280. package/dist/esm/write-flag.js +25 -0
  281. package/dist/esm/write-flag.js.map +1 -0
  282. package/package.json +68 -224
  283. package/dist/commonjs/get-write-flag.d.ts +0 -2
  284. package/dist/commonjs/get-write-flag.d.ts.map +0 -1
  285. package/dist/commonjs/get-write-flag.js +0 -32
  286. package/dist/commonjs/get-write-flag.js.map +0 -1
  287. package/dist/commonjs/make-command.d.ts +0 -49
  288. package/dist/commonjs/make-command.d.ts.map +0 -1
  289. package/dist/commonjs/make-command.js +0 -52
  290. package/dist/commonjs/make-command.js.map +0 -1
  291. package/dist/commonjs/normalize-windows-path.d.ts +0 -2
  292. package/dist/commonjs/normalize-windows-path.d.ts.map +0 -1
  293. package/dist/commonjs/normalize-windows-path.js +0 -12
  294. package/dist/commonjs/normalize-windows-path.js.map +0 -1
  295. package/dist/commonjs/parse.d.ts +0 -92
  296. package/dist/commonjs/parse.d.ts.map +0 -1
  297. package/dist/commonjs/parse.js +0 -655
  298. package/dist/commonjs/parse.js.map +0 -1
  299. package/dist/commonjs/process-umask.d.ts +0 -2
  300. package/dist/commonjs/process-umask.d.ts.map +0 -1
  301. package/dist/commonjs/process-umask.js +0 -7
  302. package/dist/commonjs/process-umask.js.map +0 -1
  303. package/dist/commonjs/warn-method.d.ts +0 -24
  304. package/dist/commonjs/warn-method.d.ts.map +0 -1
  305. package/dist/commonjs/warn-method.js +0 -31
  306. package/dist/commonjs/warn-method.js.map +0 -1
  307. package/dist/esm/get-write-flag.d.ts +0 -2
  308. package/dist/esm/get-write-flag.d.ts.map +0 -1
  309. package/dist/esm/get-write-flag.js +0 -26
  310. package/dist/esm/get-write-flag.js.map +0 -1
  311. package/dist/esm/make-command.d.ts +0 -49
  312. package/dist/esm/make-command.d.ts.map +0 -1
  313. package/dist/esm/make-command.js +0 -48
  314. package/dist/esm/make-command.js.map +0 -1
  315. package/dist/esm/normalize-windows-path.d.ts +0 -2
  316. package/dist/esm/normalize-windows-path.d.ts.map +0 -1
  317. package/dist/esm/normalize-windows-path.js +0 -9
  318. package/dist/esm/normalize-windows-path.js.map +0 -1
  319. package/dist/esm/parse.d.ts +0 -92
  320. package/dist/esm/parse.d.ts.map +0 -1
  321. package/dist/esm/parse.js +0 -651
  322. package/dist/esm/parse.js.map +0 -1
  323. package/dist/esm/process-umask.d.ts +0 -2
  324. package/dist/esm/process-umask.d.ts.map +0 -1
  325. package/dist/esm/process-umask.js +0 -3
  326. package/dist/esm/process-umask.js.map +0 -1
  327. package/dist/esm/warn-method.d.ts +0 -24
  328. package/dist/esm/warn-method.d.ts.map +0 -1
  329. package/dist/esm/warn-method.js +0 -27
  330. package/dist/esm/warn-method.js.map +0 -1
@@ -1,373 +1,333 @@
1
- // the PEND/UNPEND stuff tracks whether we're ready to emit end/close yet.
2
- // but the path reservations are required to avoid race conditions where
3
- // parallelized unpack ops may mess with one another, due to dependencies
4
- // (like a Link depending on its target) or destructive operations (like
5
- // clobbering an fs object to create one of a different type.)
6
- import * as fsm from '@isaacs/fs-minipass';
7
- import assert from 'node:assert';
8
- import { randomBytes } from 'node:crypto';
9
- import fs from 'node:fs';
10
- import path from 'node:path';
11
- import { getWriteFlag } from './get-write-flag.js';
12
- import { mkdir, mkdirSync } from './mkdir.js';
13
- import { normalizeWindowsPath } from './normalize-windows-path.js';
14
- import { Parser } from './parse.js';
15
- import { stripAbsolutePath } from './strip-absolute-path.js';
1
+ import { SymlinkError } from './symlink-error.js';
16
2
  import * as wc from './winchars.js';
3
+ import { TarReader, TarReaderSync } from './entries.js';
4
+ import { mkdir, mkdirSync } from './mkdir.js';
5
+ import { countOption, ownOptions, } from './options.js';
17
6
  import { PathReservations } from './path-reservations.js';
18
- import { SymlinkError } from './symlink-error.js';
19
- import { umask } from './process-umask.js';
20
- const ONENTRY = Symbol('onEntry');
21
- const CHECKFS = Symbol('checkFs');
22
- const CHECKFS2 = Symbol('checkFs2');
23
- const ISREUSABLE = Symbol('isReusable');
24
- const MAKEFS = Symbol('makeFs');
25
- const FILE = Symbol('file');
26
- const DIRECTORY = Symbol('directory');
27
- const LINK = Symbol('link');
28
- const SYMLINK = Symbol('symlink');
29
- const HARDLINK = Symbol('hardlink');
30
- const ENSURE_NO_SYMLINK = Symbol('ensureNoSymlink');
31
- const UNSUPPORTED = Symbol('unsupported');
32
- const CHECKPATH = Symbol('checkPath');
33
- const STRIPABSOLUTEPATH = Symbol('stripAbsolutePath');
34
- const MKDIR = Symbol('mkdir');
35
- const ONERROR = Symbol('onError');
36
- const PENDING = Symbol('pending');
37
- const PEND = Symbol('pend');
38
- const UNPEND = Symbol('unpend');
39
- const ENDED = Symbol('ended');
40
- const MAYBECLOSE = Symbol('maybeClose');
41
- const SKIP = Symbol('skip');
42
- const DOCHOWN = Symbol('doChown');
43
- const UID = Symbol('uid');
44
- const GID = Symbol('gid');
45
- const CHECKED_CWD = Symbol('checkedCwd');
46
- const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform;
47
- const isWindows = platform === 'win32';
7
+ import { dirname, isAbsolute, join, normalize, relative, resolve, } from './path.js';
8
+ import { stripAbsolutePath } from './strip-absolute-path.js';
9
+ import { warn } from './warn.js';
10
+ import { win32Dirname, win32IsAbsolute, win32Resolve, win32Root, } from './win32-path.js';
11
+ import { writeFlags } from './write-flag.js';
48
12
  const DEFAULT_MAX_DEPTH = 1024;
49
- // Unlinks on Windows are not atomic.
50
- //
51
- // This means that if you have a file entry, followed by another
52
- // file entry with an identical name, and you cannot re-use the file
53
- // (because it's a hardlink, or because unlink:true is set, or it's
54
- // Windows, which does not have useful nlink values), then the unlink
55
- // will be committed to the disk AFTER the new file has been written
56
- // over the old one, deleting the new file.
57
- //
58
- // To work around this, on Windows systems, we rename the file and then
59
- // delete the renamed file. It's a sloppy kludge, but frankly, I do not
60
- // know of a better way to do this, given windows' non-atomic unlink
61
- // semantics.
62
- //
63
- // See: https://github.com/npm/node-tar/issues/183
64
- /* c8 ignore start */
65
- const unlinkFile = (path, cb) => {
66
- if (!isWindows) {
67
- return fs.unlink(path, cb);
68
- }
69
- const name = path + '.DELETE.' + randomBytes(16).toString('hex');
70
- fs.rename(path, name, er => {
71
- if (er) {
72
- return cb(er);
73
- }
74
- fs.unlink(name, cb);
75
- });
76
- };
77
- /* c8 ignore stop */
78
- /* c8 ignore start */
79
- const unlinkFileSync = (path) => {
80
- if (!isWindows) {
81
- return fs.unlinkSync(path);
82
- }
83
- const name = path + '.DELETE.' + randomBytes(16).toString('hex');
84
- fs.renameSync(path, name);
85
- fs.unlinkSync(name);
86
- };
87
- /* c8 ignore stop */
88
- // this.gid, entry.gid, this.processUid
89
- const uint32 = (a, b, c) => a !== undefined && a === a >>> 0 ? a
13
+ // Longer than any path that a supported platform can create.
14
+ const MAX_PATH_LENGTH = 32768;
15
+ const DEFAULT_JOBS = 16;
16
+ const fileTypes = new Set([
17
+ 'File',
18
+ 'OldFile',
19
+ 'ContiguousFile',
20
+ ]);
21
+ const dirTypes = new Set(['Directory', 'GNUDumpDir']);
22
+ const linkTypes = new Set(['Link', 'SymbolicLink']);
23
+ // The first of the values that is an unsigned 32-bit integer, or the
24
+ // last value.
25
+ const uint32 = (a, b, c) => a !== undefined ? a
90
26
  : b !== undefined && b === b >>> 0 ? b
91
27
  : c;
92
- export class Unpack extends Parser {
93
- [ENDED] = false;
94
- [CHECKED_CWD] = false;
95
- [PENDING] = 0;
96
- reservations = new PathReservations();
97
- transform;
98
- writable = true;
99
- readable = false;
28
+ /**
29
+ * The parts of the extraction that do not use the file system: the
30
+ * options, the checks of each entry, and the warnings. `Unpack` and
31
+ * `UnpackSync` add the file system work.
32
+ */
33
+ export class UnpackBase {
34
+ /** The options, with no prototype. */
35
+ opt;
36
+ /** The absolute path of the extraction directory. */
37
+ cwd;
38
+ win32;
39
+ strip;
40
+ maxDepth;
41
+ preservePaths;
42
+ unlink;
43
+ keep;
44
+ newer;
45
+ noMtime;
46
+ chmod;
100
47
  uid;
101
48
  gid;
102
- setOwner;
103
49
  preserveOwner;
104
- processGid;
105
- processUid;
106
- maxDepth;
107
50
  forceChown;
108
- win32;
109
- newer;
110
- keep;
111
- noMtime;
112
- preservePaths;
113
- unlink;
114
- cwd;
115
- strip;
51
+ processUid;
52
+ processGid;
116
53
  processUmask;
117
54
  umask;
118
55
  dmode;
119
56
  fmode;
120
- chmod;
121
- constructor(opt = {}) {
122
- opt.ondone = () => {
123
- this[ENDED] = true;
124
- this[MAYBECLOSE]();
125
- };
126
- super(opt);
127
- this.transform = opt.transform;
128
- this.chmod = !!opt.chmod;
57
+ /** Gives the `open` flag for a new file of a given size. */
58
+ writeFlag;
59
+ /** Resolve a path from an absolute path. */
60
+ resolve;
61
+ /** The parent directory of an absolute path. */
62
+ dirname;
63
+ /** Set when an error stops the extraction. */
64
+ fatal;
65
+ constructor(options) {
66
+ const opt = (this.opt = ownOptions(options));
67
+ const win32 = (this.win32 = opt.platform === 'win32');
68
+ this.resolve = win32 ? win32Resolve : resolve;
69
+ this.dirname = win32 ? win32Dirname : dirname;
70
+ if (typeof opt.cwd !== 'string') {
71
+ throw new TypeError('cwd is required');
72
+ }
73
+ const cwd = win32 ? opt.cwd.replaceAll('\\', '/') : opt.cwd;
74
+ if (!(win32 ? win32IsAbsolute : isAbsolute)(cwd)) {
75
+ throw new TypeError('cwd must be an absolute path');
76
+ }
77
+ this.cwd = this.resolve(cwd, '');
129
78
  if (typeof opt.uid === 'number' || typeof opt.gid === 'number') {
130
79
  // need both or neither
131
80
  if (typeof opt.uid !== 'number' || typeof opt.gid !== 'number') {
132
81
  throw new TypeError('cannot set owner without number uid and gid');
133
82
  }
83
+ // A value that is not valid must not fall back to the owner
84
+ // in the archive.
85
+ if (opt.uid !== opt.uid >>> 0 || opt.gid !== opt.gid >>> 0) {
86
+ throw new TypeError('uid and gid must be unsigned 32-bit integers');
87
+ }
134
88
  if (opt.preserveOwner) {
135
89
  throw new TypeError('cannot preserve owner in archive and also set owner explicitly');
136
90
  }
137
91
  this.uid = opt.uid;
138
92
  this.gid = opt.gid;
139
- this.setOwner = true;
140
- }
141
- else {
142
- this.uid = undefined;
143
- this.gid = undefined;
144
- this.setOwner = false;
145
93
  }
146
- // default true for root
94
+ this.processUid = opt.processUid;
95
+ this.processGid = opt.processGid;
147
96
  this.preserveOwner =
148
97
  opt.preserveOwner === undefined && typeof opt.uid !== 'number' ?
149
- !!(process.getuid?.() === 0)
98
+ opt.processUid === 0
150
99
  : !!opt.preserveOwner;
151
- this.processUid =
152
- (this.preserveOwner || this.setOwner) && process.getuid ?
153
- process.getuid()
154
- : undefined;
155
- this.processGid =
156
- (this.preserveOwner || this.setOwner) && process.getgid ?
157
- process.getgid()
158
- : undefined;
159
- // prevent excessively deep nesting of subfolders
160
- // set to `Infinity` to remove this restriction
100
+ this.forceChown = opt.forceChown === true;
161
101
  this.maxDepth =
162
102
  typeof opt.maxDepth === 'number' ? opt.maxDepth : DEFAULT_MAX_DEPTH;
163
- // mostly just for testing, but useful in some cases.
164
- // Forcibly trigger a chown on every entry, no matter what
165
- this.forceChown = opt.forceChown === true;
166
- // turn ><?| in filenames into 0xf000-higher encoded forms
167
- this.win32 = !!opt.win32 || isWindows;
168
- // do not unpack over files that are newer than what's in the archive
169
- this.newer = !!opt.newer;
170
- // do not unpack over ANY files
171
- this.keep = !!opt.keep;
172
- // do not set mtime/atime of extracted entries
173
- this.noMtime = !!opt.noMtime;
174
- // allow .., absolute path entries, and unpacking through symlinks
175
- // without this, warn and skip .., relativize absolutes, and error
176
- // on symlinks in extraction path
103
+ this.strip = Number(opt.strip) || 0;
177
104
  this.preservePaths = !!opt.preservePaths;
178
- // unlink files and links before writing. This breaks existing hard
179
- // links, and removes symlink directories rather than erroring
180
105
  this.unlink = !!opt.unlink;
181
- this.cwd = normalizeWindowsPath(path.resolve(opt.cwd || process.cwd()));
182
- this.strip = Number(opt.strip) || 0;
183
- // if we're not chmodding, then we don't need the process umask
106
+ this.keep = !!opt.keep;
107
+ this.newer = !!opt.newer;
108
+ this.noMtime = !!opt.noMtime;
109
+ this.chmod = !!opt.chmod;
110
+ // Without chmod, the umask of the process is not needed.
184
111
  this.processUmask =
185
112
  !this.chmod ? 0
186
113
  : typeof opt.processUmask === 'number' ? opt.processUmask
187
- : umask();
114
+ : 0o22;
188
115
  this.umask =
189
116
  typeof opt.umask === 'number' ? opt.umask : this.processUmask;
190
- // default mode for dirs created as parents
191
- this.dmode = opt.dmode || 0o0777 & ~this.umask;
192
- this.fmode = opt.fmode || 0o0666 & ~this.umask;
193
- this.on('entry', entry => this[ONENTRY](entry));
194
- }
195
- // a bad or damaged archive is a warning for Parser, but an error
196
- // when extracting. Mark those errors as unrecoverable, because
197
- // the Unpack contract cannot be met.
198
- warn(code, msg, data = {}) {
117
+ this.dmode = opt.dmode || 0o777 & ~this.umask;
118
+ this.fmode = opt.fmode || 0o666 & ~this.umask;
119
+ this.writeFlag = writeFlags(opt.fs.constants, win32);
120
+ }
121
+ /**
122
+ * Report a problem to `onwarn`, or throw it if `strict` is set. A
123
+ * damaged archive is always an error here, because the extraction
124
+ * cannot be complete.
125
+ */
126
+ warn(code, message, data = {}) {
199
127
  if (code === 'TAR_BAD_ARCHIVE' || code === 'TAR_ABORT') {
200
128
  data.recoverable = false;
201
129
  }
202
- return super.warn(code, msg, data);
130
+ data.cwd = this.cwd;
131
+ warn(this.opt, code, message, data);
203
132
  }
204
- [MAYBECLOSE]() {
205
- if (this[ENDED] && this[PENDING] === 0) {
206
- this.emit('prefinish');
207
- this.emit('finish');
208
- this.emit('end');
209
- }
133
+ /** The options for the reader. Its warnings go to `warn()`. */
134
+ readerOptions() {
135
+ return ownOptions(this.opt, {
136
+ strict: false,
137
+ onwarn: (code, message, data) => data instanceof Error ?
138
+ this.warn(code, data)
139
+ : this.warn(code, message, data),
140
+ });
210
141
  }
211
- // return false if we need to skip this file
212
- // return true if the field was successfully sanitized
213
- [STRIPABSOLUTEPATH](entry, field) {
142
+ /**
143
+ * Report the failure of one entry as a `TAR_ENTRY_ERROR` warning.
144
+ * Throws the error if it stops the extraction: the extraction
145
+ * directory is not usable, the archive cannot be read, or `strict`
146
+ * is set.
147
+ */
148
+ entryError(er, entry) {
149
+ if (this.fatal?.error === er || er?.name === 'CwdError') {
150
+ throw er;
151
+ }
152
+ this.warn('TAR_ENTRY_ERROR', er, { entry });
153
+ }
154
+ /** Record the error that stops the extraction. Returns it. */
155
+ fail(error) {
156
+ this.fatal ??= { error };
157
+ return error;
158
+ }
159
+ // Remove the root of an absolute path, and refuse a path that can
160
+ // leave the extraction directory. False if the entry is refused.
161
+ #stripAbsolutePath(entry, field) {
214
162
  const p = entry[field];
215
- const { type } = entry;
216
163
  if (!p || this.preservePaths)
217
164
  return true;
218
- // strip off the root
219
165
  const [root, stripped] = stripAbsolutePath(p);
220
- const parts = stripped.replaceAll(/\\/g, '/').split('/');
221
- if (parts.includes('..') ||
222
- /* c8 ignore next */
223
- (isWindows && /^[a-z]:\.\.$/i.test(parts[0] ?? ''))) {
224
- // For linkpath, check if the resolved path escapes cwd rather than
225
- // just rejecting any path with '..' - relative symlinks like
226
- // '../sibling/file' are valid if they resolve within the cwd.
227
- // For paths, they just simply may not ever use .. at all.
228
- if (field === 'path' || type === 'Link') {
166
+ const parts = stripped.replaceAll('\\', '/').split('/');
167
+ if (parts.includes('..')) {
168
+ // A path, and the target of a hard link, cannot have '..' at
169
+ // all. The target of a symbolic link is relative to the
170
+ // directory of the link, so '../sibling/file' can be valid.
171
+ if (field === 'path' || entry.type === 'Link') {
229
172
  this.warn('TAR_ENTRY_ERROR', `${field} contains '..'`, {
230
173
  entry,
231
174
  [field]: p,
232
175
  });
233
- // not ok!
234
176
  return false;
235
177
  }
236
- // Resolve linkpath relative to the entry's directory.
237
- // `path.posix` is safe to use because we're operating on
238
- // tar paths, not a filesystem.
239
- const entryDir = path.posix.dirname(entry.path);
240
- const resolved = path.posix.normalize(path.posix.join(entryDir, parts.join('/')));
241
- // If the resolved path escapes (starts with ..), reject it
178
+ // A '..' is only safe at the start of the target. Any named
179
+ // part before it can be a symlink, and then the '..' goes to
180
+ // the parent of the target of that symlink.
181
+ const firstName = parts.findIndex(part => part !== '..' && part !== '.' && part !== '');
182
+ if (firstName !== -1 && parts.includes('..', firstName)) {
183
+ this.warn('TAR_ENTRY_ERROR', `${field} contains '..' after a path portion`, { entry, [field]: p });
184
+ return false;
185
+ }
186
+ // Normalize the path, so that the directory is the one where
187
+ // the link is created. The path 'x/.' creates the link 'x'.
188
+ const entryDir = dirname(normalize(entry.path));
189
+ const resolved = normalize(join(entryDir, parts.join('/')));
242
190
  if (resolved.startsWith('../') || resolved === '..') {
243
- this.warn('TAR_ENTRY_ERROR', `${field} escapes extraction directory`, {
244
- entry,
245
- [field]: p,
246
- });
191
+ this.warn('TAR_ENTRY_ERROR', `${field} escapes extraction directory`, { entry, [field]: p });
247
192
  return false;
248
193
  }
249
194
  }
250
195
  if (root) {
251
- // ok, but triggers warning about stripping root
252
- entry[field] = String(stripped);
253
- this.warn('TAR_ENTRY_INFO', `stripping ${root} from absolute ${field}`, {
254
- entry,
255
- [field]: p,
256
- });
196
+ ;
197
+ entry[field] = stripped;
198
+ this.warn('TAR_ENTRY_INFO', `stripping ${root} from absolute ${field}`, { entry, [field]: p });
257
199
  }
258
200
  return true;
259
201
  }
260
- // no IO, just string checking for absolute indicators
261
- [CHECKPATH](entry) {
262
- const p = normalizeWindowsPath(entry.path);
202
+ /**
203
+ * Check the entry, with no use of the file system. Set its
204
+ * `absolute` path, and change its `path`, `linkpath`, and `mode` to
205
+ * the values to extract. False if the entry must not be extracted.
206
+ */
207
+ check(entry) {
208
+ const p = entry.path;
263
209
  const parts = p.split('/');
264
210
  if (this.strip) {
265
- if (parts.length < this.strip) {
211
+ if (parts.length < this.strip)
266
212
  return false;
267
- }
268
213
  if (entry.type === 'Link') {
269
- const linkparts = normalizeWindowsPath(String(entry.linkpath)).split('/');
270
- if (linkparts.length >= this.strip) {
271
- entry.linkpath = linkparts.slice(this.strip).join('/');
272
- }
273
- else {
214
+ const linkparts = String(entry.linkpath).split('/');
215
+ if (linkparts.length < this.strip)
274
216
  return false;
275
- }
217
+ entry.linkpath = linkparts.slice(this.strip).join('/');
276
218
  }
277
219
  parts.splice(0, this.strip);
220
+ // No part of the path is left, as for the top directory of a
221
+ // package. The entry must not change the extraction directory.
222
+ if (parts.every(part => part === ''))
223
+ return false;
278
224
  entry.path = parts.join('/');
279
225
  }
280
- if (isFinite(this.maxDepth) && parts.length > this.maxDepth) {
226
+ const { maxDepth } = this;
227
+ if (isFinite(maxDepth) && parts.length > maxDepth) {
281
228
  this.warn('TAR_ENTRY_ERROR', 'path excessively deep', {
282
229
  entry,
283
230
  path: p,
284
231
  depth: parts.length,
285
- maxDepth: this.maxDepth,
232
+ maxDepth,
233
+ });
234
+ return false;
235
+ }
236
+ // The path reservations do work for each parent directory of the
237
+ // path and of the linkpath.
238
+ const { linkpath } = entry;
239
+ if (linkpath &&
240
+ isFinite(maxDepth) &&
241
+ linkpath.split('/').length > maxDepth) {
242
+ this.warn('TAR_ENTRY_ERROR', 'linkpath excessively deep', {
243
+ entry,
244
+ path: p,
245
+ linkpath,
246
+ maxDepth,
286
247
  });
287
248
  return false;
288
249
  }
289
- if (!this[STRIPABSOLUTEPATH](entry, 'path') ||
290
- !this[STRIPABSOLUTEPATH](entry, 'linkpath')) {
250
+ for (const field of ['path', 'linkpath']) {
251
+ const { length } = entry[field] ?? '';
252
+ if (length > MAX_PATH_LENGTH) {
253
+ this.warn('TAR_ENTRY_ERROR', `${field} excessively long`, {
254
+ entry,
255
+ path: p,
256
+ length,
257
+ maxLength: MAX_PATH_LENGTH,
258
+ });
259
+ return false;
260
+ }
261
+ }
262
+ if (!this.#stripAbsolutePath(entry, 'path') ||
263
+ !this.#stripAbsolutePath(entry, 'linkpath')) {
291
264
  return false;
292
265
  }
293
- entry.absolute =
294
- path.isAbsolute(entry.path) ?
295
- normalizeWindowsPath(path.resolve(entry.path))
296
- : normalizeWindowsPath(path.resolve(this.cwd, entry.path));
297
- // if we somehow ended up with a path that escapes the cwd, and we are
298
- // not in preservePaths mode, then something is fishy! This should have
299
- // been prevented above, so ignore this for coverage.
300
- /* c8 ignore start - defense in depth */
266
+ const { cwd } = this;
267
+ let absolute = this.resolve(cwd, entry.path);
268
+ // The checks above refuse a path that leaves the extraction
269
+ // directory. This check is defense in depth.
301
270
  if (!this.preservePaths &&
302
- typeof entry.absolute === 'string' &&
303
- entry.absolute.indexOf(this.cwd + '/') !== 0 &&
304
- entry.absolute !== this.cwd) {
271
+ absolute !== cwd &&
272
+ // A root, such as `/` or `c:/`, ends with a slash.
273
+ !absolute.startsWith(cwd.endsWith('/') ? cwd : cwd + '/')) {
305
274
  this.warn('TAR_ENTRY_ERROR', 'path escaped extraction target', {
306
275
  entry,
307
- path: normalizeWindowsPath(entry.path),
308
- resolvedPath: entry.absolute,
309
- cwd: this.cwd,
276
+ path: entry.path,
277
+ resolvedPath: absolute,
278
+ cwd,
310
279
  });
311
280
  return false;
312
281
  }
313
- /* c8 ignore stop */
314
- // an archive can set properties on the extraction directory, but it
315
- // may not replace the cwd with a different kind of thing entirely.
316
- if (entry.absolute === this.cwd &&
317
- entry.type !== 'Directory' &&
318
- entry.type !== 'GNUDumpDir') {
282
+ // An archive can set properties of the extraction directory, but
283
+ // it cannot replace it with a different kind of thing.
284
+ if (absolute === cwd && !dirTypes.has(entry.type))
319
285
  return false;
320
- }
321
- // only encode : chars that aren't drive letter indicators
286
+ // Do not change the ':' of a drive letter.
322
287
  if (this.win32) {
323
- const { root: aRoot } = path.win32.parse(String(entry.absolute));
324
- entry.absolute =
325
- aRoot + wc.encode(String(entry.absolute).slice(aRoot.length));
326
- const { root: pRoot } = path.win32.parse(entry.path);
288
+ const aRoot = win32Root(absolute);
289
+ absolute = aRoot + wc.encode(absolute.slice(aRoot.length));
290
+ const pRoot = win32Root(entry.path);
327
291
  entry.path = pRoot + wc.encode(entry.path.slice(pRoot.length));
328
292
  }
329
- return true;
330
- }
331
- [ONENTRY](entry) {
332
- if (!this[CHECKPATH](entry)) {
333
- return entry.resume();
334
- }
335
- assert.equal(typeof entry.absolute, 'string');
336
- switch (entry.type) {
337
- case 'Directory':
338
- case 'GNUDumpDir':
339
- if (entry.mode) {
340
- entry.mode = entry.mode | 0o700;
341
- }
342
- // eslint-disable-next-line no-fallthrough
343
- case 'File':
344
- case 'OldFile':
345
- case 'ContiguousFile':
346
- case 'Link':
347
- case 'SymbolicLink':
348
- return this[CHECKFS](entry);
349
- case 'CharacterDevice':
350
- case 'BlockDevice':
351
- case 'FIFO':
352
- default:
353
- return this[UNSUPPORTED](entry);
354
- }
355
- }
356
- [ONERROR](er, entry) {
357
- // Cwd has to exist, or else nothing works. That's serious.
358
- // Other errors are warnings, which raise the error in strict
359
- // mode, but otherwise continue on.
360
- if (er.name === 'CwdError') {
361
- this.emit('error', er);
362
- }
363
- else {
364
- this.warn('TAR_ENTRY_ERROR', er, { entry });
365
- this[UNPEND]();
366
- entry.resume();
293
+ entry.absolute = absolute;
294
+ // Never set the setuid, setgid, or sticky bit from an archive.
295
+ if (typeof entry.mode === 'number')
296
+ entry.mode &= 0o777;
297
+ if (dirTypes.has(entry.type)) {
298
+ if (entry.mode)
299
+ entry.mode |= 0o700;
300
+ }
301
+ else if (!fileTypes.has(entry.type) && !linkTypes.has(entry.type)) {
302
+ // A device or a FIFO is never made.
303
+ entry.unsupported = true;
304
+ this.warn('TAR_ENTRY_UNSUPPORTED', `unsupported entry type: ${entry.type}`, { entry });
305
+ return false;
367
306
  }
307
+ return true;
368
308
  }
369
- [MKDIR](dir, mode, cb) {
370
- void mkdir(normalizeWindowsPath(dir), {
309
+ /**
310
+ * The paths that the entry must have for itself while it is made.
311
+ * A link also reserves its target, so that an entry that makes the
312
+ * target, and an entry that goes through the link, do not run at
313
+ * the same time as the link.
314
+ */
315
+ reservedPaths(entry) {
316
+ const { path, linkpath } = entry;
317
+ if (!linkpath)
318
+ return [path];
319
+ // The target of a symlink is relative to the directory of the
320
+ // link. The target of a hard link is relative to the cwd.
321
+ return [
322
+ path,
323
+ entry.type === 'SymbolicLink' && !isAbsolute(linkpath) ?
324
+ join(dirname(path), linkpath)
325
+ : linkpath,
326
+ ];
327
+ }
328
+ /** The options to make a directory with a mode. */
329
+ mkdirOptions(mode) {
330
+ return {
371
331
  uid: this.uid,
372
332
  gid: this.gid,
373
333
  processUid: this.processUid,
@@ -376,516 +336,615 @@ export class Unpack extends Parser {
376
336
  preserve: this.preservePaths,
377
337
  unlink: this.unlink,
378
338
  cwd: this.cwd,
379
- mode: mode,
380
- }, cb);
339
+ mode,
340
+ };
381
341
  }
382
- [DOCHOWN](entry) {
383
- // in preserve owner mode, chown if the entry doesn't match process
384
- // in set owner mode, chown if setting doesn't match process
385
- return (this.forceChown ||
342
+ /**
343
+ * The owner to set on the entry, if it needs one: with
344
+ * `preserveOwner`, when the owner in the archive is not the process
345
+ * owner, and with `uid` and `gid`, when they are not the process
346
+ * owner.
347
+ */
348
+ owner(entry) {
349
+ const doChown = this.forceChown ||
386
350
  (this.preserveOwner &&
387
351
  ((typeof entry.uid === 'number' &&
388
352
  entry.uid !== this.processUid) ||
389
353
  (typeof entry.gid === 'number' &&
390
354
  entry.gid !== this.processGid))) ||
391
355
  (typeof this.uid === 'number' && this.uid !== this.processUid) ||
392
- (typeof this.gid === 'number' && this.gid !== this.processGid));
393
- }
394
- [UID](entry) {
395
- return uint32(this.uid, entry.uid, this.processUid);
396
- }
397
- [GID](entry) {
398
- return uint32(this.gid, entry.gid, this.processGid);
356
+ (typeof this.gid === 'number' && this.gid !== this.processGid);
357
+ const uid = uint32(this.uid, entry.uid, this.processUid);
358
+ const gid = uint32(this.gid, entry.gid, this.processGid);
359
+ return doChown && typeof uid === 'number' && typeof gid === 'number' ?
360
+ { uid, gid }
361
+ : undefined;
362
+ }
363
+ /** The times to set on the entry, if it needs them. */
364
+ times(entry) {
365
+ return entry.mtime && !this.noMtime ?
366
+ { atime: entry.atime || new Date(), mtime: entry.mtime }
367
+ : undefined;
368
+ }
369
+ /** True if the object on disk at the path of the entry must stay. */
370
+ skip(entry, st) {
371
+ return (this.keep || (this.newer && st.mtime > (entry.mtime ?? st.mtime)));
372
+ }
373
+ /**
374
+ * True if the entry can be written into the file that is on disk.
375
+ * A file with more than one link is not used, because the write
376
+ * would change the other links. Windows does not report a useful
377
+ * link count.
378
+ */
379
+ isReusable(entry, st) {
380
+ return (entry.type === 'File' &&
381
+ !this.unlink &&
382
+ st.isFile() &&
383
+ st.nlink <= 1 &&
384
+ !this.win32);
385
+ }
386
+ /**
387
+ * The parts of the path from the extraction directory to the
388
+ * target of a link entry. None of them can be a symbolic link.
389
+ */
390
+ linkParts(entry, absolute) {
391
+ const linkpath = String(entry.linkpath);
392
+ return entry.type === 'Link' ?
393
+ linkpath.split('/')
394
+ : relative(this.cwd, this.resolve(this.dirname(absolute), linkpath)).split('/');
395
+ }
396
+ /**
397
+ * The parts of the path from the extraction directory to the
398
+ * parent directory of an entry. The extraction checks them again
399
+ * after it makes the entry: none of them can be a symbolic link
400
+ * then. So a directory that another process replaced with a
401
+ * symbolic link during the extraction is an error of the entry.
402
+ */
403
+ parentParts(absolute) {
404
+ const { cwd } = this;
405
+ const parent = absolute === cwd ? cwd : this.dirname(absolute);
406
+ return parent === cwd ? [] : relative(cwd, parent).split('/');
407
+ }
408
+ /** The error for a link target that goes through a symbolic link. */
409
+ symlinkError(symlink, parts) {
410
+ return new SymlinkError(symlink, this.resolve(this.cwd, parts.join('/')));
399
411
  }
400
- [FILE](entry, fullyDone) {
401
- const mode = typeof entry.mode === 'number' ? entry.mode & 0o7777 : this.fmode;
402
- const stream = new fsm.WriteStream(String(entry.absolute), {
403
- // slight lie, but it can be numeric flags
404
- flags: getWriteFlag(entry.size),
405
- mode: mode,
406
- autoClose: false,
407
- });
408
- stream.on('error', (er) => {
409
- if (stream.fd) {
410
- fs.close(stream.fd, () => { });
411
- }
412
- // flush all the data out so that we aren't left hanging
413
- // if the error wasn't actually fatal. otherwise the parse
414
- // is blocked, and we never proceed.
415
- stream.write = () => true;
416
- this[ONERROR](er, entry);
417
- fullyDone();
418
- });
419
- let actions = 1;
420
- const done = (er) => {
421
- if (er) {
422
- /* c8 ignore start - we should always have a fd by now */
423
- if (stream.fd) {
424
- fs.close(stream.fd, () => { });
412
+ }
413
+ // Unlinks on Windows are not atomic. A file that is made at the path
414
+ // of a file that was just removed can be removed with it. So rename
415
+ // the file first, and then remove it under the new name.
416
+ const deleteName = (path) => path +
417
+ '.DELETE.' +
418
+ Array.from(crypto.getRandomValues(new Uint8Array(16)), b => b.toString(16).padStart(2, '0')).join('');
419
+ /**
420
+ * Extracts the entries of an archive with async file system
421
+ * functions.
422
+ *
423
+ * Several entries are extracted at one time. Entries that use the
424
+ * same path, or a path and a directory above it, are extracted in
425
+ * the order of the archive.
426
+ */
427
+ export class Unpack extends UnpackBase {
428
+ #fs;
429
+ #reservations;
430
+ #jobs;
431
+ // the number of entries that are in work
432
+ #active = 0;
433
+ #wake;
434
+ #checkedCwd = false;
435
+ #cwdCheck;
436
+ constructor(opt) {
437
+ super(opt);
438
+ this.#fs = this.opt.fs;
439
+ this.#reservations = new PathReservations(this.win32);
440
+ this.#jobs = countOption('jobs', this.opt.jobs, DEFAULT_JOBS);
441
+ }
442
+ /**
443
+ * Extract the archive. The promise settles when all the file
444
+ * system work is done. It rejects with the first error that stops
445
+ * the extraction.
446
+ */
447
+ async extract(input) {
448
+ const reader = new TarReader(input, this.readerOptions());
449
+ const { onEntry } = this.opt;
450
+ const stream = !!this.opt.transform;
451
+ try {
452
+ while (!this.fatal) {
453
+ const entry = reader.poll();
454
+ if (entry === null)
455
+ break;
456
+ if (entry === undefined) {
457
+ await reader.fill();
458
+ continue;
425
459
  }
426
- /* c8 ignore stop */
427
- this[ONERROR](er, entry);
428
- fullyDone();
429
- return;
430
- }
431
- if (--actions === 0) {
432
- if (stream.fd !== undefined) {
433
- fs.close(stream.fd, er => {
434
- if (er) {
435
- this[ONERROR](er, entry);
460
+ if (onEntry)
461
+ await onEntry(entry);
462
+ // The caller took the content, so there is nothing to write.
463
+ if (entry.bodyUsed)
464
+ continue;
465
+ if (!this.check(entry))
466
+ continue;
467
+ // A file whose content is all in memory is written while the
468
+ // next entries are read. Other files are written as their
469
+ // content arrives.
470
+ const body = [];
471
+ let inMemory = !stream;
472
+ if (inMemory && fileTypes.has(entry.type)) {
473
+ for (;;) {
474
+ const part = reader.readBody(entry);
475
+ if (part === null)
476
+ break;
477
+ if (part === undefined) {
478
+ inMemory = false;
479
+ break;
436
480
  }
437
- else {
438
- this[UNPEND]();
439
- }
440
- fullyDone();
441
- });
481
+ body.push(part);
482
+ }
442
483
  }
484
+ const work = this.#start(entry, body, inMemory ? undefined : reader);
485
+ if (!inMemory)
486
+ await work;
487
+ while (this.#active >= this.#jobs)
488
+ await this.#idle();
443
489
  }
444
- };
445
- stream.on('finish', () => {
446
- // if futimes fails, try utimes
447
- // if utimes fails, fail with the original error
448
- // same for fchown/chown
449
- const abs = String(entry.absolute);
450
- const fd = stream.fd;
451
- if (typeof fd === 'number' && entry.mtime && !this.noMtime) {
452
- actions++;
453
- const atime = entry.atime || new Date();
454
- const mtime = entry.mtime;
455
- fs.futimes(fd, atime, mtime, er => er ?
456
- fs.utimes(abs, atime, mtime, er2 => done(er2 && er))
457
- : done());
458
- }
459
- if (typeof fd === 'number' && this[DOCHOWN](entry)) {
460
- actions++;
461
- const uid = this[UID](entry);
462
- const gid = this[GID](entry);
463
- if (typeof uid === 'number' && typeof gid === 'number') {
464
- fs.fchown(fd, uid, gid, er => er ? fs.chown(abs, uid, gid, er2 => done(er2 && er)) : done());
465
- }
490
+ }
491
+ catch (er) {
492
+ this.fail(er);
493
+ }
494
+ await reader.return().catch(er => this.fail(er));
495
+ while (this.#active > 0)
496
+ await this.#idle();
497
+ if (this.fatal) {
498
+ const { error } = this.fatal;
499
+ if (error && typeof error === 'object' && 'tarCode' in error) {
500
+ Object.assign(error, { cwd: this.cwd });
466
501
  }
467
- done();
468
- });
469
- const tx = this.transform ? this.transform(entry) || entry : entry;
470
- if (tx !== entry) {
471
- tx.on('error', er => {
472
- this[ONERROR](er, entry);
473
- fullyDone();
474
- });
475
- entry.pipe(tx);
502
+ throw error;
476
503
  }
477
- tx.pipe(stream);
478
504
  }
479
- [DIRECTORY](entry, fullyDone) {
480
- const mode = typeof entry.mode === 'number' ? entry.mode & 0o7777 : this.dmode;
481
- this[MKDIR](String(entry.absolute), mode, er => {
482
- if (er) {
483
- this[ONERROR](er, entry);
484
- fullyDone();
485
- return;
505
+ // Resolves when an entry that is in work is done.
506
+ #idle() {
507
+ return new Promise(res => {
508
+ this.#wake = res;
509
+ });
510
+ }
511
+ // Extract the entry when its paths are free. The promise never
512
+ // rejects: a failure is a warning, or it sets `fatal`.
513
+ #start(entry, body, reader) {
514
+ this.#active++;
515
+ return this.#reservations.reserve(this.reservedPaths(entry), async () => {
516
+ try {
517
+ if (!this.fatal)
518
+ await this.#extract(entry, body, reader);
486
519
  }
487
- let actions = 1;
488
- const done = () => {
489
- if (--actions === 0) {
490
- fullyDone();
491
- this[UNPEND]();
492
- entry.resume();
520
+ catch (er) {
521
+ try {
522
+ this.entryError(er, entry);
523
+ }
524
+ catch (fatal) {
525
+ this.fail(fatal);
493
526
  }
494
- };
495
- if (entry.mtime && !this.noMtime) {
496
- actions++;
497
- fs.utimes(String(entry.absolute), entry.atime || new Date(), entry.mtime, done);
498
- }
499
- if (this[DOCHOWN](entry)) {
500
- actions++;
501
- fs.chown(String(entry.absolute), Number(this[UID](entry)), Number(this[GID](entry)), done);
502
527
  }
503
- done();
504
- });
505
- }
506
- [UNSUPPORTED](entry) {
507
- entry.unsupported = true;
508
- this.warn('TAR_ENTRY_UNSUPPORTED', `unsupported entry type: ${entry.type}`, { entry });
509
- entry.resume();
510
- }
511
- [SYMLINK](entry, done) {
512
- const parts = normalizeWindowsPath(path.relative(this.cwd, path.resolve(path.dirname(String(entry.absolute)), String(entry.linkpath)))).split('/');
513
- this[ENSURE_NO_SYMLINK](entry, this.cwd, parts, () => this[LINK](entry, String(entry.linkpath), 'symlink', done), er => {
514
- this[ONERROR](er, entry);
515
- done();
516
- });
517
- }
518
- [HARDLINK](entry, done) {
519
- const linkpath = normalizeWindowsPath(path.resolve(this.cwd, String(entry.linkpath)));
520
- const parts = normalizeWindowsPath(String(entry.linkpath)).split('/');
521
- this[ENSURE_NO_SYMLINK](entry, this.cwd, parts, () => this[LINK](entry, linkpath, 'link', done), er => {
522
- this[ONERROR](er, entry);
523
- done();
524
- });
525
- }
526
- [ENSURE_NO_SYMLINK](entry, cwd, parts, done, onError) {
527
- const p = parts.shift();
528
- if (this.preservePaths || p === undefined)
529
- return done();
530
- const t = path.resolve(cwd, p);
531
- fs.lstat(t, (er, st) => {
532
- if (er)
533
- return done();
534
- if (st?.isSymbolicLink()) {
535
- return onError(new SymlinkError(t, path.resolve(t, parts.join('/'))));
536
- }
537
- this[ENSURE_NO_SYMLINK](entry, t, parts, done, onError);
528
+ this.#active--;
529
+ this.#wake?.();
538
530
  });
539
531
  }
540
- [PEND]() {
541
- this[PENDING]++;
542
- }
543
- [UNPEND]() {
544
- this[PENDING]--;
545
- this[MAYBECLOSE]();
532
+ #mkdir(dir, mode) {
533
+ return mkdir(this.#fs, dir, this.mkdirOptions(mode));
534
+ }
535
+ // The extraction directory must exist. Entries that start at the
536
+ // same time share one check.
537
+ #checkCwd() {
538
+ return (this.#cwdCheck ??= this.#mkdir(this.cwd, this.dmode).then(() => {
539
+ this.#checkedCwd = true;
540
+ }, er => {
541
+ this.#cwdCheck = undefined;
542
+ throw er;
543
+ }));
544
+ }
545
+ async #extract(entry, body, reader) {
546
+ const fs = this.#fs;
547
+ const absolute = entry.absolute;
548
+ const { cwd } = this;
549
+ if (!this.#checkedCwd)
550
+ await this.#checkCwd();
551
+ if (absolute !== cwd) {
552
+ const parent = this.dirname(absolute);
553
+ if (parent !== cwd)
554
+ await this.#mkdir(parent, this.dmode);
555
+ }
556
+ // Remove what is at the path, if the entry cannot use it.
557
+ const st = await fs.lstat(absolute).catch(() => undefined);
558
+ if (st && this.skip(entry, st))
559
+ return;
560
+ if (st && !this.isReusable(entry, st)) {
561
+ if (st.isDirectory() && dirTypes.has(entry.type)) {
562
+ if (this.chmod &&
563
+ entry.mode &&
564
+ (st.mode & 0o7777) !== entry.mode) {
565
+ await fs.chmod(absolute, entry.mode);
566
+ }
567
+ }
568
+ else if (absolute !== cwd) {
569
+ if (st.isDirectory())
570
+ await fs.rmdir(absolute);
571
+ else
572
+ await this.#unlink(absolute);
573
+ }
574
+ }
575
+ if (fileTypes.has(entry.type)) {
576
+ return this.#file(entry, absolute, body, reader);
577
+ }
578
+ if (dirTypes.has(entry.type))
579
+ await this.#directory(entry, absolute);
580
+ else {
581
+ await this.#ensureNoSymlink(this.linkParts(entry, absolute));
582
+ const linkpath = String(entry.linkpath);
583
+ if (entry.type === 'Link') {
584
+ await fs.link(this.resolve(cwd, linkpath), absolute);
585
+ }
586
+ else {
587
+ await fs.symlink(linkpath, absolute);
588
+ }
589
+ }
590
+ await this.#ensureNoSymlink(this.parentParts(absolute));
546
591
  }
547
- [SKIP](entry) {
548
- this[UNPEND]();
549
- entry.resume();
592
+ async #unlink(path) {
593
+ const fs = this.#fs;
594
+ if (!this.win32)
595
+ return fs.unlink(path);
596
+ const name = deleteName(path);
597
+ await fs.rename(path, name);
598
+ await fs.unlink(name);
550
599
  }
551
- // Check if we can reuse an existing filesystem entry safely and
552
- // overwrite it, rather than unlinking and recreating
553
- // Windows doesn't report a useful nlink, so we just never reuse entries
554
- [ISREUSABLE](entry, st) {
555
- return (entry.type === 'File' &&
556
- !this.unlink &&
557
- st.isFile() &&
558
- st.nlink <= 1 &&
559
- !isWindows);
600
+ async #ensureNoSymlink(parts) {
601
+ if (this.preservePaths)
602
+ return;
603
+ let t = this.cwd;
604
+ for (const p of parts) {
605
+ t = this.resolve(t, p);
606
+ const st = await this.#fs.lstat(t).catch(() => undefined);
607
+ if (!st)
608
+ return;
609
+ if (st.isSymbolicLink())
610
+ throw this.symlinkError(t, parts);
611
+ }
560
612
  }
561
- // check if a thing is there, and if so, try to clobber it
562
- [CHECKFS](entry) {
563
- this[PEND]();
564
- const paths = [entry.path];
565
- if (entry.linkpath) {
566
- paths.push(entry.linkpath);
613
+ async #directory(entry, absolute) {
614
+ const fs = this.#fs;
615
+ await this.#mkdir(absolute, entry.mode ?? this.dmode);
616
+ // These do not follow a symbolic link that replaced the
617
+ // directory. A failure is not an error of the entry.
618
+ const times = this.times(entry);
619
+ if (times) {
620
+ await fs.lutimes(absolute, times.atime, times.mtime).catch(() => { });
621
+ }
622
+ const owner = this.owner(entry);
623
+ if (owner) {
624
+ await fs.lchown(absolute, owner.uid, owner.gid).catch(() => { });
567
625
  }
568
- this.reservations.reserve(paths, done => this[CHECKFS2](entry, done));
569
626
  }
570
- [CHECKFS2](entry, fullyDone) {
571
- const done = (er) => {
572
- fullyDone(er);
573
- };
574
- const checkCwd = () => {
575
- this[MKDIR](this.cwd, this.dmode, er => {
576
- if (er) {
577
- this[ONERROR](er, entry);
578
- done();
579
- return;
627
+ async #file(entry, absolute, body, reader) {
628
+ const fs = this.#fs;
629
+ const handle = await fs.open(absolute, this.writeFlag(entry.size), entry.mode ?? this.fmode);
630
+ try {
631
+ // The file is open. Write to it only if no parent directory
632
+ // became a symbolic link before the open.
633
+ await this.#ensureNoSymlink(this.parentParts(absolute));
634
+ if (reader)
635
+ await this.#pipe(entry, body, reader, handle);
636
+ else
637
+ for (const part of body)
638
+ await handle.write(part);
639
+ // Use the open file, so that a symbolic link that replaced the
640
+ // path is not followed. If that fails, use the path.
641
+ const times = this.times(entry);
642
+ if (times) {
643
+ const { atime, mtime } = times;
644
+ await handle.utimes(atime, mtime).catch(async (er) => {
645
+ await fs.utimes(absolute, atime, mtime).catch(() => {
646
+ throw er;
647
+ });
648
+ });
649
+ }
650
+ const owner = this.owner(entry);
651
+ if (owner) {
652
+ const { uid, gid } = owner;
653
+ await handle.chown(uid, gid).catch(async (er) => {
654
+ await fs.chown(absolute, uid, gid).catch(() => {
655
+ throw er;
656
+ });
657
+ });
658
+ }
659
+ }
660
+ catch (er) {
661
+ await handle.close().catch(() => { });
662
+ throw er;
663
+ }
664
+ await handle.close();
665
+ }
666
+ // Write the content of the entry as it arrives, through the
667
+ // transform stream if there is one.
668
+ async #pipe(entry, body, reader, handle) {
669
+ let i = 0;
670
+ const next = async () => {
671
+ if (i < body.length)
672
+ return body[i++];
673
+ try {
674
+ for (;;) {
675
+ const part = reader.readBody(entry);
676
+ if (part !== undefined)
677
+ return part;
678
+ await reader.fill();
580
679
  }
581
- this[CHECKED_CWD] = true;
582
- start();
583
- });
680
+ }
681
+ catch (er) {
682
+ // The archive cannot be read.
683
+ throw this.fail(er);
684
+ }
584
685
  };
585
- const start = () => {
586
- if (entry.absolute !== this.cwd) {
587
- const parent = normalizeWindowsPath(path.dirname(String(entry.absolute)));
588
- if (parent !== this.cwd) {
589
- return this[MKDIR](parent, this.dmode, er => {
590
- if (er) {
591
- this[ONERROR](er, entry);
592
- done();
593
- return;
594
- }
595
- afterMakeParent();
686
+ const tx = this.opt.transform?.(entry);
687
+ if (!tx) {
688
+ // Write one part while the next part is read.
689
+ let writing;
690
+ let failed;
691
+ try {
692
+ for (let part; (part = await next());) {
693
+ await writing;
694
+ if (failed)
695
+ break;
696
+ writing = handle.write(part).then(() => { }, error => {
697
+ failed = { error };
596
698
  });
597
699
  }
598
700
  }
599
- afterMakeParent();
701
+ finally {
702
+ await writing;
703
+ }
704
+ if (failed)
705
+ throw failed.error;
706
+ return;
707
+ }
708
+ const writer = tx.writable.getWriter();
709
+ const out = tx.readable.getReader();
710
+ let failed;
711
+ // Stop the two streams. A read that waits gets the end of the
712
+ // stream, and a write that waits fails.
713
+ const stop = async (error) => {
714
+ failed ??= { error };
715
+ await out.cancel(error).catch(() => { });
716
+ await writer.abort(error).catch(() => { });
600
717
  };
601
- const afterMakeParent = () => {
602
- fs.lstat(String(entry.absolute), (lstatEr, st) => {
603
- if (st &&
604
- (this.keep ||
605
- /* c8 ignore next */
606
- (this.newer && st.mtime > (entry.mtime ?? st.mtime)))) {
607
- this[SKIP](entry);
608
- done();
609
- return;
610
- }
611
- if (lstatEr || this[ISREUSABLE](entry, st)) {
612
- return this[MAKEFS](null, entry, done);
613
- }
614
- if (st.isDirectory()) {
615
- if (entry.type === 'Directory') {
616
- const needChmod = this.chmod && entry.mode && (st.mode & 0o7777) !== entry.mode;
617
- const afterChmod = (er) => this[MAKEFS](er ?? null, entry, done);
618
- if (!needChmod) {
619
- return afterChmod();
620
- }
621
- return fs.chmod(String(entry.absolute), Number(entry.mode), afterChmod);
622
- }
623
- // Not a dir entry, have to remove it.
624
- // NB: the only way to end up with an entry that is the cwd
625
- // itself, in such a way that == does not detect, is a
626
- // tricky windows absolute path with UNC or 8.3 parts (and
627
- // preservePaths:true, or else it will have been stripped).
628
- // In that case, the user has opted out of path protections
629
- // explicitly, so if they blow away the cwd, c'est la vie.
630
- if (entry.absolute !== this.cwd) {
631
- return fs.rmdir(String(entry.absolute), (er) => this[MAKEFS](er ?? null, entry, done));
632
- }
718
+ const feed = (async () => {
719
+ try {
720
+ for (let part; (part = await next());)
721
+ await writer.write(part);
722
+ await writer.close();
723
+ }
724
+ catch (er) {
725
+ await stop(er);
726
+ }
727
+ })();
728
+ try {
729
+ for (;;) {
730
+ const { done, value } = await out.read();
731
+ if (done)
732
+ break;
733
+ await handle.write(value);
734
+ }
735
+ }
736
+ catch (er) {
737
+ await stop(er);
738
+ }
739
+ // The feed reads the archive, so it must end before the next
740
+ // entry is read.
741
+ await feed;
742
+ if (failed)
743
+ throw failed.error;
744
+ }
745
+ }
746
+ /**
747
+ * Extracts the entries of an archive with sync file system
748
+ * functions, one entry at a time.
749
+ */
750
+ export class UnpackSync extends UnpackBase {
751
+ #fs;
752
+ #checkedCwd = false;
753
+ constructor(opt) {
754
+ super(opt);
755
+ this.#fs = this.opt.fs;
756
+ }
757
+ /** Extract the archive. Throws the first error that stops it. */
758
+ extract(input) {
759
+ const reader = new TarReaderSync(input, this.readerOptions());
760
+ const { onEntry } = this.opt;
761
+ try {
762
+ for (const entry of reader) {
763
+ onEntry?.(entry);
764
+ if (entry.bodyUsed)
765
+ continue;
766
+ if (!this.check(entry))
767
+ continue;
768
+ try {
769
+ this.#extract(entry, reader);
633
770
  }
634
- // not a dir, and not reusable
635
- // don't remove if the cwd, we want that error
636
- if (entry.absolute === this.cwd) {
637
- return this[MAKEFS](null, entry, done);
771
+ catch (er) {
772
+ this.entryError(er, entry);
638
773
  }
639
- unlinkFile(String(entry.absolute), er => this[MAKEFS](er ?? null, entry, done));
640
- });
641
- };
642
- if (this[CHECKED_CWD]) {
643
- start();
774
+ }
644
775
  }
645
- else {
646
- checkCwd();
776
+ catch (error) {
777
+ if (error && typeof error === 'object' && 'tarCode' in error) {
778
+ Object.assign(error, { cwd: this.cwd });
779
+ }
780
+ throw error;
647
781
  }
648
782
  }
649
- [MAKEFS](er, entry, done) {
650
- if (er) {
651
- this[ONERROR](er, entry);
652
- done();
783
+ #mkdir(dir, mode) {
784
+ mkdirSync(this.#fs, dir, this.mkdirOptions(mode));
785
+ }
786
+ #extract(entry, reader) {
787
+ const fs = this.#fs;
788
+ const absolute = entry.absolute;
789
+ const { cwd } = this;
790
+ if (!this.#checkedCwd) {
791
+ this.#mkdir(cwd, this.dmode);
792
+ this.#checkedCwd = true;
793
+ }
794
+ if (absolute !== cwd) {
795
+ const parent = this.dirname(absolute);
796
+ if (parent !== cwd)
797
+ this.#mkdir(parent, this.dmode);
798
+ }
799
+ // Remove what is at the path, if the entry cannot use it.
800
+ let st;
801
+ try {
802
+ st = fs.lstatSync(absolute);
803
+ }
804
+ catch { }
805
+ if (st && this.skip(entry, st))
653
806
  return;
807
+ if (st && !this.isReusable(entry, st)) {
808
+ if (st.isDirectory() && dirTypes.has(entry.type)) {
809
+ if (this.chmod &&
810
+ entry.mode &&
811
+ (st.mode & 0o7777) !== entry.mode) {
812
+ fs.chmodSync(absolute, entry.mode);
813
+ }
814
+ }
815
+ else if (absolute !== cwd) {
816
+ if (st.isDirectory())
817
+ fs.rmdirSync(absolute);
818
+ else
819
+ this.#unlink(absolute);
820
+ }
654
821
  }
655
- switch (entry.type) {
656
- case 'File':
657
- case 'OldFile':
658
- case 'ContiguousFile':
659
- return this[FILE](entry, done);
660
- case 'Link':
661
- return this[HARDLINK](entry, done);
662
- case 'SymbolicLink':
663
- return this[SYMLINK](entry, done);
664
- case 'Directory':
665
- case 'GNUDumpDir':
666
- return this[DIRECTORY](entry, done);
667
- }
668
- }
669
- [LINK](entry, linkpath, link, done) {
670
- fs[link](linkpath, String(entry.absolute), er => {
671
- if (er) {
672
- this[ONERROR](er, entry);
822
+ if (fileTypes.has(entry.type)) {
823
+ return this.#file(entry, absolute, reader);
824
+ }
825
+ if (dirTypes.has(entry.type))
826
+ this.#directory(entry, absolute);
827
+ else {
828
+ this.#ensureNoSymlink(this.linkParts(entry, absolute));
829
+ const linkpath = String(entry.linkpath);
830
+ if (entry.type === 'Link') {
831
+ fs.linkSync(this.resolve(cwd, linkpath), absolute);
673
832
  }
674
833
  else {
675
- this[UNPEND]();
676
- entry.resume();
677
- }
678
- done();
679
- });
680
- }
681
- }
682
- const callSync = (fn) => {
683
- try {
684
- return [null, fn()];
685
- }
686
- catch (er) {
687
- return [er, null];
688
- }
689
- };
690
- export class UnpackSync extends Unpack {
691
- sync = true;
692
- [MAKEFS](er, entry) {
693
- return super[MAKEFS](er, entry, () => { });
694
- }
695
- [CHECKFS](entry) {
696
- if (!this[CHECKED_CWD]) {
697
- const er = this[MKDIR](this.cwd, this.dmode);
698
- if (er) {
699
- return this[ONERROR](er, entry);
700
- }
701
- this[CHECKED_CWD] = true;
702
- }
703
- // don't bother to make the parent if the current entry is the cwd,
704
- // we've already checked it.
705
- if (entry.absolute !== this.cwd) {
706
- const parent = normalizeWindowsPath(path.dirname(String(entry.absolute)));
707
- if (parent !== this.cwd) {
708
- const mkParent = this[MKDIR](parent, this.dmode);
709
- if (mkParent) {
710
- return this[ONERROR](mkParent, entry);
711
- }
834
+ fs.symlinkSync(linkpath, absolute);
712
835
  }
713
836
  }
714
- const [lstatEr, st] = callSync(() => fs.lstatSync(String(entry.absolute)));
715
- if (st &&
716
- (this.keep ||
717
- /* c8 ignore next */
718
- (this.newer && st.mtime > (entry.mtime ?? st.mtime)))) {
719
- return this[SKIP](entry);
720
- }
721
- if (lstatEr || this[ISREUSABLE](entry, st)) {
722
- return this[MAKEFS](null, entry);
723
- }
724
- if (st.isDirectory()) {
725
- if (entry.type === 'Directory') {
726
- const needChmod = this.chmod && entry.mode && (st.mode & 0o7777) !== entry.mode;
727
- const [er] = needChmod ?
728
- callSync(() => {
729
- fs.chmodSync(String(entry.absolute), Number(entry.mode));
730
- })
731
- : [];
732
- return this[MAKEFS](er, entry);
733
- }
734
- // not a dir entry, have to remove it
735
- const [er] = callSync(() => fs.rmdirSync(String(entry.absolute)));
736
- this[MAKEFS](er, entry);
737
- }
738
- // not a dir, and not reusable.
739
- // don't remove if it's the cwd, since we want that error.
740
- const [er] = entry.absolute === this.cwd ?
741
- []
742
- : callSync(() => unlinkFileSync(String(entry.absolute)));
743
- this[MAKEFS](er, entry);
744
- }
745
- [FILE](entry, done) {
746
- const mode = typeof entry.mode === 'number' ? entry.mode & 0o7777 : this.fmode;
747
- const oner = (er) => {
748
- let closeError;
837
+ this.#ensureNoSymlink(this.parentParts(absolute));
838
+ }
839
+ #unlink(path) {
840
+ const fs = this.#fs;
841
+ if (!this.win32)
842
+ return fs.unlinkSync(path);
843
+ const name = deleteName(path);
844
+ fs.renameSync(path, name);
845
+ fs.unlinkSync(name);
846
+ }
847
+ #ensureNoSymlink(parts) {
848
+ if (this.preservePaths)
849
+ return;
850
+ let t = this.cwd;
851
+ for (const p of parts) {
852
+ t = this.resolve(t, p);
853
+ let st;
749
854
  try {
750
- fs.closeSync(fd);
751
- }
752
- catch (e) {
753
- closeError = e;
855
+ st = this.#fs.lstatSync(t);
754
856
  }
755
- if (er || closeError) {
756
- this[ONERROR](er || closeError, entry);
857
+ catch {
858
+ return;
757
859
  }
758
- done();
759
- };
760
- let fd;
761
- try {
762
- fd = fs.openSync(String(entry.absolute), getWriteFlag(entry.size), mode);
763
- /* c8 ignore start - This is only a problem if the file was successfully
764
- * statted, BUT failed to open. Testing this is annoying, and we
765
- * already have ample testint for other uses of oner() methods.
766
- */
860
+ if (st.isSymbolicLink())
861
+ throw this.symlinkError(t, parts);
767
862
  }
768
- catch (er) {
769
- return oner(er);
770
- }
771
- /* c8 ignore stop */
772
- const tx = this.transform ? this.transform(entry) || entry : entry;
773
- if (tx !== entry) {
774
- tx.on('error', er => this[ONERROR](er, entry));
775
- entry.pipe(tx);
863
+ }
864
+ #directory(entry, absolute) {
865
+ const fs = this.#fs;
866
+ this.#mkdir(absolute, entry.mode ?? this.dmode);
867
+ // These do not follow a symbolic link that replaced the
868
+ // directory. A failure is not an error of the entry.
869
+ const times = this.times(entry);
870
+ if (times) {
871
+ try {
872
+ fs.lutimesSync(absolute, times.atime, times.mtime);
873
+ }
874
+ catch { }
776
875
  }
777
- tx.on('data', (chunk) => {
876
+ const owner = this.owner(entry);
877
+ if (owner) {
778
878
  try {
779
- fs.writeSync(fd, chunk, 0, chunk.length);
879
+ fs.lchownSync(absolute, owner.uid, owner.gid);
780
880
  }
781
- catch (er) {
782
- oner(er);
881
+ catch { }
882
+ }
883
+ }
884
+ #file(entry, absolute, reader) {
885
+ const fs = this.#fs;
886
+ const fd = fs.openSync(absolute, this.writeFlag(entry.size), entry.mode ?? this.fmode);
887
+ try {
888
+ // The file is open. Write to it only if no parent directory
889
+ // became a symbolic link before the open.
890
+ this.#ensureNoSymlink(this.parentParts(absolute));
891
+ const tx = this.opt.transform?.(entry);
892
+ for (;;) {
893
+ let part;
894
+ try {
895
+ part = reader.readBody(entry);
896
+ }
897
+ catch (er) {
898
+ // The archive cannot be read.
899
+ throw this.fail(er);
900
+ }
901
+ if (!part)
902
+ break;
903
+ fs.writeSync(fd, tx ? tx(part) : part);
783
904
  }
784
- });
785
- tx.on('end', () => {
786
- let er = null;
787
- // try both, falling futimes back to utimes
788
- // if either fails, handle the first error
789
- if (entry.mtime && !this.noMtime) {
790
- const atime = entry.atime || new Date();
791
- const mtime = entry.mtime;
905
+ // Use the open file, so that a symbolic link that replaced the
906
+ // path is not followed. If that fails, use the path.
907
+ const times = this.times(entry);
908
+ if (times) {
909
+ const { atime, mtime } = times;
792
910
  try {
793
911
  fs.futimesSync(fd, atime, mtime);
794
912
  }
795
- catch (futimeser) {
913
+ catch (er) {
796
914
  try {
797
- fs.utimesSync(String(entry.absolute), atime, mtime);
915
+ fs.utimesSync(absolute, atime, mtime);
798
916
  }
799
917
  catch {
800
- er = futimeser;
918
+ throw er;
801
919
  }
802
920
  }
803
921
  }
804
- if (this[DOCHOWN](entry)) {
805
- const uid = this[UID](entry);
806
- const gid = this[GID](entry);
922
+ const owner = this.owner(entry);
923
+ if (owner) {
924
+ const { uid, gid } = owner;
807
925
  try {
808
- fs.fchownSync(fd, Number(uid), Number(gid));
926
+ fs.fchownSync(fd, uid, gid);
809
927
  }
810
- catch (fchowner) {
928
+ catch (er) {
811
929
  try {
812
- fs.chownSync(String(entry.absolute), Number(uid), Number(gid));
930
+ fs.chownSync(absolute, uid, gid);
813
931
  }
814
932
  catch {
815
- er = er || fchowner;
933
+ throw er;
816
934
  }
817
935
  }
818
936
  }
819
- oner(er);
820
- });
821
- }
822
- [DIRECTORY](entry, done) {
823
- const mode = typeof entry.mode === 'number' ? entry.mode & 0o7777 : this.dmode;
824
- const er = this[MKDIR](String(entry.absolute), mode);
825
- if (er) {
826
- this[ONERROR](er, entry);
827
- done();
828
- return;
829
- }
830
- if (entry.mtime && !this.noMtime) {
831
- try {
832
- fs.utimesSync(String(entry.absolute), entry.atime || new Date(), entry.mtime);
833
- /* c8 ignore next */
834
- }
835
- catch { }
836
937
  }
837
- if (this[DOCHOWN](entry)) {
938
+ catch (er) {
939
+ // Close the file one time, and do not use the descriptor again:
940
+ // the system can give its number to a different file.
838
941
  try {
839
- fs.chownSync(String(entry.absolute), Number(this[UID](entry)), Number(this[GID](entry)));
942
+ fs.closeSync(fd);
840
943
  }
841
944
  catch { }
945
+ throw er;
842
946
  }
843
- done();
844
- entry.resume();
845
- }
846
- [MKDIR](dir, mode) {
847
- try {
848
- return mkdirSync(normalizeWindowsPath(dir), {
849
- uid: this.uid,
850
- gid: this.gid,
851
- processUid: this.processUid,
852
- processGid: this.processGid,
853
- umask: this.processUmask,
854
- preserve: this.preservePaths,
855
- unlink: this.unlink,
856
- cwd: this.cwd,
857
- mode: mode,
858
- });
859
- }
860
- catch (er) {
861
- return er;
862
- }
863
- }
864
- [ENSURE_NO_SYMLINK](_entry, cwd, parts, done, onError) {
865
- if (this.preservePaths || parts.length === 0)
866
- return done();
867
- let t = cwd;
868
- for (const p of parts) {
869
- t = path.resolve(t, p);
870
- const [er, st] = callSync(() => fs.lstatSync(t));
871
- if (er)
872
- return done();
873
- if (st.isSymbolicLink()) {
874
- return onError(new SymlinkError(t, path.resolve(cwd, parts.join('/'))));
875
- }
876
- }
877
- done();
878
- }
879
- [LINK](entry, linkpath, link, done) {
880
- const linkSync = `${link}Sync`;
881
- try {
882
- fs[linkSync](linkpath, String(entry.absolute));
883
- done();
884
- entry.resume();
885
- }
886
- catch (er) {
887
- return this[ONERROR](er, entry);
888
- }
947
+ fs.closeSync(fd);
889
948
  }
890
949
  }
891
950
  //# sourceMappingURL=unpack.js.map