pax_global_header00006660000000000000000000000064150362315670014522gustar00rootroot0000000000000052 comment=83a0c45fe190f4fcb8b515c18065db9cb9029dd1 expressjs-compression-83a0c45/000077500000000000000000000000001503623156700164405ustar00rootroot00000000000000expressjs-compression-83a0c45/.eslintignore000066400000000000000000000000261503623156700211410ustar00rootroot00000000000000coverage node_modules expressjs-compression-83a0c45/.eslintrc.yml000066400000000000000000000002321503623156700210610ustar00rootroot00000000000000root: true extends: - standard - plugin:markdown/recommended plugins: - markdown overrides: - files: '**/*.md' processor: 'markdown/markdown' expressjs-compression-83a0c45/.github/000077500000000000000000000000001503623156700200005ustar00rootroot00000000000000expressjs-compression-83a0c45/.github/dependabot.yml000066400000000000000000000005651503623156700226360ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: github-actions directory: / schedule: interval: monthly - package-ecosystem: npm directory: / schedule: interval: monthly time: "23:00" timezone: Europe/London open-pull-requests-limit: 10 ignore: - dependency-name: "*" update-types: ["version-update:semver-major"]expressjs-compression-83a0c45/.github/workflows/000077500000000000000000000000001503623156700220355ustar00rootroot00000000000000expressjs-compression-83a0c45/.github/workflows/ci.yml000066400000000000000000000161401503623156700231550ustar00rootroot00000000000000name: ci on: pull_request: branches: - master paths-ignore: - '*.md' push: paths-ignore: - '*.md' permissions: contents: read # Cancel in progress workflows # in the scenario where we already had a run going for that PR/branch/tag but then triggered a new run concurrency: group: "${{ github.workflow }} ✨ ${{ github.event.pull_request.head.label || github.head_ref || github.ref }}" cancel-in-progress: true jobs: lint: name: Lint runs-on: ubuntu-latest steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - name: Setup Node.js uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 'lts/*' - name: Install dependencies run: npm install --ignore-scripts --only=dev - name: Run lint run: npm run lint test: runs-on: ubuntu-latest strategy: fail-fast: false matrix: name: - Node.js 0.8 - Node.js 0.10 - Node.js 0.12 - io.js 1.x - io.js 2.x - io.js 3.x - Node.js 4.x - Node.js 5.x - Node.js 6.x - Node.js 7.x - Node.js 8.x - Node.js 9.x - Node.js 10.x - Node.js 11.x - Node.js 12.x - Node.js 13.x - Node.js 14.x - Node.js 15.x - Node.js 16.x - Node.js 17.x - Node.js 18.x - Node.js 19.x - Node.js 20.x - Node.js 21.x - Node.js 22.x - Node.js 23.x include: - name: Node.js 0.8 node-version: "0.8" npm-i: mocha@2.5.3 supertest@1.1.0 npm-rm: nyc - name: Node.js 0.10 node-version: "0.10" npm-i: mocha@3.5.3 nyc@10.3.2 supertest@2.0.0 - name: Node.js 0.12 node-version: "0.12" npm-i: mocha@3.5.3 nyc@10.3.2 supertest@2.0.0 - name: io.js 1.x node-version: "1.8" npm-i: mocha@3.5.3 nyc@10.3.2 supertest@2.0.0 - name: io.js 2.x node-version: "2.5" npm-i: mocha@3.5.3 nyc@10.3.2 supertest@2.0.0 - name: io.js 3.x node-version: "3.3" npm-i: mocha@3.5.3 nyc@10.3.2 supertest@2.0.0 - name: Node.js 4.x node-version: "4" npm-i: mocha@5.2.0 nyc@11.9.0 supertest@3.4.2 - name: Node.js 5.x node-version: "5" npm-i: mocha@5.2.0 nyc@11.9.0 supertest@3.4.2 - name: Node.js 6.x node-version: "6" npm-i: mocha@6.2.3 nyc@14.1.1 supertest@6.1.6 - name: Node.js 7.x node-version: "7" npm-i: mocha@6.2.3 nyc@14.1.1 supertest@6.1.6 - name: Node.js 8.x node-version: "8" npm-i: mocha@7.2.0 nyc@14.1.1 supertest@6.1.6 - name: Node.js 9.x node-version: "9" npm-i: mocha@7.2.0 nyc@14.1.1 supertest@6.1.6 - name: Node.js 10.x node-version: "10" npm-i: mocha@8.4.0 supertest@6.1.6 - name: Node.js 11.x node-version: "11" npm-i: mocha@8.4.0 supertest@6.1.6 - name: Node.js 12.x node-version: "12" npm-i: "supertest@6.1.6" - name: Node.js 13.x node-version: "13" npm-i: "supertest@6.1.6" - name: Node.js 14.x node-version: "14" - name: Node.js 15.x node-version: "15" npm-i: "supertest@6.1.6" - name: Node.js 16.x node-version: "16" - name: Node.js 17.x node-version: "17" - name: Node.js 18.x node-version: "18" - name: Node.js 19.x node-version: "19" - name: Node.js 20.x node-version: "20" - name: Node.js 21.x node-version: "21" - name: Node.js 22.x node-version: "22" - name: Node.js 23.x node-version: "23" steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - name: Install Node.js ${{ matrix.node-version }} shell: bash -eo pipefail -l {0} run: | nvm install --default ${{ matrix.node-version }} if [[ "${{ matrix.node-version }}" == 0.* && "$(cut -d. -f2 <<< "${{ matrix.node-version }}")" -lt 10 ]]; then nvm install --alias=npm 0.10 nvm use ${{ matrix.node-version }} sed -i '1s;^.*$;'"$(printf '#!%q' "$(nvm which npm)")"';' "$(readlink -f "$(which npm)")" npm config set strict-ssl false fi dirname "$(nvm which ${{ matrix.node-version }})" >> "$GITHUB_PATH" - name: Configure npm run: | if [[ "$(npm config get package-lock)" == "true" ]]; then npm config set package-lock false else npm config set shrinkwrap false fi - name: Remove npm module(s) ${{ matrix.npm-rm }} run: npm rm --silent --save-dev ${{ matrix.npm-rm }} if: matrix.npm-rm != '' - name: Install npm module(s) ${{ matrix.npm-i }} run: npm install --save-dev ${{ matrix.npm-i }} if: matrix.npm-i != '' - name: Setup Node.js version-specific dependencies shell: bash run: | # eslint for linting # - remove on Node.js < 10 if [[ "$(cut -d. -f1 <<< "${{ matrix.node-version }}")" -lt 10 ]]; then node -pe 'Object.keys(require("./package").devDependencies).join("\n")' | \ grep -E '^eslint(-|$)' | \ sort -r | \ xargs -n1 npm rm --silent --save-dev fi - name: Install Node.js dependencies run: npm install - name: List environment id: list_env shell: bash run: | echo "node@$(node -v)" echo "npm@$(npm -v)" npm -s ls ||: (npm -s ls --depth=0 ||:) | awk -F'[ @]' 'NR>1 && $2 { print "::set-output name=" $2 "::" $3 }' - name: Run tests shell: bash run: | if npm -ps ls nyc | grep -q nyc; then npm run test-ci else npm test fi - name: Upload code coverage if: steps.list_env.outputs.nyc != '' uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: coverage-node-${{ matrix.node-version }} path: ./coverage/lcov.info retention-days: 1 coverage: needs: test runs-on: ubuntu-latest permissions: contents: read checks: write steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - name: Install lcov shell: bash run: sudo apt-get -y install lcov - name: Collect coverage reports uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: path: ./coverage pattern: coverage-node-* - name: Merge coverage reports shell: bash run: find ./coverage -name lcov.info -exec printf '-a %q\n' {} \; | xargs lcov -o ./lcov.info - name: Upload coverage report uses: coverallsapp/github-action@648a8eb78e6d50909eff900e4ec85cab4524a45b # v2.3.6 with: github-token: ${{ secrets.GITHUB_TOKEN }} file: ./lcov.infoexpressjs-compression-83a0c45/.github/workflows/codeql.yml000066400000000000000000000046441503623156700240370ustar00rootroot00000000000000# For most projects, this workflow file will not need changing; you simply need # to commit it to your repository. # # You may wish to alter this file to override the set of languages analyzed, # or to provide custom queries or build logic. # # ******** NOTE ******** # We have attempted to detect the languages in your repository. Please check # the `language` matrix defined below to confirm you have the correct set of # supported CodeQL languages. # name: "CodeQL" on: push: branches: ["master"] pull_request: # The branches below must be a subset of the branches above branches: ["master"] schedule: - cron: "0 0 * * 1" permissions: contents: read jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write steps: - name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2 with: languages: javascript # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file. # Prefix the list here with "+" to use these queries and those in the config file. # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) # - name: Autobuild # uses: github/codeql-action/autobuild@662472033e021d55d94146f66f6058822b0b39fd # v3.27.0 # â„šī¸ Command-line programs to run using the OS shell. # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun # If the Autobuild fails above, remove it and uncomment the following three lines. # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. # - run: | # echo "Run, Build Application using script" # ./location_of_script_within_repo/buildscript.sh - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2 with: category: "/language:javascript"expressjs-compression-83a0c45/.github/workflows/scorecard.yml000066400000000000000000000054521503623156700245330ustar00rootroot00000000000000# This workflow uses actions that are not certified by GitHub. They are provided # by a third-party and are governed by separate terms of service, privacy # policy, and support documentation. name: Scorecard supply-chain security on: # For Branch-Protection check. Only the default branch is supported. See # https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection branch_protection_rule: # To guarantee Maintained check is occasionally updated. See # https://github.com/ossf/scorecard/blob/main/docs/checks.md#maintained schedule: - cron: '16 21 * * 1' push: branches: [ "master" ] # Declare default permissions as read only. permissions: read-all jobs: analysis: name: Scorecard analysis runs-on: ubuntu-latest permissions: # Needed to upload the results to code-scanning dashboard. security-events: write # Needed to publish results and get a badge (see publish_results below). id-token: write steps: - name: "Checkout code" uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.1.2 with: persist-credentials: false - name: "Run analysis" uses: ossf/scorecard-action@05b42c624433fc40578a4040d5cf5e36ddca8cde # v2.4.2 with: results_file: results.sarif results_format: sarif # (Optional) "write" PAT token. Uncomment the `repo_token` line below if: # - you want to enable the Branch-Protection check on a *public* repository, or # - you are installing Scorecard on a *private* repository # To create the PAT, follow the steps in https://github.com/ossf/scorecard-action#authentication-with-pat. # repo_token: ${{ secrets.SCORECARD_TOKEN }} # Public repositories: # - Publish results to OpenSSF REST API for easy access by consumers # - Allows the repository to include the Scorecard badge. # - See https://github.com/ossf/scorecard-action#publishing-results. # For private repositories: # - `publish_results` will always be set to `false`, regardless # of the value entered here. publish_results: true # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF # format to the repository Actions tab. - name: "Upload artifact" uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: SARIF file path: results.sarif retention-days: 5 # Upload the results to GitHub's code scanning dashboard. - name: "Upload to code-scanning" uses: github/codeql-action/upload-sarif@181d5eefc20863364f96762470ba6f862bdef56b # v3.29.2 with: sarif_file: results.sarif expressjs-compression-83a0c45/.gitignore000066400000000000000000000001031503623156700204220ustar00rootroot00000000000000.nyc_output/ coverage node_modules npm-debug.log package-lock.json expressjs-compression-83a0c45/HISTORY.md000066400000000000000000000176411503623156700201340ustar00rootroot000000000000001.8.1 / 2025-07-17 ========== * deps: on-headers@~1.1.0 - Fix [CVE-2025-7339](https://www.cve.org/CVERecord?id=CVE-2025-7339) ([GHSA-76c9-3jph-rj3q](https://github.com/expressjs/on-headers/security/advisories/GHSA-76c9-3jph-rj3q)) 1.8.0 / 2025-02-10 ================== * Use `res.headersSent` when available * Replace `_implicitHeader` with `writeHead` property * add brotli support for versions of node that support it * Add the enforceEncoding option for requests without `Accept-Encoding` header 1.7.5 / 2024-10-31 ================== * deps: Replace accepts with negotiator@~0.6.4 - Add preference option * deps: bytes@3.1.2 - Add petabyte (`pb`) support - Fix "thousandsSeparator" incorrecting formatting fractional part - Fix return value for un-parsable strings * deps: compressible@~2.0.18 - Mark `font/ttf` as compressible - Remove compressible from `multipart/mixed` - deps: mime-db@'>= 1.43.0 < 2' * deps: safe-buffer@5.2.1 1.7.4 / 2019-03-18 ================== * deps: compressible@~2.0.16 - Mark `text/less` as compressible - deps: mime-db@'>= 1.38.0 < 2' * deps: on-headers@~1.0.2 - Fix `res.writeHead` patch missing return value * perf: prevent unnecessary buffer copy 1.7.3 / 2018-07-15 ================== * deps: accepts@~1.3.5 - deps: mime-types@~2.1.18 * deps: compressible@~2.0.14 - Mark all XML-derived types as compressible - deps: mime-db@'>= 1.34.0 < 2' * deps: safe-buffer@5.1.2 1.7.2 / 2018-02-18 ================== * deps: compressible@~2.0.13 - deps: mime-db@'>= 1.33.0 < 2' 1.7.1 / 2017-09-26 ================== * deps: accepts@~1.3.4 - deps: mime-types@~2.1.16 * deps: bytes@3.0.0 * deps: compressible@~2.0.11 - deps: mime-db@'>= 1.29.0 < 2' * deps: debug@2.6.9 * deps: vary@~1.1.2 - perf: improve header token parsing speed 1.7.0 / 2017-07-10 ================== * Use `safe-buffer` for improved Buffer API * deps: bytes@2.5.0 * deps: compressible@~2.0.10 - Fix regex fallback to not override `compressible: false` in db - deps: mime-db@'>= 1.27.0 < 2' * deps: debug@2.6.8 - Allow colors in workers - Deprecated `DEBUG_FD` environment variable set to `3` or higher - Fix error when running under React Native - Fix `DEBUG_MAX_ARRAY_LENGTH` - Use same color for same namespace - deps: ms@2.0.0 * deps: vary@~1.1.1 - perf: hoist regular expression 1.6.2 / 2016-05-12 ================== * deps: accepts@~1.3.3 - deps: mime-types@~2.1.11 - deps: negotiator@0.6.1 * deps: bytes@2.3.0 - Drop partial bytes on all parsed units - Fix parsing byte string that looks like hex - perf: hoist regular expressions * deps: compressible@~2.0.8 - deps: mime-db@'>= 1.23.0 < 2' 1.6.1 / 2016-01-19 ================== * deps: bytes@2.2.0 * deps: compressible@~2.0.7 - deps: mime-db@'>= 1.21.0 < 2' * deps: accepts@~1.3.1 - deps: mime-types@~2.1.9 1.6.0 / 2015-09-29 ================== * Skip compression when response has `Cache-Control: no-transform` * deps: accepts@~1.3.0 - deps: mime-types@~2.1.7 - deps: negotiator@0.6.0 * deps: compressible@~2.0.6 - deps: mime-db@'>= 1.19.0 < 2' * deps: on-headers@~1.0.1 - perf: enable strict mode * deps: vary@~1.1.0 - Only accept valid field names in the `field` argument 1.5.2 / 2015-07-30 ================== * deps: accepts@~1.2.12 - deps: mime-types@~2.1.4 * deps: compressible@~2.0.5 - deps: mime-db@'>= 1.16.0 < 2' * deps: vary@~1.0.1 - Fix setting empty header from empty `field` - perf: enable strict mode - perf: remove argument reassignments 1.5.1 / 2015-07-05 ================== * deps: accepts@~1.2.10 - deps: mime-types@~2.1.2 * deps: compressible@~2.0.4 - deps: mime-db@'>= 1.14.0 < 2' - perf: enable strict mode 1.5.0 / 2015-06-09 ================== * Fix return value from `.end` and `.write` after end * Improve detection of zero-length body without `Content-Length` * deps: accepts@~1.2.9 - deps: mime-types@~2.1.1 - perf: avoid argument reassignment & argument slice - perf: avoid negotiator recursive construction - perf: enable strict mode - perf: remove unnecessary bitwise operator * deps: bytes@2.1.0 - Slight optimizations - Units no longer case sensitive when parsing * deps: compressible@~2.0.3 - Fix regex fallback to work if type exists, but is undefined - deps: mime-db@'>= 1.13.0 < 2' - perf: hoist regex declaration - perf: use regex to extract mime * perf: enable strict mode * perf: remove flush reassignment * perf: simplify threshold detection 1.4.4 / 2015-05-11 ================== * deps: accepts@~1.2.7 - deps: mime-types@~2.0.11 - deps: negotiator@0.5.3 * deps: debug@~2.2.0 - deps: ms@0.7.1 1.4.3 / 2015-03-14 ================== * deps: accepts@~1.2.5 - deps: mime-types@~2.0.10 * deps: debug@~2.1.3 - Fix high intensity foreground color for bold - deps: ms@0.7.0 1.4.2 / 2015-03-11 ================== * Fix error when code calls `res.end(str, encoding)` - Specific to Node.js 0.8 * deps: debug@~2.1.2 - deps: ms@0.7.0 1.4.1 / 2015-02-15 ================== * deps: accepts@~1.2.4 - deps: mime-types@~2.0.9 - deps: negotiator@0.5.1 1.4.0 / 2015-02-01 ================== * Prefer `gzip` over `deflate` on the server - Not all clients agree on what "deflate" coding means 1.3.1 / 2015-01-31 ================== * deps: accepts@~1.2.3 - deps: mime-types@~2.0.8 * deps: compressible@~2.0.2 - deps: mime-db@'>= 1.1.2 < 2' 1.3.0 / 2014-12-30 ================== * Export the default `filter` function for wrapping * deps: accepts@~1.2.2 - deps: mime-types@~2.0.7 - deps: negotiator@0.5.0 * deps: debug@~2.1.1 1.2.2 / 2014-12-10 ================== * Fix `.end` to only proxy to `.end` - Fixes an issue with Node.js 0.11.14 * deps: accepts@~1.1.4 - deps: mime-types@~2.0.4 1.2.1 / 2014-11-23 ================== * deps: accepts@~1.1.3 - deps: mime-types@~2.0.3 1.2.0 / 2014-10-16 ================== * deps: debug@~2.1.0 - Implement `DEBUG_FD` env variable support 1.1.2 / 2014-10-15 ================== * deps: accepts@~1.1.2 - Fix error when media type has invalid parameter - deps: negotiator@0.4.9 1.1.1 / 2014-10-12 ================== * deps: accepts@~1.1.1 - deps: mime-types@~2.0.2 - deps: negotiator@0.4.8 * deps: compressible@~2.0.1 - deps: mime-db@1.x 1.1.0 / 2014-09-07 ================== * deps: accepts@~1.1.0 * deps: compressible@~2.0.0 * deps: debug@~2.0.0 1.0.11 / 2014-08-10 =================== * deps: on-headers@~1.0.0 * deps: vary@~1.0.0 1.0.10 / 2014-08-05 =================== * deps: compressible@~1.1.1 - Fix upper-case Content-Type characters prevent compression 1.0.9 / 2014-07-20 ================== * Add `debug` messages * deps: accepts@~1.0.7 - deps: negotiator@0.4.7 1.0.8 / 2014-06-20 ================== * deps: accepts@~1.0.5 - use `mime-types` 1.0.7 / 2014-06-11 ================== * use vary module for better `Vary` behavior * deps: accepts@1.0.3 * deps: compressible@1.1.0 1.0.6 / 2014-06-03 ================== * fix regression when negotiation fails 1.0.5 / 2014-06-03 ================== * fix listeners for delayed stream creation - fixes regression for certain `stream.pipe(res)` situations 1.0.4 / 2014-06-03 ================== * fix adding `Vary` when value stored as array * fix back-pressure behavior * fix length check for `res.end` 1.0.3 / 2014-05-29 ================== * use `accepts` for negotiation * use `on-headers` to handle header checking * deps: bytes@1.0.0 1.0.2 / 2014-04-29 ================== * only version compatible with node.js 0.8 * support headers given to `res.writeHead` * deps: bytes@0.3.0 * deps: negotiator@0.4.3 1.0.1 / 2014-03-08 ================== * bump negotiator * use compressible * use .headersSent (drops 0.8 support) * handle identity;q=0 case expressjs-compression-83a0c45/LICENSE000066400000000000000000000022241503623156700174450ustar00rootroot00000000000000(The MIT License) Copyright (c) 2014 Jonathan Ong Copyright (c) 2014-2015 Douglas Christopher Wilson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. expressjs-compression-83a0c45/README.md000066400000000000000000000233521503623156700177240ustar00rootroot00000000000000# compression [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Build Status][github-actions-ci-image]][github-actions-ci-url] [![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer] [![Funding][funding-image]][funding-url] Node.js compression middleware. The following compression codings are supported: - deflate - gzip - br (brotli) **Note** Brotli is supported only since Node.js versions v11.7.0 and v10.16.0. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```bash $ npm install compression ``` ## API ```js var compression = require('compression') ``` ### compression([options]) Returns the compression middleware using the given `options`. The middleware will attempt to compress response bodies for all requests that traverse through the middleware, based on the given `options`. This middleware will never compress responses that include a `Cache-Control` header with the [`no-transform` directive](https://tools.ietf.org/html/rfc7234#section-5.2.2.4), as compressing will transform the body. #### Options `compression()` accepts these properties in the options object. In addition to those listed below, [zlib](https://nodejs.org/api/zlib.html) options may be passed in to the options object or [brotli](https://nodejs.org/api/zlib.html#zlib_class_brotlioptions) options. ##### chunkSize Type: `Number`
Default: `zlib.constants.Z_DEFAULT_CHUNK`, or `16384`. See [Node.js documentation](https://nodejs.org/api/zlib.html#zlib_memory_usage_tuning) regarding the usage. ##### filter Type: `Function` A function to decide if the response should be considered for compression. This function is called as `filter(req, res)` and is expected to return `true` to consider the response for compression, or `false` to not compress the response. The default filter function uses the [compressible](https://www.npmjs.com/package/compressible) module to determine if `res.getHeader('Content-Type')` is compressible. ##### level Type: `Number`
Default: `zlib.constants.Z_DEFAULT_COMPRESSION`, or `-1` The level of zlib compression to apply to responses. A higher level will result in better compression, but will take longer to complete. A lower level will result in less compression, but will be much faster. This is an integer in the range of `0` (no compression) to `9` (maximum compression). The special value `-1` can be used to mean the "default compression level", which is a default compromise between speed and compression (currently equivalent to level 6). - `-1` Default compression level (also `zlib.constants.Z_DEFAULT_COMPRESSION`). - `0` No compression (also `zlib.constants.Z_NO_COMPRESSION`). - `1` Fastest compression (also `zlib.constants.Z_BEST_SPEED`). - `2` - `3` - `4` - `5` - `6` (currently what `zlib.constants.Z_DEFAULT_COMPRESSION` points to). - `7` - `8` - `9` Best compression (also `zlib.constants.Z_BEST_COMPRESSION`). **Note** in the list above, `zlib` is from `zlib = require('zlib')`. ##### memLevel Type: `Number`
Default: `zlib.constants.Z_DEFAULT_MEMLEVEL`, or `8` This specifies how much memory should be allocated for the internal compression state and is an integer in the range of `1` (minimum level) and `9` (maximum level). See [Node.js documentation](https://nodejs.org/api/zlib.html#zlib_memory_usage_tuning) regarding the usage. ##### brotli Type: `Object` This specifies the options for configuring Brotli. See [Node.js documentation](https://nodejs.org/api/zlib.html#class-brotlioptions) for a complete list of available options. ##### strategy Type: `Number`
Default: `zlib.constants.Z_DEFAULT_STRATEGY` This is used to tune the compression algorithm. This value only affects the compression ratio, not the correctness of the compressed output, even if it is not set appropriately. - `zlib.constants.Z_DEFAULT_STRATEGY` Use for normal data. - `zlib.constants.Z_FILTERED` Use for data produced by a filter (or predictor). Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. The effect is to force more Huffman coding and less string matching; it is somewhat intermediate between `zlib.constants.Z_DEFAULT_STRATEGY` and `zlib.constants.Z_HUFFMAN_ONLY`. - `zlib.constants.Z_FIXED` Use to prevent the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. - `zlib.constants.Z_HUFFMAN_ONLY` Use to force Huffman encoding only (no string match). - `zlib.constants.Z_RLE` Use to limit match distances to one (run-length encoding). This is designed to be almost as fast as `zlib.constants.Z_HUFFMAN_ONLY`, but give better compression for PNG image data. **Note** in the list above, `zlib` is from `zlib = require('zlib')`. ##### threshold Type: `Number` or `String`
Default: `1kb` The byte threshold for the response body size before compression is considered for the response. This is a number of bytes or any string accepted by the [bytes](https://www.npmjs.com/package/bytes) module. **Note** this is only an advisory setting; if the response size cannot be determined at the time the response headers are written, then it is assumed the response is _over_ the threshold. To guarantee the response size can be determined, be sure set a `Content-Length` response header. ##### windowBits Type: `Number`
Default: `zlib.constants.Z_DEFAULT_WINDOWBITS`, or `15` See [Node.js documentation](https://nodejs.org/api/zlib.html#zlib_memory_usage_tuning) regarding the usage. ##### enforceEncoding Type: `String`
Default: `identity` This is the default encoding to use when the client does not specify an encoding in the request's [Accept-Encoding](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding) header. #### .filter The default `filter` function. This is used to construct a custom filter function that is an extension of the default function. ```js var compression = require('compression') var express = require('express') var app = express() app.use(compression({ filter: shouldCompress })) function shouldCompress (req, res) { if (req.headers['x-no-compression']) { // don't compress responses with this request header return false } // fallback to standard filter function return compression.filter(req, res) } ``` ### res.flush This module adds a `res.flush()` method to force the partially-compressed response to be flushed to the client. ## Examples ### express When using this module with express, simply `app.use` the module as high as you like. Requests that pass through the middleware will be compressed. ```js var compression = require('compression') var express = require('express') var app = express() // compress all responses app.use(compression()) // add all routes ``` ### Node.js HTTP server ```js var compression = require('compression')({ threshold: 0 }) var http = require('http') function createServer (fn) { return http.createServer(function (req, res) { compression(req, res, function (err) { if (err) { res.statusCode = err.status || 500 res.end(err.message) return } fn(req, res) }) }) } var server = createServer(function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello world!') }) server.listen(3000, () => { console.log('> Listening at http://localhost:3000') }) ``` ### Server-Sent Events Because of the nature of compression this module does not work out of the box with server-sent events. To compress content, a window of the output needs to be buffered up in order to get good compression. Typically when using server-sent events, there are certain block of data that need to reach the client. You can achieve this by calling `res.flush()` when you need the data written to actually make it to the client. ```js var compression = require('compression') var express = require('express') var app = express() // compress responses app.use(compression()) // server-sent event stream app.get('/events', function (req, res) { res.setHeader('Content-Type', 'text/event-stream') res.setHeader('Cache-Control', 'no-cache') // send a ping approx every 2 seconds var timer = setInterval(function () { res.write('data: ping\n\n') // !!! this is the important part res.flush() }, 2000) res.on('close', function () { clearInterval(timer) }) }) ``` ## Contributing The Express.js project welcomes all constructive contributions. Contributions take many forms, from code for bug fixes and enhancements, to additions and fixes to documentation, additional tests, triaging incoming pull requests and issues, and more! See the [Contributing Guide](https://github.com/expressjs/express/blob/master/Contributing.md) for more technical details on contributing. ## License [MIT](LICENSE) [npm-image]: https://badgen.net/npm/v/compression [npm-url]: https://npmjs.org/package/compression [downloads-image]: https://badgen.net/npm/dm/compression [downloads-url]: https://npmcharts.com/compare/compression?minimal=true [github-actions-ci-image]: https://badgen.net/github/checks/expressjs/compression/master?label=CI [github-actions-ci-url]: https://github.com/expressjs/compression/actions?query=workflow%3Aci [ossf-scorecard-badge]: https://api.scorecard.dev/projects/github.com/expressjs/compression/badge [ossf-scorecard-visualizer]: https://ossf.github.io/scorecard-visualizer/#/projects/github.com/expressjs/compression [funding-url]: https://opencollective.com/express [funding-image]: https://badgen.net/badge/icon/sponsor/pink?icon=github&label=Open%20Collectiveexpressjs-compression-83a0c45/index.js000066400000000000000000000157521503623156700201170ustar00rootroot00000000000000/*! * compression * Copyright(c) 2010 Sencha Inc. * Copyright(c) 2011 TJ Holowaychuk * Copyright(c) 2014 Jonathan Ong * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ 'use strict' /** * Module dependencies. * @private */ var Negotiator = require('negotiator') var Buffer = require('safe-buffer').Buffer var bytes = require('bytes') var compressible = require('compressible') var debug = require('debug')('compression') var onHeaders = require('on-headers') var vary = require('vary') var zlib = require('zlib') /** * Module exports. */ module.exports = compression module.exports.filter = shouldCompress /** * @const * whether current node version has brotli support */ var hasBrotliSupport = 'createBrotliCompress' in zlib /** * Module variables. * @private */ var cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/ var SUPPORTED_ENCODING = hasBrotliSupport ? ['br', 'gzip', 'deflate', 'identity'] : ['gzip', 'deflate', 'identity'] var PREFERRED_ENCODING = hasBrotliSupport ? ['br', 'gzip'] : ['gzip'] var encodingSupported = ['gzip', 'deflate', 'identity', 'br'] /** * Compress response data with gzip / deflate. * * @param {Object} [options] * @return {Function} middleware * @public */ function compression (options) { var opts = options || {} var optsBrotli = {} if (hasBrotliSupport) { Object.assign(optsBrotli, opts.brotli) var brotliParams = {} brotliParams[zlib.constants.BROTLI_PARAM_QUALITY] = 4 // set the default level to a reasonable value with balanced speed/ratio optsBrotli.params = Object.assign(brotliParams, optsBrotli.params) } // options var filter = opts.filter || shouldCompress var threshold = bytes.parse(opts.threshold) var enforceEncoding = opts.enforceEncoding || 'identity' if (threshold == null) { threshold = 1024 } return function compression (req, res, next) { var ended = false var length var listeners = [] var stream var _end = res.end var _on = res.on var _write = res.write // flush res.flush = function flush () { if (stream) { stream.flush() } } // proxy res.write = function write (chunk, encoding) { if (ended) { return false } if (!headersSent(res)) { this.writeHead(this.statusCode) } return stream ? stream.write(toBuffer(chunk, encoding)) : _write.call(this, chunk, encoding) } res.end = function end (chunk, encoding) { if (ended) { return false } if (!headersSent(res)) { // estimate the length if (!this.getHeader('Content-Length')) { length = chunkLength(chunk, encoding) } this.writeHead(this.statusCode) } if (!stream) { return _end.call(this, chunk, encoding) } // mark ended ended = true // write Buffer for Node.js 0.8 return chunk ? stream.end(toBuffer(chunk, encoding)) : stream.end() } res.on = function on (type, listener) { if (!listeners || type !== 'drain') { return _on.call(this, type, listener) } if (stream) { return stream.on(type, listener) } // buffer listeners for future stream listeners.push([type, listener]) return this } function nocompress (msg) { debug('no compression: %s', msg) addListeners(res, _on, listeners) listeners = null } onHeaders(res, function onResponseHeaders () { // determine if request is filtered if (!filter(req, res)) { nocompress('filtered') return } // determine if the entity should be transformed if (!shouldTransform(req, res)) { nocompress('no transform') return } // vary vary(res, 'Accept-Encoding') // content-length below threshold if (Number(res.getHeader('Content-Length')) < threshold || length < threshold) { nocompress('size below threshold') return } var encoding = res.getHeader('Content-Encoding') || 'identity' // already encoded if (encoding !== 'identity') { nocompress('already encoded') return } // head if (req.method === 'HEAD') { nocompress('HEAD request') return } // compression method var negotiator = new Negotiator(req) var method = negotiator.encoding(SUPPORTED_ENCODING, PREFERRED_ENCODING) // if no method is found, use the default encoding if (!req.headers['accept-encoding'] && encodingSupported.indexOf(enforceEncoding) !== -1) { method = enforceEncoding } // negotiation failed if (!method || method === 'identity') { nocompress('not acceptable') return } // compression stream debug('%s compression', method) stream = method === 'gzip' ? zlib.createGzip(opts) : method === 'br' ? zlib.createBrotliCompress(optsBrotli) : zlib.createDeflate(opts) // add buffered listeners to stream addListeners(stream, stream.on, listeners) // header fields res.setHeader('Content-Encoding', method) res.removeHeader('Content-Length') // compression stream.on('data', function onStreamData (chunk) { if (_write.call(res, chunk) === false) { stream.pause() } }) stream.on('end', function onStreamEnd () { _end.call(res) }) _on.call(res, 'drain', function onResponseDrain () { stream.resume() }) }) next() } } /** * Add bufferred listeners to stream * @private */ function addListeners (stream, on, listeners) { for (var i = 0; i < listeners.length; i++) { on.apply(stream, listeners[i]) } } /** * Get the length of a given chunk */ function chunkLength (chunk, encoding) { if (!chunk) { return 0 } return Buffer.isBuffer(chunk) ? chunk.length : Buffer.byteLength(chunk, encoding) } /** * Default filter function. * @private */ function shouldCompress (req, res) { var type = res.getHeader('Content-Type') if (type === undefined || !compressible(type)) { debug('%s not compressible', type) return false } return true } /** * Determine if the entity should be transformed. * @private */ function shouldTransform (req, res) { var cacheControl = res.getHeader('Cache-Control') // Don't compress for Cache-Control: no-transform // https://tools.ietf.org/html/rfc7234#section-5.2.2.4 return !cacheControl || !cacheControlNoTransformRegExp.test(cacheControl) } /** * Coerce arguments to Buffer * @private */ function toBuffer (chunk, encoding) { return Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding) } /** * Determine if the response headers have been sent. * * @param {object} res * @returns {boolean} * @private */ function headersSent (res) { return typeof res.headersSent !== 'boolean' ? Boolean(res._header) : res.headersSent } expressjs-compression-83a0c45/package.json000066400000000000000000000024511503623156700207300ustar00rootroot00000000000000{ "name": "compression", "description": "Node.js compression middleware", "version": "1.8.1", "contributors": [ "Douglas Christopher Wilson ", "Jonathan Ong (http://jongleberry.com)" ], "license": "MIT", "repository": "expressjs/compression", "keywords": ["compression", "gzip", "deflate", "middleware", "express", "brotli", "http", "stream"], "dependencies": { "bytes": "3.1.2", "compressible": "~2.0.18", "debug": "2.6.9", "negotiator": "~0.6.4", "on-headers": "~1.1.0", "safe-buffer": "5.2.1", "vary": "~1.1.2" }, "devDependencies": { "after": "0.8.2", "eslint": "7.32.0", "eslint-config-standard": "14.1.1", "eslint-plugin-import": "2.32.0", "eslint-plugin-markdown": "2.2.1", "eslint-plugin-node": "11.1.0", "eslint-plugin-promise": "5.2.0", "eslint-plugin-standard": "4.1.0", "mocha": "9.2.2", "nyc": "15.1.0", "supertest": "6.3.4" }, "files": [ "LICENSE", "HISTORY.md", "index.js" ], "engines": { "node": ">= 0.8.0" }, "scripts": { "lint": "eslint .", "test": "mocha --check-leaks --reporter spec", "test-ci": "nyc --reporter=lcov --reporter=text npm test", "test-cov": "nyc --reporter=html --reporter=text npm test" } } expressjs-compression-83a0c45/test/000077500000000000000000000000001503623156700174175ustar00rootroot00000000000000expressjs-compression-83a0c45/test/.eslintrc.yml000066400000000000000000000000231503623156700220360ustar00rootroot00000000000000env: mocha: true expressjs-compression-83a0c45/test/compression.js000066400000000000000000000752471503623156700223350ustar00rootroot00000000000000var after = require('after') var assert = require('assert') var Buffer = require('safe-buffer').Buffer var bytes = require('bytes') var crypto = require('crypto') var http = require('http') var request = require('supertest') var zlib = require('zlib') var describeHttp2 = describe.skip try { var http2 = require('http2') describeHttp2 = describe } catch (err) { if (err) { console.log('http2 tests disabled.') } } var compression = require('..') /** * @const * whether current node version has brotli support */ var hasBrotliSupport = 'createBrotliCompress' in zlib var brotli = hasBrotliSupport ? it : it.skip describe('compression()', function () { it('should skip HEAD', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .head('/') .set('Accept-Encoding', 'gzip') .expect(shouldNotHaveHeader('Content-Encoding')) .expect(200, done) }) it('should skip unknown accept-encoding', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'bogus') .expect(shouldNotHaveHeader('Content-Encoding')) .expect(200, done) }) it('should skip if content-encoding already set', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.setHeader('Content-Encoding', 'x-custom') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'gzip') .expect('Content-Encoding', 'x-custom') .expect(200, 'hello, world', done) }) it('should set Vary', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'gzip') .expect('Content-Encoding', 'gzip') .expect('Vary', 'Accept-Encoding', done) }) it('should set Vary even if Accept-Encoding is not set', function (done) { var server = createServer({ threshold: 1000 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .expect('Vary', 'Accept-Encoding') .expect(shouldNotHaveHeader('Content-Encoding')) .expect(200, done) }) it('should not set Vary if Content-Type does not pass filter', function (done) { var server = createServer(null, function (req, res) { res.setHeader('Content-Type', 'image/jpeg') res.end() }) request(server) .get('/') .expect(shouldNotHaveHeader('Vary')) .expect(200, done) }) it('should set Vary for HEAD request', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .head('/') .set('Accept-Encoding', 'gzip') .expect('Vary', 'Accept-Encoding', done) }) it('should transfer chunked', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'gzip') .expect('Transfer-Encoding', 'chunked', done) }) it('should remove Content-Length for chunked', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .expect('Content-Encoding', 'gzip') .expect(shouldNotHaveHeader('Content-Length')) .expect(200, done) }) it('should work with encoding arguments', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.write('hello, ', 'utf8') res.end('world', 'utf8') }) request(server) .get('/') .set('Accept-Encoding', 'gzip') .expect('Transfer-Encoding', 'chunked') .expect(200, 'hello, world', done) }) it('should allow writing after close', function (done) { // UGH var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.once('close', function () { res.write('hello, ') res.end('world') done() }) res.destroy() }) request(server) .get('/') .end(function () {}) }) it('should back-pressure when compressed', function (done) { var buf var cb = after(2, done) var client var drained = false var resp var server = createServer({ threshold: 0 }, function (req, res) { resp = res res.on('drain', function () { drained = true }) res.setHeader('Content-Type', 'text/plain') res.write('start') pressure() }) crypto.randomBytes(1024 * 128, function (err, chunk) { if (err) return done(err) buf = chunk pressure() }) function pressure () { if (!buf || !resp || !client) return assert.ok(!drained) while (resp.write(buf) !== false) { resp.flush() } resp.on('drain', function () { assert.ok(resp.write('end')) resp.end() }) resp.on('finish', cb) client.resume() } request(server) .get('/') .request() .on('response', function (res) { client = res assert.strictEqual(res.headers['content-encoding'], 'gzip') res.pause() res.on('end', function () { server.close(cb) }) pressure() }) .end() }) it('should back-pressure when uncompressed', function (done) { var buf var cb = after(2, done) var client var drained = false var resp var server = createServer({ filter: function () { return false } }, function (req, res) { resp = res res.on('drain', function () { drained = true }) res.setHeader('Content-Type', 'text/plain') res.write('start') pressure() }) crypto.randomBytes(1024 * 128, function (err, chunk) { if (err) return done(err) buf = chunk pressure() }) function pressure () { if (!buf || !resp || !client) return while (resp.write(buf) !== false) { resp.flush() } resp.on('drain', function () { assert.ok(drained) assert.ok(resp.write('end')) resp.end() }) resp.on('finish', cb) client.resume() } request(server) .get('/') .request() .on('response', function (res) { client = res shouldNotHaveHeader('Content-Encoding')(res) res.pause() res.on('end', function () { server.close(cb) }) pressure() }) .end() }) it('should transfer large bodies', function (done) { var len = bytes('1mb') var buf = Buffer.alloc(len, '.') var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end(buf) }) request(server) .get('/') .set('Accept-Encoding', 'gzip') .expect('Transfer-Encoding', 'chunked') .expect('Content-Encoding', 'gzip') .expect(shouldHaveBodyLength(len)) .expect(200, buf.toString(), done) }) it('should transfer large bodies with multiple writes', function (done) { var len = bytes('40kb') var buf = Buffer.alloc(len, '.') var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.write(buf) res.write(buf) res.write(buf) res.end(buf) }) request(server) .get('/') .set('Accept-Encoding', 'gzip') .expect('Transfer-Encoding', 'chunked') .expect('Content-Encoding', 'gzip') .expect(shouldHaveBodyLength(len * 4)) .expect(200, done) }) describeHttp2('http2', function () { it('should work with http2 server', function (done) { var server = createHttp2Server({ threshold: 0 }, function (req, res) { res.setHeader(http2.constants.HTTP2_HEADER_CONTENT_TYPE, 'text/plain') res.end('hello, world') }) server.on('listening', function () { var client = createHttp2Client(server.address().port) // using ES5 as Node.js <=4.0.0 does not have Computed Property Names var reqHeaders = {} reqHeaders[http2.constants.HTTP2_HEADER_ACCEPT_ENCODING] = 'gzip' var request = client.request(reqHeaders) request.on('response', function (headers) { assert.strictEqual(headers[http2.constants.HTTP2_HEADER_STATUS], 200) assert.strictEqual(headers[http2.constants.HTTP2_HEADER_CONTENT_TYPE], 'text/plain') assert.strictEqual(headers[http2.constants.HTTP2_HEADER_CONTENT_ENCODING], 'gzip') }) var chunks = [] request.on('data', function (chunk) { chunks.push(chunk) }) request.on('end', function () { closeHttp2(client, server, function () { zlib.gunzip(Buffer.concat(chunks), function (err, data) { assert.ok(!err) assert.strictEqual(data.toString(), 'hello, world') done() }) }) }) request.end() }) }) }) describe('threshold', function () { it('should not compress responses below the threshold size', function (done) { var server = createServer({ threshold: '1kb' }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.setHeader('Content-Length', '12') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'gzip') .expect(shouldNotHaveHeader('Content-Encoding')) .expect(200, done) }) it('should compress responses above the threshold size', function (done) { var server = createServer({ threshold: '1kb' }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.setHeader('Content-Length', '2048') res.end(Buffer.alloc(2048)) }) request(server) .get('/') .set('Accept-Encoding', 'gzip') .expect('Content-Encoding', 'gzip', done) }) it('should compress when streaming without a content-length', function (done) { var server = createServer({ threshold: '1kb' }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.write('hello, ') setTimeout(function () { res.end('world') }, 10) }) request(server) .get('/') .set('Accept-Encoding', 'gzip') .expect('Content-Encoding', 'gzip', done) }) it('should not compress when streaming and content-length is lower than threshold', function (done) { var server = createServer({ threshold: '1kb' }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.setHeader('Content-Length', '12') res.write('hello, ') setTimeout(function () { res.end('world') }, 10) }) request(server) .get('/') .set('Accept-Encoding', 'gzip') .expect(shouldNotHaveHeader('Content-Encoding')) .expect(200, done) }) it('should compress when streaming and content-length is larger than threshold', function (done) { var server = createServer({ threshold: '1kb' }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.setHeader('Content-Length', '2048') res.write(Buffer.alloc(1024)) setTimeout(function () { res.end(Buffer.alloc(1024)) }, 10) }) request(server) .get('/') .set('Accept-Encoding', 'gzip') .expect('Content-Encoding', 'gzip', done) }) // res.end(str, encoding) broken in node.js 0.8 var run = /^v0\.8\./.test(process.version) ? it.skip : it run('should handle writing hex data', function (done) { var server = createServer({ threshold: 6 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('2e2e2e2e', 'hex') }) request(server) .get('/') .set('Accept-Encoding', 'gzip') .expect(shouldNotHaveHeader('Content-Encoding')) .expect(200, '....', done) }) it('should consider res.end() as 0 length', function (done) { var server = createServer({ threshold: 1 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end() }) request(server) .get('/') .set('Accept-Encoding', 'gzip') .expect(shouldNotHaveHeader('Content-Encoding')) .expect(200, '', done) }) it('should work with res.end(null)', function (done) { var server = createServer({ threshold: 1000 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end(null) }) request(server) .get('/') .set('Accept-Encoding', 'gzip') .expect(shouldNotHaveHeader('Content-Encoding')) .expect(200, '', done) }) }) describe('when "Accept-Encoding: gzip"', function () { it('should respond with gzip', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'gzip') .expect('Content-Encoding', 'gzip', done) }) it('should return false writing after end', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') assert.ok(res.write() === false) assert.ok(res.end() === false) }) request(server) .get('/') .set('Accept-Encoding', 'gzip') .expect('Content-Encoding', 'gzip', done) }) }) describe('when "Accept-Encoding: deflate"', function () { it('should respond with deflate', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'deflate') .expect('Content-Encoding', 'deflate', done) }) }) describe('when "Accept-Encoding: br"', function () { brotli('should respond with br', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'br') .expect('Content-Encoding', 'br', done) }) }) describe('when "Accept-Encoding: br" and passing compression level', function () { brotli('should respond with br', function (done) { var params = {} params[zlib.constants.BROTLI_PARAM_QUALITY] = 11 var server = createServer({ threshold: 0, brotli: { params: params } }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'br') .expect('Content-Encoding', 'br', done) }) brotli('shouldn\'t break compression when gzip is requested', function (done) { var params = {} params[zlib.constants.BROTLI_PARAM_QUALITY] = 8 var server = createServer({ threshold: 0, brotli: { params: params } }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'gzip') .expect('Content-Encoding', 'gzip', done) }) }) describe('when "Accept-Encoding: gzip, deflate"', function () { it('should respond with gzip', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'gzip, deflate') .expect('Content-Encoding', 'gzip', done) }) }) describe('when "Accept-Encoding: deflate, gzip"', function () { it('should respond with gzip', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'deflate, gzip') .expect('Content-Encoding', 'gzip', done) }) }) describe('when "Accept-Encoding: gzip, br"', function () { var brotli = hasBrotliSupport ? it : it.skip brotli('should respond with br', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'gzip, br') .expect('Content-Encoding', 'br', done) }) brotli = hasBrotliSupport ? it.skip : it brotli('should respond with gzip', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'br, gzip') .expect('Content-Encoding', 'gzip', done) }) }) describe('when "Accept-Encoding: deflate, gzip, br"', function () { brotli('should respond with br', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'deflate, gzip, br') .expect('Content-Encoding', 'br', done) }) }) describe('when "Accept-Encoding: gzip;q=1, br;q=0.3"', function () { brotli('should respond with gzip', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'gzip;q=1, br;q=0.3') .expect('Content-Encoding', 'gzip', done) }) }) describe('when "Accept-Encoding: gzip, br;q=0.8"', function () { brotli('should respond with gzip', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'gzip, br;q=0.8') .expect('Content-Encoding', 'gzip', done) }) }) describe('when "Accept-Encoding: gzip;q=0.001"', function () { brotli('should respond with gzip', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'gzip;q=0.001') .expect('Content-Encoding', 'gzip', done) }) }) describe('when "Accept-Encoding: deflate, br"', function () { brotli('should respond with br', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'deflate, br') .expect('Content-Encoding', 'br', done) }) }) describe('when "Cache-Control: no-transform" response header', function () { it('should not compress response', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Cache-Control', 'no-transform') res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'gzip') .expect('Cache-Control', 'no-transform') .expect(shouldNotHaveHeader('Content-Encoding')) .expect(200, 'hello, world', done) }) it('should not set Vary headerh', function (done) { var server = createServer({ threshold: 0 }, function (req, res) { res.setHeader('Cache-Control', 'no-transform') res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'gzip') .expect('Cache-Control', 'no-transform') .expect(shouldNotHaveHeader('Vary')) .expect(200, done) }) }) describe('.filter', function () { it('should be a function', function () { assert.strictEqual(typeof compression.filter, 'function') }) it('should return false on empty response', function (done) { var server = http.createServer(function (req, res) { res.end(String(compression.filter(req, res))) }) request(server) .get('/') .expect(200, 'false', done) }) it('should return true for "text/plain"', function (done) { var server = http.createServer(function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end(String(compression.filter(req, res))) }) request(server) .get('/') .expect(200, 'true', done) }) it('should return false for "application/x-bogus"', function (done) { var server = http.createServer(function (req, res) { res.setHeader('Content-Type', 'application/x-bogus') res.end(String(compression.filter(req, res))) }) request(server) .get('/') .expect(200, 'false', done) }) }) describe('res.flush()', function () { it('should always be present', function (done) { var server = createServer(null, function (req, res) { res.statusCode = typeof res.flush === 'function' ? 200 : 500 res.flush() res.end() }) request(server) .get('/') .expect(200, done) }) it('should flush the response', function (done) { var chunks = 0 var next var server = createServer({ threshold: 0 }, function (req, res) { next = writeAndFlush(res, 2, Buffer.alloc(1024)) res.setHeader('Content-Type', 'text/plain') res.setHeader('Content-Length', '2048') next() }) function onchunk (chunk) { assert.ok(chunks++ < 2) assert.strictEqual(chunk.length, 1024) next() } request(server) .get('/') .set('Accept-Encoding', 'gzip') .request() .on('response', unchunk('gzip', onchunk, function (err) { if (err) return done(err) server.close(done) })) .end() }) it('should flush small chunks for gzip', function (done) { var chunks = 0 var next var server = createServer({ threshold: 0 }, function (req, res) { next = writeAndFlush(res, 2, Buffer.from('..')) res.setHeader('Content-Type', 'text/plain') next() }) function onchunk (chunk) { assert.ok(chunks++ < 20) assert.strictEqual(chunk.toString(), '..') next() } request(server) .get('/') .set('Accept-Encoding', 'gzip') .request() .on('response', unchunk('gzip', onchunk, function (err) { if (err) return done(err) server.close(done) })) .end() }) brotli('should flush small chunks for brotli', function (done) { var chunks = 0 var next var server = createServer({ threshold: 0 }, function (req, res) { next = writeAndFlush(res, 2, Buffer.from('..')) res.setHeader('Content-Type', 'text/plain') next() }) function onchunk (chunk) { assert.ok(chunks++ < 20) assert.strictEqual(chunk.toString(), '..') next() } request(server) .get('/') .set('Accept-Encoding', 'br') .request() .on('response', unchunk('br', onchunk, function (err) { if (err) return done(err) server.close(done) })) .end() }) it('should flush small chunks for deflate', function (done) { var chunks = 0 var next var server = createServer({ threshold: 0 }, function (req, res) { next = writeAndFlush(res, 2, Buffer.from('..')) res.setHeader('Content-Type', 'text/plain') next() }) function onchunk (chunk) { assert.ok(chunks++ < 20) assert.strictEqual(chunk.toString(), '..') next() } request(server) .get('/') .set('Accept-Encoding', 'deflate') .request() .on('response', unchunk('deflate', onchunk, function (err) { if (err) return done(err) server.close(done) })) .end() }) }) describe('enforceEncoding', function () { it('should compress the provided encoding and not the default encoding', function (done) { var server = createServer({ threshold: 0, enforceEncoding: 'deflate' }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', 'gzip') .expect('Content-Encoding', 'gzip') .expect(200, 'hello, world', done) }) it('should not compress when enforceEncoding is identity', function (done) { var server = createServer({ threshold: 0, enforceEncoding: 'identity' }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', '') .expect(shouldNotHaveHeader('Content-Encoding')) .expect(200, 'hello, world', done) }) it('should compress when enforceEncoding is gzip', function (done) { var server = createServer({ threshold: 0, enforceEncoding: 'gzip' }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', '') .expect('Content-Encoding', 'gzip') .expect(200, 'hello, world', done) }) it('should compress when enforceEncoding is deflate', function (done) { var server = createServer({ threshold: 0, enforceEncoding: 'deflate' }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', '') .expect('Content-Encoding', 'deflate') .expect(200, 'hello, world', done) }) brotli('should compress when enforceEncoding is brotli', function (done) { var server = createServer({ threshold: 0, enforceEncoding: 'br' }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', '') .expect('Content-Encoding', 'br') .expect(200, done) }) it('should not compress when enforceEncoding is unknown', function (done) { var server = createServer({ threshold: 0, enforceEncoding: 'bogus' }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', '') .expect(shouldNotHaveHeader('Content-Encoding')) .expect(200, 'hello, world', done) }) it('should not compress when enforceEnconding is *', function (done) { var server = createServer({ threshold: 0, enforceEncoding: '*' }, function (req, res) { res.setHeader('Content-Type', 'text/plain') res.end('hello, world') }) request(server) .get('/') .set('Accept-Encoding', '') .expect(shouldNotHaveHeader('Content-Encoding')) .expect(200, done) }) }) }) function createServer (opts, fn) { var _compression = compression(opts) return http.createServer(function (req, res) { _compression(req, res, function (err) { if (err) { res.statusCode = err.status || 500 res.end(err.message) return } fn(req, res) }) }) } function createHttp2Server (opts, fn) { var _compression = compression(opts) var server = http2.createServer(function (req, res) { _compression(req, res, function (err) { if (err) { res.statusCode = err.status || 500 res.end(err.message) return } fn(req, res) }) }) server.listen(0, '127.0.0.1') return server } function createHttp2Client (port) { return http2.connect('http://127.0.0.1:' + port) } function closeHttp2 (client, server, callback) { if (typeof client.shutdown === 'function') { // this is the node v8.x way of closing the connections client.shutdown({}, function () { server.close(function () { callback() }) }) } else { // this is the node v9.x onwards way of closing the connections client.close(function () { // force existing connections to time out after 1ms. // this is done to force the server to close in some cases where it wouldn't do it otherwise. server.close(function () { callback() }) }) } } function shouldHaveBodyLength (length) { return function (res) { assert.strictEqual(res.text.length, length, 'should have body length of ' + length) } } function shouldNotHaveHeader (header) { return function (res) { assert.ok(!(header.toLowerCase() in res.headers), 'should not have header ' + header) } } function writeAndFlush (stream, count, buf) { var writes = 0 return function () { if (writes++ >= count) return if (writes === count) return stream.end(buf) stream.write(buf) stream.flush() } } function unchunk (encoding, onchunk, onend) { return function (res) { var stream assert.strictEqual(res.headers['content-encoding'], encoding) switch (encoding) { case 'deflate': stream = res.pipe(zlib.createInflate()) break case 'gzip': stream = res.pipe(zlib.createGunzip()) break case 'br': stream = res.pipe(zlib.createBrotliDecompress()) break } stream.on('data', onchunk) stream.on('end', onend) } }