read-excel-file 9.2.0 → 9.3.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 (205) hide show
  1. package/.gitlab-ci.yml +1 -1
  2. package/CHANGELOG.md +5 -0
  3. package/README.md +153 -50
  4. package/bundle/read-excel-file.min.js +1 -1
  5. package/bundle/read-excel-file.min.js.map +1 -1
  6. package/bundle/read-excel-file.min.old.js +2 -0
  7. package/bundle/read-excel-file.min.old.js.map +1 -0
  8. package/commonjs/export/convertValuesFromUint8ArraysToStrings.js +3 -0
  9. package/commonjs/export/convertValuesFromUint8ArraysToStrings.js.map +1 -1
  10. package/commonjs/export/parseSheet.js +12 -9
  11. package/commonjs/export/parseSheet.js.map +1 -1
  12. package/commonjs/export/readSheetBrowser.js +6 -2
  13. package/commonjs/export/readSheetBrowser.js.map +1 -1
  14. package/commonjs/export/readSheetNode.js +6 -2
  15. package/commonjs/export/readSheetNode.js.map +1 -1
  16. package/commonjs/export/readSheetUniversal.js +14 -2
  17. package/commonjs/export/readSheetUniversal.js.map +1 -1
  18. package/commonjs/export/readSheetWebWorker.js +12 -2
  19. package/commonjs/export/readSheetWebWorker.js.map +1 -1
  20. package/commonjs/export/readXlsxFileBrowser.js +6 -2
  21. package/commonjs/export/readXlsxFileBrowser.js.map +1 -1
  22. package/commonjs/export/readXlsxFileNode.js +6 -2
  23. package/commonjs/export/readXlsxFileNode.js.map +1 -1
  24. package/commonjs/export/readXlsxFileUniversal.js +14 -2
  25. package/commonjs/export/readXlsxFileUniversal.js.map +1 -1
  26. package/commonjs/export/readXlsxFileWebWorker.js +12 -2
  27. package/commonjs/export/readXlsxFileWebWorker.js.map +1 -1
  28. package/commonjs/export/unpackXlsxFileBrowser.js +29 -6
  29. package/commonjs/export/unpackXlsxFileBrowser.js.map +1 -1
  30. package/commonjs/export/unpackXlsxFileNode.js +6 -0
  31. package/commonjs/export/unpackXlsxFileNode.js.map +1 -1
  32. package/commonjs/export/unpackXlsxFileUniversal.js +6 -0
  33. package/commonjs/export/unpackXlsxFileUniversal.js.map +1 -1
  34. package/commonjs/export/unpackXlsxFileWebWorker.js +14 -0
  35. package/commonjs/export/unpackXlsxFileWebWorker.js.map +1 -0
  36. package/commonjs/parseSheetData/parseSheetData.js +6 -6
  37. package/commonjs/parseSheetData/parseSheetData.js.map +1 -1
  38. package/commonjs/utility/checkpoint.js +33 -0
  39. package/commonjs/utility/checkpoint.js.map +1 -0
  40. package/commonjs/utility/isObject.js +15 -0
  41. package/commonjs/utility/isObject.js.map +1 -0
  42. package/commonjs/utility/isPromise.js +18 -0
  43. package/commonjs/utility/isPromise.js.map +1 -0
  44. package/commonjs/xlsx/convertCellsToData2dArray.js +0 -3
  45. package/commonjs/xlsx/convertCellsToData2dArray.js.map +1 -1
  46. package/commonjs/xlsx/isDateFormatStyle.js +2 -2
  47. package/commonjs/xlsx/isDateFormatStyle.js.map +1 -1
  48. package/commonjs/xlsx/parseCell.js +89 -24
  49. package/commonjs/xlsx/parseCell.js.map +1 -1
  50. package/{modules/xlsx/parseCellCoordinates.js → commonjs/xlsx/parseCellAddress.js} +18 -7
  51. package/commonjs/xlsx/parseCellAddress.js.map +1 -0
  52. package/commonjs/xlsx/parseCellValue.js +7 -23
  53. package/commonjs/xlsx/parseCellValue.js.map +1 -1
  54. package/commonjs/xlsx/parseFilePaths.js +31 -32
  55. package/commonjs/xlsx/parseFilePaths.js.map +1 -1
  56. package/commonjs/xlsx/parseNumber.js +20 -0
  57. package/commonjs/xlsx/parseNumber.js.map +1 -0
  58. package/commonjs/xlsx/parseSharedString.js +64 -0
  59. package/commonjs/xlsx/parseSharedString.js.map +1 -0
  60. package/commonjs/xlsx/parseSharedStrings.js +45 -5
  61. package/commonjs/xlsx/parseSharedStrings.js.map +1 -1
  62. package/commonjs/xlsx/parseSheet.js +93 -9
  63. package/commonjs/xlsx/parseSheet.js.map +1 -1
  64. package/commonjs/xlsx/parseSheetData.js +68 -0
  65. package/commonjs/xlsx/parseSheetData.js.map +1 -0
  66. package/commonjs/xlsx/parseSpreadsheetContents.js +244 -43
  67. package/commonjs/xlsx/parseSpreadsheetContents.js.map +1 -1
  68. package/commonjs/xlsx/parseSpreadsheetInfo.js +67 -36
  69. package/commonjs/xlsx/parseSpreadsheetInfo.js.map +1 -1
  70. package/commonjs/xlsx/parseStyles.js +89 -36
  71. package/commonjs/xlsx/parseStyles.js.map +1 -1
  72. package/commonjs/xml/dom.js +2 -1
  73. package/commonjs/xml/dom.js.map +1 -1
  74. package/commonjs/xml/parseXmlStream.js +14 -0
  75. package/commonjs/xml/parseXmlStream.js.map +1 -0
  76. package/commonjs/xml/parseXmlStream.sax.js +109 -0
  77. package/commonjs/xml/parseXmlStream.sax.js.map +1 -0
  78. package/commonjs/xml/parseXmlStream.saxen.code.js +953 -0
  79. package/commonjs/xml/parseXmlStream.saxen.code.js.map +1 -0
  80. package/commonjs/xml/parseXmlStream.saxen.js +85 -0
  81. package/commonjs/xml/parseXmlStream.saxen.js.map +1 -0
  82. package/commonjs/xml/xlsx.js +75 -40
  83. package/commonjs/xml/xlsx.js.map +1 -1
  84. package/commonjs/zip/unzipFromArrayBuffer.js +5 -14
  85. package/commonjs/zip/unzipFromArrayBuffer.js.map +1 -1
  86. package/commonjs/zip/unzipFromStream.fflate.js +154 -25
  87. package/commonjs/zip/unzipFromStream.fflate.js.map +1 -1
  88. package/commonjs/zip/unzipFromStream.js.map +1 -1
  89. package/commonjs/zip/unzipFromStream.unzipper.js +37 -26
  90. package/commonjs/zip/unzipFromStream.unzipper.js.map +1 -1
  91. package/modules/export/convertValuesFromUint8ArraysToStrings.js +2 -0
  92. package/modules/export/convertValuesFromUint8ArraysToStrings.js.map +1 -1
  93. package/modules/export/parseSheet.js +12 -9
  94. package/modules/export/parseSheet.js.map +1 -1
  95. package/modules/export/readSheetBrowser.js +5 -2
  96. package/modules/export/readSheetBrowser.js.map +1 -1
  97. package/modules/export/readSheetNode.js +5 -2
  98. package/modules/export/readSheetNode.js.map +1 -1
  99. package/modules/export/readSheetUniversal.js +14 -2
  100. package/modules/export/readSheetUniversal.js.map +1 -1
  101. package/modules/export/readSheetWebWorker.js +12 -2
  102. package/modules/export/readSheetWebWorker.js.map +1 -1
  103. package/modules/export/readXlsxFileBrowser.js +5 -2
  104. package/modules/export/readXlsxFileBrowser.js.map +1 -1
  105. package/modules/export/readXlsxFileNode.js +5 -2
  106. package/modules/export/readXlsxFileNode.js.map +1 -1
  107. package/modules/export/readXlsxFileUniversal.js +14 -2
  108. package/modules/export/readXlsxFileUniversal.js.map +1 -1
  109. package/modules/export/readXlsxFileWebWorker.js +12 -2
  110. package/modules/export/readXlsxFileWebWorker.js.map +1 -1
  111. package/modules/export/unpackXlsxFileBrowser.js +26 -6
  112. package/modules/export/unpackXlsxFileBrowser.js.map +1 -1
  113. package/modules/export/unpackXlsxFileNode.js +3 -0
  114. package/modules/export/unpackXlsxFileNode.js.map +1 -1
  115. package/modules/export/unpackXlsxFileUniversal.js +3 -0
  116. package/modules/export/unpackXlsxFileUniversal.js.map +1 -1
  117. package/modules/export/unpackXlsxFileWebWorker.js +6 -0
  118. package/modules/export/unpackXlsxFileWebWorker.js.map +1 -0
  119. package/modules/parseSheetData/parseSheetData.js +4 -4
  120. package/modules/parseSheetData/parseSheetData.js.map +1 -1
  121. package/modules/utility/checkpoint.js +25 -0
  122. package/modules/utility/checkpoint.js.map +1 -0
  123. package/modules/utility/isObject.js +9 -0
  124. package/modules/utility/isObject.js.map +1 -0
  125. package/modules/utility/isPromise.js +12 -0
  126. package/modules/utility/isPromise.js.map +1 -0
  127. package/modules/xlsx/convertCellsToData2dArray.js +0 -3
  128. package/modules/xlsx/convertCellsToData2dArray.js.map +1 -1
  129. package/modules/xlsx/isDateFormatStyle.js +2 -2
  130. package/modules/xlsx/isDateFormatStyle.js.map +1 -1
  131. package/modules/xlsx/parseCell.js +85 -24
  132. package/modules/xlsx/parseCell.js.map +1 -1
  133. package/{commonjs/xlsx/parseCellCoordinates.js → modules/xlsx/parseCellAddress.js} +12 -13
  134. package/modules/xlsx/parseCellAddress.js.map +1 -0
  135. package/modules/xlsx/parseCellValue.js +7 -23
  136. package/modules/xlsx/parseCellValue.js.map +1 -1
  137. package/modules/xlsx/parseFilePaths.js +31 -33
  138. package/modules/xlsx/parseFilePaths.js.map +1 -1
  139. package/modules/xlsx/parseNumber.js +14 -0
  140. package/modules/xlsx/parseNumber.js.map +1 -0
  141. package/modules/xlsx/parseSharedString.js +55 -0
  142. package/modules/xlsx/parseSharedString.js.map +1 -0
  143. package/modules/xlsx/parseSharedStrings.js +46 -5
  144. package/modules/xlsx/parseSharedStrings.js.map +1 -1
  145. package/modules/xlsx/parseSheet.js +91 -9
  146. package/modules/xlsx/parseSheet.js.map +1 -1
  147. package/modules/xlsx/parseSheetData.js +55 -0
  148. package/modules/xlsx/parseSheetData.js.map +1 -0
  149. package/modules/xlsx/parseSpreadsheetContents.js +242 -43
  150. package/modules/xlsx/parseSpreadsheetContents.js.map +1 -1
  151. package/modules/xlsx/parseSpreadsheetInfo.js +67 -37
  152. package/modules/xlsx/parseSpreadsheetInfo.js.map +1 -1
  153. package/modules/xlsx/parseStyles.js +88 -36
  154. package/modules/xlsx/parseStyles.js.map +1 -1
  155. package/modules/xml/dom.js +2 -1
  156. package/modules/xml/dom.js.map +1 -1
  157. package/modules/xml/parseXmlStream.js +18 -0
  158. package/modules/xml/parseXmlStream.js.map +1 -0
  159. package/modules/xml/parseXmlStream.sax.js +103 -0
  160. package/modules/xml/parseXmlStream.sax.js.map +1 -0
  161. package/modules/xml/parseXmlStream.saxen.code.js +947 -0
  162. package/modules/xml/parseXmlStream.saxen.code.js.map +1 -0
  163. package/modules/xml/parseXmlStream.saxen.js +79 -0
  164. package/modules/xml/parseXmlStream.saxen.js.map +1 -0
  165. package/modules/xml/xlsx.js +72 -36
  166. package/modules/xml/xlsx.js.map +1 -1
  167. package/modules/zip/unzipFromArrayBuffer.js +5 -14
  168. package/modules/zip/unzipFromArrayBuffer.js.map +1 -1
  169. package/modules/zip/unzipFromStream.fflate.js +157 -24
  170. package/modules/zip/unzipFromStream.fflate.js.map +1 -1
  171. package/modules/zip/unzipFromStream.js +56 -2
  172. package/modules/zip/unzipFromStream.js.map +1 -1
  173. package/modules/zip/unzipFromStream.unzipper.js +38 -26
  174. package/modules/zip/unzipFromStream.unzipper.js.map +1 -1
  175. package/package.json +4 -6
  176. package/commonjs/xlsx/parseCellCoordinates.js.map +0 -1
  177. package/commonjs/xlsx/parseCells.js +0 -34
  178. package/commonjs/xlsx/parseCells.js.map +0 -1
  179. package/commonjs/xlsx/parseSheetDimensions.js +0 -43
  180. package/commonjs/xlsx/parseSheetDimensions.js.map +0 -1
  181. package/commonjs/xml/xml.js +0 -13
  182. package/commonjs/xml/xml.js.map +0 -1
  183. package/commonjs/xml/xmlBrowser.js +0 -17
  184. package/commonjs/xml/xmlBrowser.js.map +0 -1
  185. package/commonjs/xml/xpath/xlsx-xpath.js +0 -92
  186. package/commonjs/xml/xpath/xlsx-xpath.js.map +0 -1
  187. package/commonjs/xml/xpath/xpathBrowser.js +0 -33
  188. package/commonjs/xml/xpath/xpathBrowser.js.map +0 -1
  189. package/commonjs/xml/xpath/xpathNode.js +0 -16
  190. package/commonjs/xml/xpath/xpathNode.js.map +0 -1
  191. package/modules/xlsx/parseCellCoordinates.js.map +0 -1
  192. package/modules/xlsx/parseCells.js +0 -27
  193. package/modules/xlsx/parseCells.js.map +0 -1
  194. package/modules/xlsx/parseSheetDimensions.js +0 -37
  195. package/modules/xlsx/parseSheetDimensions.js.map +0 -1
  196. package/modules/xml/xml.js +0 -7
  197. package/modules/xml/xml.js.map +0 -1
  198. package/modules/xml/xmlBrowser.js +0 -11
  199. package/modules/xml/xmlBrowser.js.map +0 -1
  200. package/modules/xml/xpath/xlsx-xpath.js +0 -73
  201. package/modules/xml/xpath/xlsx-xpath.js.map +0 -1
  202. package/modules/xml/xpath/xpathBrowser.js +0 -27
  203. package/modules/xml/xpath/xpathBrowser.js.map +0 -1
  204. package/modules/xml/xpath/xpathNode.js +0 -9
  205. package/modules/xml/xpath/xpathNode.js.map +0 -1
@@ -1,8 +1,29 @@
1
- // `fflate` uses a javascript-only implementation of `.zip` compression/decompression.
2
- // This means that it could likely be less performant than Node.js's "native" `zlib` module`.
1
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
3
+ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
4
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
5
+ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
7
+ function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
8
+ // Considerations:
9
+ //
10
+ // * `fflate` uses a pure-javascript implementation of `.zip` compression/decompression by default.
11
+ // This pure-javascript implementation is about 2x slower than Node.js's "native" `zlib` module.
12
+ // This issue is worked around by "marrying" `fflate` with Node.js's `zlib` "native" module through some tinkering.
13
+ // https://github.com/101arrowz/fflate/issues/284
14
+ //
15
+ // * Even though `fflate` implements a "streaming" mode of its own,
16
+ // it does not implement Node.js streams "contract", i.e. it just unzips the archive
17
+ // as fast as it can consume it from the input stream, without throttling the data throughput
18
+ // in cases when the input data flows faster than `fflate` can process it. This means that
19
+ // in the "worst case" scenario when `fflate`'s decompressor is unable to keep up with the
20
+ // data influx, it would "buffer" the entire `.zip` archive in RAM until it's processed.
21
+ // And while this is no big deal by any means, it's still not as elegant as adhering to
22
+ // Node.js streaming protocol.
3
23
 
4
24
  // This code was originally submitted by Stian Jensen.
5
25
  // https://github.com/catamphetamine/read-excel-file/pull/122
26
+ // https://github.com/catamphetamine/read-excel-file/pull/123
6
27
 
7
28
  // A `*.zip` file consists of individual file entries with the "total" summary section
8
29
  // placed at the end of the file rather than at the start of it, which was originally done
@@ -28,10 +49,12 @@
28
49
  //
29
50
  // When the "summary" section is reached, we assume that the archive has ended.
30
51
  //
31
- // To read a `.zip` archive, the code uses `fflate`'s `Unzip` class
32
- // with `UnzipInflate` decompression implementation to decompress the data
33
- // that was previously compressed using `DEFLATE` compressing algorithm,
34
- // which is what `*.xlsx` files use.
52
+ // To read a `.zip` archive, the code uses `fflate`'s `Unzip` class.
53
+ // The actual decompression could be performed either by using
54
+ // `fflate`'s pure-javascript `UnzipInflate` implementation, which is
55
+ // about 2x slower than Node.js's "native" module `zlib`,
56
+ // or it could use the aforementioned `zlib` module as a drop-in replacement
57
+ // (with some tinkering).
35
58
  //
36
59
  // The `Unzip` class doesn't speak the Node.js stream interface, and `fflate`'s readme
37
60
  // doesn't include a clear "reading a `.zip` file from a Node.js stream" section.
@@ -46,8 +69,29 @@
46
69
  // https://github.com/101arrowz/fflate/issues/277
47
70
  // So just the regular `UnzipInflate` is used here.
48
71
  //
49
- import { Unzip, UnzipInflate } from 'fflate';
72
+ import { Unzip } from 'fflate';
73
+ // import { AsyncUnzipInflate, UnzipInflate } from 'fflate'
74
+
50
75
  import { Buffer } from 'node:buffer';
76
+ import zlib from 'node:zlib';
77
+
78
+ // Native `zlib` is faster than `UnzipInflate`.
79
+ // * When decompressing a `1 MB` `.xlsx` file, the decompression time is `100 ms`
80
+ // when using `zlib` decompressor and `150 ms` when using `fflate` "sync" decompressor.
81
+ // * When decompressing a `10 MB` `.xlsx` file, the decompression time is `500 ms`
82
+ // when using `zlib` decompressor and `650 ms` when using `fflate` "sync" decompressor.
83
+ // * When decompressing a `50 MB` `.xlsx` file, the decompression time is `2800 ms`
84
+ // when using `zlib` decompressor and `3600 ms` when using `fflate` "sync" decompressor.
85
+ var USE_ZLIB_DECOMPRESSOR = true;
86
+
87
+ // `AsyncZipInflate` is faster than `UnzipInflate` for `.xlsx` files that're larger
88
+ // than a few megabytes.
89
+ // * When decompressing a `1 MB` `.xlsx` file, the decompression time is `150 ms`
90
+ // when using "sync" decompressor and `170 ms` when using "async" decompressor.
91
+ // * When decompressing a `10 MB` `.xlsx` file, the decompression time is about the same.
92
+ // * When decompressing a `50 MB` `.xlsx` file, the decompression time is `3600 ms`
93
+ // when using "sync" decompressor and `3200 ms` when using "async" decompressor.
94
+ var USE_ASYNC_FFLATE_DECOMPRESSOR = false;
51
95
 
52
96
  /**
53
97
  * Reads `*.zip` file contents.
@@ -59,6 +103,31 @@ export default function unzipFromStream(stream) {
59
103
  filter = _ref.filter;
60
104
  // The `files` object stores the files and their contents.
61
105
  var files = {};
106
+ var filesChunks = {};
107
+ var onFile = function onFile(filePath) {
108
+ // See if this file should be ignored.
109
+ // If it should, this entry won't be processed, i.e. `Unzip` will not try
110
+ // to decompress its data, and will just discard it.
111
+ if (filter && !filter({
112
+ path: filePath
113
+ })) {
114
+ return false;
115
+ }
116
+ filesChunks[filePath] = [];
117
+ };
118
+ var onFileData = function onFileData(filePath, chunk) {
119
+ filesChunks[filePath].push(chunk);
120
+ };
121
+ var onFileDataEnd = function onFileDataEnd(filePath) {
122
+ files[filePath] = Buffer.concat(filesChunks[filePath]);
123
+ delete filesChunks[filePath];
124
+ };
125
+ return unzipFromStream_(stream, onFile, onFileData, onFileDataEnd).then(function () {
126
+ return files;
127
+ });
128
+ }
129
+ var PROMISE_RESOLVE_VALUE = undefined;
130
+ function unzipFromStream_(stream, onFile, onFileData, onFileDataEnd) {
62
131
  return new Promise(function (resolve, reject) {
63
132
  var errored = false;
64
133
  var onError = function onError(error) {
@@ -67,6 +136,19 @@ export default function unzipFromStream(stream) {
67
136
  reject(error);
68
137
  }
69
138
  };
139
+
140
+ // The native `zlib` decoder finishes inflating an entry asynchronously, so
141
+ // the archive's `end` event can fire while entries are still decompressing.
142
+ // It counts "decompression still in-progress" entries the decompression for which
143
+ // has started but not yet finished, and the main promise only resolves once
144
+ // the input stream has ended *and* every entry is done decompressing.
145
+ var stillDecompressingEntriesCount = 0;
146
+ var noMoreEntries = false;
147
+ var resolveIfDone = function resolveIfDone() {
148
+ if (!errored && noMoreEntries && stillDecompressingEntriesCount === 0) {
149
+ resolve(PROMISE_RESOLVE_VALUE);
150
+ }
151
+ };
70
152
  var _createZipFileValidat = createZipFileValidator(function (isValid) {
71
153
  if (!isValid) {
72
154
  onError(new Error('Invalid `.zip` archive'));
@@ -88,26 +170,22 @@ export default function unzipFromStream(stream) {
88
170
  if (entry.name.endsWith('/')) {
89
171
  return;
90
172
  }
91
-
92
- // See if this file should be ignored.
93
- // If it should, this entry won't be processed, i.e. `Unzip` will not try
94
- // to decompress its data, and will just discard it.
95
- if (filter && !filter({
96
- path: entry.name
97
- })) {
173
+ if (onFile(entry.name) === false) {
98
174
  return;
99
175
  }
100
- var chunks = [];
176
+ stillDecompressingEntriesCount++;
101
177
 
102
178
  // `entry.ondata` is called with each decompressed chunk of the entry,
103
- // and a final time with `isLast === true` once the entry is complete.
179
+ // and then a final time with `isLast === true` once the entry is complete.
104
180
  entry.ondata = function (error, chunk, isLast) {
105
181
  if (error) {
106
182
  return onError(error);
107
183
  }
108
- chunks.push(chunk);
184
+ onFileData(entry.name, chunk);
109
185
  if (isLast) {
110
- files[entry.name] = Buffer.concat(chunks);
186
+ stillDecompressingEntriesCount--;
187
+ onFileDataEnd(entry.name);
188
+ resolveIfDone();
111
189
  }
112
190
  };
113
191
 
@@ -118,7 +196,7 @@ export default function unzipFromStream(stream) {
118
196
  // Register the decompressor for the data that was compressed using
119
197
  // `DEFLATE` compression algorithm (compression method `8`),
120
198
  // which is what `.xlsx` files use.
121
- unzip.register(UnzipInflate);
199
+ unzip.register(USE_ZLIB_DECOMPRESSOR ? NativeZlibInflate : USE_ASYNC_FFLATE_DECOMPRESSOR ? AsyncUnzipInflate : UnzipInflate);
122
200
  stream
123
201
  // Catch errors emitted from the input stream (for example, a file read error).
124
202
  .on('error', onError)
@@ -137,9 +215,15 @@ export default function unzipFromStream(stream) {
137
215
  return;
138
216
  }
139
217
  // Push the next data chunk to `fflate`'s `Unzip` class instance.
140
- // The `.push()` function is synchronous, meaning that by the time it returns,
141
- // any complete files entries encountered so far have already been decompressed
142
- // and populated in the `files` object.
218
+ //
219
+ // The `.push()` function of `fflate`'s own `ZipInflate` decompressor is synchronous,
220
+ // meaning that by the time it returns, any complete files entries encountered so far
221
+ // have already been decompressed and populated in the `files` object.
222
+ //
223
+ // The `.push()` function of `NativeZlibInflate` decompressor is asynchronous,
224
+ // so it requires hacking around with the counter of "still being decompressed" entries
225
+ // in order to detect the actual finish of the archive's decompression process.
226
+ //
143
227
  try {
144
228
  unzip.push(chunk, false);
145
229
  } catch (error) {
@@ -158,8 +242,12 @@ export default function unzipFromStream(stream) {
158
242
  // Signal the end of the archive to `fflate`'s `Unzip` class instance.
159
243
  // It will flush any remaining state in it.
160
244
  unzip.push(new Uint8Array(0), true);
161
- // Resolve with the unzipped files.
162
- resolve(files);
245
+ // The input stream has ended.
246
+ noMoreEntries = true;
247
+ // The entries may still be decompressing asynchronously.
248
+ // In that case, resolve once they all finish decompresssing.
249
+ // Or, resolve if all entries have already finished decompressing by now.
250
+ resolveIfDone();
163
251
  } catch (error) {
164
252
  onError(error);
165
253
  }
@@ -200,4 +288,49 @@ function createZipFileValidator(onValidationResult) {
200
288
  }
201
289
  };
202
290
  }
291
+
292
+ // An implemenation of a `DEFLATE` decompressor for `fflate`'s `Unzip` class
293
+ // that uses Node.js's "native" module `zlib`.
294
+ //
295
+ // It implements `fflate`'s decoder interface: `Unzip` constructs one decoder
296
+ // per each entry, sets `ondata(error, chunk, isLast)` callback on it, and feeds it
297
+ // the entry's compressed bytes by calling `push(chunk, isLast)` method.
298
+ //
299
+ // Unlike `fflate`'s synchronous `UnzipInflate` decoder, `zlib` decompresses asynchronously,
300
+ // so an entry only finishes some "ticks" after its last chunk of its data is `push()`ed
301
+ // by `fflate`'s `Unzip` class. To work around this issue, pending entries counter is used
302
+ // to track when the archive really finishes unpacking.
303
+ //
304
+ var NativeZlibInflate = /*#__PURE__*/function () {
305
+ function NativeZlibInflate() {
306
+ var _this = this;
307
+ _classCallCheck(this, NativeZlibInflate);
308
+ this.inflate = zlib.createInflateRaw();
309
+ this.inflate.on('data', function (chunk) {
310
+ return _this.ondata(null, chunk, false);
311
+ });
312
+ this.inflate.on('end', function () {
313
+ return _this.ondata(null, new Uint8Array(0), true);
314
+ });
315
+ this.inflate.on('error', function (error) {
316
+ return _this.ondata(error, null, false);
317
+ });
318
+ }
319
+ _createClass(NativeZlibInflate, [{
320
+ key: "push",
321
+ value: function push(chunk, isLast) {
322
+ this.inflate.write(Buffer.from(chunk));
323
+ if (isLast) {
324
+ this.inflate.end();
325
+ }
326
+ }
327
+ }, {
328
+ key: "terminate",
329
+ value: function terminate() {
330
+ this.inflate.destroy();
331
+ }
332
+ }]);
333
+ return NativeZlibInflate;
334
+ }();
335
+ _defineProperty(NativeZlibInflate, "compression", 8);
203
336
  //# sourceMappingURL=unzipFromStream.fflate.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"unzipFromStream.fflate.js","names":["Unzip","UnzipInflate","Buffer","unzipFromStream","stream","_ref","arguments","length","undefined","filter","files","Promise","resolve","reject","errored","onError","error","_createZipFileValidat","createZipFileValidator","isValid","Error","validateChunk","unzip","entry","name","endsWith","path","chunks","ondata","chunk","isLast","push","concat","start","register","on","Uint8Array","onValidationResult","firstBytesCount","firstBytes","firstBytesCheckResult","i"],"sources":["../../source/zip/unzipFromStream.fflate.js"],"sourcesContent":["// `fflate` uses a javascript-only implementation of `.zip` compression/decompression.\r\n// This means that it could likely be less performant than Node.js's \"native\" `zlib` module`.\r\n\r\n// This code was originally submitted by Stian Jensen.\r\n// https://github.com/catamphetamine/read-excel-file/pull/122\r\n\r\n// A `*.zip` file consists of individual file entries with the \"total\" summary section\r\n// placed at the end of the file rather than at the start of it, which was originally done\r\n// to allow for easy append of data to a given `.zip` file.\r\n// https://en.wikipedia.org/wiki/ZIP_(file_format)\r\n//\r\n// But this also means that reading a `*.zip` file from a stream can't really be done\r\n// using the \"officially recommended\" way of first reading the \"total\" summary section\r\n// and only then reading the individual file entries specified in that summary section.\r\n//\r\n// So in order to be able to read a `*.zip` file from a stream, some corners have to be cut.\r\n// For example, the \"total\" summary section is completely ignored and instead the reader\r\n// should adopt \"data recovery\" software approach — it should proactively \"scan\" the input stream\r\n// for individual file entries and handle them one-by-one as they come.\r\n//\r\n// Such approach doesn't seem to contradict with the XLSX specification\r\n// because an `*.xlsx` files is supposed to be a normal `.zip` archive\r\n// without any \"trickery\" such as \"deleted\" files or \"garbage\" data\r\n// hiding under the hood.\r\n//\r\n// So when handling `*.xlsx` file, we assume that each such file must start\r\n// with an individual file entry followed by another individual file entry, etc.\r\n//\r\n// When the \"summary\" section is reached, we assume that the archive has ended.\r\n//\r\n// To read a `.zip` archive, the code uses `fflate`'s `Unzip` class\r\n// with `UnzipInflate` decompression implementation to decompress the data\r\n// that was previously compressed using `DEFLATE` compressing algorithm,\r\n// which is what `*.xlsx` files use.\r\n//\r\n// The `Unzip` class doesn't speak the Node.js stream interface, and `fflate`'s readme\r\n// doesn't include a clear \"reading a `.zip` file from a Node.js stream\" section.\r\n// https://github.com/101arrowz/fflate/issues/251\r\n// Instead, the `Unzip` class has its own `push(chunk)` / `onfile` / `entry.ondata` protocol.\r\n// This code reads the binary input stream and forwards each chunk of it to `unzip.push()`,\r\n// and then collects the decompressed file entries.\r\n//\r\n// P.S. In the comments to `UnzipInflate` in `fflate` package, it says:\r\n// \"Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for better performance.\"\r\n// But there seems to be no `AsyncZipInflate` class in the `fflate` package.\r\n// https://github.com/101arrowz/fflate/issues/277\r\n// So just the regular `UnzipInflate` is used here.\r\n//\r\nimport { Unzip, UnzipInflate } from 'fflate'\r\n\r\nimport { Buffer } from 'node:buffer'\r\n\r\n/**\r\n * Reads `*.zip` file contents.\r\n * @param {Stream} stream\r\n * @return {Promise<Record<string,Buffer>>} Resolves to an object holding `*.zip` file entries. P.S. `Buffer` is a `Uint8Array`.\r\n */\r\nexport default function unzipFromStream(stream, { filter } = {}) {\r\n\t// The `files` object stores the files and their contents.\r\n\tconst files = {}\r\n\r\n\treturn new Promise((resolve, reject) => {\r\n\t\tlet errored = false\r\n\r\n\t\tconst onError = (error) => {\r\n\t\t\tif (!errored) {\r\n\t\t\t\terrored = true\r\n\t\t\t\treject(error)\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst { validateChunk } = createZipFileValidator((isValid) => {\r\n\t\t\tif (!isValid) {\r\n\t\t\t\tonError(new Error('Invalid `.zip` archive'))\r\n\t\t\t}\r\n\t\t})\r\n\r\n\t\t// `Unzip` discovers each individual file entry in the input data stream\r\n\t\t// and then calls the callback function for each such entry.\r\n\t\tconst unzip = new Unzip((entry) => {\r\n\t\t\t// If there already was an error while reading this `.zip` file,\r\n\t\t\t// ignore any follow-up entries.\r\n\t\t\tif (errored) {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\r\n\t\t\t// Skip directory entries (their names end with a slash).\r\n\t\t\t// Only files are of any interest.\r\n\t\t\tif (entry.name.endsWith('/')) {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\r\n\t\t\t// See if this file should be ignored.\r\n\t\t\t// If it should, this entry won't be processed, i.e. `Unzip` will not try\r\n\t\t\t// to decompress its data, and will just discard it.\r\n\t\t\tif (filter && !filter({ path: entry.name })) {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\r\n\t\t\tconst chunks = []\r\n\r\n\t\t\t// `entry.ondata` is called with each decompressed chunk of the entry,\r\n\t\t\t// and a final time with `isLast === true` once the entry is complete.\r\n\t\t\tentry.ondata = (error, chunk, isLast) => {\r\n\t\t\t\tif (error) {\r\n\t\t\t\t\treturn onError(error)\r\n\t\t\t\t}\r\n\t\t\t\tchunks.push(chunk)\r\n\t\t\t\tif (isLast) {\r\n\t\t\t\t\tfiles[entry.name] = Buffer.concat(chunks)\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t// Start decompressing this entry.\r\n\t\t\tentry.start()\r\n\t\t})\r\n\r\n\t\t// Register the decompressor for the data that was compressed using\r\n\t\t// `DEFLATE` compression algorithm (compression method `8`),\r\n\t\t// which is what `.xlsx` files use.\r\n\t\tunzip.register(UnzipInflate)\r\n\r\n\t\tstream\r\n\t\t\t// Catch errors emitted from the input stream (for example, a file read error).\r\n\t\t\t.on('error', onError)\r\n\t\t\t// When another chunk of data is read from the input stream.\r\n\t\t\t.on('data', (chunk) => {\r\n\t\t\t\t// If there already was an error while reading this `.zip` file,\r\n\t\t\t\t// ignore any follow-up data chunks.\r\n\t\t\t\tif (errored) {\r\n\t\t\t\t\treturn\r\n\t\t\t\t}\r\n\t\t\t\t// Validate the `.zip` archive as its data comes through.\r\n\t\t\t\tvalidateChunk(chunk)\r\n\t\t\t\t// If the `.zip` archive is found to be invalid, stop any further\r\n\t\t\t\t// processing of it.\r\n\t\t\t\tif (errored) {\r\n\t\t\t\t\treturn\r\n\t\t\t\t}\r\n\t\t\t\t// Push the next data chunk to `fflate`'s `Unzip` class instance.\r\n\t\t\t\t// The `.push()` function is synchronous, meaning that by the time it returns,\r\n\t\t\t\t// any complete files entries encountered so far have already been decompressed\r\n\t\t\t\t// and populated in the `files` object.\r\n\t\t\t\ttry {\r\n\t\t\t\t\tunzip.push(chunk, false)\r\n\t\t\t\t} catch (error) {\r\n\t\t\t\t\tonError(error)\r\n\t\t\t\t}\r\n\t\t\t})\r\n\t\t\t// When there's no more data in the input stream to consume,\r\n\t\t\t// finish reading the `.zip` archive.\r\n\t\t\t.on('end', () => {\r\n\t\t\t\t// If there were any errors when reading the `.zip` archive,\r\n\t\t\t\t// don't `resolve()` with anything.\r\n\t\t\t\tif (errored) {\r\n\t\t\t\t\treturn\r\n\t\t\t\t}\r\n\t\t\t\ttry {\r\n\t\t\t\t\t// Signal the end of the archive to `fflate`'s `Unzip` class instance.\r\n\t\t\t\t\t// It will flush any remaining state in it.\r\n\t\t\t\t\tunzip.push(new Uint8Array(0), true)\r\n\t\t\t\t\t// Resolve with the unzipped files.\r\n\t\t\t\t\tresolve(files)\r\n\t\t\t\t} catch (error) {\r\n\t\t\t\t\tonError(error)\r\n\t\t\t\t}\r\n\t\t\t})\r\n\t})\r\n}\r\n\r\n// Every section in a `.zip` archive is marked with 4 bytes, the first two of which\r\n// are `0x50` and `0x4B`, which reads \"PK\", referencing the initials of the inventor Phil Katz.\r\n//\r\n// It looks like `fflate`'s `Unzip` doesn't ever complain about whatever data is thrown at it.\r\n// Due to how `.zip` file format is defined, \"garbage\" data could be placed at various\r\n// places in it and it'd still be a valid `.zip` archive. It's likely that for this reason\r\n// `fflate` doesn't ever complain and simply emits no entries when fed any kind of invalid data.\r\n//\r\n// In order to introduce some basic validation, here we specifically demand\r\n// that a `.zip` archive must at least start with an individual file entry\r\n// because an `.xlsx` file creator softwared really shouldn't attempt doing\r\n// anything \"funny\" when writing a file, hence this adherence requirement.\r\n//\r\nfunction createZipFileValidator(onValidationResult) {\r\n\tconst firstBytesCount = 2\r\n\tconst firstBytes = []\r\n\tlet firstBytesCheckResult\r\n\treturn {\r\n\t\tvalidateChunk(chunk) {\r\n\t\t\tif (firstBytes.length < 2) {\r\n\t\t\t\tlet i = 0\r\n\t\t\t\twhile (i < chunk.length && i < firstBytesCount) {\r\n\t\t\t\t\tfirstBytes.push(chunk[i])\r\n\t\t\t\t\ti++\r\n\t\t\t\t}\r\n\t\t\t\tif (firstBytes.length === 2) {\r\n\t\t\t\t\tconst isValid = firstBytes[0] === 0x50 && firstBytes[1] === 0x4B\r\n\t\t\t\t\tonValidationResult(isValid)\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}"],"mappings":"AAAA;AACA;;AAEA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,KAAK,EAAEC,YAAY,QAAQ,QAAQ;AAE5C,SAASC,MAAM,QAAQ,aAAa;;AAEpC;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,eAAeA,CAACC,MAAM,EAAmB;EAAA,IAAAC,IAAA,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAJ,CAAC,CAAC;IAAbG,MAAM,GAAAJ,IAAA,CAANI,MAAM;EACvD;EACA,IAAMC,KAAK,GAAG,CAAC,CAAC;EAEhB,OAAO,IAAIC,OAAO,CAAC,UAACC,OAAO,EAAEC,MAAM,EAAK;IACvC,IAAIC,OAAO,GAAG,KAAK;IAEnB,IAAMC,OAAO,GAAG,SAAVA,OAAOA,CAAIC,KAAK,EAAK;MAC1B,IAAI,CAACF,OAAO,EAAE;QACbA,OAAO,GAAG,IAAI;QACdD,MAAM,CAACG,KAAK,CAAC;MACd;IACD,CAAC;IAED,IAAAC,qBAAA,GAA0BC,sBAAsB,CAAC,UAACC,OAAO,EAAK;QAC7D,IAAI,CAACA,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"file":"unzipFromStream.fflate.js","names":["Unzip","Buffer","zlib","USE_ZLIB_DECOMPRESSOR","USE_ASYNC_FFLATE_DECOMPRESSOR","unzipFromStream","stream","_ref","arguments","length","undefined","filter","files","filesChunks","onFile","filePath","path","onFileData","chunk","push","onFileDataEnd","concat","unzipFromStream_","then","PROMISE_RESOLVE_VALUE","Promise","resolve","reject","errored","onError","error","stillDecompressingEntriesCount","noMoreEntries","resolveIfDone","_createZipFileValidat","createZipFileValidator","isValid","Error","validateChunk","unzip","entry","name","endsWith","ondata","isLast","start","register","NativeZlibInflate","AsyncUnzipInflate","UnzipInflate","on","Uint8Array","onValidationResult","firstBytesCount","firstBytes","firstBytesCheckResult","i","_this","_classCallCheck","inflate","createInflateRaw","_createClass","key","value","write","from","end","terminate","destroy","_defineProperty"],"sources":["../../source/zip/unzipFromStream.fflate.js"],"sourcesContent":["// Considerations:\r\n//\r\n// * `fflate` uses a pure-javascript implementation of `.zip` compression/decompression by default.\r\n// This pure-javascript implementation is about 2x slower than Node.js's \"native\" `zlib` module.\r\n// This issue is worked around by \"marrying\" `fflate` with Node.js's `zlib` \"native\" module through some tinkering.\r\n// https://github.com/101arrowz/fflate/issues/284\r\n//\r\n// * Even though `fflate` implements a \"streaming\" mode of its own,\r\n// it does not implement Node.js streams \"contract\", i.e. it just unzips the archive\r\n// as fast as it can consume it from the input stream, without throttling the data throughput\r\n// in cases when the input data flows faster than `fflate` can process it. This means that\r\n// in the \"worst case\" scenario when `fflate`'s decompressor is unable to keep up with the\r\n// data influx, it would \"buffer\" the entire `.zip` archive in RAM until it's processed.\r\n// And while this is no big deal by any means, it's still not as elegant as adhering to\r\n// Node.js streaming protocol.\r\n\r\n// This code was originally submitted by Stian Jensen.\r\n// https://github.com/catamphetamine/read-excel-file/pull/122\r\n// https://github.com/catamphetamine/read-excel-file/pull/123\r\n\r\n// A `*.zip` file consists of individual file entries with the \"total\" summary section\r\n// placed at the end of the file rather than at the start of it, which was originally done\r\n// to allow for easy append of data to a given `.zip` file.\r\n// https://en.wikipedia.org/wiki/ZIP_(file_format)\r\n//\r\n// But this also means that reading a `*.zip` file from a stream can't really be done\r\n// using the \"officially recommended\" way of first reading the \"total\" summary section\r\n// and only then reading the individual file entries specified in that summary section.\r\n//\r\n// So in order to be able to read a `*.zip` file from a stream, some corners have to be cut.\r\n// For example, the \"total\" summary section is completely ignored and instead the reader\r\n// should adopt \"data recovery\" software approach — it should proactively \"scan\" the input stream\r\n// for individual file entries and handle them one-by-one as they come.\r\n//\r\n// Such approach doesn't seem to contradict with the XLSX specification\r\n// because an `*.xlsx` files is supposed to be a normal `.zip` archive\r\n// without any \"trickery\" such as \"deleted\" files or \"garbage\" data\r\n// hiding under the hood.\r\n//\r\n// So when handling `*.xlsx` file, we assume that each such file must start\r\n// with an individual file entry followed by another individual file entry, etc.\r\n//\r\n// When the \"summary\" section is reached, we assume that the archive has ended.\r\n//\r\n// To read a `.zip` archive, the code uses `fflate`'s `Unzip` class.\r\n// The actual decompression could be performed either by using\r\n// `fflate`'s pure-javascript `UnzipInflate` implementation, which is\r\n// about 2x slower than Node.js's \"native\" module `zlib`,\r\n// or it could use the aforementioned `zlib` module as a drop-in replacement\r\n// (with some tinkering).\r\n//\r\n// The `Unzip` class doesn't speak the Node.js stream interface, and `fflate`'s readme\r\n// doesn't include a clear \"reading a `.zip` file from a Node.js stream\" section.\r\n// https://github.com/101arrowz/fflate/issues/251\r\n// Instead, the `Unzip` class has its own `push(chunk)` / `onfile` / `entry.ondata` protocol.\r\n// This code reads the binary input stream and forwards each chunk of it to `unzip.push()`,\r\n// and then collects the decompressed file entries.\r\n//\r\n// P.S. In the comments to `UnzipInflate` in `fflate` package, it says:\r\n// \"Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for better performance.\"\r\n// But there seems to be no `AsyncZipInflate` class in the `fflate` package.\r\n// https://github.com/101arrowz/fflate/issues/277\r\n// So just the regular `UnzipInflate` is used here.\r\n//\r\nimport { Unzip } from 'fflate'\r\n// import { AsyncUnzipInflate, UnzipInflate } from 'fflate'\r\n\r\nimport { Buffer } from 'node:buffer'\r\nimport zlib from 'node:zlib'\r\n\r\n// Native `zlib` is faster than `UnzipInflate`.\r\n// * When decompressing a `1 MB` `.xlsx` file, the decompression time is `100 ms`\r\n// when using `zlib` decompressor and `150 ms` when using `fflate` \"sync\" decompressor.\r\n// * When decompressing a `10 MB` `.xlsx` file, the decompression time is `500 ms`\r\n// when using `zlib` decompressor and `650 ms` when using `fflate` \"sync\" decompressor.\r\n// * When decompressing a `50 MB` `.xlsx` file, the decompression time is `2800 ms`\r\n// when using `zlib` decompressor and `3600 ms` when using `fflate` \"sync\" decompressor.\r\nconst USE_ZLIB_DECOMPRESSOR = true\r\n\r\n// `AsyncZipInflate` is faster than `UnzipInflate` for `.xlsx` files that're larger\r\n// than a few megabytes.\r\n// * When decompressing a `1 MB` `.xlsx` file, the decompression time is `150 ms`\r\n// when using \"sync\" decompressor and `170 ms` when using \"async\" decompressor.\r\n// * When decompressing a `10 MB` `.xlsx` file, the decompression time is about the same.\r\n// * When decompressing a `50 MB` `.xlsx` file, the decompression time is `3600 ms`\r\n// when using \"sync\" decompressor and `3200 ms` when using \"async\" decompressor.\r\nconst USE_ASYNC_FFLATE_DECOMPRESSOR = false\r\n\r\n/**\r\n * Reads `*.zip` file contents.\r\n * @param {Stream} stream\r\n * @return {Promise<Record<string,Buffer>>} Resolves to an object holding `*.zip` file entries. P.S. `Buffer` is a `Uint8Array`.\r\n */\r\nexport default function unzipFromStream(stream, { filter } = {}) {\r\n\t// The `files` object stores the files and their contents.\r\n\tconst files = {}\r\n\tconst filesChunks = {}\r\n\r\n\tconst onFile = (filePath) => {\r\n\t\t// See if this file should be ignored.\r\n\t\t// If it should, this entry won't be processed, i.e. `Unzip` will not try\r\n\t\t// to decompress its data, and will just discard it.\r\n\t\tif (filter && !filter({ path: filePath })) {\r\n\t\t\treturn false\r\n\t\t}\r\n\t\tfilesChunks[filePath] = []\r\n\t}\r\n\r\n\tconst onFileData = (filePath, chunk) => {\r\n\t\tfilesChunks[filePath].push(chunk)\r\n\t}\r\n\r\n\tconst onFileDataEnd = (filePath) => {\r\n\t\tfiles[filePath] = Buffer.concat(filesChunks[filePath])\r\n\t\tdelete filesChunks[filePath]\r\n\t}\r\n\r\n\treturn unzipFromStream_(stream, onFile, onFileData, onFileDataEnd).then(() => {\r\n\t\treturn files\r\n\t})\r\n}\r\n\r\nconst PROMISE_RESOLVE_VALUE = undefined\r\n\r\nfunction unzipFromStream_(stream, onFile, onFileData, onFileDataEnd) {\r\n\treturn new Promise((resolve, reject) => {\r\n\t\tlet errored = false\r\n\r\n\t\tconst onError = (error) => {\r\n\t\t\tif (!errored) {\r\n\t\t\t\terrored = true\r\n\t\t\t\treject(error)\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// The native `zlib` decoder finishes inflating an entry asynchronously, so\r\n\t\t// the archive's `end` event can fire while entries are still decompressing.\r\n\t\t// It counts \"decompression still in-progress\" entries the decompression for which\r\n\t\t// has started but not yet finished, and the main promise only resolves once\r\n\t\t// the input stream has ended *and* every entry is done decompressing.\r\n\t\tlet stillDecompressingEntriesCount = 0\r\n\t\tlet noMoreEntries = false\r\n\t\tconst resolveIfDone = () => {\r\n\t\t\tif (!errored && noMoreEntries && stillDecompressingEntriesCount === 0) {\r\n\t\t\t\tresolve(PROMISE_RESOLVE_VALUE)\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tconst { validateChunk } = createZipFileValidator((isValid) => {\r\n\t\t\tif (!isValid) {\r\n\t\t\t\tonError(new Error('Invalid `.zip` archive'))\r\n\t\t\t}\r\n\t\t})\r\n\r\n\t\t// `Unzip` discovers each individual file entry in the input data stream\r\n\t\t// and then calls the callback function for each such entry.\r\n\t\tconst unzip = new Unzip((entry) => {\r\n\t\t\t// If there already was an error while reading this `.zip` file,\r\n\t\t\t// ignore any follow-up entries.\r\n\t\t\tif (errored) {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\r\n\t\t\t// Skip directory entries (their names end with a slash).\r\n\t\t\t// Only files are of any interest.\r\n\t\t\tif (entry.name.endsWith('/')) {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\r\n\t\t\tif (onFile(entry.name) === false) {\r\n\t\t\t\treturn\r\n\t\t\t}\r\n\r\n\t\t\tstillDecompressingEntriesCount++\r\n\r\n\t\t\t// `entry.ondata` is called with each decompressed chunk of the entry,\r\n\t\t\t// and then a final time with `isLast === true` once the entry is complete.\r\n\t\t\tentry.ondata = (error, chunk, isLast) => {\r\n\t\t\t\tif (error) {\r\n\t\t\t\t\treturn onError(error)\r\n\t\t\t\t}\r\n\t\t\t\tonFileData(entry.name, chunk)\r\n\t\t\t\tif (isLast) {\r\n\t\t\t\t\tstillDecompressingEntriesCount--\r\n\t\t\t\t\tonFileDataEnd(entry.name)\r\n\t\t\t\t\tresolveIfDone()\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t// Start decompressing this entry.\r\n\t\t\tentry.start()\r\n\t\t})\r\n\r\n\t\t// Register the decompressor for the data that was compressed using\r\n\t\t// `DEFLATE` compression algorithm (compression method `8`),\r\n\t\t// which is what `.xlsx` files use.\r\n\t\tunzip.register(USE_ZLIB_DECOMPRESSOR ? NativeZlibInflate : (USE_ASYNC_FFLATE_DECOMPRESSOR ? AsyncUnzipInflate : UnzipInflate))\r\n\r\n\t\tstream\r\n\t\t\t// Catch errors emitted from the input stream (for example, a file read error).\r\n\t\t\t.on('error', onError)\r\n\t\t\t// When another chunk of data is read from the input stream.\r\n\t\t\t.on('data', (chunk) => {\r\n\t\t\t\t// If there already was an error while reading this `.zip` file,\r\n\t\t\t\t// ignore any follow-up data chunks.\r\n\t\t\t\tif (errored) {\r\n\t\t\t\t\treturn\r\n\t\t\t\t}\r\n\t\t\t\t// Validate the `.zip` archive as its data comes through.\r\n\t\t\t\tvalidateChunk(chunk)\r\n\t\t\t\t// If the `.zip` archive is found to be invalid, stop any further\r\n\t\t\t\t// processing of it.\r\n\t\t\t\tif (errored) {\r\n\t\t\t\t\treturn\r\n\t\t\t\t}\r\n\t\t\t\t// Push the next data chunk to `fflate`'s `Unzip` class instance.\r\n\t\t\t\t//\r\n\t\t\t\t// The `.push()` function of `fflate`'s own `ZipInflate` decompressor is synchronous,\r\n\t\t\t\t// meaning that by the time it returns, any complete files entries encountered so far\r\n\t\t\t\t// have already been decompressed and populated in the `files` object.\r\n\t\t\t\t//\r\n\t\t\t\t// The `.push()` function of `NativeZlibInflate` decompressor is asynchronous,\r\n\t\t\t\t// so it requires hacking around with the counter of \"still being decompressed\" entries\r\n\t\t\t\t// in order to detect the actual finish of the archive's decompression process.\r\n\t\t\t\t//\r\n\t\t\t\ttry {\r\n\t\t\t\t\tunzip.push(chunk, false)\r\n\t\t\t\t} catch (error) {\r\n\t\t\t\t\tonError(error)\r\n\t\t\t\t}\r\n\t\t\t})\r\n\t\t\t// When there's no more data in the input stream to consume,\r\n\t\t\t// finish reading the `.zip` archive.\r\n\t\t\t.on('end', () => {\r\n\t\t\t\t// If there were any errors when reading the `.zip` archive,\r\n\t\t\t\t// don't `resolve()` with anything.\r\n\t\t\t\tif (errored) {\r\n\t\t\t\t\treturn\r\n\t\t\t\t}\r\n\t\t\t\ttry {\r\n\t\t\t\t\t// Signal the end of the archive to `fflate`'s `Unzip` class instance.\r\n\t\t\t\t\t// It will flush any remaining state in it.\r\n\t\t\t\t\tunzip.push(new Uint8Array(0), true)\r\n\t\t\t\t\t// The input stream has ended.\r\n\t\t\t\t\tnoMoreEntries = true\r\n\t\t\t\t\t// The entries may still be decompressing asynchronously.\r\n\t\t\t\t\t// In that case, resolve once they all finish decompresssing.\r\n\t\t\t\t\t// Or, resolve if all entries have already finished decompressing by now.\r\n\t\t\t\t\tresolveIfDone()\r\n\t\t\t\t} catch (error) {\r\n\t\t\t\t\tonError(error)\r\n\t\t\t\t}\r\n\t\t\t})\r\n\t})\r\n}\r\n\r\n// Every section in a `.zip` archive is marked with 4 bytes, the first two of which\r\n// are `0x50` and `0x4B`, which reads \"PK\", referencing the initials of the inventor Phil Katz.\r\n//\r\n// It looks like `fflate`'s `Unzip` doesn't ever complain about whatever data is thrown at it.\r\n// Due to how `.zip` file format is defined, \"garbage\" data could be placed at various\r\n// places in it and it'd still be a valid `.zip` archive. It's likely that for this reason\r\n// `fflate` doesn't ever complain and simply emits no entries when fed any kind of invalid data.\r\n//\r\n// In order to introduce some basic validation, here we specifically demand\r\n// that a `.zip` archive must at least start with an individual file entry\r\n// because an `.xlsx` file creator softwared really shouldn't attempt doing\r\n// anything \"funny\" when writing a file, hence this adherence requirement.\r\n//\r\nfunction createZipFileValidator(onValidationResult) {\r\n\tconst firstBytesCount = 2\r\n\tconst firstBytes = []\r\n\tlet firstBytesCheckResult\r\n\treturn {\r\n\t\tvalidateChunk(chunk) {\r\n\t\t\tif (firstBytes.length < 2) {\r\n\t\t\t\tlet i = 0\r\n\t\t\t\twhile (i < chunk.length && i < firstBytesCount) {\r\n\t\t\t\t\tfirstBytes.push(chunk[i])\r\n\t\t\t\t\ti++\r\n\t\t\t\t}\r\n\t\t\t\tif (firstBytes.length === 2) {\r\n\t\t\t\t\tconst isValid = firstBytes[0] === 0x50 && firstBytes[1] === 0x4B\r\n\t\t\t\t\tonValidationResult(isValid)\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n// An implemenation of a `DEFLATE` decompressor for `fflate`'s `Unzip` class\r\n// that uses Node.js's \"native\" module `zlib`.\r\n//\r\n// It implements `fflate`'s decoder interface: `Unzip` constructs one decoder\r\n// per each entry, sets `ondata(error, chunk, isLast)` callback on it, and feeds it\r\n// the entry's compressed bytes by calling `push(chunk, isLast)` method.\r\n//\r\n// Unlike `fflate`'s synchronous `UnzipInflate` decoder, `zlib` decompresses asynchronously,\r\n// so an entry only finishes some \"ticks\" after its last chunk of its data is `push()`ed\r\n// by `fflate`'s `Unzip` class. To work around this issue, pending entries counter is used\r\n// to track when the archive really finishes unpacking.\r\n//\r\nclass NativeZlibInflate {\r\n\tstatic compression = 8\r\n\r\n\tconstructor() {\r\n\t\tthis.inflate = zlib.createInflateRaw()\r\n\t\tthis.inflate.on('data', (chunk) => this.ondata(null, chunk, false))\r\n\t\tthis.inflate.on('end', () => this.ondata(null, new Uint8Array(0), true))\r\n\t\tthis.inflate.on('error', (error) => this.ondata(error, null, false))\r\n\t}\r\n\r\n\tpush(chunk, isLast) {\r\n\t\tthis.inflate.write(Buffer.from(chunk))\r\n\t\tif (isLast) {\r\n\t\t\tthis.inflate.end()\r\n\t\t}\r\n\t}\r\n\r\n\tterminate() {\r\n\t\tthis.inflate.destroy()\r\n\t}\r\n}\r\n"],"mappings":";;;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,KAAK,QAAQ,QAAQ;AAC9B;;AAEA,SAASC,MAAM,QAAQ,aAAa;AACpC,OAAOC,IAAI,MAAM,WAAW;;AAE5B;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAMC,qBAAqB,GAAG,IAAI;;AAElC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAMC,6BAA6B,GAAG,KAAK;;AAE3C;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,eAAeA,CAACC,MAAM,EAAmB;EAAA,IAAAC,IAAA,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAJ,CAAC,CAAC;IAAbG,MAAM,GAAAJ,IAAA,CAANI,MAAM;EACvD;EACA,IAAMC,KAAK,GAAG,CAAC,CAAC;EA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,CAAC,CAAC;MACtC,IAAI0B,MAAM,EAAE;QACX,IAAI,CAACe,OAAO,CAACO,GAAG,CAAC,CAAC;MACnB;IACD;EAAC;IAAAJ,GAAA;IAAAC,KAAA,EAED,SAAAI,UAAA,EAAY;MACX,IAAI,CAACR,OAAO,CAACS,OAAO,CAAC,CAAC;IACvB;EAAC;EAAA,OAAArB,iBAAA;AAAA;AAAAsB,eAAA,CAnBItB,iBAAiB,iBACD,CAAC"}
@@ -1,4 +1,14 @@
1
- // Currently, there're two implementations:
1
+ // `unzipFromStream` function reads `.zip` archive data from a Node.js stream.
2
+ //
3
+ // Even though it receives a Node.js stream as an input, it doesn't return the results
4
+ // as a Node.js output stream (with `objectMode: true` setting). The reason is that
5
+ // the result of this function is then passed to the XML parser which currently
6
+ // doesn't support consuming a Node.js stream and instead consumes the entire XML document
7
+ // as a single string. This means that implementing streaming output in this function
8
+ // wouldn't result in any performance improvements, so currently it simply returns
9
+ // a "map" of all files in the input `.zip` archive, and that seems to be enough.
10
+ //
11
+ // Currently, there're two decompressor implementations:
2
12
  // * `fflate` — a pure-javascript implementation that uses `fflate` package.
3
13
  // * `unzipper` — a "native" Node.js module that uses Node's `zlib` which is written in C.
4
14
  //
@@ -8,7 +18,51 @@
8
18
  // npm run test:benchmark:unzipFromStream
9
19
  // ```
10
20
  //
11
- // The benchmark tells that `unzipper` is 2x faster than `fflate`.
21
+ // The benchmark tells that `unzipper` is 2x faster than `fflate` with the default `ZipInflate` decompressor.
22
+ //
23
+ // However, when swapping `fflate`'s default `ZipInflate` decompressor with a custom
24
+ // "native" `zlib` one, `fflate` happens to be about 20% faster than `unzipper`.
25
+ //
26
+ // Still, when measuring the total time of parsing `.xlsx` files,
27
+ // the time difference becomes unmeasurable between `unzipper`
28
+ // and `fflate` with "native" `zlib` decompressor,
29
+ // as could be seen by running `npm run test:benchmark` command
30
+ // where `fflate` is slightly faster than `unzipper`.
31
+ //
32
+ // * When decompressing a `1 MB` `.xlsx` file, the decompression time is `90 ms`
33
+ // when using `fflate` with `zlib` decompressor and `100 ms` when using `unzipper` decompressor.
34
+ // * When decompressing a `10 MB` `.xlsx` file, the decompression time is `530 ms`
35
+ // when using `fflate` with `zlib` decompressor and `550 ms` when using `unzipper` decompressor.
36
+ // * When decompressing a `50 MB` `.xlsx` file, the decompression time is `2800 ms`
37
+ // when using `fflate` with `zlib` decompressor and `3000 ms` when using `unzipper` decompressor.
38
+ //
39
+ // So, at the end of the day, there's no substantial difference between the two
40
+ // when it comes to parsing `.xlsx` files, and one may choose depending on personal preference.
41
+ //
42
+ // And my personal preference leans towards `unzipper` because:
43
+ //
44
+ // * I personally refactored it into `unzipper-esm` in about 5-6 hours.
45
+ // https://github.com/ZJONSSON/node-unzipper/pull/356
46
+ //
47
+ // * It is designed as a Node.js-first module, i.e. it is designed around the concept
48
+ // of Node.js streams "from the ground up". Meanwhile, `fflate` is a "universal" module
49
+ // and it does not implement Node.js streams "contract", i.e. it just unzips the archive
50
+ // as fast as it can consume it from the input stream, without throttling the data throughput
51
+ // in cases when the input data flows faster than `fflate` can process it. This means that
52
+ // in the "worst case" scenario when `fflate`'s decompressor is unable to keep up with the
53
+ // data influx, it would "buffer" the entire `.zip` archive in RAM until it's processed.
54
+ // And while this is no big deal by any means, it's still not as elegant as adhering to
55
+ // Node.js streaming protocol.
56
+ //
57
+ // * `unzipper` uses native `zlib` decompressor which `fflate` doesn't officially include
58
+ // and it had to be hacked into it using a couple of tricks. That's also no big deal,
59
+ // but still a slightly weird experience.
60
+ //
61
+ // * Rumors are circulating that `fflate`'s "streaming" `Zip`/`Unzip` classes have a few
62
+ // implementation issues when compared to non-"streaming" `zipSync`/`unzipSync`/`zip`/`unzip` functions.
63
+ // Some people even suggested in the comments that `Zip`/`Unzip` classes are not really production-ready
64
+ // when compared to `zipSync`/`unzipSync`/`zip`/`unzip` functions.
65
+ // https://github.com/101arrowz/fflate/issues/282
12
66
  //
13
67
  export { default } from './unzipFromStream.unzipper.js';
14
68
  //# sourceMappingURL=unzipFromStream.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"unzipFromStream.js","names":["default"],"sources":["../../source/zip/unzipFromStream.js"],"sourcesContent":["// Currently, there're two implementations:\r\n// * `fflate` — a pure-javascript implementation that uses `fflate` package.\r\n// * `unzipper` — a \"native\" Node.js module that uses Node's `zlib` which is written in C.\r\n//\r\n// The implementations are compared in a benchmark:\r\n//\r\n// ```\r\n// npm run test:benchmark:unzipFromStream\r\n// ```\r\n//\r\n// The benchmark tells that `unzipper` is 2x faster than `fflate`.\r\n//\r\nexport { default as default } from './unzipFromStream.unzipper.js'"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,OAAkB,QAAQ,+BAA+B"}
1
+ {"version":3,"file":"unzipFromStream.js","names":["default"],"sources":["../../source/zip/unzipFromStream.js"],"sourcesContent":["// `unzipFromStream` function reads `.zip` archive data from a Node.js stream.\r\n//\r\n// Even though it receives a Node.js stream as an input, it doesn't return the results\r\n// as a Node.js output stream (with `objectMode: true` setting). The reason is that\r\n// the result of this function is then passed to the XML parser which currently\r\n// doesn't support consuming a Node.js stream and instead consumes the entire XML document\r\n// as a single string. This means that implementing streaming output in this function\r\n// wouldn't result in any performance improvements, so currently it simply returns\r\n// a \"map\" of all files in the input `.zip` archive, and that seems to be enough.\r\n//\r\n// Currently, there're two decompressor implementations:\r\n// * `fflate` — a pure-javascript implementation that uses `fflate` package.\r\n// * `unzipper` — a \"native\" Node.js module that uses Node's `zlib` which is written in C.\r\n//\r\n// The implementations are compared in a benchmark:\r\n//\r\n// ```\r\n// npm run test:benchmark:unzipFromStream\r\n// ```\r\n//\r\n// The benchmark tells that `unzipper` is 2x faster than `fflate` with the default `ZipInflate` decompressor.\r\n//\r\n// However, when swapping `fflate`'s default `ZipInflate` decompressor with a custom\r\n// \"native\" `zlib` one, `fflate` happens to be about 20% faster than `unzipper`.\r\n//\r\n// Still, when measuring the total time of parsing `.xlsx` files,\r\n// the time difference becomes unmeasurable between `unzipper`\r\n// and `fflate` with \"native\" `zlib` decompressor,\r\n// as could be seen by running `npm run test:benchmark` command\r\n// where `fflate` is slightly faster than `unzipper`.\r\n//\r\n// * When decompressing a `1 MB` `.xlsx` file, the decompression time is `90 ms`\r\n// when using `fflate` with `zlib` decompressor and `100 ms` when using `unzipper` decompressor.\r\n// * When decompressing a `10 MB` `.xlsx` file, the decompression time is `530 ms`\r\n// when using `fflate` with `zlib` decompressor and `550 ms` when using `unzipper` decompressor.\r\n// * When decompressing a `50 MB` `.xlsx` file, the decompression time is `2800 ms`\r\n// when using `fflate` with `zlib` decompressor and `3000 ms` when using `unzipper` decompressor.\r\n//\r\n// So, at the end of the day, there's no substantial difference between the two\r\n// when it comes to parsing `.xlsx` files, and one may choose depending on personal preference.\r\n//\r\n// And my personal preference leans towards `unzipper` because:\r\n//\r\n// * I personally refactored it into `unzipper-esm` in about 5-6 hours.\r\n// https://github.com/ZJONSSON/node-unzipper/pull/356\r\n//\r\n// * It is designed as a Node.js-first module, i.e. it is designed around the concept\r\n// of Node.js streams \"from the ground up\". Meanwhile, `fflate` is a \"universal\" module\r\n// and it does not implement Node.js streams \"contract\", i.e. it just unzips the archive\r\n// as fast as it can consume it from the input stream, without throttling the data throughput\r\n// in cases when the input data flows faster than `fflate` can process it. This means that\r\n// in the \"worst case\" scenario when `fflate`'s decompressor is unable to keep up with the\r\n// data influx, it would \"buffer\" the entire `.zip` archive in RAM until it's processed.\r\n// And while this is no big deal by any means, it's still not as elegant as adhering to\r\n// Node.js streaming protocol.\r\n//\r\n// * `unzipper` uses native `zlib` decompressor which `fflate` doesn't officially include\r\n// and it had to be hacked into it using a couple of tricks. That's also no big deal,\r\n// but still a slightly weird experience.\r\n//\r\n// * Rumors are circulating that `fflate`'s \"streaming\" `Zip`/`Unzip` classes have a few\r\n// implementation issues when compared to non-\"streaming\" `zipSync`/`unzipSync`/`zip`/`unzip` functions.\r\n// Some people even suggested in the comments that `Zip`/`Unzip` classes are not really production-ready\r\n// when compared to `zipSync`/`unzipSync`/`zip`/`unzip` functions.\r\n// https://github.com/101arrowz/fflate/issues/282\r\n//\r\nexport { default as default } from './unzipFromStream.unzipper.js'"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,OAAkB,QAAQ,+BAA+B"}
@@ -1,22 +1,14 @@
1
- // `unzipper` uses Node.js native `zlib` module.
2
- // This means that most likely it's more performant than an equivalent javascript-only implementation.
3
-
4
- // `unzipper` has a bug — it is written in CommonJS and uses a conditional `require()` call
5
- // to create an AWS S3 client instance: `require('@aws-sdk/client-s3')`.
6
- // https://github.com/ZJONSSON/node-unzipper/issues/330
7
- // The author of the package refuses to acknowledge the issue and apply a simple fix.
8
- // The package, therefore, looks like an "abandonware".
9
- // Someone could easily fix the issue though by forking the package.
1
+ // Considerations:
10
2
  //
11
- // When not forking to apply the fix, a workaround could be to install "@aws-sdk/client-s3"
12
- // package manually, which introduces unnecessary complexity and "esoteric knowledge" to the application setup.
3
+ // * `unzipper` unpacks a `.zip` file using Node.js's "native" `zlib` module.
4
+ // This means that it's more performant than any equivalent pure-javascript decompressor.
13
5
  //
14
- // Another workaround could be to "alias" "@aws-sdk/client-s3" package in a "bundler" configuration file
15
- // with a path to a `*.js` file containing just "export default null". But that kind of a workaround would also
16
- // result in errors when using other packages that happen to `import` anything from "@aws-sdk/client-s3" package,
17
- // so it's not really a workaround but more of a ticking bomb. Not to mention that it introduces
18
- // unnecessary complexity and "esoteric knowledge" to the application setup.
6
+ // * `unzipper` is a true "streaming" unpacker: it works in a "pull" fashion rather than a "push" one.
7
+ // New chunks of archived data are only read and decompressed as the receiver is ready to process them.
19
8
  //
9
+ // * `unzipper` can completely skip a given compressed file entry if it's of no interest.
10
+ // This means that a `.zip` archive could be read in multiple passes without performance penalty.
11
+
20
12
  import { Parse } from 'unzipper-esm';
21
13
  import { Buffer } from 'buffer';
22
14
 
@@ -30,6 +22,31 @@ export default function unzipFromStream(stream) {
30
22
  filter = _ref.filter;
31
23
  // The `files` object stores the files and their contents.
32
24
  var files = {};
25
+ var filesChunks = {};
26
+ var onFile = function onFile(filePath) {
27
+ // See if this file should be ignored.
28
+ // If it should, this entry won't be processed, i.e. `Unzip` will not try
29
+ // to decompress its data, and will just discard it.
30
+ if (filter && !filter({
31
+ path: filePath
32
+ })) {
33
+ return false;
34
+ }
35
+ filesChunks[filePath] = [];
36
+ };
37
+ var onFileData = function onFileData(filePath, chunk) {
38
+ filesChunks[filePath].push(chunk);
39
+ };
40
+ var onFileDataEnd = function onFileDataEnd(filePath) {
41
+ files[filePath] = Buffer.concat(filesChunks[filePath]);
42
+ delete filesChunks[filePath];
43
+ };
44
+ return unzipFromStream_(stream, onFile, onFileData, onFileDataEnd).then(function () {
45
+ return files;
46
+ });
47
+ }
48
+ var PROMISE_RESOLVE_VALUE = undefined;
49
+ function unzipFromStream_(stream, onFile, onFileData, onFileDataEnd) {
33
50
  return new Promise(function (resolve, reject) {
34
51
  var promises = [];
35
52
  var errored = false;
@@ -70,7 +87,7 @@ export default function unzipFromStream(stream) {
70
87
  // but I didn't remove it just to potentially prevent any potential silly bugs
71
88
  // in case of some potential changes in some potential future.
72
89
  Promise.all(promises).then(function () {
73
- resolve(files);
90
+ resolve(PROMISE_RESOLVE_VALUE);
74
91
  }, onError);
75
92
  }
76
93
  }).on('entry', function (entry) {
@@ -84,12 +101,8 @@ export default function unzipFromStream(stream) {
84
101
  if (errored) {
85
102
  ignore = true;
86
103
  }
87
- if (filter) {
88
- if (!filter({
89
- path: entry.path
90
- })) {
91
- ignore = true;
92
- }
104
+ if (onFile(entry.path) === false) {
105
+ ignore = true;
93
106
  }
94
107
 
95
108
  // If this file should be ignored.
@@ -100,18 +113,17 @@ export default function unzipFromStream(stream) {
100
113
  entry.autodrain().on('error', onError);
101
114
  return;
102
115
  }
103
- var chunks = [];
104
116
  promises.push(new Promise(function (resolve) {
105
117
  // `entry` seems to be a generic Node.js stream.
106
118
  // `entry.pipe()` pipes the file contents to a stream.
107
119
  // `entry.stream()` returns a readable stream.
108
120
  // `entry.buffer()` returns a promise that resolves to a `Buffer` with the file contents.
109
121
  entry.on('data', function (data) {
110
- chunks.push(data);
122
+ onFileData(entry.path, data);
111
123
  }).on('error', function (error) {
112
124
  onError(error);
113
125
  }).on('finish', function () {
114
- files[entry.path] = Buffer.concat(chunks);
126
+ onFileDataEnd(entry.path);
115
127
  resolve();
116
128
  });
117
129
  }));
@@ -1 +1 @@
1
- {"version":3,"file":"unzipFromStream.unzipper.js","names":["Parse","Buffer","unzipFromStream","stream","_ref","arguments","length","undefined","filter","files","Promise","resolve","reject","promises","errored","onError","error","on","pipe","all","then","entry","ignore","type","path","autodrain","chunks","push","data","concat"],"sources":["../../source/zip/unzipFromStream.unzipper.js"],"sourcesContent":["// `unzipper` uses Node.js native `zlib` module.\r\n// This means that most likely it's more performant than an equivalent javascript-only implementation.\r\n\r\n// `unzipper` has a bug — it is written in CommonJS and uses a conditional `require()` call\r\n// to create an AWS S3 client instance: `require('@aws-sdk/client-s3')`.\r\n// https://github.com/ZJONSSON/node-unzipper/issues/330\r\n// The author of the package refuses to acknowledge the issue and apply a simple fix.\r\n// The package, therefore, looks like an \"abandonware\".\r\n// Someone could easily fix the issue though by forking the package.\r\n//\r\n// When not forking to apply the fix, a workaround could be to install \"@aws-sdk/client-s3\"\r\n// package manually, which introduces unnecessary complexity and \"esoteric knowledge\" to the application setup.\r\n//\r\n// Another workaround could be to \"alias\" \"@aws-sdk/client-s3\" package in a \"bundler\" configuration file\r\n// with a path to a `*.js` file containing just \"export default null\". But that kind of a workaround would also\r\n// result in errors when using other packages that happen to `import` anything from \"@aws-sdk/client-s3\" package,\r\n// so it's not really a workaround but more of a ticking bomb. Not to mention that it introduces\r\n// unnecessary complexity and \"esoteric knowledge\" to the application setup.\r\n//\r\nimport { Parse } from 'unzipper-esm'\r\n\r\nimport { Buffer } from 'buffer'\r\n\r\n/**\r\n * Reads `*.zip` file contents.\r\n * @param {Stream} stream\r\n * @return {Promise<Record<string,Buffer>>} Resolves to an object holding `*.zip` file entries. P.S. `Buffer` is a `Uint8Array`.\r\n */\r\nexport default function unzipFromStream(stream, { filter } = {}) {\r\n\t// The `files` object stores the files and their contents.\r\n\tconst files = {}\r\n\r\n\treturn new Promise((resolve, reject) => {\r\n\t\tconst promises = []\r\n\r\n\t\tlet errored = false\r\n\r\n\t\tconst onError = (error) => {\r\n\t\t\tif (!errored) {\r\n\t\t\t\terrored = true\r\n\t\t\t\treject(error)\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tstream\r\n\t\t\t// This first \"error\" listener catches the original stream errors.\r\n\t\t\t//\r\n\t\t\t// That's because the .pipe() method does not automatically propagate errors\r\n\t\t\t// from a source (input) stream to the destination stream or the end of the pipeline.\r\n\t\t\t// You would need to attach an 'error' event handler to each stream in the chain.\r\n\t\t\t//\r\n\t\t\t// A more convenient alternative would be to use `stream.pipeline()` function:\r\n\t\t\t// `pipeline(stream1, stream2, (error) => { ... })`\r\n\t\t\t//\r\n\t\t\t.on('error', onError)\r\n\t\t\t// Pipe the input stream through the unzipper stream.\r\n\t\t\t.pipe(Parse())\r\n\t\t\t// This second \"error\" listener catches the unzipper stream errors.\r\n\t\t\t//\r\n\t\t\t// That's because the .pipe() method does not automatically propagate errors\r\n\t\t\t// from a source (input) stream to the destination stream or the end of the pipeline.\r\n\t\t\t// You would need to attach an 'error' event handler to each stream in the chain.\r\n\t\t\t//\r\n\t\t\t// A more convenient alternative would be to use `stream.pipeline()` function:\r\n\t\t\t// `pipeline(stream1, stream2, (error) => { ... })`\r\n\t\t\t//\r\n\t\t\t.on('error', onError)\r\n\t\t\t// The unzipper stream is closed when all `entries` have been reported.\r\n\t\t\t.on('finish', () => {\r\n\t\t\t\tif (!errored) {\r\n\t\t\t\t\t// Wait for all `entries` to be read.\r\n\t\t\t\t\t// The second argument of `.then()` function is not required\r\n\t\t\t\t\t// but I didn't remove it just to potentially prevent any potential silly bugs\r\n\t\t\t\t\t// in case of some potential changes in some potential future.\r\n\t\t\t\t\tPromise.all(promises).then(() => {\r\n\t\t\t\t\t\tresolve(files)\r\n\t\t\t\t\t}, onError)\r\n\t\t\t\t}\r\n\t\t\t})\r\n\t\t\t.on('entry', (entry) => {\r\n\t\t\t\t// See if this file should be ignored.\r\n\t\t\t\tlet ignore = false\r\n\t\t\t\t// `entry.type` could be 'Directory' or 'File'.\r\n\t\t\t\t// Ignore anything except files.\r\n\t\t\t\tif (entry.type === 'Directory') {\r\n\t\t\t\t\tignore = true\r\n\t\t\t\t}\r\n\t\t\t\tif (errored) {\r\n\t\t\t\t\tignore = true\r\n\t\t\t\t}\r\n\t\t\t\tif (filter) {\r\n\t\t\t\t\tif (!filter({ path: entry.path })) {\r\n\t\t\t\t\t\tignore = true\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// If this file should be ignored.\r\n\t\t\t\tif (ignore) {\r\n\t\t\t\t\t// Call `entry.autodrain()` when you do not intend to process a specific `entry`'s raw data.\r\n\t\t\t\t\t// Otherwise, if an `entry` is not consumed (via .pipe(), .buffer(), or .autodrain()),\r\n\t\t\t\t\t// the stream will halt, preventing further file processing.\r\n\t\t\t\t\tentry.autodrain().on('error', onError)\r\n\t\t\t\t\treturn\r\n\t\t\t\t}\r\n\r\n\t\t\t\tconst chunks = []\r\n\r\n\t\t\t\tpromises.push(new Promise((resolve) => {\r\n\t\t\t\t\t// `entry` seems to be a generic Node.js stream.\r\n\t\t\t\t\t// `entry.pipe()` pipes the file contents to a stream.\r\n\t\t\t\t\t// `entry.stream()` returns a readable stream.\r\n\t\t\t\t\t// `entry.buffer()` returns a promise that resolves to a `Buffer` with the file contents.\r\n\t\t\t\t\tentry\r\n\t\t\t\t\t\t.on('data', (data) => {\r\n\t\t\t\t\t\t\tchunks.push(data)\r\n\t\t\t\t\t\t})\r\n\t\t\t\t\t\t.on('error', (error) => {\r\n\t\t\t\t\t\t\tonError(error)\r\n\t\t\t\t\t\t})\r\n\t\t\t\t\t\t.on('finish', () => {\r\n\t\t\t\t\t\t\tfiles[entry.path] = Buffer.concat(chunks)\r\n\t\t\t\t\t\t\tresolve()\r\n\t\t\t\t\t\t})\r\n\t\t\t\t}))\r\n\t\t\t})\r\n\t})\r\n}"],"mappings":"AAAA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASA,KAAK,QAAQ,cAAc;AAEpC,SAASC,MAAM,QAAQ,QAAQ;;AAE/B;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,eAAeA,CAACC,MAAM,EAAmB;EAAA,IAAAC,IAAA,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAJ,CAAC,CAAC;IAAbG,MAAM,GAAAJ,IAAA,CAANI,MAAM;EACvD;EACA,IAAMC,KAAK,GAAG,CAAC,CAAC;EAEhB,OAAO,IAAIC,OAAO,CAAC,UAACC,OAAO,EAAEC,MAAM,EAAK;IACvC,IAAMC,QAAQ,GAAG,EAAE;IAEnB,IAAIC,OAAO,GAAG,KAAK;IAEnB,IAAMC,OAAO,GAAG,SAAVA,OAAOA,CAAIC,KAAK,EAAK;MAC1B,IAAI,CAACF,OAAO,EAAE;QACbA,OAAO,GAAG,IAAI;QACdF,MAAM,CAACI,KAAK,CAAC;MACd;IACD,CAAC;IAEDb;IACC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IAAA,CACCc,EAAE,CAAC,OAAO,E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C;QACf,CAAC,CAAC,CACDC,EAAE,CAAC,QAAQ,EAAE,YAAM;UACnBR,KAAK,CAACY,KAAK,CAACG,IAAI,CAAC,GAAGvB,MAAM,CAAC4B,MAAM,CAACH,MAAM,CAAC;UACzCf,OAAO,CAAC,CAAC;QACV,CAAC,CAAC;MACJ,CAAC,CAAC,CAAC;IACJ,CAAC,CAAC;EACJ,CAAC,CAAC;AACH"}
1
+ {"version":3,"file":"unzipFromStream.unzipper.js","names":["Parse","Buffer","unzipFromStream","stream","_ref","arguments","length","undefined","filter","files","filesChunks","onFile","filePath","path","onFileData","chunk","push","onFileDataEnd","concat","unzipFromStream_","then","PROMISE_RESOLVE_VALUE","Promise","resolve","reject","promises","errored","onError","error","on","pipe","all","entry","ignore","type","autodrain","data"],"sources":["../../source/zip/unzipFromStream.unzipper.js"],"sourcesContent":["// Considerations:\r\n//\r\n// * `unzipper` unpacks a `.zip` file using Node.js's \"native\" `zlib` module.\r\n// This means that it's more performant than any equivalent pure-javascript decompressor.\r\n//\r\n// * `unzipper` is a true \"streaming\" unpacker: it works in a \"pull\" fashion rather than a \"push\" one.\r\n// New chunks of archived data are only read and decompressed as the receiver is ready to process them.\r\n//\r\n// * `unzipper` can completely skip a given compressed file entry if it's of no interest.\r\n// This means that a `.zip` archive could be read in multiple passes without performance penalty.\r\n\r\nimport { Parse } from 'unzipper-esm'\r\n\r\nimport { Buffer } from 'buffer'\r\n\r\n/**\r\n * Reads `*.zip` file contents.\r\n * @param {Stream} stream\r\n * @return {Promise<Record<string,Buffer>>} Resolves to an object holding `*.zip` file entries. P.S. `Buffer` is a `Uint8Array`.\r\n */\r\nexport default function unzipFromStream(stream, { filter } = {}) {\r\n\t// The `files` object stores the files and their contents.\r\n\tconst files = {}\r\n\tconst filesChunks = {}\r\n\r\n\tconst onFile = (filePath) => {\r\n\t\t// See if this file should be ignored.\r\n\t\t// If it should, this entry won't be processed, i.e. `Unzip` will not try\r\n\t\t// to decompress its data, and will just discard it.\r\n\t\tif (filter && !filter({ path: filePath })) {\r\n\t\t\treturn false\r\n\t\t}\r\n\t\tfilesChunks[filePath] = []\r\n\t}\r\n\r\n\tconst onFileData = (filePath, chunk) => {\r\n\t\tfilesChunks[filePath].push(chunk)\r\n\t}\r\n\r\n\tconst onFileDataEnd = (filePath) => {\r\n\t\tfiles[filePath] = Buffer.concat(filesChunks[filePath])\r\n\t\tdelete filesChunks[filePath]\r\n\t}\r\n\r\n\treturn unzipFromStream_(stream, onFile, onFileData, onFileDataEnd).then(() => {\r\n\t\treturn files\r\n\t})\r\n}\r\n\r\nconst PROMISE_RESOLVE_VALUE = undefined\r\n\r\nfunction unzipFromStream_(stream, onFile, onFileData, onFileDataEnd) {\r\n\treturn new Promise((resolve, reject) => {\r\n\t\tconst promises = []\r\n\r\n\t\tlet errored = false\r\n\r\n\t\tconst onError = (error) => {\r\n\t\t\tif (!errored) {\r\n\t\t\t\terrored = true\r\n\t\t\t\treject(error)\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tstream\r\n\t\t\t// This first \"error\" listener catches the original stream errors.\r\n\t\t\t//\r\n\t\t\t// That's because the .pipe() method does not automatically propagate errors\r\n\t\t\t// from a source (input) stream to the destination stream or the end of the pipeline.\r\n\t\t\t// You would need to attach an 'error' event handler to each stream in the chain.\r\n\t\t\t//\r\n\t\t\t// A more convenient alternative would be to use `stream.pipeline()` function:\r\n\t\t\t// `pipeline(stream1, stream2, (error) => { ... })`\r\n\t\t\t//\r\n\t\t\t.on('error', onError)\r\n\t\t\t// Pipe the input stream through the unzipper stream.\r\n\t\t\t.pipe(Parse())\r\n\t\t\t// This second \"error\" listener catches the unzipper stream errors.\r\n\t\t\t//\r\n\t\t\t// That's because the .pipe() method does not automatically propagate errors\r\n\t\t\t// from a source (input) stream to the destination stream or the end of the pipeline.\r\n\t\t\t// You would need to attach an 'error' event handler to each stream in the chain.\r\n\t\t\t//\r\n\t\t\t// A more convenient alternative would be to use `stream.pipeline()` function:\r\n\t\t\t// `pipeline(stream1, stream2, (error) => { ... })`\r\n\t\t\t//\r\n\t\t\t.on('error', onError)\r\n\t\t\t// The unzipper stream is closed when all `entries` have been reported.\r\n\t\t\t.on('finish', () => {\r\n\t\t\t\tif (!errored) {\r\n\t\t\t\t\t// Wait for all `entries` to be read.\r\n\t\t\t\t\t// The second argument of `.then()` function is not required\r\n\t\t\t\t\t// but I didn't remove it just to potentially prevent any potential silly bugs\r\n\t\t\t\t\t// in case of some potential changes in some potential future.\r\n\t\t\t\t\tPromise.all(promises).then(() => {\r\n\t\t\t\t\t\tresolve(PROMISE_RESOLVE_VALUE)\r\n\t\t\t\t\t}, onError)\r\n\t\t\t\t}\r\n\t\t\t})\r\n\t\t\t.on('entry', (entry) => {\r\n\t\t\t\t// See if this file should be ignored.\r\n\t\t\t\tlet ignore = false\r\n\t\t\t\t// `entry.type` could be 'Directory' or 'File'.\r\n\t\t\t\t// Ignore anything except files.\r\n\t\t\t\tif (entry.type === 'Directory') {\r\n\t\t\t\t\tignore = true\r\n\t\t\t\t}\r\n\t\t\t\tif (errored) {\r\n\t\t\t\t\tignore = true\r\n\t\t\t\t}\r\n\t\t\t\tif (onFile(entry.path) === false) {\r\n\t\t\t\t\tignore = true\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// If this file should be ignored.\r\n\t\t\t\tif (ignore) {\r\n\t\t\t\t\t// Call `entry.autodrain()` when you do not intend to process a specific `entry`'s raw data.\r\n\t\t\t\t\t// Otherwise, if an `entry` is not consumed (via .pipe(), .buffer(), or .autodrain()),\r\n\t\t\t\t\t// the stream will halt, preventing further file processing.\r\n\t\t\t\t\tentry.autodrain().on('error', onError)\r\n\t\t\t\t\treturn\r\n\t\t\t\t}\r\n\r\n\t\t\t\tpromises.push(new Promise((resolve) => {\r\n\t\t\t\t\t// `entry` seems to be a generic Node.js stream.\r\n\t\t\t\t\t// `entry.pipe()` pipes the file contents to a stream.\r\n\t\t\t\t\t// `entry.stream()` returns a readable stream.\r\n\t\t\t\t\t// `entry.buffer()` returns a promise that resolves to a `Buffer` with the file contents.\r\n\t\t\t\t\tentry\r\n\t\t\t\t\t\t.on('data', (data) => {\r\n\t\t\t\t\t\t\tonFileData(entry.path, data)\r\n\t\t\t\t\t\t})\r\n\t\t\t\t\t\t.on('error', (error) => {\r\n\t\t\t\t\t\t\tonError(error)\r\n\t\t\t\t\t\t})\r\n\t\t\t\t\t\t.on('finish', () => {\r\n\t\t\t\t\t\t\tonFileDataEnd(entry.path)\r\n\t\t\t\t\t\t\tresolve()\r\n\t\t\t\t\t\t})\r\n\t\t\t\t}))\r\n\t\t\t})\r\n\t})\r\n}"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAASA,KAAK,QAAQ,cAAc;AAEpC,SAASC,MAAM,QAAQ,QAAQ;;AAE/B;AACA;AACA;AACA;AACA;AACA,eAAe,SAASC,eAAeA,CAACC,MAAM,EAAmB;EAAA,IAAAC,IAAA,GAAAC,SAAA,CAAAC,MAAA,QAAAD,SAAA,QAAAE,SAAA,GAAAF,SAAA,MAAJ,CAAC,CAAC;IAAbG,MAAM,GAAAJ,IAAA,CAANI,MAAM;EACvD;EACA,IAAMC,KAAK,GAAG,CAAC,CAAC;EAChB,IAAMC,WAAW,GAAG,CAAC,CAAC;EAEtB,IAAMC,MAAM,GAAG,SAATA,MAAMA,CAAIC,QAAQ,EAAK;IAC5B;IACA;IACA;IACA,IAAIJ,MAAM,IAAI,CAACA,MAAM,CAAC;MAAEK,IAAI,EAAED;IAAS,CAAC,CAAC,EAAE;MAC1C,OAAO,KAAK;IACb;IACAF,WAAW,CAACE,QAAQ,CAAC,GAAG,EAAE;EAC3B,CAAC;EAED,IAAME,UAAU,GAAG,SAAbA,UAAUA,CAAIF,QAAQ,EAAEG,KAAK,EAAK;IACvCL,WAAW,CAACE,QAAQ,CAAC,CAACI,IAAI,CAACD,KAAK,CAAC;EAClC,CAAC;EAED,IAAME,aAAa,GAAG,SAAhBA,aAAaA,CAAIL,QAAQ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