Limits and safety¶
korpress removes comments and whitespace and leaves your code otherwise as it is. This page says what it promises, what it does not check, and how to test its output on your own site.
This call shows the main rule: JavaScript that korpress cannot read is refused, with the place of the problem.
try:
korpress.minify_js('var a = "oops;')
except korpress.KorpressError as err:
print(err) # unterminated string at line 1, column 9
What korpress guarantees¶
- It tries not to change what your code does. It removes comments and whitespace and makes a few safe rewrites (see the HTML, CSS and JavaScript pages). It does not rename, reorder or remove code.
- JavaScript it cannot read is refused, not guessed.
minify_jsraisesKorpressErrorwith a line and a column, and returns nothing. - A failed file is not written. The CLI minifies in memory first and writes only on success.
- Inline code that cannot be minified safely is left as it was inside an HTML page.
This is a promise of intent, not a proof. korpress has no parser (a program that checks code against the grammar of the language) and does not check that your program is valid. Read on for where the output can differ.
What it rejects, and what it passes through¶
Rejected: JavaScript errors¶
Only minify_js raises. It raises KorpressError (a ValueError, with .line and .column) for:
| Source | Message |
|---|---|
var a = "oops; |
unterminated string at line 1, column 9 |
var a = 1; then /* never closed |
unterminated comment at line 2, column 1 |
x = `abc ${ 1 |
unterminated template literal at line 1, column 5 |
x = /abc |
unterminated regular expression at line 1, column 5 |
The position is where the string, comment, template or regular expression starts. The CLI prints korpress: site/bad.js: unterminated string at line 1, column 9, skips that file, goes on with the others, and exits with code 1.
A file that is not valid UTF-8 is also refused: the API raises UnicodeDecodeError, and the CLI reports it as a failure for that file. A UTF-8 byte order mark at the start of a file is read and left out of the output.
Passed through: everything else¶
korpress does not parse, so most invalid code is not noticed. These real results are not errors:
korpress.minify_js("var a = ;") # 'var a=;'
korpress.minify_js("a = 1 }") # 'a=1}'
korpress.minify_js("function ( {") # 'function({'
korpress.minify_js("let x: number = 1") # 'let x:number=1'
Broken code goes out as broken code. TypeScript annotations survive because they are made of ordinary tokens, but korpress is not a TypeScript minifier: use it on the JavaScript your compiler produces.
JSX is not supported. The < and > of a tag are read as operators, and the text between tags is read as code, so an apostrophe in the text starts a "string":
korpress.minify_js("const el = <p>it's</p>")
# KorpressError: unterminated string at line 1, column 17
Tags with a closing tag, like these, usually raise. Do not rely on an error to catch JSX: korpress does not check for it. Compile JSX first, then minify.
CSS never raises: it minifies what it understands and keeps the rest (korpress.minify_css("a { color : red") gives 'a{color:red}'). HTML never raises either: korpress.minify_html("<p>hi") gives '<p>hi'. Broken HTML is minified, not repaired.
Check your own output¶
The tests above cover korpress, not your site. Before you ship minified files:
- Run your own tests on the minified files. Build to a separate folder (
korpress site/ -o dist/ --copy), then run your end-to-end tests, or open the site, againstdist/. - Compare a script in Node. Run the original and the minified file and compare what they print, as
tests/test_node.pydoes. - Look at the browser console. A
SyntaxErrorat load time is the usual sign of a problem. - Keep the sources. Minify into another folder, or in your build, and never edit the minified files.
- Watch for code that reads its own source. If your code calls
Function.prototype.toString, the minified text is not the original text.
If you find a file where the output differs, the smallest input that shows it is a good bug report.
In depth¶
The parts below are for people who want the exact behavior: how the tests work, which differences are known, and what the command line does to files.
How korpress was tested¶
- Rust unit tests (
cargo test) and Python tests (pytest) cover the behavior of each minifier, including errors and past bugs. - Differential tests with Node, in CI. A differential test runs the original and the changed version and compares the results.
tests/test_node.pyholds six scripts that use the risky parts: semicolon insertion,/as a regular expression or a division, templates, classes, odd operators, labels andswitch. Each test runs the original and the minified script in Node and checks that they print the same thing. The CI job installs Node for this. Without Node the tests are skipped, not failed. Six scripts cover the known hard cases, not every program. - Corpus checks, run by hand. A corpus is a large set of real files.
tests/corpusholds scripts that you point at a folder of real files. They are not part of CI.
| Check | Script | |
|---|---|---|
| JS | same syntax tree before and after (acorn), empty statements ignored | js_ast.js |
| CSS | csso gives the same result on the original and on the korpress output | css_diff.js |
| HTML | same DOM (parse5) and same rendered text | html_dom.js |
The project README records a run on files found on a disk: 15 237 JS files (15 235 identical, 2 do not parse with acorn), 747 CSS files (741 identical, 5 differ), 422 HTML files (412 identical, 10 differ). These numbers are copied from the README. The corpus was not run again for this page.
To run the JS check on your own files:
cd tests/corpus && npm install
cargo build --release --example min
../../target/release/examples/min path/to/*.js # writes FILE.min next to each file
ls path/to/*.js > list.txt
node js_ast.js list.txt
Known accepted differences¶
- CSS
var()fallbacks. Invar(--x, 1)the space after the comma is removed, so a fallback that is a list can be read differently. Together with invalid CSS, this causes the CSS differences in the corpus. - Malformed HTML. Removing the whitespace between tags can change how a broken document is parsed. An unclosed
<a>is the usual example. Templates ({{ ... }},<% ... %>) are not HTML and can differ too. - JavaScript is smaller, not smallest. No renaming and no dead code removal, so expect less than terser or esbuild. The README measured 22 % on a mix of many already-minified files.
- Function text.
fn.toString()gives the minified source. - Not supported. JSX, TypeScript and Flow syntax, CSS rule merging, HTML optional-tag omission.
yieldandawaitas variable names. In an old non-strict script,var yield = 4; a = yield / 2 / 1is read as ifyieldstarted a regular expression. Telling the two apart needs scope tracking, which korpress does not do. Rename such variables, or leave the file unminified.
File safety of the command line¶
This describes what the CLI does today, from korpress/cli.py and minify_file in korpress/__init__.py. The behavior below is covered by tests/test_cli.py and was checked on Linux.
Reading. Each file is read fully, decoded as UTF-8 (a BOM is removed), and minified in memory. If that fails, nothing is written and the file stays as it was.
Writing a file (-o file, -o dir/, or --in-place). The result is written to a new temporary file in the same folder (app.js.<random>.korpress-tmp), created exclusively with an unpredictable name. Then os.replace moves it onto the target in one step, so a failure never leaves the target half written, and the temporary file is removed on any error. An existing *.korpress-tmp file is never touched. Missing folders in the output path are created.
What that means in practice, in-place mode included:
- Symlinks are kept. If
site/link.jsis a symlink toreal/app.js,korpress --in-place site/link.jsminifiesreal/app.jsandlink.jsstays a symlink. The same goes for a symlink given as-otarget. - The mode is kept. The new file gets the mode of the file it replaces (
750stays750,600stays600), or the mode of the source when the destination is new. Hard links to the old file no longer point at the result. Extended attributes and other metadata are not copied. - Two processes can write the same target without sharing a temporary file. The last one to finish wins.
- A stale temporary file can stay only if the process is killed between the write and the move. It is an extra file you can delete.
- In a folder, one bad file does not stop the others. An unreadable file or a minifier error is reported on stderr as one line (
korpress: path: reason), the other files are still done, and the exit code is 1. There is no rollback of the files that succeeded. --copyand symlinks. A non-minified file that is a symlink pointing outside the input folder is skipped with a warning, not copied. Symlinks that stay inside the folder are copied as files.- Skipped files. In a folder run, names with
.min., hidden folders andnode_modulesare skipped. Without--copy, skipped files are not copied into-o dir/.
Other cases:
- One file and no
-oprints on the screen and writes nothing to disk. - stdin with
-o filewrites the file directly withPath.write_text, not through a temporary file. A bad-o(a folder, say) gives a one-line error and exit code 1. - No backup is made.
--in-placeoverwrites the original. Use version control, or-o.
Next: Glossary