[
  {
    "path": ".editorconfig",
    "content": "# top-most EditorConfig file\nroot = true\n\n# Unix-style newlines with a newline ending every file\n[*]\nend_of_line = lf\ncharset = utf-8\ntrim_trailing_whitespace = true\ninsert_final_newline = true\nindent_style = space\nindent_size = 2\n"
  },
  {
    "path": ".github/workflows/docker.yml",
    "content": "name: Run Docker\non:\n  push:\n    branches:\n    - main\n  pull_request:\n    branches:\n    - main\njobs:\n  build:\n    runs-on: ubuntu-latest\n    steps:\n    - name: Harden Runner\n      uses: step-security/harden-runner@5ef0c079ce82195b2a36a210272d6b661572d83e # v2.14.2\n      with:\n        egress-policy: block\n        allowed-endpoints: >\n          archive.ubuntu.com:80\n          auth.docker.io:443\n          github.com:443\n          production.cloudflare.docker.com:443\n          registry-1.docker.io:443\n          registry.npmjs.org:443\n          security.ubuntu.com:80\n    - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6\n    - name: Build the container\n      run: docker build -f test/Dockerfile . -t sitespeedio/throttle\n    - name: Test Throttle\n      run: docker run --cap-add=NET_ADMIN sitespeedio/throttle"
  },
  {
    "path": ".github/workflows/install.yml",
    "content": "name: Install latest release\non:\n  push:\n    branches:\n    - main\n  pull_request:\n    branches:\n    - main\njobs:\n  build:\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        node-version: [24.x]\n    steps:\n    - name: Harden Runner\n      uses: step-security/harden-runner@5ef0c079ce82195b2a36a210272d6b661572d83e # v2.14.2\n      with:\n        egress-policy: block\n        allowed-endpoints: >\n          registry.npmjs.org:443\n    - name: Install throttle\n      run: npm install @sitespeed.io/throttle -g\n    - name: Install dependencies\n      run: sudo apt-get install -y net-tools\n    - name: Show interfaces\n      run: sudo ip r\n    - name: Show version\n      run: throttle --version\n    - name: Test cable\n      run: throttle cable"
  },
  {
    "path": ".github/workflows/linux.yml",
    "content": "name: Linux\non:\n  push:\n    branches:\n    - main\n  pull_request:\n    branches:\n    - main\njobs:\n  build:\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        node-version: [20.x, 22.x, 24.x]\n    steps:\n    - name: Harden Runner\n      uses: step-security/harden-runner@5ef0c079ce82195b2a36a210272d6b661572d83e # v2.14.2\n      with:\n        egress-policy: audit\n    - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6\n    - name: Use Node.js ${{ matrix.node-version }}\n      uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6\n      with:\n        node-version: ${{ matrix.node-version }}\n    - name: Install throttle\n      run: npm ci\n    - name: Install dependencies\n      run: sudo apt-get install -y net-tools\n    - name: Verify lint\n      run: npm run lint\n    - name: Show interfaces\n      run: sudo ip route show\n    - name: Get default interface\n      run: sudo ip route | awk '/default/ {print $5; exit}' | tr -d '\\n'\n    - name: Test cable \n      run: LOG_THROTTLE=true bin/index.js cable && bin/index.js stop\n    - name: Test configuration \n      run: LOG_THROTTLE=true bin/index.js throttle --up 330 --down 780 --rtt 200 && bin/index.js stop\n    - name: Test localhost \n      run: LOG_THROTTLE=true bin/index.js --rtt 200 --localhost && bin/index.js stop --localhost\n    - name: Test config file\n      run: LOG_THROTTLE=true bin/index.js --config test/config.json && bin/index.js stop\n    - name: Test packet loss\n      run: LOG_THROTTLE=true bin/index.js throttle --up 330 --down 780 --rtt 200 --packetLoss 10 && bin/index.js stop\n    - name: Test packet loss and profile\n      run: LOG_THROTTLE=true bin/index.js 3g --packetLoss 10 && bin/index.js stop\n"
  },
  {
    "path": ".github/workflows/osx.yml",
    "content": "name: OSX\non:\n  push:\n    branches:\n    - main\n  pull_request:\n    branches:\n    - main\njobs:\n  build:\n    runs-on: macos-latest\n    steps:\n    - name: Harden Runner\n      uses: step-security/harden-runner@5ef0c079ce82195b2a36a210272d6b661572d83e # v2.14.2\n      with:\n        egress-policy: audit\n    - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6\n    - name: Use Node.js\n      uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6\n      with:\n        node-version: '20.x'\n    - name: Install dependencies \n      run: npm ci\n    - name: Test 3g \n      run: bin/index.js 3g && bin/index.js stop\n    - name: Test configuration \n      run: bin/index.js throttle --up 330 --down 780 --rtt 200 && bin/index.js stop\n    - name: Test localhost\n      run: bin/index.js throttle --rtt 200 --localhost && bin/index.js stop --localhost\n    - name: Test profile and packet loss \n      run: bin/index.js 3g --packetLoss 5 && bin/index.js stop\n    - name: Test configuration  and packet loss\n      run: bin/index.js throttle --up 330 --down 780 --rtt 200 --packetLoss 5 && bin/index.js stop\n"
  },
  {
    "path": ".gitignore",
    "content": "node_modules"
  },
  {
    "path": ".npmignore",
    "content": "test/*\nrelease.sh\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# CHANGELOG - throttle\n\n# 6.0.0 - 2026-03-23\n### Added\n* Added IPv6 throttling support on macOS [#94](https://github.com/sitespeedio/throttle/pull/94) and Linux [#100](https://github.com/sitespeedio/throttle/pull/100).\n* Apply packet loss also to the upload interface [#69](https://github.com/sitespeedio/throttle/pull/69).\n\n### Fixed\n* More robust detection of the default network interface on Linux, falling back to global IP address lookup when the default route is unavailable [#104](https://github.com/sitespeedio/throttle/pull/104).\n* Fixed README profile values for DSL and Edge to match actual code, and fixed Node.js API examples to use named imports.\n\n### Tech\n* Updated ESLint to 10, Prettier to 3, and migrated to flat config [#101](https://github.com/sitespeedio/throttle/pull/101) [#103](https://github.com/sitespeedio/throttle/pull/103).\n* Updated GitHub Actions to use actions/checkout@v4 and actions/setup-node@v4.\n\n# 5.0.1 - 2024-08-26\n### Fixed\n* Smarter ifb0 handling on Linux [#93](https://github.com/sitespeedio/throttle/pull/93).\n\n# 5.0.0 - 2022-07-02\n### Changed\n* Dropped support for NodeJS 12 since it's unmaintaned.\n\n### Tech\n* Code cleanup using eslint-plugin-unicorn.\n# 4.0.3 - 2022-06-29\n### Fixed\n* Fixed `--version` so it actually shows the version again [#75](https://github.com/sitespeedio/throttle/pull/75).\n# 4.0.2 - 2022-06-21\n### Fixed\n* The E6 Module convertion in 4.0 broke version check (`--version`) making installs failed. PR [#74](https://github.com/sitespeedio/throttle/pull/74) is a temporaty fix for that.\n\n# 4.0.1 - 2022-06-17\n### Fixed\n* Removed the dependecy of route. Using `ip route` instead and we already have `ip` as a requirement.\n# 4.0.0 - 2022-04-14\n### Changed\n* Converting the project to ES6 module. If you run Throttle by command line it will work exactly as before except that we dropped support for NodeJS 10 [#67](https://github.com/sitespeedio/throttle/pull/67). You can read [Sindre Sorhus ESM package guide](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c).\n\n### Fixed\n* Updated dev dependencies to latest versions [#68](https://github.com/sitespeedio/throttle/pull/68)\n\n# 3.1.1 - 2022-04-19\n### Fixed\n* Updated minimist dependency.\n# 3.1.0 - 2021-12-26\n### Added\n* Add support for setting packet loss. Add `--packetLoss` and set the loss in percentage.\n# 3.0.0 - 2021-08-09\n\n### Changed\n* When you run on Mac OS we changed so localhost traffic is not throttled by default. To throttle on localhost use `--localhost`. This makes sence if you use WebDriver to drive your browser on your local machine. And Mac OS now works the same as Linux.\n# 2.1.2 - 2021-07-29\n### Fixed\n* Fix breakage when multiple default routes are declared , thank you [Andy Richardson](https://github.com/andyrichardson) for PR [#62](https://github.com/sitespeedio/throttle/pull/62).\n# 2.1.1 - 2021-03-19\n### Fixed\n* A better check for missing net-tools on Linux, thank you [Radu Micu](https://github.com/radum) for the PR [#56](https://github.com/sitespeedio/throttle/pull/56).\n# 2.1.0 - 2021-03-10\n## Added\n* Added support for config files. Use `--config config.json` to read configuration setup from a file.\n# 2.0.2 - 2020-09-10\n## Fixed\n* Make the install as small as possible.\n\n# 2.0.1 - 2020-08-22\n## Fixed\n* Removed the execa dependency to make sure we have minimal dependencies [#53](https://github.com/sitespeedio/throttle/pull/53).\n\n# 2.0.0 - 2020-08-14\n### Changed\n* You can now set one of up/down/rtt if you like as introduced by [Iñaki Baz Castillo](https://github.com/ibc) - thank you! Implemented in [#46](https://github.com/sitespeedio/throttle/pull/46). This also remove the default profile meaning there's a change in behavior if you run throttle without any parameters. Before a default profile was used but now you get an error (you know need to set a profile or set up/down or rtt).\n\n### Added\n* You can use ```--log``` to log all networks commands [#45](https://github.com/sitespeedio/throttle/pull/45).\n* Added support to add delay on for localhost on OS X. Use ```--rtt 100 --localhost``` [#51](https://github.com/sitespeedio/throttle/pull/51).\n\n### Fixed\n* Add missing await when removing the ingress if removing root fails for tc [#47](https://github.com/sitespeedio/throttle/pull/47).\n* Better error handling in the CLI [#48](https://github.com/sitespeedio/throttle/pull/48). Make sure that the exit code is > 0 if setting the throttling fails.\n\n### Tech\n* Removed configuration file for pfctl to make it easier to set up dynamic dummynet [#49](https://github.com/sitespeedio/throttle/pull/49)\n\n## 1.1.0 2020-07-29\n### Fixed\n* Updated execa to 4.0.3.\n* Removed log message \"using default profile\"\n\n### Added\n* You can log all the commands that sets up the throttling by setting ```LOG_THROTTLE=true``` [#44](https://github.com/sitespeedio/throttle/pull/44).\n\n## 1.0.3 2020-06-20\n### Fixed\n* Updated minimist\n\n## 1.0.2 2020-03-09\n### Fixed\n* Fixed dependency tree and npm-shrinkwrap to only hold dependencies for production.\n\n## 1.0.1 2020-02-03\n### Fixed\n* Another fix to 2g to get that right, thank you Matt! [#37](https://github.com/sitespeedio/throttle/pull/37).\n\n## 1.0.0 2020-02-03\n### Changed\n* 2g speed was updated to become more usable and follow WPT [#36](https://github.com/sitespeedio/throttle/pull/36) - thank you [Matt Hobbs](https://github.com/Nooshu) for the PR.\n\n### Added\n* More pre-made profiles: dsl, 3gem, 4g, lte, edge, dial, fois [#36](https://github.com/sitespeedio/throttle/pull/36) - thank you [Matt Hobbs](https://github.com/Nooshu) for the PR.\n\n## 0.5.4 2019-08-26\n### Fixed\n* Another execa fix, hopefully fixing the last thing + added more tests in Travis.\n\n## 0.5.3 2019-08-26\n### Fixed\n* Over optimistic Execa upgraded caused Throttle to stop working [#32](https://github.com/sitespeedio/throttle/pull/32).\n\n## 0.5.2 2019-08-26\n### Fixed\n* Updated dependencies [#31](https://github.com/sitespeedio/throttle/pull/31). \n\n## 0.5.1 2019-04-23\n### Fixed\n* Calling stop on Linux throwed error see [#20](https://github.com/sitespeedio/throttle/issues/20) and fixed by [Iñaki Baz Castillo](https://github.com/ibc), thank you!\n\n## 0.5.0 2018-12-07\n### Added\n* Simplified profile/stop/help. You can now start with: ```throttle $profile``` and stop with ```throttle stop```\n\n## 0.4.3 2018-09-01\n### Fixed\n* Upload throttling was wrong on Mac OS X, thank you [Paul](https://github.com/paulz) for the [PR](https://github.com/sitespeedio/throttle/pull/16).\n\n## 0.4.2 2018-05-30\n### Fixed\n* Catching when ifb has already been setup.\n\n## 0.4.1 2018-05-30\n### Fixed\n* Another go at trying to try/catch failing settings.\n\n## 0.4.0 2018-05-30\n### Added\n* Rewrite to async/await from promises\n\n## 0.3.0 2018-04-12\n\n### Fixed\n* Ensure setup has completed fully before returning when starting throttling with tc.\n* Always return Promises from start() and stop(), even in case of errors.\n* Typo in the CLI help\n* Simpler way to set connectivity with tc\n\n## 0.2.0 2017-10-31\n\n### Added\n* You can now see the version with --version\n* You can now use pre defined profiles.\n\n## 0.1.0 2017-10-13\n\n### Fixed\n* Always remove filters before we try to set them.\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2017 Peter Hedenskog & Tobias Lidskog\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Simulate slow network connections on Linux and Mac OS X\n\n[![Linux](https://github.com/sitespeedio/throttle/workflows/Linux/badge.svg)](https://github.com/sitespeedio/throttle/actions/workflows/linux.yml)\n[![OSX](https://github.com/sitespeedio/throttle/workflows/OSX/badge.svg)](https://github.com/sitespeedio/throttle/actions/workflows/osx.yml)\n[![Docker](https://github.com/sitespeedio/throttle/workflows/Run%20Docker/badge.svg)](https://github.com/sitespeedio/throttle/actions/workflows/docker.yml)\n\nInspired by [tylertreat/Comcast](https://github.com/tylertreat/Comcast), the [connectivity setting in the WPTAgent](https://github.com/WPO-Foundation/wptagent/blob/master/internal/traffic_shaping.py) and [sltc](https://github.com/sitespeedio/sltc).\n\nThrottle uses *pfctl* on Mac and *tc* on Linux to simulate different network speeds. On Linux you also need *ip* for Throttle to work (install using `sudo apt-get install -y net-tools`).\n\nYou can set the download/upload speed and/or RTT. Upload/download is in kbit/s and RTT in ms.\n\nUse with [latest NodeJS LTS](https://nodejs.org/en/).\n\n## Install\n\n```\nnpm install @sitespeed.io/throttle -g\n```\n\nOn OSX, add these lines to ```/etc/pf.conf``` if they don't exist, to prevent the ```pfctl: Syntax error in config file: pf rules not loaded``` error when you try to run throttle\n\n```\npf_enable=\"YES\"\npflog_enable=\"YES\"\n```\n\nOn Linux you need to make sure *ip* and *route* is installed (install using `sudo apt-get install -y net-tools`).\n\n## Start simulate a slower network connection\n\nHere is an example for running with 3G connectivity. Remember: Throttle will use sudo so your user will need sudo rights.\n\n```\nthrottle --up 330 --down 780 --rtt 200\n```\n\n## Pre made profiles\nTo make it easier we have pre made profiles, check them out by *throttle --help*:\n\n```\n--profile         Premade profiles, set to one of the following\n                     3g: up:768 down:1600 rtt:150\n                     3gfast: up:768 down:1600 rtt:75\n                     3gslow: up:400 down:400 rtt:200\n                     2g: up:256 down:280 rtt:400\n                     cable: up:1000 down:5000 rtt:14\n                     dsl: up:384 down:1500 rtt:25\n                     3gem: up:400 down:400 rtt:200\n                     4g: up:9000 down:9000 rtt:85\n                     lte: up:12000 down:12000 rtt:35\n                     edge: up:200 down:240 rtt:420\n                     dial: up:30 down:49 rtt:60\n                     fois: up:5000 down:20000 rtt:2\n```\n\nYou can start throttle with one of the premade profiles:\n\n```\nthrottle --profile 3gslow\n```\n\nor even simpler\n```\nthrottle 3gslow\n```\n\n## Add packet loss\n\nBy default there's no packet loss. That is by design: If you want to use Throttle and have the same network speed, packet loss is no good. However if you want to simalate a really crappy network you probably want to add packet loss. You do that with the `--packetLoss` option. You set the packet loss in percent.\n\n```\nthrottle --profile 3gslow --packetLoss 5\n```\n\n\n## Use a configuration file\nYou can also use a configuration file with your settings. Use `--config` to map your config file to throttle.\n\nconfig.json\n```json\n{\n    \"up\": 330 ,\n    \"down\": 200,\n    \"rtt\": 1000\n}\n```\n\nAnd then run:\n```\nthrottle --config config.json\n```\n\n## Stop simulate the network\nStopping is as easy as giving the parameter *stop* to throttle.\n\n```\nthrottle --stop\n```\n\nor\n\n```\nthrottle stop\n```\n\n## Add delay on your localhost \nThis is useful if you test a local web server or run [WebPageReplay](https://github.com/catapult-project/catapult/blob/master/web_page_replay_go/README.md) and want to add some latency to your tests.\n\n```\nthrottle --rtt 200 --localhost\n```\n\n## Stop adding delay on localhost\n\n```\nthrottle --stop --localhost\n```\n\n## Use directly in NodeJS\n\n```javascript\nimport { start, stop } from '@sitespeed.io/throttle'\n// Returns a promise\nstart({up: 360, down: 780, rtt: 200}).then(() => ...\n```\n\nor\n\n```javascript\nimport { start, stop } from '@sitespeed.io/throttle'\nconst options = {up: 360, down: 780, rtt: 200};\nawait start(options);\n// Do your thing and then stop\nawait stop();\n```\n\n## Log all commands\nYou can log all the commands that sets up the throttling by setting `LOG_THROTTLE=true`.\n\n```\nLOG_THROTTLE=true throttle 3gslow\n```\n\nor \n\n```\nthrottle 3gslow --log\n```\n\n## Run in Docker (on Linux)\n\nMake sure to run ```sudo modprobe ifb numifbs=1``` before you start the container.\n\nAnd then when you actually start your Docker container, give it the right privileges with ```--cap-add=NET_ADMIN```.\n"
  },
  {
    "path": "bin/index.js",
    "content": "#!/usr/bin/env node\n\nimport { readFileSync } from 'node:fs';\nimport minimist from 'minimist';\nimport { stop, start } from '../lib/index.js';\nimport { createRequire } from 'node:module';\nconst require = createRequire(import.meta.url);\nconst version = require('../package.json').version;\n\nconst profiles = {\n  '3g': {\n    down: 1600,\n    up: 768,\n    rtt: 150\n  },\n  '3gfast': {\n    down: 1600,\n    up: 768,\n    rtt: 75\n  },\n  '3gslow': {\n    down: 400,\n    up: 400,\n    rtt: 200\n  },\n  '2g': {\n    down: 280,\n    up: 256,\n    rtt: 400\n  },\n  cable: {\n    down: 5000,\n    up: 1000,\n    rtt: 14\n  },\n  dsl: {\n    down: 1500,\n    up: 384,\n    rtt: 25\n  },\n  '3gem': {\n    down: 400,\n    up: 400,\n    rtt: 200\n  },\n  '4g': {\n    down: 9000,\n    up: 9000,\n    rtt: 85\n  },\n  lte: {\n    down: 12_000,\n    up: 12_000,\n    rtt: 35\n  },\n  edge: {\n    down: 240,\n    up: 200,\n    rtt: 420\n  },\n  dial: {\n    down: 49,\n    up: 30,\n    rtt: 60\n  },\n  fois: {\n    down: 20_000,\n    up: 5000,\n    rtt: 2\n  }\n};\n\nconst argv = minimist(process.argv.slice(2), {\n  boolean: ['stop', 'localhost']\n});\n\nasync function run(argv) {\n  if (argv.help || argv._[0] === 'help') {\n    console.log('   Set the connectivity using the throttler (pfctl/tc)');\n    console.log('   Usage: throttler [options]');\n    console.log(\n      '   If you run in Docker throttler will only work on a Linux host'\n    );\n    console.log('   In Docker make sure to run: sudo modprobe ifb numifbs=1');\n    console.log('   And run your container with --cap-add=NET_ADMIN\\n');\n    console.log('   Options:');\n    console.log('   --stop            Remove all settings');\n    console.log('   --up              Upload in Kbit/s ');\n    console.log('   --down            Download Kbit/s');\n    console.log('   --rtt             RTT in ms');\n    console.log('   --packetLoss      Packet loss in %. Default is 0');\n    console.log(\n      '   --profile         Premade profiles, set to one of the following'\n    );\n    console.log('   --config          Path to config file');\n    for (const profile of Object.keys(profiles)) {\n      console.log(\n        '                     ' +\n          profile +\n          ': ' +\n          'up:' +\n          profiles[profile].up +\n          ' down:' +\n          profiles[profile].down +\n          ' rtt:' +\n          profiles[profile].rtt\n      );\n    }\n    console.log('   --log             Log all network commands to the console');\n  } else if (argv.version) {\n    console.log(`${version}`);\n  } else {\n    if (argv.stop || argv._[0] === 'stop') {\n      const options = {\n        localhost: argv.localhost\n      };\n      await stop(options);\n      console.log('Stopped throttler');\n    } else {\n      let options;\n      if (argv.log) {\n        process.env.LOG_THROTTLE = true;\n      }\n      if (argv.profile in profiles || argv._[0] in profiles) {\n        options = profiles[argv.profile || argv._[0]];\n\n        if (argv.packetLoss) {\n          options.packetLoss = argv.packetLoss;\n        }\n\n        console.log('Using profile ' + (argv.profile || argv._[0]));\n      } else if (argv.config) {\n        try {\n          const data = readFileSync(argv.config, 'utf8');\n          options = JSON.parse(data);\n        } catch (error) {\n          console.error(error);\n          process.exitCode = 1;\n        }\n      } else {\n        options = {\n          up: argv.up,\n          down: argv.down,\n          rtt: argv.rtt,\n          localhost: argv.localhost,\n          packetLoss: argv.packetLoss || 0\n        };\n      }\n\n      try {\n        await start(options);\n        if (options.localhost) {\n          console.log(`Started throttler on localhost RTT:${options.rtt}ms `);\n        } else {\n          let message = 'Started throttler:';\n          if (options.down !== undefined) {\n            message += ` Down:${options.down}kbit/s`;\n          }\n          if (options.up !== undefined) {\n            message += ` Up:${options.up}kbit/s`;\n          }\n          if (options.rtt !== undefined) {\n            message += ` RTT:${options.rtt}ms`;\n          }\n          if (options.packetLoss !== undefined) {\n            message += ` PacketLoss:${options.packetLoss}%`;\n          }\n          console.log(message);\n        }\n      } catch (error) {\n        console.error(error);\n        process.exitCode = 1;\n      }\n    }\n  }\n}\n\nawait run(argv);\n"
  },
  {
    "path": "eslint.config.js",
    "content": "import prettier from 'eslint-plugin-prettier';\nimport unicorn from 'eslint-plugin-unicorn';\nimport globals from 'globals';\nimport js from '@eslint/js';\n\nexport default [\n  js.configs.recommended,\n  unicorn.configs.recommended,\n  {\n    plugins: {\n      prettier\n    },\n\n    languageOptions: {\n      globals: {\n        ...globals.node\n      },\n\n      ecmaVersion: 'latest',\n      sourceType: 'module'\n    },\n\n    rules: {\n      'prettier/prettier': [\n        'error',\n        {\n          singleQuote: true,\n          trailingComma: 'none'\n        }\n      ],\n\n      'no-extra-semi': 'off',\n      'no-mixed-spaces-and-tabs': 'off',\n      'no-unexpected-multiline': 'off',\n      'no-return-await': 'error',\n      'unicorn/filename-case': 'off'\n    }\n  }\n];\n"
  },
  {
    "path": "lib/execFile.js",
    "content": "import { promisify } from 'node:util';\nimport { execFile } from 'node:child_process';\nconst execFilePromisified = promisify(execFile);\n\nexport default function shell(command, options) {\n  return execFilePromisified(command, options);\n}\n"
  },
  {
    "path": "lib/index.js",
    "content": "import { platform } from 'node:os';\nimport { start as startPfctl, stop as stopPfctl } from './pfctl.js';\nimport { start as startTc, stop as stopTc } from './tc.js';\nimport {\n  start as startTcLocalhost,\n  stop as stopTcLocalhost\n} from './localHostTc.js';\nimport {\n  start as startPfctlLocalhost,\n  stop as stopPfctlLocalhost\n} from './localHostPfctl.js';\n\nfunction verify(options) {\n  if (options.localhost) {\n    if (!Number.isInteger(options.rtt)) {\n      throw new TypeError('You need to set rtt as an integer for localhost');\n    }\n  } else if (\n    (options.up && !Number.isInteger(options.up)) ||\n    (options.down && !Number.isInteger(options.down)) ||\n    (options.rtt && !Number.isInteger(options.rtt))\n  ) {\n    throw new Error('Input values needs to be integers');\n  } else if (!options.up && !options.down && !options.rtt && !options.stop) {\n    throw new Error('You need to at least set one of up/down/rtt.');\n  }\n}\n\nexport async function start(options = {}) {\n  verify(options);\n\n  switch (platform()) {\n    case 'darwin': {\n      if (options.localhost) {\n        return startPfctlLocalhost(options.rtt);\n      }\n      return startPfctl(\n        options.up,\n        options.down,\n        options.rtt,\n        options.packetLoss\n      );\n    }\n\n    case 'linux': {\n      return options.localhost\n        ? startTcLocalhost(options.rtt)\n        : startTc(options.up, options.down, options.rtt, options.packetLoss);\n    }\n\n    default: {\n      throw new Error('Platform ' + platform() + ' not supported');\n    }\n  }\n}\nexport async function stop(options = {}) {\n  switch (platform()) {\n    case 'darwin': {\n      return options.localhost ? stopPfctlLocalhost() : stopPfctl();\n    }\n\n    case 'linux': {\n      return options.localhost ? stopTcLocalhost() : stopTc();\n    }\n\n    default: {\n      throw new Error('Platform ' + platform() + ' not supported');\n    }\n  }\n}\n"
  },
  {
    "path": "lib/localHostPfctl.js",
    "content": "import sudo from './sudo.js';\nimport shell from './shell.js';\n\nexport async function start(rtt) {\n  const halfWayRTT = rtt / 2;\n\n  await stop();\n\n  await sudo('dnctl', '-q', 'flush');\n  await sudo('dnctl', '-q', 'pipe', 'flush');\n\n  await sudo(\n    'dnctl',\n    'pipe',\n    1,\n    'config',\n    'delay',\n    `${halfWayRTT}ms`,\n    'noerror'\n  );\n\n  await shell(\n    'echo \"dummynet out from any to 127.0.0.1 pipe 1\" | sudo pfctl -f -'\n  );\n\n  await sudo('pfctl', '-E');\n}\nexport async function stop() {\n  await sudo('dnctl', '-q', 'flush');\n  await sudo('dnctl', '-q', 'pipe', 'flush');\n  await sudo('pfctl', '-f', '/etc/pf.conf');\n  await sudo('pfctl', '-E');\n  await sudo('pfctl', '-d');\n}\n"
  },
  {
    "path": "lib/localHostTc.js",
    "content": "import sudo from './sudo.js';\n\nexport async function start(delay) {\n  const halfWayDelay = delay / 2;\n\n  try {\n    await stop();\n  } catch {\n    // ignore\n  }\n\n  await sudo(\n    'tc',\n    'qdisc',\n    'add',\n    'dev',\n    'lo',\n    'root',\n    'handle',\n    '1:0',\n    'netem',\n    'delay',\n    `${halfWayDelay}ms`\n  );\n}\nexport async function stop() {\n  await sudo('tc', 'qdisc', 'del', 'dev', 'lo', 'root');\n}\n"
  },
  {
    "path": "lib/pfctl.js",
    "content": "import sudo from './sudo.js';\nimport shell from './shell.js';\n\nexport async function start(up, down, rtt = 0, packetLoss = 0) {\n  const halfWayRTT = rtt / 2;\n\n  await stop();\n\n  await sudo('dnctl', '-q', 'flush');\n  await sudo('dnctl', '-q', 'pipe', 'flush');\n\n  await sudo('dnctl', 'pipe', 1, 'config', 'delay', '0ms', 'noerror');\n  await sudo('dnctl', 'pipe', 2, 'config', 'delay', '0ms', 'noerror');\n\n  await shell(\n    'echo \"dummynet in inet from any to ! 127.0.0.1 pipe 1\\n' +\n      'dummynet out inet from ! 127.0.0.1 to any pipe 2\\n' +\n      'dummynet in inet6 from any to ! ::1 pipe 1\\n' +\n      'dummynet out inet6 from ! ::1 to any pipe 2\" | sudo pfctl -f -'\n  );\n\n  if (down) {\n    const parameters = [\n      'dnctl',\n      'pipe',\n      1,\n      'config',\n      'bw',\n      `${down}Kbit/s`,\n      'delay',\n      `${halfWayRTT}ms`\n    ];\n    if (packetLoss > 0) {\n      parameters.push('plr', packetLoss / 100, 'noerror');\n    }\n    await sudo.apply(this, parameters);\n  }\n\n  if (up) {\n    await sudo(\n      'dnctl',\n      'pipe',\n      2,\n      'config',\n      'bw',\n      `${up}Kbit/s`,\n      'delay',\n      `${halfWayRTT}ms`\n    );\n  }\n\n  if (!up && !down && rtt > 0) {\n    await sudo('dnctl', 'pipe', 1, 'config', 'delay', `${halfWayRTT}ms`);\n    await sudo('dnctl', 'pipe', 2, 'config', 'delay', `${halfWayRTT}ms`);\n  }\n\n  await sudo('pfctl', '-E');\n}\nexport async function stop() {\n  await sudo('dnctl', '-q', 'flush');\n  await sudo('dnctl', '-q', 'pipe', 'flush');\n  await sudo('pfctl', '-f', '/etc/pf.conf');\n  await sudo('pfctl', '-E');\n  await sudo('pfctl', '-d');\n}\n"
  },
  {
    "path": "lib/shell.js",
    "content": "import execFile from './execFile.js';\n\nexport default function shell(command) {\n  if (process.env.LOG_THROTTLE) {\n    console.log(command);\n  }\n  return execFile(command, { shell: true });\n}\n"
  },
  {
    "path": "lib/sudo.js",
    "content": "import execFile from './execFile.js';\n\nexport default function sudo(command, ...arguments_) {\n  if (process.env.LOG_THROTTLE) {\n    console.log('sudo', command, ...arguments_);\n  }\n  return execFile('sudo', [command, ...arguments_]);\n}\n"
  },
  {
    "path": "lib/tc.js",
    "content": "import shell from './shell.js';\nimport sudo from './sudo.js';\n\nasync function getDefaultInterface() {\n  // Try the default route first\n  const routeResult = await shell(\n    \"sudo ip route | awk '/default/ {print $5; exit}' | tr -d '\\n'\"\n  );\n  if (routeResult.stdout.length > 0) {\n    return routeResult.stdout;\n  }\n\n  // Fall back to finding the interface with a global IP address,\n  // since the default route may be gone while throttling is active\n  const addrResult = await shell(\n    \"ip -o -4 addr show scope global | awk '{print $2; exit}'\"\n  );\n  if (addrResult.stdout.trim().length > 0) {\n    return addrResult.stdout.trim();\n  }\n\n  throw new Error('Could not find the default network interface');\n}\n\nasync function moduleProbe() {\n  try {\n    await sudo('modprobe', 'ifb');\n    // eslint-disable-next-line no-empty\n  } catch {}\n}\nasync function setupifb0() {\n  try {\n    // Check if ifb0 exist\n    await sudo('ip', 'link', 'show', 'ifb0');\n  } catch {\n    // Add the interface\n    await sudo('ip', 'link', 'add', 'ifb0', 'type', 'ifb');\n  }\n\n  // Bring the interface up\n  await sudo('ip', 'link', 'set', 'ifb0', 'up');\n}\n\nasync function setup(defaultInterface) {\n  await sudo('tc', 'qdisc', 'add', 'dev', defaultInterface, 'ingress');\n  await sudo(\n    'tc',\n    'filter',\n    'add',\n    'dev',\n    defaultInterface,\n    'parent',\n    'ffff:',\n    'protocol',\n    'ip',\n    'u32',\n    'match',\n    'u32',\n    '0',\n    '0',\n    'flowid',\n    '1:1',\n    'action',\n    'mirred',\n    'egress',\n    'redirect',\n    'dev',\n    'ifb0'\n  );\n  await sudo(\n    'tc',\n    'filter',\n    'add',\n    'dev',\n    defaultInterface,\n    'parent',\n    'ffff:',\n    'protocol',\n    'ipv6',\n    'u32',\n    'match',\n    'u32',\n    '0',\n    '0',\n    'flowid',\n    '1:1',\n    'action',\n    'mirred',\n    'egress',\n    'redirect',\n    'dev',\n    'ifb0'\n  );\n}\n\nasync function setLimits(up, down, halfWayRTT, packetLoss, indexFace) {\n  if (down) {\n    const parameters = [\n      'tc',\n      'qdisc',\n      'add',\n      'dev',\n      'ifb0',\n      'root',\n      'handle',\n      '1:0',\n      'netem',\n      'delay',\n      `${halfWayRTT}ms`,\n      'rate',\n      `${down}kbit`\n    ];\n\n    if (packetLoss) {\n      parameters.push('loss', `${packetLoss}%`);\n    }\n\n    await sudo.apply(this, parameters);\n  }\n  if (up) {\n    const parameters = [\n      'tc',\n      'qdisc',\n      'add',\n      'dev',\n      indexFace,\n      'root',\n      'handle',\n      '1:0',\n      'netem',\n      'delay',\n      `${halfWayRTT}ms`,\n      'rate',\n      `${up}kbit`\n    ];\n\n    if (packetLoss) {\n      parameters.push('loss', `${packetLoss}%`);\n    }\n\n    await sudo.apply(this, parameters);\n  }\n\n  if (!up && !down && halfWayRTT > 0) {\n    await sudo(\n      'tc',\n      'qdisc',\n      'add',\n      'dev',\n      'ifb0',\n      'root',\n      'handle',\n      '1:0',\n      'netem',\n      'delay',\n      `${halfWayRTT}ms`\n    );\n\n    await sudo(\n      'tc',\n      'qdisc',\n      'add',\n      'dev',\n      indexFace,\n      'root',\n      'handle',\n      '1:0',\n      'netem',\n      'delay',\n      `${halfWayRTT}ms`\n    );\n  }\n}\n\nexport async function start(up, down, rtt = 0, packetLoss = 0) {\n  const halfWayRTT = rtt / 2;\n\n  try {\n    await stop();\n  } catch {\n    // ignore\n  }\n\n  const indexFace = await getDefaultInterface();\n  await moduleProbe();\n  await setupifb0();\n  await setup(indexFace);\n  await setLimits(up, down, halfWayRTT, packetLoss, indexFace);\n}\nexport async function stop() {\n  const indexFace = await getDefaultInterface();\n\n  try {\n    try {\n      await sudo('tc', 'qdisc', 'del', 'dev', indexFace, 'root');\n      await sudo('tc', 'qdisc', 'del', 'dev', indexFace, 'ingress');\n    } catch {\n      // make sure we try to remove the ingress\n      await sudo('tc', 'qdisc', 'del', 'dev', indexFace, 'ingress');\n    }\n  } catch {\n    // ignore\n  }\n\n  try {\n    await sudo('tc', 'qdisc', 'del', 'dev', 'ifb0', 'root');\n  } catch {\n    // do nada\n  }\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"@sitespeed.io/throttle\",\n  \"version\": \"6.0.0\",\n  \"description\": \"Throttle your connection\",\n  \"type\": \"module\",\n  \"exports\": \"./lib/index.js\",\n  \"engines\": {\n    \"node\": \">=14.16\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/sitespeedio/throttle.git\"\n  },\n  \"keywords\": [\n    \"latency\",\n    \"throttle\",\n    \"bandwith\",\n    \"webperf\",\n    \"perfmatters\"\n  ],\n  \"author\": {\n    \"name\": \"Peter Hedenskog\",\n    \"url\": \"https://www.peterhedenskog.com\"\n  },\n  \"contributors\": [\n    {\n      \"name\": \"Tobias Lidskog\"\n    },\n    {\n      \"name\": \"Jonathan Lee\"\n    }\n  ],\n  \"license\": \"MIT\",\n  \"bugs\": {\n    \"url\": \"https://github.com/sitespeedio/throttle/issues\"\n  },\n  \"homepage\": \"https://www.sitespeed.io\",\n  \"devDependencies\": {\n    \"@eslint/js\": \"10.0.1\",\n    \"eslint\": \"10.1.0\",\n    \"eslint-plugin-prettier\": \"5.5.5\",\n    \"eslint-plugin-unicorn\": \"63.0.0\",\n    \"globals\": \"17.4.0\",\n    \"prettier\": \"3.8.1\"\n  },\n  \"dependencies\": {\n    \"minimist\": \"1.2.8\"\n  },\n  \"scripts\": {\n    \"lint\": \"eslint .\",\n    \"lint:fix\": \"eslint . --fix\"\n  },\n  \"bin\": \"./bin/index.js\",\n  \"main\": \"./lib/index.js\"\n}\n"
  },
  {
    "path": "release.sh",
    "content": "#!/bin/bash\nset -e\n\n\n# Super simple release script for sitespeed.io\n# Lets use it it for now and make it better over time :)\n# You need np for this to work\n# npm install --global np\nnp $1  --any-branch \n\n# Update the docs with latest release number\nbin/index.js --version  > ../sitespeed.io/docs/_includes/version/throttle.txt"
  },
  {
    "path": "test/Dockerfile",
    "content": "FROM sitespeedio/node:ubuntu-20.04-nodejs-16.5.0\n\nRUN apt-get update && apt-get install libnss3-tools iproute2 sudo net-tools -y\nRUN mkdir -p /usr/src/app\n\nVOLUME /throttle\nWORKDIR /usr/src/app\n\nCOPY package.json /usr/src/app/\nCOPY package-lock.json /usr/src/app/\nRUN npm install --production\nCOPY . /usr/src/app\n\nCOPY test/start.sh /start.sh\n\nENTRYPOINT [\"/start.sh\"]\n"
  },
  {
    "path": "test/config.json",
    "content": "{\n    \"up\": 330 ,\n    \"down\": 200,\n    \"rtt\": 1000\n}"
  },
  {
    "path": "test/start.sh",
    "content": "#!/bin/bash\nset -e\n\n## Start/stop a couple of times\nbin/index.js --profile 3gslow\nbin/index.js --stop\nbin/index.js --profile cable\nbin/index.js --stop"
  }
]