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.
KokyuErrorclass 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 theKokyuErrorCodestrings and stays the same across versions. The message is for people: it starts withkokyu:and says what went wrong, andnameis'KokyuError'.An error raised in a pool worker reaches you as a
KokyuErrorwith the same code and message, soinstanceofworks the same for the async calls as for the sync ones.Two failures pass through as they are, never wrapped: an async call whose
signalaborts rejects with the signal's reason, and an error your ownUnzipOptions.filterthrows 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
KokyuErrorCodestrings. 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.
KokyuErrorCodetype KokyuErrorCode = 'truncated' | 'invalid-data' | 'invalid-header' | 'too-large' | 'unsupported' | 'invalid-option' | 'invalid-state' | 'worker'Why a call failed: the
codeof everyKokyuError.A union of string literals, so a
switchonKokyuError.codecan cover every case and TypeScript checks that it does. The first five are about the data,invalid-optionandinvalid-stateabout how a call was made, andworkercomes 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.maxSizeorUnzipOptions.maxSize, the length of the buffer an…Intocall decodes into, or inunzipthe 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
outthat isn't a readableUint8Array, a level outside 0 to 9, amaxSizethat 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.
Leveltype Level = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9A compression level, from 0 (store without compressing) to 9 (search hardest).
Every compressor takes one as
level:DeflateOptions.level,GzipOptions.level,ZipOptions.levelandZipEntryOptions.level. Left out, it is 6. Anything else, a fraction or a number outside 0 to 9, fails withinvalid-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) // 60270- 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.
DeflateOptionsinterface DeflateOptions { level?: Level | undefined; dictionary?: Uint8Array | undefined; }Options for
deflate,zliband their streams.Both are optional, and
nullor 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,deflateStreamAsyncandzlibStreamAsync.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 byteslevel?: Level | undefined- How hard to look for repeats, from 0 (stored, no compression) to 9; see
Level. Default 6. Anything else fails withinvalid-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 aUint8Arrayfails withinvalid-option.
InflateOptionsinterface 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…Intoforms, their streams and their async forms all take them. Both are optional, andnullor no options at all mean no dictionary and no cap. Wheredecompressfinds gzip, onlymaxSizeapplies.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 withinvalid-optionwhen this is missing or different. Raw deflate names none, so a missing one shows only asinvalid-dataonce 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 aUint8Arrayfails withinvalid-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, orInfinity; anything else fails withinvalid-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 indecompress. With an…Intocall, the smaller of this and the length ofoutis 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.
GzipOptionsinterface GzipOptions { level?: Level | undefined; filename?: string | undefined; mtime?: Date | string | number | undefined; }Options for
gzip,gzipStreamand 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 headerlevel?: 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 withinvalid-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.gunzipskips 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, asDatetakes 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 withinvalid-option. Default none: the field is 0, so the same input always gives the same bytes.
GunzipOptionsinterface GunzipOptions { maxSize?: number | undefined; }Options for
gunzip,gunzipInto,gunzipStreamand 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, orInfinityfor no cap; anything else fails withinvalid-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.
ZipInputinterface 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
Uint8Arrayis a file with the archive's options, and[bytes, options]a file withZipEntryOptionsof 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: aMapor a class instance fails withinvalid-option, and so do bytes in any typed array but aUint8Array.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 asC:, 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..bornotes:v2.txt, are kept.Two names for one path fail with
invalid-optiontoo: the same name twice, a file and a folder of one name (aanda/), 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.
ZipOptionsinterface ZipOptions { level?: Level | undefined; mtime?: Date | string | number | undefined; comment?: string | undefined; }Options for a whole archive, as
zipandzipStreamtake them.An entry's own
ZipEntryOptionsoverridelevelandmtimefor that entry.zipStreamreads these once, when you call it.zipAsyncandzipStreamAsynctake 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 byteslevel?: 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.zipstores an entry that deflate can't make smaller;zipStreamdeflates 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 stringDatecan 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 withinvalid-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 (
PKand the bytes 5 and 6), which readers would take for the record itself. Either fails withinvalid-option. kokyu's readers don't return it.
ZipEntryOptionsinterface 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 aZipInputor toZipStream.file.An option left out falls back to the archive's
ZipOptions, then to the default.mode,osandattrsdecide the permissions extractors give the file, andextraadds 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.mtimetakes. 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.commentreads 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 as0o100644 << 16, is negative in JavaScript. Default: on Unix, mode 0o644 or 0o755 with its file type; with anotheros, 0 for a file and the MS-DOS directory bit (0x10) for a folder. Withoutosthe entry stays Unix, so attributes for another system need theirostoo. It can't be combined withmode. 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 withmode. 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
osorattrs: that fails withinvalid-option.ZipEntry.modereads it back.
ZipEntryInfointerface ZipEntryInfo { name: string; size?: number | undefined; originalSize?: number | undefined; compression: number; mtime: Date; }What
unzipStreamknows about an entry when it reaches the entry's local header.Every
UnzipChunkcarries one asUnzipChunk.entry, andUnzipStreamOptions.filtersees a copy of one.ZipEntry, whichzipEntriesreturns, 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
zipStreamwrites 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.
ZipEntryinterface ZipEntry extends ZipEntryInfo { size: number; originalSize: number; comment: string; mode?: number | undefined; }An entry as the archive's central directory lists it, as
zipEntriesreturns it.It is a
ZipEntryInfothat always has both sizes, plus the entry's comment and Unix mode, which only the central directory holds.UnzipOptions.filtersees one for each entry too.zipEntriesbuilds 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.
unzipholds each entry to exactly this, and adds them up againstUnzipOptions.maxSizebefore 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.
UnzipOptionsinterface 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.unzipAsynctakes 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 againstmaxSize. An error it throws comes out ofunzipas it is. Default: every entry. maxSize?: number | undefined- A cap in bytes on the kept entries'
ZipEntry.originalSizeadded up. Each entry must decode to exactly that size, so the cap is checked before anything is decoded: past it,unzipfails withtoo-largehaving decoded nothing. A whole number, 0 or more; left out orInfinity, there is no cap. Anything else fails withinvalid-option.
UnzipStreamOptionsinterface UnzipStreamOptions { filter?: ((entry: ZipEntryInfo) => boolean) | undefined; maxSize?: number | undefined; }Options for
unzipStream: which entries to read, and a cap on the bytes it returns.unzipStreamAsynctakes 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
ZipEntryInfoas 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 orInfinity, there is no cap. Anything else fails withinvalid-option.
UnzipChunkinterface UnzipChunk { entry: ZipEntryInfo; data: Uint8Array<ArrayBuffer>; final: boolean; }A piece of one entry's data, as
unzipStreamreturns it.Each entry the filter keeps comes as chunks of its data with
finalfalse, then one chunk withfinaltrue 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.
ZipStreaminterface ZipStream { file(name: string, opts?: ZipEntryOptions): Stream; finish(): Uint8Array<ArrayBuffer>; }A zip archive being written as a stream, as
zipStreamreturns it.Write the entries one at a time:
ZipStream.filestarts 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 withinvalid-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 itsZipEntryOptions, and returns itsStream. Eachpushreturns the entry's bytes it completes, the first also its local header, andfinishthe rest with the data descriptor. A name ending in/is a folder: finish it with no data. The name follows the rules ofZipInput, and one for a path the archive already has fails withinvalid-option. It fails withinvalid-statewhile another entry is open or once the archive is finished, and the entry's stream fails withinvalid-stateonce 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-statewhile an entry is open or once already finished, and withtoo-largewhen the archive needs ZIP64.
UnzipStreamtype UnzipStream = Stream<Uint8Array, UnzipChunk[]>A zip archive being read as a stream: a
Streamthat takes its bytes and returnsUnzipChunkarrays.unzipStreamreturns one.pushtakes the next piece of the archive, of any size, and returns the chunks of entry data it completes, possibly none;finishtakes an optional last piece and returns the rest.It ends at the central directory and ignores anything after it.
finishbefore the central directory fails withtruncated. Afterfinishevery call fails withinvalid-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 throughtoTransformStreamof one, and eachUnzipChunkcomes 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.
Streaminterface 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.filefor each zip entry, and the text streams.InandOutdefault to bytes;encodeTextStreamtakes strings,decodeTextStreamreturns them, andunzipStreamreturns arrays ofUnzipChunk.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.finishhas returned, every call fails withinvalid-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: seezipStream). A chunk that isn't aUint8Array, pushed to a stream that takes bytes, fails withinvalid-optionbefore 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.toTransformStreamturns one into a webTransformStream. Each format's stream has an async form, such asgzipStreamAsync, 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
Uint8Arrayfails withinvalid-optionand 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 withinvalid-state.
CompressStreaminterface CompressStream extends Stream { flush(): Uint8Array<ArrayBuffer>; }A compression stream that can also flush, as
deflateStream,zlibStreamandgzipStreamreturn.It is a
Streamof 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.flushsends 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-stateonce 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.
AsyncOptionsinterface AsyncOptions { signal?: AbortSignal | undefined; transfer?: boolean | undefined; }Options every async call takes besides its format's own:
signalto cancel it, andtransferto 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
KokyuErrorcarrying the code the sync call would throw, orworkerwhen 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
TZbefore 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. InzipAsync, once the entries come to 16 KB in all, every entry that is a whole buffer moves.
AsyncStreaminterface AsyncStream<In = Uint8Array, Out = Uint8Array<ArrayBuffer>> { push(chunk: In): Promise<Out>; finish(chunk?: In): Promise<Out>; }An async stream:
pushandfinishas a syncStreamhas them, each returning a promise.The
…StreamAsyncfunctions return one, or a type built on it, and each entry of anAsyncZipStreamis 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
finishis 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.unzipStreamAsyncwith 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.transfermoves it, so one buffer can be refilled for the next push straight away. A chunk that isn't a Uint8Array is refused withinvalid-optionand 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 orderpush(chunk: In): Promise<Out>- Adds a chunk and resolves to the output it completes, which may be empty: bytes, or for an
AsyncUnzipStreaman array ofUnzipChunks. 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. Afinishwhose chunk is refused leaves the stream open.
AsyncCompressStreaminterface AsyncCompressStream extends AsyncStream { flush(): Promise<Uint8Array<ArrayBuffer>>; }An
AsyncStreamthat compresses, and can alsoflush.deflateStreamAsync,zlibStreamAsyncandgzipStreamAsyncreturn one. ItsflushisCompressStream.flushas 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 backflush(): 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.
AsyncZipStreaminterface AsyncZipStream { file(name: string, opts?: ZipEntryOptions): AsyncStream; finish(): Promise<Uint8Array<ArrayBuffer>>; }A zip archive written as an async stream, one entry at a time.
zipStreamAsyncreturns one. Open an entry withfile, 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-stateand changes nothing: the calls of an entry opened while another is still open, andfinishwhile 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 nextfileorfinish, without having to await it. The name follows the rules of aZipInputpath, and the options are read now. An entry with nomtime, 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.
AsyncUnzipStreamtype AsyncUnzipStream = AsyncStream<Uint8Array, UnzipChunk[]>A zip archive read as an async stream: push its bytes, and get back chunks of its entries.
unzipStreamAsyncreturns one. It's anAsyncStreamwhose calls resolve to arrays ofUnzipChunks, as anUnzipStream'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.entryobject, 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.
TextOptionsinterface TextOptions { latin1?: boolean | undefined; }Options for
encodeText,decodeTextand 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-8latin1?: boolean | undefinedtruefor one byte per character, U+0000 to U+00FF, instead of UTF-8. Encoding a character past U+00FF then fails withinvalid-option, and decoding never fails, since every byte is a character. Defaultfalse.