zztaeha

Types

25 types in kokyu 0.1.0, as the compiler exports them, filed by area: the options each call takes, the streams it hands back, what a zip entry says about itself, and the error. Each field and method has its own words, and each type an example that was type-checked and run against 0.1.0.

An option left out, or set to undefined, takes its default. Options are read when the call is made, so changing the object afterward changes nothing.

Errors and basics

What every other area shares: KokyuError, the error every failure kokyu raises itself comes as, its KokyuErrorCode, and the compression Level.

KokyuError
class KokyuError extends Error {
    readonly code: KokyuErrorCode;
    constructor(code: KokyuErrorCode, message: string);
}

The error every failure kokyu raises itself comes as.

The sync calls throw it and the async ones reject with it. Branch on KokyuError.code, which is one of the KokyuErrorCode strings and stays the same across versions. The message is for people: it starts with kokyu: and says what went wrong, and name is 'KokyuError'.

An error raised in a pool worker reaches you as a KokyuError with the same code and message, so instanceof works the same for the async calls as for the sync ones.

Two failures pass through as they are, never wrapped: an async call whose signal aborts rejects with the signal's reason, and an error your own UnzipOptions.filter throws comes out unchanged.

import { KokyuError, encodeText, inflate } from 'kokyu'

try {
  inflate(encodeText('this is not compressed at all'))
} catch (e) {
  if (!(e instanceof KokyuError)) throw e
  e.code // 'invalid-data': branch on this
  e.message // 'kokyu: invalid Huffman code', for people to read
}

const mine = new KokyuError('too-large', 'uploads are limited to 10 MB')
mine.message // 'kokyu: uploads are limited to 10 MB'
readonly code: KokyuErrorCode
What went wrong, one of the KokyuErrorCode strings. It is stable across versions, so it is what code should branch on, never the message.
constructor(code: KokyuErrorCode, message: string)
Makes one from a code and a message. The message gets kokyu: in front of it. kokyu makes every one it throws itself; make your own only where code of yours should fail the way kokyu does.
KokyuErrorCode
type KokyuErrorCode = 'truncated' | 'invalid-data' | 'invalid-header' | 'too-large' | 'unsupported' | 'invalid-option' | 'invalid-state' | 'worker'

Why a call failed: the code of every KokyuError.

A union of string literals, so a switch on KokyuError.code can cover every case and TypeScript checks that it does. The first five are about the data, invalid-option and invalid-state about how a call was made, and worker comes only from the async calls.

import { KokyuError, unzlib, zlib } from 'kokyu'
import type { KokyuErrorCode } from 'kokyu'

const codeOf = (run: () => unknown): KokyuErrorCode | undefined => {
  try {
    run()
  } catch (e) {
    if (e instanceof KokyuError) return e.code
    throw e
  }
  return undefined
}

const packed = zlib(new Uint8Array(1000))
codeOf(() => unzlib(packed.subarray(0, 6))) // 'truncated'
codeOf(() => unzlib(packed.subarray(1))) // 'invalid-header'
codeOf(() => unzlib(Uint8Array.of(0x78, 0x9c, 0xff))) // 'invalid-data'
codeOf(() => unzlib(packed, { maxSize: 999 })) // 'too-large'
codeOf(() => unzlib(packed, { maxSize: -1 })) // 'invalid-option'
'truncated'
The data ends before it is complete: deflate data cut off before its last block, a zlib or gzip header or trailer that isn't all there, or a zip archive or entry that ends early. A stream reports it from Stream.finish, since until then more data may come.
'invalid-data'
The data is corrupt: deflate that breaks the format's rules, a gzip trailer whose length doesn't match the output, or zip records that are broken or contradict each other. So does raw deflate that refers back into a dictionary it wasn't given.
'invalid-header'
A zlib or gzip header is wrong: the data doesn't start with a valid header of the format it is decoded as, or a gzip header sets reserved flags.
'too-large'
The output would pass a cap: InflateOptions.maxSize, GunzipOptions.maxSize or UnzipOptions.maxSize, the length of the buffer an …Into call decodes into, or in unzip the size a zip entry states for itself. Writing a zip that would need ZIP64 fails with it too, since kokyu reads ZIP64 but doesn't write it.
'unsupported'
Valid data in a form kokyu doesn't read: gzip compressed with a method other than deflate, a zip entry that is encrypted, holds patch data or uses a method other than stored or deflate, and a zip archive split into several files.
'invalid-option'
An argument is wrong: input, a chunk or out that isn't a readable Uint8Array, a level outside 0 to 9, a maxSize that isn't a whole number of bytes, or a value the format can't hold, such as a bad zip entry name. A zlib stream whose preset dictionary is missing or doesn't match fails with it too.
'invalid-state'
A stream used out of turn: after it finished, from inside one of its own calls, or, for the zip streams, in an order the format doesn't allow, such as a second entry while one is still open.
'worker'
A pool worker behind an async call failed to start, crashed or exited. Only the async calls fail with it.
Level
type Level = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

A compression level, from 0 (store without compressing) to 9 (search hardest).

Every compressor takes one as level: DeflateOptions.level, GzipOptions.level, ZipOptions.level and ZipEntryOptions.level. Left out, it is 6. Anything else, a fraction or a number outside 0 to 9, fails with invalid-option.

A higher level spends more time looking for repeats. On most data that buys smaller output, but not at every step: a level can come out larger than the one below it. The level changes only how the data is compressed, never how it is read: every decoder reads every level.

import { deflate, encodeText } from 'kokyu'
import type { Level } from 'kokyu'

const log = encodeText(Array.from({ length: 2000 }, (_, i) => `line ${i}: value ${i * 37 % 101}\n`).join(''))
const size = (level: Level): number => deflate(log, { level }).length
size(0) // 38717: the 38,712 bytes as they are, in one stored block
size(1) // 7617
size(4) // 6084
size(5) // 6085: 1 byte larger than level 4 here
size(6) // 6028, the default
size(9) // 6027
0
No compression: the input goes out as it is, in stored blocks of up to 65,535 bytes with 5 bytes of framing each. The fastest by far, and a dictionary changes nothing but zlib's header.
1
The fastest level that compresses: the shortest search, and each match goes out as soon as it is found.
2
As 1, with a longer search.
3
As 2, with a longer search. The last level that takes each match as soon as it is found.
4
The first level that, before it takes a short match, checks whether the next byte starts a longer one.
5
As 4, holding back longer matches to check and searching longer.
6
The default for every compressor: three times the search of 5, though it holds back only matches under 16 bytes.
7
As 6, holding back longer matches, and searching on until a match is as long as it can be.
8
As 7, except that every match short of the 258-byte maximum waits to see whether the next byte starts a longer one.
9
As 8, with twice the search. The slowest level.

Deflate and zlib

Raw deflate (RFC 1951) and zlib (RFC 1950), whole or as streams. zlib wraps deflate in a 2-byte header and an Adler-32 trailer, and can name a preset dictionary. Each decoder takes a maxSize, and has an …Into form that decodes into a buffer you already own.

DeflateOptions
interface DeflateOptions {
    level?: Level | undefined;
    dictionary?: Uint8Array | undefined;
}

Options for deflate, zlib and their streams.

Both are optional, and null or no options at all mean level 6 and no dictionary. They are read when the call or the stream is made, so changing them later changes nothing. The async forms take them too: deflateAsync, zlibAsync, deflateStreamAsync and zlibStreamAsync.

import { deflate, encodeText, inflate } from 'kokyu'
import type { DeflateOptions } from 'kokyu'

const dictionary = encodeText('{"type":"event","user":')
const message = encodeText('{"type":"event","user":"ada"}') // 29 bytes
const opts: DeflateOptions = { level: 9, dictionary }
deflate(message) // 31 bytes: too short to repeat itself
deflate(message, opts) // 10 bytes
inflate(deflate(message, opts), { dictionary }) // the 29 bytes
level?: Level | undefined
How hard to look for repeats, from 0 (stored, no compression) to 9; see Level. Default 6. Anything else fails with invalid-option.
dictionary?: Uint8Array | undefined
Bytes the input likely repeats, such as a shared header or the start of a typical message. Matches can refer back into it as if it came just before the input, which helps short inputs most. They reach only into its last 32 KB. Whoever decodes the data needs the same bytes, in InflateOptions.dictionary: zlib names it in its header, raw deflate doesn't. At level 0 nothing is compressed, so it changes nothing but zlib's header. An empty one counts as none, and anything but a Uint8Array fails with invalid-option.
InflateOptions
interface InflateOptions {
    dictionary?: Uint8Array | undefined;
    maxSize?: number | undefined;
}

Options for decoding raw deflate or zlib, and for decompress, which may find gzip.

inflate, unzlib, decompress, their …Into forms, their streams and their async forms all take them. Both are optional, and null or no options at all mean no dictionary and no cap. Where decompress finds gzip, only maxSize applies.

import { KokyuError, deflate, inflate } from 'kokyu'
import type { InflateOptions } from 'kokyu'

const bomb = deflate(new Uint8Array(10_000_000)) // 10 MB of zeros in 10,176 bytes
const opts: InflateOptions = { maxSize: 1_000_000 }
try {
  inflate(bomb, opts)
} catch (e) {
  if (e instanceof KokyuError) e.code // 'too-large', thrown once the output passes 1 MB
}
dictionary?: Uint8Array | undefined
The preset dictionary the data was compressed with: the same bytes as DeflateOptions.dictionary. zlib data names its dictionary in its header, and decoding it fails with invalid-option when this is missing or different. Raw deflate names none, so a missing one shows only as invalid-data once a match reaches back into it, and a wrong one can decode to wrong bytes without failing. It is ignored for data that needs none, but anything other than a Uint8Array fails with invalid-option.
maxSize?: number | undefined
The most bytes the output may hold. Output that would pass it fails with too-large, and exactly this many is fine. A whole number, 0 or more, or Infinity; anything else fails with invalid-option. No cap by default, so set it for untrusted input. It covers all the output: a stream's across every push, and every member of a gzip file in decompress. With an …Into call, the smaller of this and the length of out is the cap.

Gzip

gzip (RFC 1952), whole or as streams: deflate inside a header that can hold a file name and a time, and a trailer with a CRC-32 and the length. The decoders read every member of a file, one after another.

GzipOptions
interface GzipOptions {
    level?: Level | undefined;
    filename?: string | undefined;
    mtime?: Date | string | number | undefined;
}

Options for gzip, gzipStream and their async forms: the level, and what the header records.

Every field is optional. With none set, the header holds no name and a time of 0, so the output depends on the input alone.

import { gzip, encodeText, decodeText } from 'kokyu'
import type { GzipOptions } from 'kokyu'

const opts: GzipOptions = { level: 9, filename: 'notes.txt', mtime: new Date('2025-01-01T00:00:00Z') }
const packed = gzip(encodeText('notes'), opts)
new DataView(packed.buffer).getUint32(4, true) // 1735689600: the time, in whole seconds
decodeText(packed.subarray(10, 19), { latin1: true }) // 'notes.txt', right after the 10-byte header
level?: Level | undefined
How hard to compress: 0 stores without compressing, 1 is fastest, 9 searches hardest; see Level. Default 6. Anything but a whole number from 0 to 9 fails with invalid-option.
filename?: string | undefined
The original file name, stored in the header for a tool that restores it. The header holds latin1, so each character must be from U+0001 to U+00FF; a NUL or anything past U+00FF fails with invalid-option. An empty string stores no name. gunzip skips it when reading.
mtime?: Date | string | number | undefined
The modification time to store: a Date, a date string, or a number of milliseconds since 1970, as Date takes it. The header keeps whole seconds, rounded down. A time before 1970 or past February 2106, the most its 32 bits hold, or one that isn't a date, fails with invalid-option. Default none: the field is 0, so the same input always gives the same bytes.
GunzipOptions
interface GunzipOptions {
    maxSize?: number | undefined;
}

Options for gunzip, gunzipInto, gunzipStream and their async forms.

Its one field caps the output. Without it there is no cap, so set it for any input you don't trust.

import { gzip, gunzip, KokyuError } from 'kokyu'
import type { GunzipOptions } from 'kokyu'

const bomb = gzip(new Uint8Array(10_000_000)) // 10 MB of zeros in 10,194 bytes
const opts: GunzipOptions = { maxSize: 1_000_000 }
try {
  gunzip(bomb, opts)
} catch (e) {
  if (e instanceof KokyuError && e.code === 'too-large') { /* refuse it */ }
}
maxSize?: number | undefined
The most bytes of output to allow, over every member together. Output that would pass it fails with too-large, so a hostile input can't decode to more than you allow. It must be a whole number from 0 up, or Infinity for no cap; anything else fails with invalid-option. No cap by default.

Zip

Zip archives: written from an object of paths, or entry by entry as a stream, and read whole, listed, or as a stream of entries. Entries are stored or deflated. ZIP64, data descriptors and names that aren't UTF-8 are all read.

ZipInput
interface ZipInput {
    [path: string]: Uint8Array | readonly [Uint8Array, ZipEntryOptions] | ZipInput;
}

The files to zip: each key a path, each value its bytes, its bytes with options, or a folder of more.

A Uint8Array is a file with the archive's options, and [bytes, options] a file with ZipEntryOptions of its own. A plain object is a folder: its keys are joined to its path with /, and an empty one becomes a directory entry, its name ending in /. A key can hold / itself, so { 'a/b.txt': x } and { a: { 'b.txt': x } } write the same entry. Only a plain object counts as a folder: a Map or a class instance fails with invalid-option, and so do bytes in any typed array but a Uint8Array.

A name that extractors would write somewhere else fails with invalid-option: an empty name, one holding \ or a control character (U+0000 to U+001F, or U+007F), one that starts with / or a drive letter such as C:, one that holds an empty, . or .. folder (a//b, ./a, a/../b), and a file name that ends in ; and any digits (a;1, a;), which Info-ZIP drops as a VMS version. Each of these lands on another path in Info-ZIP, bsdtar or Python's zipfile. Names that only look alike, such as .profile, a..b or notes:v2.txt, are kept.

Two names for one path fail with invalid-option too: the same name twice, a file and a folder of one name (a and a/), or two strings that encode to the same UTF-8. A name, like an entry's comment, holds at most 65,535 bytes of UTF-8.

import { encodeText, KokyuError, zip, zipEntries } from 'kokyu'
import type { ZipInput } from 'kokyu'

const input: ZipInput = {
  'index.html': encodeText('<h1>Hi</h1>'),
  'assets/app.js': encodeText('main()'), // a key can hold folders
  assets: { 'logo.png': [new Uint8Array(64), { level: 0 }] },
  cache: {}, // an empty folder becomes a directory entry
}
zipEntries(zip(input)).map((e) => e.name) // ['index.html', 'assets/app.js', 'assets/logo.png', 'cache/']

try {
  zip({ '../notes.txt': encodeText('out of reach') })
} catch (e) {
  if (e instanceof KokyuError) console.log(e.code) // 'invalid-option'
}
[path: string]: Uint8Array | readonly [Uint8Array, ZipEntryOptions] | ZipInput
A path from the archive's root, or inside a folder from that folder, with / between folders. Its value is the file's bytes, [bytes, options], or a nested folder.
ZipOptions
interface ZipOptions {
    level?: Level | undefined;
    mtime?: Date | string | number | undefined;
    comment?: string | undefined;
}

Options for a whole archive, as zip and zipStream take them.

An entry's own ZipEntryOptions override level and mtime for that entry. zipStream reads these once, when you call it. zipAsync and zipStreamAsync take the same options.

import { decodeText, encodeText, zip, zipEntries } from 'kokyu'
import type { ZipOptions } from 'kokyu'

const opts: ZipOptions = { level: 9, mtime: new Date(2024, 4, 1, 12, 30, 15), comment: 'Build 812' }
const archive = zip({ 'a.txt': encodeText('a'.repeat(500)) }, opts)

zipEntries(archive)[0]!.mtime.getSeconds() // 14: zip keeps time to 2 seconds
decodeText(archive.subarray(-9)) // 'Build 812', the archive's last bytes
level?: Level | undefined
The compression level of every entry without its own: 0 stores, 1 is fastest, 9 searches hardest. Default 6. Anything but a whole number from 0 to 9 fails with invalid-option. zip stores an entry that deflate can't make smaller; zipStream deflates every entry, and at 0 writes deflate's stored blocks.
mtime?: Date | string | number | undefined
The modification time of every entry without its own, as a Date, a string Date can parse, or milliseconds since 1970. Default: the current time. Zip stores it in local time to 2 seconds, so an odd second is rounded down, and only from 1980 to 2107: a year outside those, or a date that isn't valid, fails with invalid-option.
comment?: string | undefined
The archive's comment, stored as UTF-8 at the very end of the archive. It holds at most 16,361 bytes, since bsdtar looks for an archive's end record only in its last 16 KB, and can't hold the end record's signature (PK and the bytes 5 and 6), which readers would take for the record itself. Either fails with invalid-option. kokyu's readers don't return it.
ZipEntryOptions
interface ZipEntryOptions {
    level?: Level | undefined;
    mtime?: Date | string | number | undefined;
    comment?: string | undefined;
    attrs?: number | undefined;
    os?: number | undefined;
    extra?: Record<number, Uint8Array> | undefined;
    mode?: number | undefined;
}

Options for one entry, given as [bytes, options] in a ZipInput or to ZipStream.file.

An option left out falls back to the archive's ZipOptions, then to the default. mode, os and attrs decide the permissions extractors give the file, and extra adds raw extra fields.

An entry left to the defaults is marked as made on Unix (os 3) with mode 0o644, or 0o755 for a folder, as Info-ZIP and Python write them on Unix. Apple's unzip can't extract a non-ASCII name that an MS-DOS host wrote, which is why MS-DOS isn't the default.

import { encodeText, zip, zipEntries } from 'kokyu'
import type { ZipEntryOptions } from 'kokyu'

const script: ZipEntryOptions = { mode: 0o755, comment: 'run me', level: 9 }
const archive = zip({
  'build.sh': [encodeText('#!/bin/sh\nnpm run build\n'), script],
  'README.txt': [encodeText('read me'), { os: 0 }], // MS-DOS, so no Unix mode
})
zipEntries(archive).map((e) => [e.name, e.mode?.toString(8), e.comment])
// [['build.sh', '755', 'run me'], ['README.txt', undefined, '']]
level?: Level | undefined
This entry's compression level, 0 to 9. Default: the archive's ZipOptions.level, or 6.
mtime?: Date | string | number | undefined
This entry's modification time, in the forms and range ZipOptions.mtime takes. Default: the archive's, or the current time.
comment?: string | undefined
A comment stored with this entry in the central directory, at most 65,535 bytes of UTF-8. ZipEntry.comment reads it back.
attrs?: number | undefined
The raw 32-bit external attributes, which readers interpret by os. Any 32-bit pattern goes, negative included, since a Unix mode shifted into the high half, such as 0o100644 << 16, is negative in JavaScript. Default: on Unix, mode 0o644 or 0o755 with its file type; with another os, 0 for a file and the MS-DOS directory bit (0x10) for a folder. Without os the entry stays Unix, so attributes for another system need their os too. It can't be combined with mode.
os?: number | undefined
The system the entry is marked as made on, which tells readers how to read attrs: 3 is Unix, the default, and 0 is MS-DOS. A whole number from 0 to 255. It can't be combined with mode.
extra?: Record<number, Uint8Array> | undefined
Extra fields, as an object from each field's 16-bit header ID to its data bytes; kokyu writes each field's 4-byte header. They go in both the local header and the central directory. A field holds at most 65,535 bytes, and so do all of them together with their headers. IDs 1 (ZIP64) and 0x7075 (Unicode Path, which some readers take as the entry's name) fail with invalid-option.
mode?: number | undefined
Unix permission bits, such as 0o644 or 0o755, from 0 to 0o7777. It marks the entry as made on Unix and writes the mode into the attributes with the file type, file or folder, so it can't be combined with os or attrs: that fails with invalid-option. ZipEntry.mode reads it back.
ZipEntryInfo
interface ZipEntryInfo {
    name: string;
    size?: number | undefined;
    originalSize?: number | undefined;
    compression: number;
    mtime: Date;
}

What unzipStream knows about an entry when it reaches the entry's local header.

Every UnzipChunk carries one as UnzipChunk.entry, and UnzipStreamOptions.filter sees a copy of one. ZipEntry, which zipEntries returns, extends it with the comment and mode that only the central directory holds, and always has both sizes.

The sizes come from the local header. An entry written with a data descriptor, as zipStream writes every one, has its sizes after its data, so here they're left out rather than given as 0: treat a missing size as one that could be anything.

import { encodeText, unzipStream, zip, zipStream } from 'kokyu'
import type { ZipEntryInfo } from 'kokyu'

// zip knows each entry's sizes before its header; a zipStream entry has them after its data
const whole = zip({ 'a.txt': encodeText('hello') })
const zs = zipStream()
const streamed = [zs.file('b.txt').finish(encodeText('hello')), zs.finish()]

const seen: ZipEntryInfo[] = []
const filter = (e: ZipEntryInfo) => { seen.push(e); return false }
unzipStream({ filter }).finish(whole)
const reader = unzipStream({ filter })
for (const part of streamed) reader.push(part)
reader.finish()

seen.map((e) => [e.name, e.originalSize]) // [['a.txt', 5], ['b.txt', undefined]]
name: string
The full path, with / between folders; a folder's ends in /. It is read as UTF-8 when the entry is flagged as UTF-8 or the bytes are valid UTF-8, and as code page 437 otherwise. kokyu doesn't check names it reads, and another tool's archive can hold .. or a leading /, so check a name before you use it as a file path.
size?: number | undefined
The compressed size in bytes. Missing when the entry's sizes follow its data.
originalSize?: number | undefined
The size in bytes once decompressed. Missing when the entry's sizes follow its data.
compression: number
The compression method: 0 is stored and 8 is deflate. An entry with any other is listed, but reading its data fails with unsupported.
mtime: Date
The modification time, read as local time, to the 2 seconds zip stores. Each entry has its own Date.
ZipEntry
interface ZipEntry extends ZipEntryInfo {
    size: number;
    originalSize: number;
    comment: string;
    mode?: number | undefined;
}

An entry as the archive's central directory lists it, as zipEntries returns it.

It is a ZipEntryInfo that always has both sizes, plus the entry's comment and Unix mode, which only the central directory holds. UnzipOptions.filter sees one for each entry too.

zipEntries builds new objects on every call, and a filter is handed a copy, so editing one changes nothing kokyu reads.

import { encodeText, zip, zipEntries } from 'kokyu'
import type { ZipEntry } from 'kokyu'

const archive = zip({
  tool: [encodeText('#!/bin/sh\n'), { mode: 0o755, comment: 'the CLI' }],
  'data.csv': encodeText('id,name\n'.repeat(100)),
})
const runnable = (e: ZipEntry) => ((e.mode ?? 0) & 0o111) !== 0
zipEntries(archive).filter(runnable).map((e) => [e.name, e.comment]) // [['tool', 'the CLI']]
size: number
The compressed size in bytes, from the central directory or its ZIP64 field.
originalSize: number
The size in bytes once decompressed. unzip holds each entry to exactly this, and adds them up against UnzipOptions.maxSize before it decodes anything.
comment: string
The entry's comment, or an empty string when it has none. It is decoded the way the name is.
mode?: number | undefined
The Unix permission bits, such as 0o755, from 0 to 0o7777, when the entry was made on Unix (os 3) and its attributes hold a mode. Missing otherwise, as for an entry made on MS-DOS.
UnzipOptions
interface UnzipOptions {
    filter?: ((entry: ZipEntry) => boolean) | undefined;
    maxSize?: number | undefined;
}

Options for unzip: which entries to read, and a cap on what they add up to.

unzipAsync takes the same options.

import { encodeText, KokyuError, unzip, zip } from 'kokyu'
import type { UnzipOptions } from 'kokyu'

const archive = zip({ 'a.txt': encodeText('a'.repeat(5000)), 'b.png': new Uint8Array(3000) })

const opts: UnzipOptions = { filter: (e) => e.name.endsWith('.txt'), maxSize: 10_000 }
Object.keys(unzip(archive, opts)) // ['a.txt']

try {
  unzip(archive, { maxSize: 7000 })
} catch (e) {
  // The two add up to 8,000 bytes, so nothing is decoded
  if (e instanceof KokyuError) console.log(e.code) // 'too-large'
}
filter?: ((entry: ZipEntry) => boolean) | undefined
Called once for each entry, in central directory order, with a copy of its ZipEntry, before anything is decoded. Return false to skip the entry, which is then neither checked nor decompressed, so an entry kokyu can't read does no harm once skipped. Only the entries it keeps count against maxSize. An error it throws comes out of unzip as it is. Default: every entry.
maxSize?: number | undefined
A cap in bytes on the kept entries' ZipEntry.originalSize added up. Each entry must decode to exactly that size, so the cap is checked before anything is decoded: past it, unzip fails with too-large having decoded nothing. A whole number, 0 or more; left out or Infinity, there is no cap. Anything else fails with invalid-option.
UnzipStreamOptions
interface UnzipStreamOptions {
    filter?: ((entry: ZipEntryInfo) => boolean) | undefined;
    maxSize?: number | undefined;
}

Options for unzipStream: which entries to read, and a cap on the bytes it returns.

unzipStreamAsync takes the same options.

import { encodeText, unzipStream, zip } from 'kokyu'
import type { UnzipStreamOptions } from 'kokyu'

const archive = zip({ 'small.txt': encodeText('hi'), 'big.log': encodeText('x'.repeat(50_000)) })

// Skip anything that states 1 KiB or more, and anything whose size isn't known yet
const opts: UnzipStreamOptions = { filter: (e) => (e.originalSize ?? Infinity) < 1024, maxSize: 1 << 20 }
unzipStream(opts).finish(archive).map((c) => c.entry.name) // ['small.txt', 'small.txt']
filter?: ((entry: ZipEntryInfo) => boolean) | undefined
Called with a copy of each entry's ZipEntryInfo as its local header arrives, in archive order. Return false to skip the entry, which then returns no chunks. Its sizes are missing when they follow its data, and a skipped deflated entry like that is still decompressed, its output thrown away, since only that finds where it ends. An error it throws comes out of the call that reached the header, and every later call throws it again. Default: every entry.
maxSize?: number | undefined
A cap on the bytes of kept entries the stream returns, all calls together. It is checked as the data comes out, and the call that would pass it fails with too-large, so what was returned before never adds up to more. A whole number, 0 or more; left out or Infinity, there is no cap. Anything else fails with invalid-option.
UnzipChunk
interface UnzipChunk {
    entry: ZipEntryInfo;
    data: Uint8Array<ArrayBuffer>;
    final: boolean;
}

A piece of one entry's data, as unzipStream returns it.

Each entry the filter keeps comes as chunks of its data with final false, then one chunk with final true and no data. An empty entry comes as that last chunk alone. Entries come one at a time: every chunk of one before any of the next.

import { encodeText, unzipStream, zip } from 'kokyu'
import type { UnzipChunk } from 'kokyu'

const archive = zip({ 'a.txt': encodeText('hello'), 'empty.txt': new Uint8Array(0) })
const chunks: UnzipChunk[] = unzipStream().finish(archive)
chunks.map((c) => [c.entry.name, c.data.length, c.final])
// [['a.txt', 5, false], ['a.txt', 0, true], ['empty.txt', 0, true]]
entry: ZipEntryInfo
The entry the data belongs to. It is the same object for every chunk of one entry, so it can key a Map, and a new one for the next entry, even one of the same name.
data: Uint8Array<ArrayBuffer>
The next bytes of the entry, decompressed, in an array of their own, never a view of your input. Never empty, except on the final chunk, where it always is.
final: boolean
True on the entry's last chunk, which comes once the entry's size has been checked. False on every other.
ZipStream
interface ZipStream {
    file(name: string, opts?: ZipEntryOptions): Stream;
    finish(): Uint8Array<ArrayBuffer>;
}

A zip archive being written as a stream, as zipStream returns it.

Write the entries one at a time: ZipStream.file starts one and returns its stream, you push its data and finish it, and only then start the next or finish the archive. Every push and finish returns the bytes it completes, in archive order.

A call out of order fails with invalid-state, and a bad name with invalid-option, and either leaves the archive as it was, so you can go on with the right call.

import { encodeText, unzip, zipStream } from 'kokyu'
import type { ZipStream } from 'kokyu'

const zs: ZipStream = zipStream()
const a = zs.file('a.txt')
const parts = [a.push(encodeText('first '))]
// zs.file('b.txt') here would fail with invalid-state: a.txt is still open
parts.push(a.finish(encodeText('entry')))
parts.push(zs.file('b.txt').finish(encodeText('second entry')))
parts.push(zs.finish())

const files = unzip(new Uint8Array(await new Blob(parts).arrayBuffer()))
Object.keys(files) // ['a.txt', 'b.txt']
file(name: string, opts?: ZipEntryOptions): Stream
Starts an entry named name, with its ZipEntryOptions, and returns its Stream. Each push returns the entry's bytes it completes, the first also its local header, and finish the rest with the data descriptor. A name ending in / is a folder: finish it with no data. The name follows the rules of ZipInput, and one for a path the archive already has fails with invalid-option. It fails with invalid-state while another entry is open or once the archive is finished, and the entry's stream fails with invalid-state once the entry is finished.
finish(): Uint8Array<ArrayBuffer>
Ends the archive and returns its last bytes, the central directory and the end record. It fails with invalid-state while an entry is open or once already finished, and with too-large when the archive needs ZIP64.
UnzipStream
type UnzipStream = Stream<Uint8Array, UnzipChunk[]>

A zip archive being read as a stream: a Stream that takes its bytes and returns UnzipChunk arrays.

unzipStream returns one. push takes the next piece of the archive, of any size, and returns the chunks of entry data it completes, possibly none; finish takes an optional last piece and returns the rest.

It ends at the central directory and ignores anything after it. finish before the central directory fails with truncated. After finish every call fails with invalid-state, and once the data or the filter has made a call throw, every later call throws that error again.

To read a web ReadableStream, pipe it through toTransformStream of one, and each UnzipChunk comes out on its own.

import { encodeText, toTransformStream, unzipStream, zip } from 'kokyu'
import type { UnzipChunk, UnzipStream } from 'kokyu'

const archive = zip({ 'a.txt': encodeText('alpha'), 'b.txt': encodeText('beta') })
const reader: UnzipStream = unzipStream()

// Here from a Blob; a fetch response's body pipes the same way
const names: string[] = []
await new Blob([archive]).stream().pipeThrough(toTransformStream(reader)).pipeTo(new WritableStream({
  write(chunk: UnzipChunk) { if (chunk.final) names.push(chunk.entry.name) },
}))
names // ['a.txt', 'b.txt']

Streams

What every sync stream shares, the compressors' flush, and toTransformStream, which turns any kokyu stream, sync or async, into a web TransformStream.

Stream
interface Stream<In = Uint8Array, Out = Uint8Array<ArrayBuffer>> {
    push(chunk: In): Out;
    finish(chunk?: In): Out;
}

A sync stream: push input in pieces, get back the output each completes, then finish it.

The compressors return one, as a CompressStream, and so do the decoders, unzipStream, ZipStream.file for each zip entry, and the text streams. In and Out default to bytes; encodeTextStream takes strings, decodeTextStream returns them, and unzipStream returns arrays of UnzipChunk.

Each call returns the output its input completes, and only that, so a push may return nothing: no bytes, an empty string or an empty array. Chunks can be any size and split the data anywhere. A stream keeps nothing of a chunk once the call returns, copying what it still needs, so you can refill one buffer and push it again. Each output is memory of its own.

Once Stream.finish has returned, every call fails with invalid-state. A call that fails partway can't be undone, so every later call rethrows that same error (a zip entry follows its archive's rules instead: see zipStream). A chunk that isn't a Uint8Array, pushed to a stream that takes bytes, fails with invalid-option before anything starts, and leaves the stream as it was.

A stream called again from inside one of its own calls, by a getter on a chunk say, refuses the inner call with invalid-state, and the outer call goes on unharmed.

toTransformStream turns one into a web TransformStream. Each format's stream has an async form, such as gzipStreamAsync, whose calls return promises.

import { gzip, gunzipStream, encodeText, decodeText, KokyuError } from 'kokyu'
import type { Stream } from 'kokyu'

const packed = gzip(encodeText('pushed in two pieces'))
const stream: Stream = gunzipStream()
stream.push(packed.subarray(0, 10)) // Uint8Array []: the header alone decodes to nothing
decodeText(stream.finish(packed.subarray(10))) // 'pushed in two pieces'

try {
  stream.push(packed)
} catch (e) {
  if (e instanceof KokyuError) e.code // 'invalid-state': the stream has finished
}
push(chunk: In): Out
Adds a chunk, of any size, and returns the output it completes, possibly empty. In a stream that takes bytes, a chunk that isn't a Uint8Array fails with invalid-option and leaves the stream as it was.
finish(chunk?: In): Out
Adds an optional last chunk and returns the rest of the output. A decoder whose data stops short fails with truncated. Once it has returned, any further call fails with invalid-state.
CompressStream
interface CompressStream extends Stream {
    flush(): Uint8Array<ArrayBuffer>;
}

A compression stream that can also flush, as deflateStream, zlibStream and gzipStream return.

It is a Stream of bytes with one more method. A compressor holds input back to compress it better, so its pushes return output in bursts, and a reader on the other end can wait a long time for data already pushed. CompressStream.flush sends all of it without ending the stream, for a reader that needs it now: a log being tailed, or events sent as they happen.

A flush closes the block under way and adds an empty stored block, which brings the output to a whole byte. That costs bytes of its own, 5 when nothing was pushed since the last flush, so flush when a reader is waiting, not after every push.

The compressor keeps its window across a flush, so later input still matches against earlier, and a decoder reads the whole output, flushes and all, as one stream.

import { gzipStream, gunzipStream, gunzip, encodeText, decodeText } from 'kokyu'
import type { CompressStream } from 'kokyu'

const writer: CompressStream = gzipStream()
const reader = gunzipStream()
const first = writer.push(encodeText('event: tick')) // the 10-byte header, and nothing compressed yet
decodeText(reader.push(first)) // ''
decodeText(reader.push(writer.flush())) // 'event: tick'
decodeText(reader.finish(writer.finish(encodeText(', event: done')))) // ', event: done'
flush(): Uint8Array<ArrayBuffer>
Returns everything pushed so far as output a decoder can read in full, without ending the stream. Fails with invalid-state once the stream has finished.

Async

Every format off the main thread. One-shot inputs under 16 KB run on the calling thread, and larger ones in a pool of workers that start on first use. An async stream runs in a worker unless the whole stream is under 16 KB and finished at once. Every call takes a signal and transfer.

AsyncOptions
interface AsyncOptions {
    signal?: AbortSignal | undefined;
    transfer?: boolean | undefined;
}

Options every async call takes besides its format's own: signal to cancel it, and transfer to hand a worker its input.

A one-shot call whose input is under 16 KB (16,384 bytes) runs on the calling thread and is done before the call returns, where a round trip to a worker would cost a real share of the work. A larger input goes to a pool of workers, which starts on first use and holds up to min(4, cores − 1) of them, at least 1, with cores read from navigator.hardwareConcurrency (1 worker where the runtime doesn't report it). A worker runs a single one-shot call at a time while the rest wait their turn, and an async stream keeps its state in one worker for its whole life.

An idle pool never keeps a process running. In Node and Bun a worker holds the process open only while a call is under way in it. Deno's workers can't be let go that way, so each one is stopped after 500 ms with nothing to do; one holding an open async stream stays, and keeps the process running, until the stream finishes, fails, is aborted or is garbage collected.

A call is done with your input by the time it returns: work on the calling thread is already finished, and a worker gets a copy taken at the call. So the buffer can be reused or overwritten at once. Options are read at the call too: a dictionary is copied and a date taken, so changing them afterward changes nothing. An async stream reads its options, these two included, once, when it's made, and copies each chunk as it's pushed.

No async call throws. Every failure, a bad argument included, rejects a promise: kokyu's own with a KokyuError carrying the code the sync call would throw, or worker when a worker fails to start or dies. An abort rejects with the signal's reason, and an error your filter throws comes back as it is.

Zip times are local times, and in Node a worker keeps the time zone it started with. Set TZ before the first async call: a later change reaches work on the calling thread, but not a worker already running.

import { gzipAsync } from 'kokyu'
import type { AsyncOptions } from 'kokyu'

const controller = new AbortController()
const options: AsyncOptions = { signal: controller.signal, transfer: true }
const upload = new Uint8Array(256 << 10)
const pending = gzipAsync(upload, options)
upload.length // 0: the worker took the buffer instead of a copy

controller.abort(new Error('upload canceled'))
const message = await pending.catch((e: Error) => e.message) // 'upload canceled'
signal?: AbortSignal | undefined
Cancels the call, or every call on the stream. An abort that lands before a promise settles rejects it with the signal's reason, whatever it would have settled with, and an aborted stream rejects every later call the same way. A signal aborted before a one-shot call rejects it too, unless an argument is refused first: an input that isn't a Uint8Array, for one, still rejects with invalid-option. A one-shot call still waiting for a worker leaves the queue, and a worker running nothing but the aborted call is stopped; otherwise the worker finishes the work and its result is dropped. An aborted stream's worker session is closed.
transfer?: boolean | undefined
Lets a worker take the input's buffer instead of a copy, which empties your array: its length becomes 0. Only input bound for a worker moves, and only a view that covers its whole ArrayBuffer. An input under 16 KB is never moved, and a view of part of a larger buffer, shared memory, and memory that can't be moved, such as WebAssembly's, are copied as usual. A stream judges each chunk on its own, so one under 16 KB is copied. In zipAsync, once the entries come to 16 KB in all, every entry that is a whole buffer moves.
AsyncStream
interface AsyncStream<In = Uint8Array, Out = Uint8Array<ArrayBuffer>> {
    push(chunk: In): Promise<Out>;
    finish(chunk?: In): Promise<Out>;
}

An async stream: push and finish as a sync Stream has them, each returning a promise.

The …StreamAsync functions return one, or a type built on it, and each entry of an AsyncZipStream is one. Calls can be made without awaiting the one before: they run in the order they were made and their results resolve in that order, so a whole input can be queued at once and awaited together.

A stream whose chunks add up to under 16 KB, and whose finish is called in the same synchronous run of code as its first call, runs on the calling thread. Any other stream opens a session in one pool worker, which holds its state until the stream finishes, fails, is aborted or is garbage collected. unzipStreamAsync with a filter has a rule of its own. In Deno an open session keeps the process running, so finish or abort every stream you start.

Each chunk is copied as it's handed over, unless AsyncOptions.transfer moves it, so one buffer can be refilled for the next push straight away. A chunk that isn't a Uint8Array is refused with invalid-option and leaves the stream as it was. A compressor or decoder whose call fails stays failed: every later call rejects with the same error.

import { deflateStreamAsync, encodeText, inflate } from 'kokyu'
import type { AsyncStream } from 'kokyu'

// Every chunk goes in without waiting, and the outputs come back in the order they went in
async function feed(stream: AsyncStream, chunks: Uint8Array[]): Promise<Uint8Array<ArrayBuffer>[]> {
  const outputs = chunks.map(chunk => stream.push(chunk))
  outputs.push(stream.finish())
  return Promise.all(outputs)
}

const lines = Array.from({ length: 3000 }, (_, i) => encodeText('line ' + i + '\n'))
const parts = await feed(deflateStreamAsync(), lines)
const text = inflate(new Uint8Array(await new Blob(parts).arrayBuffer())) // every line, in order
push(chunk: In): Promise<Out>
Adds a chunk and resolves to the output it completes, which may be empty: bytes, or for an AsyncUnzipStream an array of UnzipChunks. Chunks can be any size.
finish(chunk?: In): Promise<Out>
Adds an optional last chunk, resolves to the rest of the output, and ends the stream, closing its worker session if it has one. A call made after it, even before it settles, rejects with invalid-state. A finish whose chunk is refused leaves the stream open.
AsyncCompressStream
interface AsyncCompressStream extends AsyncStream {
    flush(): Promise<Uint8Array<ArrayBuffer>>;
}

An AsyncStream that compresses, and can also flush.

deflateStreamAsync, zlibStreamAsync and gzipStreamAsync return one. Its flush is CompressStream.flush as a promise, and takes its turn among the stream's other calls in the order they were made, so it can be queued right behind a push without awaiting it.

import { decodeText, encodeText, gunzipStream, gzipStreamAsync } from 'kokyu'
import type { AsyncCompressStream } from 'kokyu'

const events: AsyncCompressStream = gzipStreamAsync()
const reader = gunzipStream()
const received: string[] = []
// Flushed after each event, so the reader gets it whole while the stream stays open
for (const event of ['connected', 'job 1 done', 'job 2 done']) {
  const [head, flushed] = await Promise.all([events.push(encodeText(event)), events.flush()])
  received.push(decodeText(reader.push(head)) + decodeText(reader.push(flushed)))
}
received // ['connected', 'job 1 done', 'job 2 done']
const rest = reader.finish(await events.finish())
rest.length // 0: nothing was held back
flush(): Promise<Uint8Array<ArrayBuffer>>
Resolves to output that lets a decoder read everything pushed so far, without ending the stream: the output before it plus this decodes to every byte pushed.
AsyncZipStream
interface AsyncZipStream {
    file(name: string, opts?: ZipEntryOptions): AsyncStream;
    finish(): Promise<Uint8Array<ArrayBuffer>>;
}

A zip archive written as an async stream, one entry at a time.

zipStreamAsync returns one. Open an entry with file, push its data and finish it, then open the next or finish the archive. Each result is the next piece of the archive, so the pieces in call order are the whole archive.

Every call, the entries' included, settles in the order it was made, on the calling thread as in a worker. So you can make every call without awaiting, and write each piece the moment it arrives.

A call out of turn is refused with invalid-state and changes nothing: the calls of an entry opened while another is still open, and finish while one is. An entry refused for its name or options, or a chunk refused for not being a Uint8Array, leaves the archive usable too.

import { encodeText, unzip, zipStreamAsync } from 'kokyu'
import type { AsyncZipStream } from 'kokyu'

const archive: AsyncZipStream = zipStreamAsync()
const out: Uint8Array<ArrayBuffer>[] = []
// Results settle in call order, so each piece can be written the moment it arrives
const write = (piece: Promise<Uint8Array<ArrayBuffer>>) => piece.then(bytes => { out.push(bytes) })
const log = archive.file('log.txt')
await Promise.all([
  write(log.push(encodeText('job done; '.repeat(5000)))),
  write(log.finish()),
  write(archive.file('empty.txt').finish()),
  write(archive.finish()),
])
const files = unzip(new Uint8Array(await new Blob(out).arrayBuffer()))
Object.keys(files) // ['log.txt', 'empty.txt']
file(name: string, opts?: ZipEntryOptions): AsyncStream
Opens an entry and returns its AsyncStream: push the entry's data, then finish it before the next file or finish, without having to await it. The name follows the rules of a ZipInput path, and the options are read now. An entry with no mtime, its own or the archive's, is stamped with the time of this call.
finish(): Promise<Uint8Array<ArrayBuffer>>
Ends the archive and resolves to its last bytes, the central directory that lists its entries. While an entry is open it rejects with invalid-state.
AsyncUnzipStream
type AsyncUnzipStream = AsyncStream<Uint8Array, UnzipChunk[]>

A zip archive read as an async stream: push its bytes, and get back chunks of its entries.

unzipStreamAsync returns one. It's an AsyncStream whose calls resolve to arrays of UnzipChunks, as an UnzipStream's calls return them: each chunk holds a piece of one entry's data, the entry's info, and whether it's the entry's last piece. An array can be empty, or span several entries.

Every chunk of an entry carries the same UnzipChunk.entry object, even when its chunks come back from a worker in different results, so the object can key a map.

import { decodeText, encodeText, unzipStreamAsync, zip } from 'kokyu'
import type { AsyncUnzipStream } from 'kokyu'

const archive = zip({ 'a.txt': encodeText('first'), 'b.txt': encodeText('second') })
const stream: AsyncUnzipStream = unzipStreamAsync()
const chunks = await stream.finish(archive)
chunks.map(chunk => [chunk.entry.name, decodeText(chunk.data), chunk.final])
// [['a.txt', 'first', false], ['a.txt', '', true], ['b.txt', 'second', false], ['b.txt', '', true]]

Text

Text to UTF-8 or latin1 bytes and back, whole or as streams that keep a character split across two chunks whole.

TextOptions
interface TextOptions {
    latin1?: boolean | undefined;
}

Options for encodeText, decodeText and their streams: which encoding to use.

UTF-8 is the default. Latin1 (ISO 8859-1) maps each character from U+0000 to U+00FF to the byte of the same value; it is what a gzip header's file name is written in.

import { encodeText, decodeText } from 'kokyu'
import type { TextOptions } from 'kokyu'

const latin1: TextOptions = { latin1: true }
const bytes = encodeText('café', latin1) // Uint8Array [0x63, 0x61, 0x66, 0xE9]
decodeText(bytes, latin1) // 'café'
decodeText(bytes) // 'caf\uFFFD': 0xE9 alone isn't UTF-8
latin1?: boolean | undefined
true for one byte per character, U+0000 to U+00FF, instead of UTF-8. Encoding a character past U+00FF then fails with invalid-option, and decoding never fails, since every byte is a character. Default false.

Type to search.