@preventive/archive 1.2.0 → 1.2.2

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 (2) hide show
  1. package/package.json +1 -1
  2. package/src/compression.js +66 -31
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/archive",
3
- "version": "1.2.0",
3
+ "version": "1.2.2",
4
4
  "description": "Strict in-memory tar and zip on browser APIs",
5
5
  "type": "module",
6
6
  "exports": {
@@ -25,49 +25,64 @@ export function supports(format) {
25
25
  }
26
26
  }
27
27
 
28
- // A stream's chunks, through async iteration where the platform has it on
29
- // streams, and a reader where it does not.
30
- async function* chunksOf(stream) {
31
- if (Symbol.asyncIterator in stream) return yield* stream
28
+ // A stream's chunks: the stream itself where the platform iterates streams,
29
+ // and a reader's where it does not. Either cancels the stream when the loop
30
+ // reading it is left before its end.
31
+ async function* readerChunks(stream) {
32
32
  const reader = stream.getReader()
33
- for (let next = await reader.read(); !next.done; next = await reader.read()) yield next.value
34
- }
35
-
36
- // Output past `limit` is refused where it is, not after it has all been
37
- // made: erroring the bound cancels the stream behind it. A bound that is
38
- // no number (NaN) refuses everything, not nothing.
39
- function bounded(limit) {
40
- let total = 0
41
- return new TransformStream({
42
- transform(chunk, controller) {
43
- total += chunk.length
44
- if (total <= limit) controller.enqueue(chunk)
45
- else controller.error(new RangeError(`output past ${limit} bytes`))
46
- },
47
- })
33
+ try {
34
+ for (let next = await reader.read(); !next.done; next = await reader.read()) yield next.value
35
+ } finally {
36
+ reader.cancel().catch(() => {})
37
+ }
48
38
  }
39
+ const chunksOf = (stream) => (Symbol.asyncIterator in stream ? stream : readerChunks(stream))
49
40
 
50
41
  // The stream is made here, so a format the runtime lacks rejects with the
51
- // platform's own error, as a bad argument rather than bad data. Output is
52
- // gathered in the pieces the stream makes and joined at the end, or, given
53
- // `into`, copied into it as each piece comes and the piece let go: joining
54
- // holds the output twice at the end, which a caller who knows how much is
55
- // coming need not pay.
56
- async function through(bytes, Stream, format, limit, verb, into) {
42
+ // platform's own error, as a bad argument rather than bad data. The bytes
43
+ // go in as one write, which the stream takes in as it can, rather than in
44
+ // a Blob's pieces, each a turn of its own. Output is gathered in the pieces
45
+ // the stream makes and joined at the end, or, given `into`, copied into it
46
+ // as each piece comes and the piece let go: joining holds the output twice
47
+ // at the end, which a caller who knows how much is coming need not pay.
48
+ // Given `expected` bytes instead, the first that many are copied into one
49
+ // array of that size as they come, and any past it gathered in pieces.
50
+ // Output past `limit` is refused where it is, not after it has all been
51
+ // made: leaving the loop cancels the stream. A bound that is no number
52
+ // (NaN) refuses everything, not nothing.
53
+ async function through(bytes, Stream, format, limit, verb, into, expected = 0) {
57
54
  if (!(bytes instanceof Uint8Array)) throw new ArchiveError('the data is not a Uint8Array')
58
55
  const transform = new Stream(format)
59
56
  const chunks = []
60
57
  let length = 0
58
+ // Where the output is copied as it comes, and how much of it is filled.
59
+ let target = into ?? (expected > 0 ? new Uint8Array(expected) : undefined)
60
+ let filled = 0
61
61
  // What has come out so far, as one array: handed back at the end, and
62
62
  // with the error if the stream fails first.
63
63
  const made = () => {
64
64
  if (into !== undefined) return into.subarray(0, length)
65
+ if (target !== undefined) return filled === target.length ? target : target.subarray(0, filled)
65
66
  return chunks.length === 1 ? chunks[0] : concat(chunks)
66
67
  }
68
+ // The stream's own failure is read from its output; the writes fail with it.
69
+ const writer = transform.writable.getWriter()
70
+ writer.write(bytes).catch(() => {})
71
+ writer.close().catch(() => {})
67
72
  try {
68
- for await (const chunk of chunksOf(new Blob([bytes]).stream().pipeThrough(transform).pipeThrough(bounded(limit)))) {
69
- if (into === undefined) chunks.push(chunk)
70
- else into.set(chunk, length)
73
+ for await (const chunk of chunksOf(transform.readable)) {
74
+ if (!(length + chunk.length <= limit)) throw new RangeError(`output past ${limit} bytes`)
75
+ if (target !== undefined && filled + chunk.length > target.length && into === undefined) {
76
+ // More than was expected: what is filled is the first piece.
77
+ chunks.push(target.subarray(0, filled))
78
+ target = undefined
79
+ }
80
+ if (target === undefined) {
81
+ chunks.push(chunk)
82
+ } else {
83
+ target.set(chunk, filled)
84
+ filled += chunk.length
85
+ }
71
86
  length += chunk.length
72
87
  }
73
88
  } catch (cause) {
@@ -79,7 +94,27 @@ async function through(bytes, Stream, format, limit, verb, into) {
79
94
 
80
95
  export const compress = (bytes, format, { limit = Infinity } = {}) => through(bytes, CompressionStream, format, limit, 'compress')
81
96
 
82
- const inflate = (bytes, format, limit) => through(bytes, DecompressionStream, format, limit, 'decompress')
97
+ // What gzip says it decompresses to: its last member's trailer ends with the
98
+ // length of that member's data, mod 2^32, which is all of it where the data
99
+ // is one member and no more than 4 GiB. It is the data's own word, so it is
100
+ // taken only where `limit` lets that much through and it is no more than
101
+ // RATIO times the data: tarballs come to 2 to 13 times theirs, so one that
102
+ // says more is gathered in pieces as before, and a trailer that lies costs
103
+ // no more than that. Else, as when the data ends in padding, none is
104
+ // expected. Where it says less than comes, the rest is gathered as any
105
+ // output is; where it says more, the stream fails on it, as zlib holds the
106
+ // trailer to what it made.
107
+ const RATIO = 16
108
+ function expectedOf(bytes, limit) {
109
+ if (bytes.length < 18) return 0
110
+ const said = new DataView(bytes.buffer, bytes.byteOffset + bytes.length - 4, 4).getUint32(0, true)
111
+ return said <= limit && said <= bytes.length * RATIO ? said : 0
112
+ }
113
+
114
+ // With `sized`, the output made into one array as big as the trailer says
115
+ // (expectedOf), which only the data as given has: a place that padding is
116
+ // tried ending at has the member's checksum or none where a trailer would be.
117
+ const inflate = (bytes, format, limit, sized) => through(bytes, DecompressionStream, format, limit, 'decompress', undefined, sized && format === 'gzip' ? expectedOf(bytes, limit) : 0)
83
118
 
84
119
  // gzip(1) and zlib take zero bytes after the last member as padding, as old
85
120
  // tarballs run on in zeros to a whole 10240-byte record, the way npm 1.0
@@ -94,13 +129,13 @@ const inflate = (bytes, format, limit) => through(bytes, DecompressionStream, fo
94
129
  // only padded data pays for.
95
130
  export async function decompress(bytes, format, { limit = Infinity } = {}) {
96
131
  try {
97
- return await inflate(bytes, format, limit)
132
+ return await inflate(bytes, format, limit, true)
98
133
  } catch (error) {
99
134
  if (format !== 'gzip' || !(error instanceof CompressionError) || error.limited || bytes.at(-1) !== 0) throw error
100
135
  const last = bytes.findLastIndex((byte) => byte !== 0)
101
136
  for (let end = last + 1; end <= Math.min(last + 10, bytes.length - 1); end++) {
102
137
  try {
103
- return await inflate(bytes.subarray(0, end), format, limit)
138
+ return await inflate(bytes.subarray(0, end), format, limit, false)
104
139
  } catch (retry) {
105
140
  // Output past the bound before the end is past it wherever the end is.
106
141
  if (!(retry instanceof CompressionError) || retry.limited) throw retry