[
  {
    "path": ".gitattributes",
    "content": "# Auto detect text files and perform LF normalization\n* text=auto\n\n# Custom for Visual Studio\n*.cs     diff=csharp\n\n# Standard to msysgit\n*.doc\t diff=astextplain\n*.DOC\t diff=astextplain\n*.docx diff=astextplain\n*.DOCX diff=astextplain\n*.dot  diff=astextplain\n*.DOT  diff=astextplain\n*.pdf  diff=astextplain\n*.PDF\t diff=astextplain\n*.rtf\t diff=astextplain\n*.RTF\t diff=astextplain\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/ad-blocking-support.md",
    "content": "---\nname: Ad blocking support\nabout: For if you're seeing ads. Request help with manually identifying ad CSS selectors\ntitle: ''\nlabels: Ad Blocking\nassignees: ''\n\n---\n\n## Please provide a screenshot of the ad or content that you think should be blocked. No support will be given until one is provided.\n\nAds are blocked based on a combination CSS selectors and text strings or regex patterns. Typically, all you need to provide is an example of the ad in a screenshot and I will be able to verify and add a rule to the list. If possible, it would also help if you are able to add a custom rule under the advanced options and provide a screenshot verifying it works. If unsure, a reliable, but slow, selector to use would be `div,span,a`\n\nFacebook doesn't give every person the same version of code that displays the site. They do this for various reasons, such as testing new features on just some users before rolling them out to everyone, or for some content that is only available in certain countries.\nBecause of this, what works for me, may not work for you. Since I am only able to work with what Facebook gives me personally, there is no way for me to investigate other users' issues that aren't also present for me.\nIt's possible that if you wait for a little while, I might start getting the same version as you, and will be able to fix the problem on my own. Otherwise, the only way to find the solution is if you do so yourself.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug Report\nabout: Report broken functionality or other problems with the extension\ntitle: ''\nlabels: bug\nassignees: ''\n\n---\n\n# Requests about ads not being hidden will be closed without response. Follow the instructions in the \"Ad blocking support\" template for that.\n\n**Describe the bug**\nA clear and concise description of what the bug is.\n\n**To Reproduce**\nSteps to reproduce the behavior:\n1. Go to '...'\n2. Click on '....'\n3. Scroll down to '....'\n4. See error\n\n**Expected behavior**\nA clear and concise description of what you expected to happen.\n\n**Screenshots**\nIf applicable, add screenshots to help explain your problem.\n\n**Please provide the following information:**\n - Device: [e.g. Desktop, iPhone6, etc.]\n - OS: [e.g. Windows, Linux, iOS]\n - Browser [e.g. firefox, chrome]\n - Extension Version [e.g. 1.6.1]\n - Extension Options\n\n**Additional context**\nAdd any other context about the problem here.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: Feature Request\nabout: Suggest an idea for this project\ntitle: ''\nlabels: enhancement\nassignees: ''\n\n---\n\n**Is your feature request related to a problem? Please describe.**\nA clear and concise description of what the problem is. Ex. I'm always frustrated when [...]\n\n**Describe the solution you'd like**\nA clear and concise description of what you want to happen.\n\n**Describe alternatives you've considered**\nA clear and concise description of any alternative solutions or features you've considered.\n\n**Additional context**\nAdd any other context or screenshots about the feature request here.\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "# Please see the documentation for all configuration options:\n# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates\n\nversion: 2\nupdates:\n  - package-ecosystem: \"github-actions\" # See documentation for possible values\n    directory: \"/\" # Location of package manifests\n    schedule:\n      interval: \"weekly\"\n  - package-ecosystem: \"gitsubmodule\"\n    directory: \"/\"\n    schedule:\n      interval: \"weekly\"\n"
  },
  {
    "path": ".github/workflows/codeql.yml",
    "content": "# For most projects, this workflow file will not need changing; you simply need\n# to commit it to your repository.\n#\n# You may wish to alter this file to override the set of languages analyzed,\n# or to provide custom queries or build logic.\n#\n# ******** NOTE ********\n# We have attempted to detect the languages in your repository. Please check\n# the `language` matrix defined below to confirm you have the correct set of\n# supported CodeQL languages.\n#\nname: \"CodeQL\"\n\non:\n  workflow_dispatch:\n  push:\n    branches: [ master ]\n    paths: [ 'src/**' ]\n  pull_request:\n    # The branches below must be a subset of the branches above\n    branches: [ master ]\n    paths: [ 'src/**' ]\n\njobs:\n  analyze:\n    name: Analyze\n    runs-on: ubuntu-latest\n    permissions:\n      actions: read\n      contents: read\n      security-events: write\n\n    strategy:\n      fail-fast: false\n      matrix:\n        language: [ 'javascript' ]\n        # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]\n        # Learn more about CodeQL language support at https://git.io/codeql-language-support\n\n    steps:\n    - name: Checkout repository\n      uses: actions/checkout@v6\n\n    # Initializes the CodeQL tools for scanning.\n    - name: Initialize CodeQL\n      uses: github/codeql-action/init@v4\n      with:\n        languages: ${{ matrix.language }}\n        # If you wish to specify custom queries, you can do so here or in a config file.\n        # By default, queries listed here will override any specified in a config file.\n        # Prefix the list here with \"+\" to use these queries and those in the config file.\n        # queries: ./path/to/local/query, your-org/your-repo/queries@main\n\n    - name: Perform CodeQL Analysis\n      uses: github/codeql-action/analyze@v4\n"
  },
  {
    "path": ".github/workflows/mirror-gitlab.yml",
    "content": "name: Mirror to Gitlab\n\non:\n  workflow_dispatch:\n  push:\n    branches: [master]\n\njobs:\n  mirror:\n    name: Mirror\n    runs-on: ubuntu-latest\n    permissions:\n      contents: read\n\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@v6\n        with:\n          fetch-depth: 0\n\n      - name: Setup SSH\n        env:\n          GITLAB_PUSH_KEY: ${{ secrets.GITLAB_PUSH_KEY }}\n        run: |\n          mkdir -p ~/.ssh/\n          chmod 700 ~/.ssh/\n          echo \"$GITLAB_PUSH_KEY\" > ~/.ssh/push_key\n          chmod 400 ~/.ssh/push_key\n\n      - name: Push to Gitlab\n        env:\n          GIT_SSH_COMMAND: ssh -v -i ~/.ssh/push_key -o IdentitiesOnly=yes -o StrictHostKeyChecking=no\n        run: git push --force --prune git@gitlab.com:mgziminsky/FacebookTrackingRemoval.git master refs/tags/*\n"
  },
  {
    "path": ".gitignore",
    "content": "_metadata/\n*.zip\nbrowser-polyfill.min.js*\nwebextension-polyfill/package-lock.json\n"
  },
  {
    "path": ".gitlab-ci.yml",
    "content": "image: alpine:latest\n\npages:\n  stage: deploy\n  script:\n    - mv data public\n  artifacts:\n    paths:\n      - public\n  rules:\n    - if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH\n      changes:\n        - data/**/*\n"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"webextension-polyfill\"]\n\tpath = webextension-polyfill\n\turl = https://github.com/mozilla/webextension-polyfill.git\n"
  },
  {
    "path": ".vscode/extensions.json",
    "content": "{\n\t// See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.\n\t// Extension identifier format: ${publisher}.${name}. Example: vscode.csharp\n\t// List of extensions which should be recommended for users of this workspace.\n\t\"recommendations\": [\n\t\t\"firefox-devtools.vscode-firefox-debug\",\n\t\t\"biomejs.biome\"\n\t],\n\t// List of extensions recommended by VS Code that should not be recommended for users of this workspace.\n\t\"unwantedRecommendations\": []\n}\n"
  },
  {
    "path": ".vscode/html.html-data.json",
    "content": "{\n    \"version\": 1.1,\n    \"tags\": [\n        {\n            \"name\": \"fbtr-i18n\",\n            \"description\": \"Renders translation string specified by `key` as html\",\n            \"attributes\": [\n                {\n                    \"name\": \"key\"\n                }\n            ]\n        }\n    ],\n    \"globalAttributes\": [\n        {\n            \"name\": \"data-i18n\",\n            \"description\": \"Translation key of which the value will be assigned to the attribute specified by [data-i18n-attr], or [title] if not specified\"\n        },\n        {\n            \"name\": \"data-i18n-attr\",\n            \"description\": \"Name of attribute that will be assigned the value of the translation specified in [data-i18n]\"\n        },\n        {\n            \"name\": \"data-i18n-vars\",\n            \"description\": \"Values of any variables needed by translation specified by [data-i18n]; Multiple values are separated by ||\"\n        }\n    ]\n}\n"
  },
  {
    "path": ".vscode/launch.json",
    "content": "{\n    // Use IntelliSense to learn about possible attributes.\n    // Hover to view descriptions of existing attributes.\n    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387\n    \"version\": \"0.2.0\",\n    \"configurations\": [\n        {\n            \"name\": \"Launch WebExtension\",\n            \"type\": \"firefox\",\n            \"request\": \"launch\",\n            \"reAttach\": true,\n            \"addonPath\": \"${workspaceFolder}\",\n            \"reloadOnChange\": {\n                \"watch\": [\n                    \"${workspaceFolder}/manifest.json\",\n                    \"${workspaceFolder}/src/background.js\",\n                    \"${workspaceFolder}/_locales/**/messages.json\",\n                ],\n            },\n            \"showConsoleCallLocation\": false,\n            \"tabFilter\": \"https://*.facebook.com/*\"\n        }\n    ]\n}\n"
  },
  {
    "path": ".vscode/settings.json",
    "content": "{\n    \"firefox.args\": [\n        \"about:debugging#/runtime/this-firefox\",\n        \"about:addons\",\n        \"https://www.facebook.com/\",\n    ],\n    \"html.customData\": [\n        \".vscode/html.html-data.json\",\n    ],\n    \"licenser.useSingleLineStyle\": false,\n    \"licenser.license\": \"GPLv3\",\n\n    \"[javascript]\": {\n        \"editor.codeActionsOnSave\": {\n            \"source.organizeImports.biome\": \"explicit\"\n        },\n    },\n    \"[javascript][json][jsonc][typescript]\": {\n        \"editor.defaultFormatter\": \"biomejs.biome\"\n    },\n    \"files.associations\": {\n        \"**/FacebookTrackingRemoval/data/**/*\": \"plaintext\"\n    }\n\n    // \"json.schemas\": [{\n    //     \"url\": \"https://json.schemastore.org/chrome-manifest.json\",\n    //     \"fileMatch\": [\"/manifest.json\"]\n    // }]\n}\n"
  },
  {
    "path": "CHANGELOG",
    "content": "v1.13.0\n- New option to detect ads with canvas labels (Default: Enabled)\n\nv1.12.0\n- Migrate to manifest v3\n\nv1.11.3\n- Link cleaning fix for FF115+\n\nv1.11.2\n- More svg label handling adjustments\n\nv1.11.1\n- Fix split text in svg labels\n\nv1.11.0\n- Refactored project into ES modules\n- Options changes are applied without a page reload\n- Existing rules won't be replaced by bundled copies in case of network errors\n- Fixes and supporting code for marketplace ads\n\nv1.10.4\n- Fix ad detection. Handle svg/aria trickery.\n\nv1.10.3\n- Fix mention completion popup - closes #62\n\nv1.10.2\n- Fix custom user rules under advanced options\n\nv1.10.1\n- Fix feed breaking when \"Hide method\" set to \"Remove\"\n\nv1.10.0.1\n- Remove marketplace sponsored\n- Themed options\n- Backend code improvements and changes\n\nv1.9.3\n- Don't block the heartbeat ping. FB disables things when it fails\n\nv1.9.2\n- Fix some internal links not being cleaned\n\nv1.9.1\n- Fix rules not updating\n\nv1.9.0\n- Remove legacy static matching and integrate functionality into content-based matching\n- Don't strip spaces from text used for content hiding rules - Closes #45\n\nv1.8.10\n- Fix some navigation issues with internal link cleaning enabled - closes #44\n\nv1.8.9\n- Block additional background tracking and metrics submission\n- Fix video volume adjustment slider - closes #43\n\nv1.8.8\n- Load at document_end again for hiding sidebar sponsored\n\nv1.8.7\n- Fix automatic page reload on options changes\n- Fix comment input not clickable, and maybe others. Closes #37\n\nv1.8.6\n- French translation provided by gatinhonico\n\nv1.8.5\n- Internal link cleaning fixes and improvements\n- Run properly on pages that are loaded in IFrames\n- Fix processing that should happen at initial page load\n- Bump min required version to FF 59\n\nv1.8.4\n- Fix infinite event recursion caused by links with a nested fbclid\n\nv1.8.3\n- Use smart detection for Suggested Posts\n\nv1.8.2\n- Better smart sponsored detection\n\nv1.8.1\n- Update to work with new FB design\n- Smarter sponsored post detection\n- Big performance improvement\n- Update default style to not break layout\n\nv1.8.0.2\n- Force refresh rules on upgrade\n- Improved performance, hopefully by a noticeable amount\n\nv1.7.1\n- Improved performance\n\nv1.7.0\n- No more tabs permission\n- Style changes now happen without reloading the page\n\nv1.6.9\n- Detect new form of sponsored posts\n- Improve performace when styling is enabled\n\nv1.6.8.1\n- Fix minor bug when cleaning link info bubble\n- Fix fallback rule loading for whitelisted clicks and param cleaning\n\nv1.6.7\n- Fix extension not working at all when \"Fix external links\" is disabled\n- Add more details to log when something is hidden/removed\n\nv1.6.6\n- Support messenger.com - Closes #27\n\nv1.6.5\n- Fixes for parts of messenger page - Closes #26\n- Prevent FB from resetting links after they've been cleaned\n\nv1.6.4\n- Internal code improvements and bug fixes\n- Moved remaining hard-coded data to hosting to support easier updates without version bumps\n\nv1.6.3\n- Fix reactions in chat and some breakages caused by internal link cleaning. Closes #25\n- Remove some new internal tracking parameters\n\nv1.6.2\n- Slightly smarter sponsored identification\n\nv1.6.1\n- Remove fbclid from links - Closes #20\n\nv1.6.0\n- New advanced option for custom, user defined ad hiding rules\n- Block requests to pixel.facebook.com\n- Per-option reset and various other options enhancements\n- Load ad hiding rules from web. No more version bumps just for selector changes.\n\nv1.5.18\n- Fix stickers, gifs, and games in chat. Closes #17\n- Fix sponsored post removal deleting everything. Closes #18\n\nv1.5.17\n- More clickable fixes\n\nv1.5.16\n- Fix potential XSS vulnerability (Thanks Bennett from EFF)\n- Fix a couple more clickables\n\nv1.5.15\n- Don't hide/remove group management controls; Closes issue #13\n- Fix various clickable components; Closes issue #15\n- General improvements to internal link cleaning\n\nv1.5.14\n- Fix regression in user interactions\n- Minor performace improvements\n- Remove desktop video cleaning option until I find a solution to the broken videos\n\nv1.5.13\n- Block ajax tracking requests. Closes issue #10\n\nv1.5.12\n- Sync options pages\n- Fix auto page reload in chrome and FF 60+\n- New classes for Sponsored and Suggested posts\n\nv1.5.11\n- Update to work on FB tor/onion service\n- Add rel=noreferrer to cleaned links\n\nv1.5.10\n- Hide \"Suggested Shows\"\n- Don't hide emergency broadcasts such as Amber Alerts and highlight them red\n\nv1.5.9\n- Fix for some links not getting cleaned\n\nv1.5.8\n- Handle new class of \"Sponsored\"\n- Handle additional type of internal link\n\nv1.5.7\n- Handle new class of \"Suggested Posts\"\n\nv1.5.6\n- Fix external links on mobile\n- Improved mobile video inlining\n\nv1.5.5\n- Strip __md__ param from internal links\n- Handle new \"SponSsored\" posts\n    * FB has been trying to get sneaky with their sponsored posts lately. First by setting the text\n      using CSS, and now misspelled with the extra letter hidden.\n\nv1.5.4\n- Fix GIFs not playing (issue #4)\n- Disable styling by default\n\nv1.5.3\n- Fix Sponsored hiding\n- Fix Mobile hiding\n- Include new \"Suggested Post\" class\n- Hide suggestions on photo overlay\n\nv1.5.2\n- Hide \"Page Stories You May Like\"\n- Hide \"Games You May Like\"\n- Disable hiding \"Sponsored Articles\" by default. No longer works correctly.\n\nv1.5.1\n- Hide \"Related Articles\" and \"Popular Across Facebook\"\n\nv1.5.0\n- Remove cross-device sync option. It needed some enhancements, but I didn't feel the feature was useful\n- Add option to enable/disable the plugin entirely\n\nv1.4.3\n- Preserve existing element styles\n\nv1.4.2\n- Ad blocking enabled by default\n- Improved internal link cleaning\n\nv1.4.1\n- Option to remove referrer tracking on internal links\n- Auto refresh Facebook™ pages after changing options\n- Improved sidebar ad blocking\n\nv1.4.0\n- Add icon and options page action\n- Fixes for mobile\n- Option to sync options across devices [FF 53+]\n\nv1.3.9\n- Hide \"A video you may like\"\n\nv1.3.8\n- Hide \"People You May Know\"\n- Use HTML5 details for collapsing posts\n\nv1.3.7\n- Hide sponsored ads panel\n- Fix non-link click tracking prevention\n- Fix options reset\n\nv1.3.6\n- Fix suggested posts not being removed\n- Add option to collapse suggested posts and sponsored/pixeled articles instead of remove\n- Changed default for some settings\n\nv1.3.5\n- Fix buttons in certain overlays not being clickable\n\nv1.3.4\n- Option to remove inline suggestions\n- Fix buttons on menus in the settings not being clickable\n- Fix logging option not showing proper state on options page\n\nv1.3.3\n- Fix Facebook page links no longer opening in an overlay.\n\nv1.3.2\n- Fix mobile article links not being clickable\nBUG - Facebook page links that are meant to open in an overlay instead open in a new window/tab\n\nv1.3.1\n- Make log messages optional\n\nv1.3.0\n- Add support for mobile site\n- Add a link to the options page to the menu on mobile site\n- Option to remove pixeled articles like \"Suggested Posts\"\n- Options page improvements\n\nv1.2.0\n- Add support for videos\n- Add options to enable/disable link and video tracking removal independently\n- Misc code cleanup\n\nv1.1.1\n- Make backwards compatible with older FF\n- Make style applied to 'fixed' links configurable\n\nv1.1.0 (FF v48+ only)\n- Add options page with outline toggle\n\nv1.0.0:\n- Remove link tracking and add green dashed border to fixed links.\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "[![GitHub release (latest by date)](https://img.shields.io/github/v/release/mgziminsky/FacebookTrackingRemoval?logo=github)](https://github.com/mgziminsky/FacebookTrackingRemoval/releases/latest)\n[![GitHub release (latest by date)](https://img.shields.io/github/downloads/mgziminsky/FacebookTrackingRemoval/latest/total)](https://github.com/mgziminsky/FacebookTrackingRemoval/releases/latest)\n[![GitHub release (total)](https://img.shields.io/github/downloads/mgziminsky/FacebookTrackingRemoval/total)](https://github.com/mgziminsky/FacebookTrackingRemoval/releases)\n\n[![Mozilla Add-on](https://img.shields.io/amo/v/facebook-tracking-removal.svg?logo=firefoxbrowser)](https://addons.mozilla.org/addon/facebook-tracking-removal?src=external-github)\n[![Mozilla Add-on](https://img.shields.io/amo/d/facebook-tracking-removal.svg)](https://addons.mozilla.org/addon/facebook-tracking-removal?src=external-github)\n[![Mozilla Add-on](https://img.shields.io/amo/users/facebook-tracking-removal.svg)](https://addons.mozilla.org/addon/facebook-tracking-removal?src=external-github)\n[![Mozilla Add-on](https://img.shields.io/amo/stars/facebook-tracking-removal.svg)](https://addons.mozilla.org/addon/facebook-tracking-removal/reviews?src=external-github)\n\n[![Chrome Web Store](https://img.shields.io/chrome-web-store/v/ldeofbdmhnnocclkaddcnamhbhanaiaj.svg?logo=googlechrome)](https://chrome.google.com/webstore/detail/facebook-tracking-ad-remo/ldeofbdmhnnocclkaddcnamhbhanaiaj)\n[![Chrome Web Store](https://img.shields.io/chrome-web-store/users/ldeofbdmhnnocclkaddcnamhbhanaiaj.svg)](https://chrome.google.com/webstore/detail/facebook-tracking-ad-remo/ldeofbdmhnnocclkaddcnamhbhanaiaj)\n[![Chrome Web Store](https://img.shields.io/chrome-web-store/rating-count/ldeofbdmhnnocclkaddcnamhbhanaiaj.svg)](https://chrome.google.com/webstore/detail/facebook-tracking-ad-remo/ldeofbdmhnnocclkaddcnamhbhanaiaj)\n[![Chrome Web Store](https://img.shields.io/chrome-web-store/stars/ldeofbdmhnnocclkaddcnamhbhanaiaj.svg)](https://chrome.google.com/webstore/detail/facebook-tracking-ad-remo/ldeofbdmhnnocclkaddcnamhbhanaiaj)\n\n\n# Facebook™ Tracking & Ad Removal\nRemoves Ads and the user interaction tracking from content on Facebook™.\nModified elements can optionally have a custom CSS style applied to them so that cleaned items can be more easily identified.\n\nFor links, the event listeners on the link and its parents are removed and/or disabled and a proper href is set on the link.\n\nFor videos on mobile, all Facebook™ event-listeners and custom controls are removed, and the video is simplified into just the bare HTML5 video tag.\n\n## Explanation of permissions: ![GitHub manifest.json dynamic](https://img.shields.io/github/manifest-json/permissions/mgziminsky/FacebookTrackingRemoval?label=Permissions)\n- Access to `facebook.com`, `messenger.com`, and `facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion` is needed for main functionality, in order to work on those pages.\n- Access to `mgziminsky.gitlab.io`, more specifically `https://mgziminsky.gitlab.io/FacebookTrackingRemoval/*`, is used to download blocking rules only\n- `webNavigation`: Needed to handle cleaning FB interactions that use the browser history API instead of doing a normal page navigation\n  - Firefox: \"Access browser activity during navigation\"\n  - Chrome: \"Read your browsing history\"\n    - This is misleading. See [here](https://github.com/mgziminsky/FacebookTrackingRemoval/issues/67#issuecomment-1346953059)\n\n## Privacy Policy\nI don't, and never will, collect or send any data to myself or any third parties\n"
  },
  {
    "path": "_locales/en/messages.json",
    "content": "{\n    \"extensionName\": {\n        \"message\": \"Tracking & Ad Removal on FaceBk\",\n        \"description\": \"Name of the extension.\"\n    },\n    \"extensionDescription\": {\n        \"message\": \"Removes Ads and the user interaction tracking from content on Facebook™\",\n        \"description\": \"Description of the extension.\"\n    },\n    \"optsTitle\": {\n        \"message\": \"Tracking & Ad Removal for Facebook™ Options\",\n        \"description\": \"Options page title\"\n    },\n    \"optsLegend\": {\n        \"message\": \"Options\"\n    },\n    \"optsReloadNotice\": {\n        \"message\": \"Changes will be applied when this options page is closed\",\n        \"description\": \"Options page notice about when changes will be applied\"\n    },\n    \"optsEnabled\": {\n        \"message\": \"Enabled\"\n    },\n    \"optsFixLinks\": {\n        \"message\": \"Remove tracking from external links\"\n    },\n    \"optsInternal\": {\n        \"message\": \"Remove tracking values from internal links <em>(If something breaks, try disabling this first)</em>\"\n    },\n    \"optsInlineVids\": {\n        \"message\": \"Inline videos on mobile <em>(Only affects mobile; May increase data usage)</em>\"\n    },\n    \"optsPixeled\": {\n        \"message\": \"Hide Sponsored articles\"\n    },\n    \"optsSuggest\": {\n        \"message\": \"Hide inline suggestions <em>(eg: Suggested Posts, People You May Know)</em>\"\n    },\n    \"optsHideMethod\": {\n        \"message\": \"Hide method:\"\n    },\n    \"optsCollapse\": {\n        \"message\": \"Collapse\"\n    },\n    \"optsRemove\": {\n        \"message\": \"Remove\"\n    },\n    \"optsUseStyle\": {\n        \"message\": \"Add styling to modified elements\"\n    },\n    \"optsAdvanced\": {\n        \"message\": \"Advanced Options\"\n    },\n    \"optsStyleLabel\": {\n        \"message\": \"Custom CSS style to be added to modified elements:\"\n    },\n    \"optsStylePreview\": {\n        \"message\": \"STYLE PREVIEW\"\n    },\n    \"optsUserRules\": {\n        \"message\": \"Custom CSS selectors to hide, one per-line. <em>FOR TESTING PURPOSES ONLY</em>\"\n    },\n    \"optsUserRulesHover\": {\n        \"message\": \"If you identify a new selector, please submit it in a PR\"\n    },\n    \"optsUserRulesPlaceholder\": {\n        \"message\": \"/* Syntax: css-selector[||innerText|/regex/,..] */\\na>span:only-of-type,.someClass||Sponsored||/suggest(ed)?/\\n.alwaysHideThis\"\n    },\n    \"optsPending\": {\n        \"message\": \"Enable pending/unconfirmed hiding rules\"\n    },\n    \"optsPendingLink\": {\n        \"message\": \"View list here\"\n    },\n    \"optsLogging\": {\n        \"message\": \"Display log messages in the console\"\n    },\n    \"optsRefresh\": {\n        \"message\": \"Refresh Rules\"\n    },\n    \"optsRefreshHover\": {\n        \"message\": \"Only once per $1 minutes\",\n        \"description\": \"Rule refresh cooldown message\"\n    },\n    \"optsDefaults\": {\n        \"message\": \"Restore Defaults\"\n    },\n    \"optsResetTitle\": {\n        \"message\": \"Default\"\n    },\n    \"optsResetAlt\": {\n        \"message\": \"Reset\"\n    },\n    \"optsCanvas\": {\n        \"message\": \"Attempt detection of ads that use images for their label\"\n    },\n    \"optsSensitivity\": {\n        \"message\": \"Image detection sensitivity\"\n    },\n    \"optsSenseHover\": {\n        \"message\": \"Higher for stricter matching, lower for looser matching\"\n    }\n}\n"
  },
  {
    "path": "_locales/fr/messages.json",
    "content": "{\n    \"extensionName\": {\n        \"message\": \"Suppression des publicités et de la surveillance sur FaceBk\",\n        \"description\": \"Nom du module complémentaire.\"\n    },\n    \"extensionDescription\": {\n        \"message\": \"Supprime les publicités et la surveillance des interactions des utilisateurs du site web Facebook™\",\n        \"description\": \"Description du module complémentaire.\"\n    },\n    \"optsTitle\": {\n        \"message\": \"Options du module complémentaire Suppression des publicités et de la surveillance pour Facebook™\",\n        \"description\": \"Titre de la page des options\"\n    },\n    \"optsLegend\": {\n        \"message\": \"Options\"\n    },\n    \"optsEnabled\": {\n        \"message\": \"Activé\"\n    },\n    \"optsFixLinks\": {\n        \"message\": \"Supprimer la surveillance des liens vers l'extérieur du site\"\n    },\n    \"optsInternal\": {\n        \"message\": \"Supprimez les valeurs pour contrer la surveillance des liens internes au site <em>(si quelque chose se casse, essayez de le désactiver d'abord)</em>\"\n    },\n    \"optsInlineVids\": {\n        \"message\": \"Vidéos en ligne sur mobile <em>(n'affecte que les mobiles; peut augmenter l'utilisation des données)</em>\"\n    },\n    \"optsPixeled\": {\n        \"message\": \"Masquer les articles sponsorisés\"\n    },\n    \"optsSuggest\": {\n        \"message\": \"Masquer les suggestions en ligne <em>(par exemple: messages suggérés, personnes que vous connaissez peut-être)</em>\"\n    },\n    \"optsHideMethod\": {\n        \"message\": \"Méthode de dissimulation:\"\n    },\n    \"optsCollapse\": {\n        \"message\": \"Effondrement\"\n    },\n    \"optsRemove\": {\n        \"message\": \"Suppression\"\n    },\n    \"optsUseStyle\": {\n        \"message\": \"Ajouter la mise en page aux éléments modifiés\"\n    },\n    \"optsAdvanced\": {\n        \"message\": \"Options Avançées\"\n    },\n    \"optsStyleLabel\": {\n        \"message\": \"Feuille de Style CSS personnalisée à ajouter aux éléments modifiés:\"\n    },\n    \"optsStylePreview\": {\n        \"message\": \"Aperçu de la mise en page\"\n    },\n    \"optsUserRules\": {\n        \"message\": \"Sélection des feuilles de styles CSS personnalisées à masquer, une par ligne. <em>À DES FINS DE TEST UNIQUEMENT</em>\"\n    },\n    \"optsUserRulesHover\": {\n        \"message\": \"Si vous identifiez une nouvelle feuille de style CSS à sélectionner, veuillez la soumettre dans un message pour les programmeurs\"\n    },\n    \"optsPending\": {\n        \"message\": \"Activer les règles de dissimulation en attente ou non confirmées\"\n    },\n    \"optsPendingLink\": {\n        \"message\": \"Voir la liste ici\"\n    },\n    \"optsLogging\": {\n        \"message\": \"Afficher les messages de journalisation dans la console\"\n    },\n    \"optsRefresh\": {\n        \"message\": \"Actualiser les règles\"\n    },\n    \"optsRefreshHover\": {\n        \"message\": \"Une seule fois par $1 minute(s)\",\n        \"description\": \"Message de compte à rebours de la règle de raffraichissemnt\"\n    },\n    \"optsDefaults\": {\n        \"message\": \"Restaurations des paramètres par défaut\"\n    },\n    \"___\": {\n        \"message\": \"From https://libretranslate.com/?source=en&target=fr\"\n    },\n    \"optsResetTitle\": {\n        \"message\": \"Par défaut\"\n    },\n    \"optsResetAlt\": {\n        \"message\": \"Réinitialiser\"\n    },\n    \"optsReloadNotice\": {\n        \"message\": \"Les changements seront appliqués lorsque cette page d'options est fermée\",\n        \"description\": \"Remarque sur la page des options sur quand les changements seront appliqués\"\n    }\n}\n"
  },
  {
    "path": "biome.json",
    "content": "{\n    \"$schema\": \"https://biomejs.dev/schemas/1.8.1/schema.json\",\n    \"formatter\": {\n        \"enabled\": true,\n        \"indentWidth\": 4,\n        \"indentStyle\": \"space\",\n        \"lineWidth\": 120,\n        \"ignore\": [\"webextension-polyfill\", \"browser-polyfill.*\", \".vscode\"]\n    },\n    \"linter\": {\n        \"enabled\": true,\n        \"ignore\": [\"webextension-polyfill\", \"browser-polyfill.*\"],\n        \"rules\": {\n            \"recommended\": true,\n            \"suspicious\": {\n                \"noAssignInExpressions\": \"off\"\n            }\n        }\n    },\n    \"javascript\": {\n        \"formatter\": {\n            \"arrowParentheses\": \"asNeeded\"\n        }\n    },\n    \"json\": {\n        \"parser\": {\n            \"allowComments\": true,\n            \"allowTrailingCommas\": true\n        }\n    },\n    \"vcs\": {\n        \"enabled\": true,\n        \"clientKind\": \"git\",\n        \"useIgnoreFile\": true\n    }\n}\n"
  },
  {
    "path": "data/click_whitelist/elements",
    "content": "/* All entries must be all UPPERCASE */\nINPUT\nSELECT\nBUTTON\nTEXTAREA\n"
  },
  {
    "path": "data/click_whitelist/roles",
    "content": "/* All entries must be all UPPERCASE */\nBUTTON\nCHECKBOX\nCOMBOBOX\nLINK\nMENUITEM\nMENUITEMCHECKBOX\nMENUITEMRADIO\nOPTION\nRADIO\nSLIDER\nTAB\nTEXTBOX\n"
  },
  {
    "path": "data/click_whitelist/selectors",
    "content": "/* Desktop */\na[data-jsid='actionLink']\na[ajaxify]\na.see_more_link\nform div.pam\na[rel='theater']\n#stories_tray\n[role=presentation][data-tooltip-content]        /* Chat emoji categories */\nform [contenteditable=\"true\"]\nform [contenteditable=\"true\"]+div:last-child     /* Post comment input */\n\n/* Messenger page */\na[aria-label='photo']       /* photos */\nspan._40fu                  /* message actions */\n\n/* Mobile */\nspan[data-sigil='more']\n\n/* Chat */\ndiv._5r8h\nimg._358\n"
  },
  {
    "path": "data/declarativeNetRequest.json",
    "content": "[\n    {\n        \"id\": 1,\n        \"action\": {\n            \"type\": \"block\"\n        },\n        \"condition\": {\n            \"resourceTypes\": [\"beacon\", \"ping\"],\n            \"urlFilter\": \"||facebook.com\"\n        }\n    },\n    {\n        \"id\": 2,\n        \"action\": {\n            \"type\": \"block\"\n        },\n        \"condition\": {\n            \"resourceTypes\": [\"beacon\", \"ping\"],\n            \"urlFilter\": \"||messenger.com\"\n        }\n    },\n    {\n        \"id\": 3,\n        \"action\": {\n            \"type\": \"block\"\n        },\n        \"condition\": {\n            \"resourceTypes\": [\"beacon\", \"ping\"],\n            \"urlFilter\": \"||facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion\"\n        }\n    },\n    {\n        \"id\": 4,\n        \"action\": {\n            \"type\": \"block\"\n        },\n        \"condition\": {\n            \"urlFilter\": \"||pixel.facebook.com\"\n        }\n    },\n    {\n        \"id\": 5,\n        \"action\": {\n            \"type\": \"block\"\n        },\n        \"condition\": {\n            \"urlFilter\": \"|*://*.facebook.com/ajax/bz*\"\n        }\n    },\n    {\n        \"id\": 6,\n        \"action\": {\n            \"type\": \"block\"\n        },\n        \"condition\": {\n            \"urlFilter\": \"|*://*.messenger.com/ajax/bz*\"\n        }\n    },\n    {\n        \"id\": 7,\n        \"action\": {\n            \"type\": \"block\"\n        },\n        \"condition\": {\n            \"urlFilter\": \"|*://*.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/ajax/bz*\"\n        }\n    },\n    {\n        \"id\": 8,\n        \"action\": {\n            \"type\": \"block\"\n        },\n        \"condition\": {\n            \"urlFilter\": \"|*://*.facebook.com/ajax/bnzai*\"\n        }\n    },\n    {\n        \"id\": 9,\n        \"action\": {\n            \"type\": \"block\"\n        },\n        \"condition\": {\n            \"urlFilter\": \"|*://*.messenger.com/ajax/bnzai*\"\n        }\n    },\n    {\n        \"id\": 10,\n        \"action\": {\n            \"type\": \"block\"\n        },\n        \"condition\": {\n            \"urlFilter\": \"|*://*.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/ajax/bnzai*\"\n        }\n    },\n    {\n        \"id\": 11,\n        \"action\": {\n            \"type\": \"block\"\n        },\n        \"condition\": {\n            \"urlFilter\": \"|*://*.facebook.com/xti.php?*\"\n        }\n    },\n    {\n        \"id\": 12,\n        \"action\": {\n            \"type\": \"block\"\n        },\n        \"condition\": {\n            \"urlFilter\": \"|*://*.messenger.com/xti.php?*\"\n        }\n    },\n    {\n        \"id\": 13,\n        \"action\": {\n            \"type\": \"block\"\n        },\n        \"condition\": {\n            \"urlFilter\": \"|*://*.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/xti.php?*\"\n        }\n    }\n]\n"
  },
  {
    "path": "data/hide_rules/article_wrapper",
    "content": "article\ndiv._55wo\ndiv.mbm\ndiv.pagelet\ndiv[data-pagelet='RightRail']>*>*    /* Sidebar - old */\n#ssrb_rhc_start+div>*>*              /* Sidebar - new */\ndiv[role='complementary'] div>span:only-child>div:only-child>div:only-child     /* Sidebar - newer */\ndiv[role='complementary'] div>span:only-of-type>div:only-child                  /* Sidebar - newerer */\ndiv[role='complementary'] div:has(>:is(div,span):empty)                         /* Sidebar - newererer */\ndiv[role=article]\ndiv[aria-posinset]                   /* Feed article */\ndiv.tr9rh885                         /* Suggestions at top of user page */\ndiv._6x84                            /* Watch Sponsored */\ndiv.dzwucfd1                         /* Page banner suggestions */\ndiv.x1pha0wt                         /* Marketplace Sponsored Label */\ndiv[style].xnpuxes:first-child       /* Marketplace Sponsored */\nspan>div>div.xod5an3                 /* Marketplace Sidebar */\ndiv[data-type='vscroller']>div[data-type='container']    /* Mobile Feed */\n"
  },
  {
    "path": "data/hide_rules/content",
    "content": "/* Syntax: css-selector[||innerText,..] */\na>span:only-of-type,._3nlk,div>a:first-child,div>a[onmousedown],a[role=link],div[role=button],h3>*||Sponsored||Sponsorisé||Patrocinado||Publicidad||Gesponsert||Sponsorizzato||Sponsorizzata\n"
  },
  {
    "path": "data/hide_rules/pending",
    "content": "/* Syntax: css-selector[||innerText|/regex/,...] */\n"
  },
  {
    "path": "data/hide_rules/sponsored/patterns",
    "content": ""
  },
  {
    "path": "data/hide_rules/sponsored/selectors",
    "content": "._3nlk\n[aria-label]\n[aria-labelledby]\na[role=link]\na>span:only-of-type\ndiv[role=button]\ndiv>a:first-child\ndiv>a[onmousedown]\nh3>*\nuse /* replaced with svg, leave temporarily for backward compatibility */\nsvg\n"
  },
  {
    "path": "data/hide_rules/sponsored/texts",
    "content": "/* * List from https://greasyfork.org/en/scripts/404309-facebook-hide-ads-a-k-a-sponsored-posts/code * */\n/* af       */ Geborg\n/* am       */ የተከፈለበት ማስታወቂያ\n/* ar       */ إعلان مُموَّل\n/* as       */ পৃষ্ঠপোষকতা কৰা\n/* ay       */ Yatiyanaka\n/* az       */ Sponsor dəstəkli\n/* be       */ Рэклама\n/* bg       */ Спонсорирано\n/* bn       */ সৌজন্যে\n/* br       */ Paeroniet\n/* bs       */ Sponzorirano\n/* ca       */ Patrocinat\n/* cb       */ پاڵپشتیکراو\n/* co       */ Spunsurizatu\n/* cs       */ Sponzorováno\n/* cx       */ Giisponsoran\n/* cy       */ Noddwyd\n/* da       */ Sponsoreret\n/* de       */ Gesponsert\n/* el       */ Χορηγούμενη\n/* en       */ Chartered\n/* en       */ Sponsored\n/* eo       */ Reklamo\n/* es,gl,pt */ Patrocinado\n/* es       */ Publicidad\n/* et       */ Sponsitud\n/* eu       */ Babestua\n/* fa       */ دارای پشتیبانی مالی\n/* fi       */ Sponsoroitu\n/* fo       */ Stuðlað\n/* fr       */ Commandité\n/* fr       */ Sponsorisé\n/* fy       */ Sponsore\n/* ga       */ Urraithe\n/* gn       */ Oñepatrosinapyre\n/* gx       */ Χορηγούμενον\n/* hi,mr,ne */ प्रायोजित\n/* hu       */ Hirdetés\n/* id       */ Bersponsor\n/* it       */ Sponsorizzata\n/* it       */ Sponsorizzato\n/* ja       */ 広告\n/* jv       */ Disponsori\n/* kk       */ Демеушілік көрсеткен\n/* km       */ បានឧបត្ថម្ភ\n/* lo       */ ໄດ້ຮັບການສະໜັບສະໜູນ\n/* mk       */ Спонзорирано\n/* ml       */ സ്പോൺസർ ചെയ്തത്\n/* mn       */ Ивээн тэтгэсэн\n/* ms       */ Ditaja\n/* nl       */ Gesponsord\n/* or       */ ପ୍ରଯୋଜିତ\n/* pa       */ ਸਰਪ੍ਰਸਤੀ ਪ੍ਰਾਪਤ\n/* pl       */ Sponsorowane\n/* ps       */ تمويل شوي\n/* ru,uk    */ Реклама\n/* sa       */ प्रायोजितः |\n/* si       */ අනුග්‍රහය දක්වන ලද\n/* so       */ La maalgeliyey\n/* sv       */ Sponsrad\n/* te       */ స్పాన్సర్ చేసినవి\n/* th       */ ได้รับการสนับสนุน\n/* tl       */ May Sponsor\n/* tr       */ Sponsorlu\n/* tz       */ ⵉⴷⵍ\n/* ur       */ تعاون کردہ\n/* vi       */ Được tài trợ\n/* zh-Hans  */ 赞助内容\n/* zh-Hant  */ 贊助\n"
  },
  {
    "path": "data/hide_rules/suggested/patterns",
    "content": ""
  },
  {
    "path": "data/hide_rules/suggested/selectors",
    "content": "[aria-label]\n[aria-labelledby]\ndiv.native-text>span        /* Mobile */\ndiv[role=\"button\"]\nh3\nspan[dir]\nuse\n"
  },
  {
    "path": "data/hide_rules/suggested/texts",
    "content": "A Video You May Like\nEvents You May Like\nFollow\nGames You May Like\nJoin\nPage Stories You May Like\nPeople You May Know\nPopular Across Facebook\nPublic Figures to Follow\nReels\nReels and short videos\nRelated Pages\nShop now\nSuggested for You\nSuggested Groups\nSuggested Live Gaming Video\nSuggested Pages\nSuggested Post\nThis shop has added new items.\nTV Watchlist\n\n/* Polish */\nDołącz /* Join */\n/* Swedish */\nReels och korta videor /* Reels and short videos */\n\n/* From https://greasyfork.org/en/scripts/431970-fb-clean-my-feeds/code */\n/* People you may know */\n/* ar      */ أشخاص قد تعرفهم\n/* bg      */ които може би познавате\n/* bg      */ Хора\n/* cs      */ Koho možná znáte\n/* de      */ die du kennen könntest\n/* de      */ Personen\n/* el      */ Άτομα που ίσως γνωρίζετε\n/* es      */ Personas que quizá conozcas\n/* fi      */ Ihmiset\n/* fi      */ jotka saatat tuntea\n/* fr      */ Connaissez-vous...\n/* he      */ אנשים שאולי אתה מכיר\n/* id      */ Orang yang Mungkin Anda Kenal\n/* it      */ Persone che potresti conoscere\n/* ja      */ あなたが知っているかもしれない人々\n/* lv      */ Cilvēki\n/* lv      */ kurus tu varētu pazīt\n/* nl      */ Mensen die je misschien kent\n/* pl      */ które możesz znać\n/* pl      */ Osoby\n/* pt      */ Pessoas que talvez conheças\n/* ru      */ которых вы можете знать\n/* ru      */ Люди\n/* tr      */ Tanıyor olabileceğin kişiler\n/* uk      */ Люди\n/* uk      */ яких Ви можете знати\n/* vi      */ Những người bạn có thể biết\n/* zh-Hans */ 你可能认识的人\n/* zh-Hant */ 你可能認識的人\n/* Reels and short videos */\n/* ar      */ ريلز ومقاطع الفيديو القصيرة\n/* bg      */ Ленти и кратки видеоклипове\n/* cs      */ Sekvence a krátká videa\n/* de      */ Reels und Kurzvideos\n/* el      */ Reel και σύντομα βίντεο\n/* es      */ Reels y vídeos cortos\n/* fi      */ Keloja ja lyhyitä videoita\n/* fr      */ Reels et vidéos courtes\n/* he      */ סרטוני Reels וקטעי וידאו קצרים\n/* id      */ Reels dan Video Pendek\n/* it      */ Reel e video brevi\n/* ja      */ リールとショート動画\n/* lv      */ Reels un īsi videoklipi\n/* nl      */ Reels en korte video\\s\n/* pl      */ Rolki i krótkie filmy\n/* pt      */ Vídeos do Reels e vídeos de curta duração\n/* ru      */ Reels и короткие видео\n/* tr      */ Makaralar ve kısa videolar\n/* uk      */ Відео Reels і короткі відео\n/* vi      */ Reels và video ngắn\n/* zh-Hans */ 卷轴和短视频\n/* zh-Hant */ Reels 和短影片\n/* Events you may like */\n/* ar      */ أحداث قد تعجبك\n/* bg      */ които може да ви харесат\n/* bg      */ Събития\n/* cs      */ které se vám mohou líbit\n/* cs      */ Události\n/* de      */ die Ihnen gefallen könnten\n/* de      */ Veranstaltungen\n/* el      */ Εκδηλώσεις που μπορεί να σας αρέσουν\n/* es      */ Eventos que te pueden gustar\n/* fi      */ Kela/lyhyt video\n/* fr      */ Évènements qui pourraient vous intéresser\n/* he      */ אירועים שאולי תאהבו\n/* id      */ Acara yang mungkin Anda sukai\n/* it      */ Eventi che potrebbero piacerti\n/* ja      */ リール/ショートビデオ\n/* lv      */ kas jums varētu patikt\n/* lv      */ Notikumi\n/* nl      */ Evenementen die je misschien leuk vindt\n/* pl      */ które mogą Ci się spodobać\n/* pl      */ Wydarzenia\n/* pt      */ Eventos que você pode gostar\n/* ru      */ которые вам могут понравиться\n/* ru      */ Мероприятия\n/* tr      */ makara/kısa video\n/* uk      */ Події\n/* uk      */ які можуть вам сподобатися\n/* vi      */ Sự kiện bạn có thể thích\n/* zh-Hans */ 您可能喜欢的活动\n/* zh-Hant */ 你可能感興趣的活動\n/* Follow */\n/* ar      */ تابع\n/* bg      */ Следвай\n/* cs      */ Sledovat\n/* de      */ Folgen\n/* el      */ Ακολούθησε\n/* es      */ Seguir\n/* fi      */ Seuraa\n/* fr      */ Suivre\n/* he      */ עקוב\n/* id      */ Ikuti\n/* it      */ Segui\n/* ja      */ フォロー\n/* lv      */ Sekot\n/* nl      */ Volgen\n/* pl      */ Obserwuj\n/* pt      */ Seguir\n/* ru      */ Подписаться\n/* tr      */ Takip Et\n/* uk      */ Слідуйте\n/* vi      */ Theo dõi\n/* zh-Hans */ 关注\n/* zh-Hant */ 追蹤\n"
  },
  {
    "path": "data/hide_rules/suggestions_smart",
    "content": "/* Syntax: css-selector[||innerText,..] */\nspan[dir]||People You May Know||Suggested Post||Suggested for You||Suggested Groups||Public Figures to Follow||Suggested Pages||Suggested Live Gaming Video||Reels||Reels and short videos\n"
  },
  {
    "path": "data/hide_rules/unconditional",
    "content": "/* Selectors that will always be removed unconditionally and never collapsed */\n.x12fkvr4           /* Marketplace sponsored hamburger menu */\na[href*=\"hoisted\"] > span:not(:empty):only-child /* feed group suggestions */\n"
  },
  {
    "path": "data/param_cleaning/params",
    "content": "_ft_\n_nc_cat\n_rdr\n_sref_\nacontext /* May break some links? Removed by Legitimate URL Shortener so try adding it again */\ncomment_tracking\ncref\ndti\neav\neid /* appears on everything... */\nentry_point\nentrypoint\nepa /* appears on hashtags */\nfb_ref\nfref\nfrom\nlst\nMedium\npaipv\nplacement\nprivacy_mutation_token\nrc\nref\nreferrer\nrefid\nsettings_tracking\nsfnsn\ntbua\ntracking\n"
  },
  {
    "path": "data/param_cleaning/prefix_patterns",
    "content": "__\n((\\w*_)?source|hc)(\\b|_)\nft\\[\npn_\nref_\nreferral\nzero_\n"
  },
  {
    "path": "data/param_cleaning/values",
    "content": "extragetparams\n"
  },
  {
    "path": "jsconfig.json",
    "content": "{\n    \"compilerOptions\": {\n        \"target\": \"esnext\",\n        \"module\": \"esnext\",\n        \"baseUrl\": \"./\",\n        \"paths\": {\n            \"/*\": [\"./*\"]\n        }\n    },\n    \"include\": [\"src/**/*\"],\n    \"typeAcquisition\": {\n        \"include\": [\"firefox-webext-browser\"]\n    }\n}\n"
  },
  {
    "path": "manifest.json",
    "content": "{\n    \"name\": \"__MSG_extensionName__\",\n    \"version\": \"1.13.0\",\n    \"description\": \"__MSG_extensionDescription__\",\n    \"default_locale\": \"en\",\n    \"icons\": {\n        \"128\": \"src/icon.png\"\n    },\n    \"author\": \"Michael Ziminsky\",\n    \"homepage_url\": \"https://github.com/mgziminsky/FacebookTrackingRemoval\",\n    \"browser_specific_settings\": {\n        \"gecko\": {\n            \"id\": \"{bb1b80be-e6b3-40a1-9b6e-9d4073343f0b}\",\n            \"strict_min_version\": \"113.0\"\n        }\n    },\n    \"permissions\": [\"alarms\", \"declarativeNetRequestWithHostAccess\", \"scripting\", \"storage\", \"webNavigation\"],\n    \"host_permissions\": [\n        \"*://*.facebook.com/*\",\n        \"*://*.messenger.com/*\",\n        \"*://*.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/*\",\n        \"https://mgziminsky.gitlab.io/FacebookTrackingRemoval/*\"\n    ],\n    \"options_ui\": {\n        \"page\": \"src/options/options.html\",\n        \"open_in_tab\": false\n    },\n    \"background\": {\n        \"type\": \"module\",\n        \"scripts\": [\"src/background/background.js\"],\n        \"service_worker\": \"src/background/background.js\"\n    },\n    \"action\": {\n        \"default_icon\": \"src/icon.png\",\n        \"default_popup\": \"src/options/options.html\"\n    },\n    \"page_action\": {\n        \"default_icon\": \"src/icon.png\",\n        \"default_popup\": \"src/options/options.html\",\n        \"show_matches\": [\n            \"*://*.facebook.com/*\",\n            \"*://*.messenger.com/*\",\n            \"*://*.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/*\"\n        ]\n    },\n    \"content_scripts\": [\n        {\n            \"all_frames\": true,\n            \"matches\": [\n                \"*://*.facebook.com/*\",\n                \"*://*.messenger.com/*\",\n                \"*://*.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/*\"\n            ],\n            \"css\": [\"src/content_script/app.css\"],\n            \"js\": [\"browser-polyfill.min.js\", \"src/content_script/content_script.js\"],\n            \"run_at\": \"document_end\",\n            \"world\": \"ISOLATED\"\n        }\n    ],\n    \"web_accessible_resources\": [\n        {\n            \"use_dynamic_url\": true,\n            \"matches\": [\n                \"*://*.facebook.com/*\",\n                \"*://*.messenger.com/*\",\n                \"*://*.facebookwkhpilnemxj7asaniu7vnjjbiltxjqhye3mhbshg7kx5tfyd.onion/*\"\n            ],\n            \"resources\": [\"/src/*\"]\n        }\n    ],\n    \"declarative_net_request\": {\n        \"rule_resources\": [\n            {\n                \"id\": \"ruleset\",\n                \"enabled\": true,\n                \"path\": \"data/declarativeNetRequest.json\"\n            }\n        ]\n    },\n    \"incognito\": \"spanning\",\n    \"manifest_version\": 3\n}\n"
  },
  {
    "path": "package.sh",
    "content": "#!/bin/bash\nset -x\n\ncd $(dirname $0)\n\nrm -f Browser_Extension.zip\ncp webextension-polyfill/dist/browser-polyfill.min.js* ./\nzip -r -ll Browser_Extension.zip . -i 'src/*' '_locales/*' 'data/*' browser-polyfill.min.js manifest.json CHANGELOG LICENSE\n"
  },
  {
    "path": "src/background/background.js",
    "content": "/*  This file is part of FacebookTrackingRemoval.\n\n    FacebookTrackingRemoval is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    FacebookTrackingRemoval is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with FacebookTrackingRemoval.  If not, see <http://www.gnu.org/licenses/>.\n\n    Copyright (C) 2016-2024 Michael Ziminsky\n*/\n\nimport \"/browser-polyfill.min.js\";\n\nimport { isChrome, log, warn } from \"../common.js\";\nimport { options, storage } from \"../config.js\";\nimport { CHROME_PORT, MSG, NOOP, STYLE_CLASS } from \"../consts.js\";\nimport { refreshRules } from \"../rules_sync.js\";\nimport \"./webrequest.js\";\n\nbrowser.action.disable(); // Default to disabled. Content script will send message to enable\n\n// Do some cleanup after updating to 1.6.4+ for the first time\n// to get rid of old storage data that is no longer used\nbrowser.runtime.onInstalled.addListener(details => {\n    // Not an update\n    if (!details.previousVersion || details.previousVersion === browser.runtime.getManifest().version) return;\n\n    // Always force refresh rules after an update for simplicity\n    // 1.8.0 changed the dynamic rules format\n    browser.storage.local.remove([\"lastRuleRefresh\", \"hide_rules\"]).finally(refreshRules.bind(undefined, true));\n\n    const old = [1, 6, 3];\n    const prev = details.previousVersion.split(\".\").map(Number);\n    if (!details.temporary && prev.every((v, i) => v <= (old[i] ?? 0))) {\n        const currentOpts = options;\n        storage.clear();\n        browser.storage.local.clear();\n        storage.set(currentOpts);\n        browser.runtime.reload();\n    }\n});\n\n/**\n * @param {(injection: browser.scripting.CSSInjection) => Promise<void>} action\n * @param {string?} style\n * @param {number} tabId\n * @param {number} frameId\n */\nfunction updateCSS(action, style, tabId, frameId) {\n    action({\n        target: {\n            tabId,\n            frameIds: [frameId],\n        },\n        origin: \"USER\",\n        css: style ? `.${STYLE_CLASS} { ${style}; }` : \"\",\n    }).catch(warn);\n}\n\n/**\n * @param {{msg: string}}\n * @param {browser.runtime.MessageSender} sender\n */\nfunction onMessage({ msg, ...data }, sender) {\n    switch (msg) {\n        case MSG.actionEnable:\n            browser.action.enable(sender.tab.id);\n            break;\n        case MSG.insertCss:\n            updateCSS(browser.scripting.insertCSS, data.style, sender.tab.id, sender.frameId);\n            break;\n        case MSG.removeCss:\n            updateCSS(browser.scripting.removeCSS, data.style, sender.tab.id, sender.frameId);\n            break;\n        case MSG.rulesRefresh:\n            return refreshRules(data.force);\n    }\n}\nbrowser.runtime.onMessage.addListener(onMessage);\n\nif (isChrome) {\n    // alarms have a min delay of 1 minute...\n    refreshRules().catch(NOOP);\n\n    // Popups don't fire unload on close, have to handle it from here\n    browser.runtime.onConnect.addListener(port => {\n        log(\"Options Connect\");\n        if (port.name === CHROME_PORT) {\n            let changes = {};\n            port.onMessage.addListener(data => (changes = data));\n            port.onDisconnect.addListener(() => {\n                log(\"Options Disconnect\");\n                if (Object.keys(changes).length) Object.assign(options, changes);\n            });\n        }\n    });\n}\n"
  },
  {
    "path": "src/background/webrequest.js",
    "content": "/**\n * Copyright (C) 2023-2024 Michael Ziminsky (Z)\n *\n * This file is part of FacebookTrackingRemoval.\n *\n * FacebookTrackingRemoval is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * FacebookTrackingRemoval is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with FacebookTrackingRemoval.  If not, see <http://www.gnu.org/licenses/>.\n */\n\nimport * as config from \"../config.js\";\nimport { MSG } from \"../consts.js\";\nimport { cleanLinkParams } from \"../util.js\";\n\nbrowser.webNavigation.onHistoryStateUpdated.addListener(\n    details => {\n        if (!config.options.enabled) return;\n\n        const orig = details.url;\n        const clean = cleanLinkParams(details.url);\n        if (orig !== clean) {\n            browser.tabs.sendMessage(details.tabId, { type: MSG.history, orig, clean });\n        }\n    },\n    {\n        url: config.host_patterns.map(h => h.replaceAll(/[^.\\w]/g, \"\")).map(hostContains => ({ hostContains })),\n    },\n);\n\nfunction updateRuleset(enable) {\n    if (enable === true) {\n        browser.declarativeNetRequest.updateEnabledRulesets({ enableRulesetIds: [\"ruleset\"] });\n    } else if (enable === false) {\n        browser.declarativeNetRequest.updateEnabledRulesets({ disableRulesetIds: [\"ruleset\"] });\n    }\n}\nconfig.storage.onChanged.addListener(({ enabled }) => updateRuleset(enabled?.newValue));\nbrowser.runtime.onInstalled.addListener(() => {\n    // Disable blocking rules on update since they get reset back to the extension default\n    config.READY.then(() => updateRuleset(config.options.enabled));\n});\n"
  },
  {
    "path": "src/common.js",
    "content": "/*  This file is part of FacebookTrackingRemoval.\n\n    FacebookTrackingRemoval is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    FacebookTrackingRemoval is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with FacebookTrackingRemoval.  If not, see <http://www.gnu.org/licenses/>.\n\n    Copyright (C) 2016-2024 Michael Ziminsky\n*/\n\nimport { options } from \"./config.js\";\n\nexport { isChrome, log, warn };\n\nconst isChrome = Object.getPrototypeOf(browser) !== Object.prototype;\n\nfunction log(arg) {\n    if (options.logging) log_to(console.log, arg);\n}\nfunction warn(arg) {\n    if (options.logging) log_to(console.warn, arg);\n}\n\nfunction log_to(logger, arg) {\n    if (typeof arg === \"function\") {\n        const res = arg();\n        if (res) logger(res);\n    } else {\n        logger(arg);\n    }\n}\n"
  },
  {
    "path": "src/config.js",
    "content": "/**\n * Copyright (C) 2023-2024 Michael Ziminsky (Z)\n *\n * This file is part of FacebookTrackingRemoval.\n *\n * FacebookTrackingRemoval is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * FacebookTrackingRemoval is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with FacebookTrackingRemoval.  If not, see <http://www.gnu.org/licenses/>.\n */\n\nimport { joinSelectors, normalizeString } from \"./util.js\";\n\nexport {\n    click_whitelist,\n    defaults,\n    domains,\n    hide_rules,\n    host_patterns,\n    initHideRule,\n    MAX_CANVAS_SENSITIVITY,\n    onChanged,\n    options,\n    param_cleaning,\n    READY,\n    reset,\n    storage,\n};\n\nconst storage = browser.storage.local;\nconst MAX_CANVAS_SENSITIVITY = 2;\n\n/** @type {Options} */\nconst defaults = Object.freeze({\n    enabled: true,\n    fixLinks: true,\n    internalRefs: false,\n    inlineVids: false,\n    fixVideos: false,\n    delPixeled: true,\n    delSuggest: true,\n    hideMethod: \"collapse\",\n    useStyle: false,\n    logging: false,\n    modStyle: \"outline: 1px dashed rgba(0, 128, 0, 0.5) !important;\",\n    userRules: \"\",\n    pendingRules: false,\n    testCanvas: true,\n    canvasSensitivity: 0.8,\n});\n\nconst host_patterns = Object.freeze([\n    ...new Set(browser.runtime.getManifest().content_scripts.flatMap(cs => cs.matches)),\n]);\nconst domains = Object.freeze([...new Set(host_patterns.map(m => m.replace(/\\W*\\*\\W?/g, \"\")))]);\n\n/** @type {Options} */\nconst _options = Object.seal(Object.assign({}, defaults));\nconst options = new Proxy(_options, {\n    set(opts, prop, val) {\n        if (!Object.hasOwn(opts, prop)) return false;\n\n        const old = opts[prop];\n        opts[prop] = val ?? defaults[prop];\n\n        let apply;\n        if (val != null) {\n            apply = storage.set.bind(storage, { [prop]: val });\n        } else {\n            apply = storage.remove.bind(storage, prop);\n        }\n        apply().catch(() => (opts[prop] = old));\n\n        return true;\n    },\n    deleteProperty(opts, prop) {\n        const old = opts[prop];\n        opts[prop] = defaults[prop];\n        storage.remove(prop).catch(() => (opts[prop] = old));\n        return false;\n    },\n});\n\n/**\n * Reset option value(s) to the default\n *\n * @param {?string | string[]} keys\n * @return {Promise<void>}\n */\nfunction reset(keys) {\n    let result;\n    if (keys) {\n        result = storage.remove(keys).then(() => {\n            for (const key of [...keys]) _options[key] = defaults[key];\n        });\n    } else {\n        result = storage.remove(Object.keys(defaults)).then(() => Object.assign(_options, defaults));\n    }\n    return result;\n}\n\nconst _data = Object.freeze({\n    hide_rules: Object.freeze({\n        /**@type {HideRules}*/\n        value: { article_wrapper: \"\", pending: {}, sponsored: {}, suggested: {}, unconditional: \"\" },\n        update(/**@type {HideRules}*/ raw) {\n            Object.assign(this.value, raw);\n            Object.values(this.value).forEach(initHideRule);\n        },\n    }),\n    param_cleaning: Object.freeze({\n        /**@type {ParamCleaning}*/\n        value: { params: [], prefix_patterns: [\"$\"], values: [] },\n        update(/**@type {ParamCleaning}*/ raw) {\n            Object.assign(this.value, raw);\n            this.value.pattern = new RegExp(`^(${this.value.prefix_patterns.join(\"|\")})`);\n        },\n    }),\n    click_whitelist: Object.freeze({\n        /**@type {ClickWhitelist}*/\n        value: { elements: [], roles: [], selectors: [] },\n        update(/**@type {ClickWhitelist}*/ raw) {\n            Object.assign(this.value, raw);\n            this.value.selector = joinSelectors(this.value.selectors.join(\"\\n\"));\n        },\n    }),\n});\n\n/** @type {ProxyHandler} */\nconst ReadOnly = {\n    set: () => false,\n    isExtensible: () => false,\n    defineProperty: () => {\n        throw new Error(\"Not Allowed\");\n    },\n    deleteProperty: () => {\n        throw new Error(\"Not Allowed\");\n    },\n};\n\n/** @type {[HideRules, ParamCleaning, ClickWhitelist]} */\nconst [hide_rules, param_cleaning, click_whitelist] = [\n    new Proxy(_data.hide_rules.value, ReadOnly),\n    new Proxy(_data.param_cleaning.value, ReadOnly),\n    new Proxy(_data.click_whitelist.value, ReadOnly),\n];\n\n/**\n * Converts the texts and patterns of a rule to final format\n * @param {Object} rule\n * @param {string[]?} rule.texts\n * @param {string[]?} rule.patterns\n *\n * @returns {HideRule}\n */\nfunction initHideRule(rule) {\n    if (rule.texts) rule.texts = rule.texts.reduce((m, t) => m.set(normalizeString(t), t), new Map());\n\n    if (Array.isArray(rule.patterns) && rule.patterns.length) rule.patterns = new RegExp(rule.patterns.join(\"|\"), \"iu\");\n    // biome-ignore lint/performance/noDelete:\n    else delete rule.patterns;\n\n    return rule;\n}\n\nconst _onChanged = new Set();\n/** @type {WebExtEvent<(changes: { [key: string]: browser.storage.StorageChange }) => void>} */\nconst onChanged = Object.freeze({\n    addListener(cb) {\n        if (typeof cb === \"function\") _onChanged.add(cb);\n    },\n    removeListener: _onChanged.delete.bind(_onChanged),\n    hasListener: _onChanged.has.bind(_onChanged),\n});\n\n/**\n * Update local options with value from storage\n *\n * @param {string | string[]} keys\n */\nasync function sync(keys) {\n    const { opts, rules } = [...keys].reduce(\n        (acc, key) => {\n            if (key in defaults) acc.opts[key] = defaults[key];\n            else if (key in _data) acc.rules[key] = _data[key].value;\n            return acc;\n        },\n        { opts: {}, rules: {} },\n    );\n\n    const result = [];\n    if (Object.keys(opts).length) result.push(storage.get(opts).then(opts => Object.assign(_options, opts)));\n\n    if (Object.keys(rules).length)\n        result.push(\n            storage.get(rules).then(rules => {\n                for (const k in rules) _data[k].update(rules[k]);\n            }),\n        );\n\n    return Promise.allSettled(result);\n}\nstorage.onChanged.addListener(changes => {\n    sync(Object.keys(changes)).then(() => {\n        for (const k of Object.keys(_data)) delete changes[k];\n\n        if (Object.keys(changes).length) for (const cb of _onChanged.values()) cb(changes);\n    });\n});\n\nconst READY = new Promise((res, rej) => {\n    Promise.all([\n        storage.get(defaults).then(vals => Object.assign(_options, vals)),\n        browser.storage.local.get(Object.keys(_data)).then(data => {\n            for (const k in data) _data[k].update(data[k]);\n        }),\n    ]).then(() => res(), rej);\n});\n"
  },
  {
    "path": "src/consts.js",
    "content": "export const RATE_LIMIT = 1000 * 60 * 15; // 15 min\n\nexport const STYLE_CLASS = \"fbtrStyled\";\nexport const PROCESSED_CLASS = \"FBTR-PROCESSED\";\nexport const COLLAPSED_SELECTOR = \".fbtrHidden\";\n\nexport const NOOP = () => {};\n\nexport const MSG = Object.freeze({\n    actionEnable: \"ACTION_ENABLE\",\n    history: \"HISTORY\",\n    insertCss: \"INSERT_CSS\",\n    removeCss: \"REMOVE_CSS\",\n    rulesRefresh: \"RULES\",\n});\n\nexport const CHROME_PORT = \"CHROME_POPUP\";\n"
  },
  {
    "path": "src/content_script/app.css",
    "content": "/*  This file is part of FacebookTrackingRemoval.\n\n    FacebookTrackingRemoval is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    FacebookTrackingRemoval is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with FacebookTrackingRemoval.  If not, see <http://www.gnu.org/licenses/>.\n\n    Copyright (C) 2016-2024 Michael Ziminsky\n*/\n\n/* Make mobile article links clickable */\nsection.touchable > a {\n    position: absolute;\n    width: 100%;\n    height: 100%;\n    top: 0;\n    left: 0;\n    z-index: 41;\n}\n\ndetails.fbtrHidden {\n    padding: 0 10px;\n}\ndetails.fbtrHidden[open] {\n    padding-bottom: 10px;\n}\n\nsummary.fbtrLabel {\n    padding: 0.5rem 0;\n    cursor: pointer;\n    font-size: 0.8rem;\n    color: var(--secondary-text);\n}\n\n.fbtrHide {\n    display: none;\n}\n\n/* Emergency Broadcast posts. eg: Amber Alert */\n._3j6k {\n    border: medium solid red !important;\n}\n"
  },
  {
    "path": "src/content_script/app.js",
    "content": "/*  This file is part of FacebookTrackingRemoval.\n\n    FacebookTrackingRemoval is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    FacebookTrackingRemoval is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with FacebookTrackingRemoval.  If not, see <http://www.gnu.org/licenses/>.\n\n    Copyright (C) 2016-2024 Michael Ziminsky\n*/\n\nimport { log } from \"../common.js\";\nimport { READY, hide_rules, initHideRule, onChanged, options } from \"../config.js\";\nimport { COLLAPSED_SELECTOR, MSG, PROCESSED_CLASS } from \"../consts.js\";\nimport { normalizeString, parseHideRules } from \"../util.js\";\nimport { computeCanvasPrints, testCanvas } from \"./canvas_fingerprint.js\";\nimport {\n    applyStyle,\n    cleanRedirectLinks,\n    cleanShimLinks,\n    fixGifs,\n    fixVideoLinks,\n    stripFBCLID,\n    stripRefs,\n} from \"./cleaning.js\";\nimport { applyEventBlockers, ariaText, buildCollapsible, inlineUse, selectAllWithBase, visibleText } from \"./dom.js\";\n\nbrowser.runtime.sendMessage({ msg: MSG.actionEnable });\n\n/** @param {Element} target */\nfunction isCollapsed(target) {\n    return !!target.closest(COLLAPSED_SELECTOR);\n}\n\n/**\n * @param {Element} elem\n * @param {string} label\n * @param {\"remove\" | \"collapse\"} method\n */\nfunction hide(elem, label, method) {\n    /** @type {Element} */\n    let target;\n    if (!(elem && (target = elem.closest(hide_rules.article_wrapper)))) {\n        log(`Unable to hide ${label} - ${elem}`);\n        return;\n    }\n\n    log(() => {\n        const selector = hide_rules.article_wrapper;\n        for (const s of selector.split(\",\")) {\n            if (target.matches(s)) {\n                return `>>> Wrapper matched for ${target.tagName}: ${selector} = ${s}`;\n            }\n        }\n    });\n\n    if (method === \"collapse\") {\n        if (isCollapsed(target)) {\n            log(`${label} already collapsed`);\n            return;\n        }\n\n        const wrapper = buildCollapsible(label);\n        applyStyle(wrapper);\n        for (const c of target.classList) wrapper.classList.add(c);\n        target.classList.add(PROCESSED_CLASS);\n\n        target.parentNode.appendChild(wrapper);\n        wrapper.appendChild(target);\n        log(`Collapsed ${label}`);\n    } else {\n        // Removing breaks things :/ Consider using class instead of inline style?\n        (target.closest(\":not(:only-child)\") || target).style = \"display: none !important\";\n        log(`Removed ${label}`);\n    }\n}\n\nfunction removeLinkTracking(node) {\n    const cleaned = cleanShimLinks(node) + fixVideoLinks(node) + cleanRedirectLinks(node) + stripFBCLID(node);\n    fixGifs(node);\n\n    if (cleaned) applyEventBlockers(node);\n\n    return cleaned;\n}\n\n/**\n * @param {Element} node\n * @param {HideRule} rule\n * @param {\"remove\" | \"collapse\"} [method=options.hideMethod]\n */\nfunction removeArticles(node, { selector, texts, patterns }, method = options.hideMethod) {\n    if (!selector || node.classList.contains(PROCESSED_CLASS)) return;\n\n    /** @argument {string} text */\n    const getMatch = text => {\n        if (!(texts?.size || patterns)) return text || \"Unconditional Hide\";\n\n        // Some sponsored have other details appended after a · (0xb7). Try matching both parts separately\n        const parts = text.split(\"\\xb7\").map(s => s.trim().toLowerCase());\n\n        if (patterns && parts.some(p => patterns.test(p))) return text;\n\n        for (const p of parts) {\n            const x = texts.get(normalizeString(p));\n            if (x) return x;\n        }\n    };\n\n    for (const e of selectAllWithBase(node, selector)) {\n        const elementText = ariaText(e) || visibleText(e);\n\n        const match = getMatch(elementText);\n        if (match) {\n            log(() => {\n                for (const s of selector.split(\",\")) {\n                    if (e.matches(s)) {\n                        return `>>> Rule matched for ${elementText}: ${selector} = ${s}`;\n                    }\n                }\n            });\n            hide(e, match, method);\n        }\n    }\n}\n\nlet fprintsComputed = false;\n/** @param {HTMLCanvasElement} canvas */\nfunction removeCanvasArticle(canvas) {\n    if (isCollapsed(canvas) || canvas.classList.contains(PROCESSED_CLASS)) return;\n    if (!fprintsComputed) {\n        const texts = new Set(userRules.texts.values());\n        if (options.delPixeled) {\n            for (const text of hide_rules.sponsored.texts.values()) texts.add(text);\n        }\n        if (options.delSuggest) {\n            for (const text of hide_rules.suggested.texts.values()) texts.add(text);\n        }\n        if (options.pendingRules) {\n            for (const text of hide_rules.pending.texts.values()) texts.add(text);\n        }\n        computeCanvasPrints(texts, canvas);\n        fprintsComputed = true;\n    }\n\n    try {\n        const ctx = canvas.getContext(\"2d\");\n        const tform = ctx.getTransform();\n        ctx.resetTransform();\n        const match = testCanvas(ctx);\n        ctx.setTransform(tform);\n        if (match) {\n            log(() => `>>> Canvas matched for \"${match}\"`);\n            hide(canvas, match, options.hideMethod);\n        }\n    } catch (error) {\n        watchCanvas(canvas);\n    }\n}\n\nfunction removeAll(target) {\n    removeArticles(target, userRules);\n\n    if (options.delSuggest) removeArticles(target, hide_rules.suggested);\n    if (options.delPixeled) {\n        removeArticles(\n            target,\n            hide_rules.sponsored,\n            document.location.pathname.startsWith(\"/marketplace\") ? \"remove\" : options.hideMethod,\n        );\n        removeArticles(target, { selector: hide_rules.unconditional }, \"remove\");\n    }\n    if (options.pendingRules) removeArticles(target, hide_rules.pending);\n    if (options.testCanvas)\n        for (const canvas of selectAllWithBase(target, \"canvas\")) {\n            removeCanvasArticle(canvas);\n        }\n\n    if (options.internalRefs) stripRefs(target);\n}\n\n/**\n * @param {MutationRecord} mutation\n * @param {(n: Node) => void} cb\n */\nfunction forEachAdded(mutation, cb) {\n    for (const node of mutation.addedNodes) {\n        if (\n            node.nodeType === Node.ELEMENT_NODE &&\n            !SKIP.includes(node.nodeName) &&\n            !node.classList.contains(PROCESSED_CLASS)\n        ) {\n            cb(node);\n        }\n    }\n}\n\n/** @type {Map<string, [Node]>} */\nconst pendingRefs = new Map();\n/**\n * Find any new elements that reference nodes that don't yet exist\n * @param {Element} target\n */\nfunction findPending(target) {\n    for (const elem of selectAllWithBase(target, \"[aria-labelledby]\")) {\n        if (elem.closest(COLLAPSED_SELECTOR)) continue;\n\n        for (const attr of elem.getAttribute(\"aria-labelledby\")?.split(\" \") ?? []) {\n            if (!document.getElementById(attr)) {\n                log(() => `New pending element referencing [${attr}]`);\n                if (!pendingRefs.has(attr)) pendingRefs.set(attr, []);\n                pendingRefs.get(attr).push(elem);\n            }\n        }\n    }\n}\n/** Check if any of the ids we are waiting for were added, and if so process their nodes */\nfunction processPending() {\n    for (const [id, elems] of pendingRefs.entries()) {\n        if (document.getElementById(id)) {\n            log(() => `Waited on element now present for [${id}]`);\n            pendingRefs.delete(id);\n            for (const elem of elems) {\n                removeAll(elem);\n            }\n        }\n    }\n}\n\nconst SKIP = [\"SCRIPT\", \"STYLE\", \"LINK\"];\nconst observer = new MutationObserver(mutations => {\n    processPending();\n    for (const mutation of mutations) {\n        if (mutation.type === \"childList\" && !SKIP.includes(mutation.target.nodeName)) {\n            const target = mutation.target;\n            inlineUse(target);\n\n            removeAll(target);\n            if (!options.testCanvas) forEachAdded(mutation, findPending);\n\n            if (options.fixLinks) forEachAdded(mutation, removeLinkTracking);\n\n            forEachAdded(mutation, node => node.classList.add(PROCESSED_CLASS));\n        } else if (mutation.target) {\n            if (options.fixLinks) removeLinkTracking(mutation.target);\n            if (options.internalRefs) stripRefs(mutation.target);\n        }\n    }\n});\nfunction watchCanvas(canvas) {\n    new MutationObserver(([record, ...rest], obs) => {\n        obs.takeRecords();\n        obs.disconnect();\n        setTimeout(() => removeCanvasArticle(record.target), 100);\n    }).observe(canvas, {\n        attributeFilter: [\"width\", \"height\"],\n    });\n}\n\n/** @type {HideRule} */\nlet userRules;\nasync function run() {\n    userRules = initHideRule(parseHideRules(options.userRules));\n\n    const body = document.body;\n\n    observer.disconnect();\n    removeAll(body);\n\n    observer.observe(\n        body,\n        (() => {\n            const opts = { childList: true, subtree: true, characterData: false };\n            if (options.fixLinks) {\n                opts.attributes = true;\n                opts.attributeFilter = [\"href\"];\n            }\n            return opts;\n        })(),\n    );\n\n    if (options.fixLinks && removeLinkTracking(body) && document.getElementById(\"newsFeedHeading\")) {\n        const feed = document.getElementById(\"newsFeedHeading\").parentNode;\n        for (const stream of feed.querySelectorAll(\"div._4ikz\")) {\n            applyEventBlockers(stream);\n        }\n    }\n}\n\n/** @param {{type: string}} */\nfunction handleMessage({ type, ...data }) {\n    switch (type) {\n        case MSG.history:\n            if (!history.state.fbtr_clean) {\n                history.replaceState(Object.assign({ fbtr_clean: true }, history.state), \"\", data.clean);\n                log(`Cleaned link navigation done via history.pushState:\\n\\t${data.orig}\\n\\t${data.clean}`);\n            }\n            break;\n    }\n}\n\nlet activeStyle;\nfunction start() {\n    run();\n    browser.runtime.onMessage.addListener(handleMessage);\n\n    if (activeStyle) browser.runtime.sendMessage({ msg: MSG.removeCss, style: activeStyle });\n\n    if (options.useStyle) browser.runtime.sendMessage({ msg: MSG.insertCss, style: (activeStyle = options.modStyle) });\n}\n\nfunction stop() {\n    observer.disconnect();\n    browser.runtime.onMessage.removeListener(handleMessage);\n    browser.runtime.sendMessage({ msg: MSG.removeCss, style: activeStyle });\n}\n\nonChanged.addListener(() => (options.enabled ? start() : stop()));\nREADY.then(() => {\n    if (options.enabled) start();\n});\n"
  },
  {
    "path": "src/content_script/canvas_fingerprint.js",
    "content": "/**\n * Copyright (C) 2024 Michael Ziminsky (Z)\n *\n * This file is part of FacebookTrackingRemoval.\n *\n * FacebookTrackingRemoval is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * FacebookTrackingRemoval is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with FacebookTrackingRemoval.  If not, see <http://www.gnu.org/licenses/>.\n */\n\nimport { log } from \"../common.js\";\nimport { MAX_CANVAS_SENSITIVITY, hide_rules, options } from \"../config.js\";\n\nexport { computeCanvasPrints, testCanvas };\n\n/** @type {Map<string, [number]>} */\nconst canvasPrints = new Map();\n\n/**\n * Measures the \"empty\" spaces between the first and last \"opaque\" pixels of a 1D, 1-pixel high row of a rendered canvas\n * @param {Uint8ClampedArray} data An array of pixels for a singal row from a canvas rendering context\n * as retured by `ctx.getImageData(x, y, ctx.canvas.width, 1)`\n */\nfunction gaps(data) {\n    const ALPHA = 180; // somewhat arbitrary based on some manual checks\n    const start = data.findIndex((n, i) => n >= ALPHA && !((i + 1) % 4));\n    if (start < 0) throw \"Empty data\";\n    const end = data.findLastIndex((n, i) => n >= ALPHA && !((i + 1) % 4));\n\n    const fprint = [];\n    for (let i = start, gap = 0, empty = false; i <= end; i += 4) {\n        const val = data[i];\n        if (empty !== val < ALPHA) {\n            if (empty) fprint.push(gap);\n            empty = !empty;\n            gap = 0;\n        }\n        ++gap;\n    }\n    return fprint;\n}\n\n/**\n * @param {CanvasRenderingContext2D} ctx\n * @param {string} [txt]\n */\nfunction fingerprintCanvas(ctx, txt) {\n    const mid = ctx.canvas.height / 2;\n    const off = ctx.measureText(\"\").alphabeticBaseline / 2;\n    if (txt) {\n        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n        ctx.fillText(txt, 0, mid);\n    }\n    const slice = ctx.getImageData(0, mid - off, ctx.canvas.width, 1).data;\n    return gaps(slice);\n}\n\n/**\n * @param {Iterable<string>} texts\n * @param {Element} [ref=document.body]\n */\nasync function computeCanvasPrints(texts, ref) {\n    canvasPrints.clear();\n    const ctx = new OffscreenCanvas(300, 50).getContext(\"2d\", { willReadFrequently: true });\n    const style = getComputedStyle(ref ?? document.body);\n    ctx.font = style.font;\n    ctx.fillStyle = style.color;\n    ctx.textBaseline = \"middle\";\n\n    for (const text of texts) {\n        const fprint = fingerprintCanvas(ctx, text);\n        if (fprint) canvasPrints.set(text, fprint);\n    }\n}\n\n/**\n * Check if the canvas context matches one of the recognized fingerprints\n * as calculated by {@link computeCanvasPrints}\n * @param {CanvasRenderingContext2D} ctx\n */\nfunction testCanvas(ctx) {\n    const fprint = fingerprintCanvas(ctx);\n    if (!fprint) return;\n\n    /** @type {[number, string][]} */\n    let matches = [];\n    for (const [txt, print] of canvasPrints.entries()) {\n        if (fprint.length !== print.length) continue;\n        let sumSq = 0;\n        for (let i = 0; i < print.length; i++) {\n            const diff = Math.abs(fprint[i] - print[i]);\n            sumSq += diff * diff;\n        }\n        const stdDev = Math.sqrt(sumSq / fprint.length);\n        if (stdDev < Number.EPSILON) {\n            matches = [[0, txt]];\n            break;\n        }\n        if (stdDev < MAX_CANVAS_SENSITIVITY - options.canvasSensitivity) {\n            matches.push([stdDev, txt]);\n        }\n    }\n    if (matches.length) {\n        const [stdDev, txt] = matches.reduce((min, match) => (match < min ? match : min));\n        log(() => `Canvas matched fingerprint for \"${txt}\": ${stdDev}`);\n        return txt;\n    }\n}\n"
  },
  {
    "path": "src/content_script/cleaning.js",
    "content": "/**\n * Copyright (C) 2023-2024 Michael Ziminsky (Z)\n *\n * This file is part of FacebookTrackingRemoval.\n *\n * FacebookTrackingRemoval is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * FacebookTrackingRemoval is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with FacebookTrackingRemoval.  If not, see <http://www.gnu.org/licenses/>.\n */\n\nimport { log } from \"../common.js\";\nimport { domains, options } from \"../config.js\";\nimport { STYLE_CLASS } from \"../consts.js\";\nimport { cleanLinkParams } from \"../util.js\";\nimport { applyEventBlockers, cleanAttrs, selectAllWithBase, stopPropagation } from \"./dom.js\";\n\nexport { applyStyle, cleanShimLinks, cleanRedirectLinks, fixGifs, fixVideoLinks, stripFBCLID, stripRefs };\n\nfunction applyStyle(elem) {\n    elem.classList.add(STYLE_CLASS);\n}\n\nconst supportedProtos = [\"http:\", \"https:\", \"ftp:\"];\nfunction cleanLink(a, href) {\n    cleanAttrs(a);\n    a.target = \"_blank\";\n    a.rel = \"noreferrer noopener\";\n    try {\n        if (supportedProtos.includes(new URL(href, origin).protocol)) a.href = href;\n        else log(`Unsupported link protocol; leaving unchanged: ${href}`);\n    } catch (_) {\n        log(`Link cleaning encountered an invalid url: ${href}`);\n    }\n    applyStyle(a);\n}\n\nfunction buildVideo(src, poster) {\n    const video = document.createElement(\"video\");\n    video.preload = \"metadata\";\n    video.controls = true;\n    video.poster = poster;\n    video.setAttribute(\"width\", \"100%\");\n    video.src = src;\n    applyStyle(video);\n    return video;\n}\n\n// Desktop only\nfunction cleanShimLinks(node) {\n    const trackedLinks = selectAllWithBase(node, \"a[onclick^='LinkshimAsyncLink.referrer_log']\");\n    for (const a of trackedLinks) {\n        cleanLink(a, extractQuotedString(a.getAttribute(\"onmouseover\")).replace(/\\\\(.)/g, \"$1\"));\n        log(`Removed tracking from shim link: ${a}`);\n    }\n    return trackedLinks.length;\n}\n\n// Mobile only\nfunction fixVideoLinks(node) {\n    const videoLinks = selectAllWithBase(node, \"div[data-sigil=inlineVideo],a[href^='/video_redirect/']\");\n    for (const vid of videoLinks) {\n        const vidSrc =\n            vid.tagName === \"DIV\"\n                ? JSON.parse(vid.getAttribute(\"data-store\")).src // Phone\n                : new URL(vid.href).searchParams.get(\"src\"); // m.facebook\n\n        const replaceVideo = target => {\n            const img = target.querySelector(\".img,img\"); // phone,m.facebook\n            const poster = extractQuotedString(img.style.backgroundImage) || img.src;\n            const video = buildVideo(vidSrc, poster);\n            target.parentNode.replaceChild(video, target);\n            return video;\n        };\n\n        if (options.inlineVids) {\n            log(`Inlined video: ${replaceVideo(vid).src}`);\n        } else {\n            cleanAttrs(vid);\n            const target = vid.cloneNode(true);\n            applyStyle(target);\n            target.classList.add(\"FBTR-SAFE\");\n            target.addEventListener(\n                \"click\",\n                e => {\n                    e.stopImmediatePropagation();\n                    e.stopPropagation();\n                    replaceVideo(target).play();\n                },\n                true,\n            );\n            vid.parentNode.replaceChild(target, vid);\n            log(`Cleaned deferred inline video: ${vidSrc}`);\n        }\n    }\n    return videoLinks.length;\n}\n\n// Desktop and Mobile\nfunction cleanRedirectLinks(node) {\n    const trackedLinks = selectAllWithBase(\n        node,\n        `a[href*='${location.hostname.split(\".\").slice(-2).join(\".\")}/l.php?']`,\n    );\n    for (const a of trackedLinks) {\n        const newHref = new URL(a.href).searchParams.get(\"u\");\n        cleanLink(a, newHref);\n        log(`Removed tracking from redirect link: ${a}`);\n    }\n    return trackedLinks.length;\n}\n\nconst fbclidFallback = /((?:[?&]|%3F|%26)fbclid=.*?)($|[?&]|%3F|%26)/gi;\nfunction stripFBCLID(node) {\n    const trackedLinks = selectAllWithBase(node, `a[href*='fbclid='i]`);\n    for (const a of trackedLinks) {\n        const link = new URL(a.href);\n\n        link.searchParams.delete(\"fbclid\");\n        if (a.href === link.href) {\n            link.href = link.href.replace(fbclidFallback, \"$2\");\n        }\n\n        if (a.href === link.href) {\n            log(`Failed to remove fbclid from link:\\n -> ${a}`);\n        } else {\n            a.href = link.href;\n            applyStyle(a);\n            log(`Removed fbclid from link: ${a}`);\n        }\n    }\n    return trackedLinks.length;\n}\n\n/** @param {Element} node */\nfunction stripRefs(node) {\n    let intLinks = 0;\n\n    /** @param {HTMLAnchorElement} a */\n    function _strip(a) {\n        if (a.nodeName !== \"A\" || !domains.some(d => a.hostname.endsWith(d))) return;\n\n        ++intLinks;\n        applyEventBlockers(a.parentNode);\n        delete a.dataset.ft;\n\n        const linkBase = a.origin + a.pathname;\n        if (a.hasAttribute(\"href\")) {\n            const orig = a.getAttribute(\"href\"); // get unexpanded value\n            const href = cleanLinkParams(orig, linkBase); // Don't assign here to avoid infinite mutation recursion\n\n            if (href !== orig) {\n                a.href = href;\n                applyStyle(a);\n                log(`Cleaned internal href:\\n\\t${orig}\\n\\t${a.getAttribute(\"href\")}`);\n            }\n        }\n\n        if (a.hasAttribute(\"ajaxify\")) {\n            const orig = a.getAttribute(\"ajaxify\");\n            a.setAttribute(\"ajaxify\", cleanLinkParams(orig, linkBase));\n            if (orig !== a.getAttribute(\"ajaxify\")) {\n                applyStyle(a);\n                log(`Cleaned internal ajaxify link:\\n\\t${orig}\\n\\t${a.getAttribute(\"ajaxify\")}`);\n            }\n        }\n\n        if (a.dataset.hovercard) {\n            delete a.dataset.hovercardReferrer;\n            const orig = a.dataset.hovercard;\n            a.dataset.hovercard = cleanLinkParams(orig, linkBase);\n            if (orig !== a.dataset.hovercard) {\n                applyStyle(a);\n                log(`Cleaned internal hovercard link:\\n\\t${orig}\\n\\t${a.dataset.hovercard}`);\n            }\n        }\n    }\n\n    _strip(node);\n    for (const a of node.getElementsByTagName(\"a\")) {\n        _strip(a);\n    }\n    return intLinks;\n}\n\nfunction fixGifs(node) {\n    const gifs = selectAllWithBase(node, \"div._5b-_\");\n    for (const g of gifs) {\n        const target = g.closest(\"div._2lhm\");\n        if (!target) continue;\n\n        const gif = target.querySelector(\"img.img\").cloneNode(false);\n        gif.classList.add(\"FBTR-SAFE\");\n        gif.dataset.placeholder = gif.src;\n        gif.dataset.src = g.parentNode.href;\n\n        const controls = target.querySelector(\"div._393-\").parentNode.cloneNode(true);\n        controls.classList.add(\"FBTR-SAFE\");\n\n        const toggle = e => {\n            gif.src = controls.classList.toggle(\"fbtrHide\") ? gif.dataset.src : gif.dataset.placeholder;\n            stopPropagation(e);\n        };\n        gif.addEventListener(\"click\", toggle, true);\n        controls.addEventListener(\"click\", toggle, true);\n\n        const wrapper = document.createElement(\"div\");\n        wrapper.appendChild(gif);\n        wrapper.appendChild(controls);\n\n        for (const c of target.classList) wrapper.classList.add(c);\n\n        target.parentNode.replaceChild(wrapper, target);\n        log(`Fixed GIF: ${gif.dataset.src}`);\n    }\n}\n\n/** @param {string} s */\nfunction extractQuotedString(s) {\n    return s.substring(s.indexOf('\"') + 1, s.lastIndexOf('\"'));\n}\n"
  },
  {
    "path": "src/content_script/content_script.js",
    "content": "import(browser.runtime.getURL(\"src/content_script/app.js\")).catch(e =>\n    console.warn(`Failed to load FacebookTrackingRemoval: ${e}`),\n);\n"
  },
  {
    "path": "src/content_script/dom.js",
    "content": "/**\n * Copyright (C) 2023-2024 Michael Ziminsky (Z)\n *\n * This file is part of FacebookTrackingRemoval.\n *\n * FacebookTrackingRemoval is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * FacebookTrackingRemoval is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with FacebookTrackingRemoval.  If not, see <http://www.gnu.org/licenses/>.\n */\n\nimport { log } from \"../common.js\";\nimport { click_whitelist } from \"../config.js\";\nimport { COLLAPSED_SELECTOR, PROCESSED_CLASS } from \"../consts.js\";\n\nexport {\n    applyEventBlockers,\n    ariaText,\n    buildCollapsible,\n    cleanAttrs,\n    inlineUse,\n    selectAllWithBase,\n    stopPropagation,\n    visibleText,\n};\n\n/** @param {Event} e */\nfunction isAllowedTarget(e) {\n    let checkTarget = e.target;\n\n    // Walk through event target and parents until the currentTarget looking for an element that clicks are allowed on\n    while (e.currentTarget.parentNode !== checkTarget) {\n        const role = checkTarget.attributes.role;\n        if (checkTarget.tagName === \"A\" && checkTarget.hostname === location.hostname) {\n            return true;\n        }\n        if (role && click_whitelist.roles.includes(role.value.toUpperCase())) {\n            return true;\n        }\n        if (\n            click_whitelist.elements.includes(checkTarget.tagName) ||\n            checkTarget.classList.contains(\"FBTR-SAFE\") ||\n            checkTarget.matches(click_whitelist.selector)\n        ) {\n            return true;\n        }\n        checkTarget = checkTarget.parentNode;\n    }\n\n    return false;\n}\n\n/**\n * Meant to be used as a capturing event handler\n * @param {Event} e\n */\nfunction restrictEventPropagation(e) {\n    if (isAllowedTarget(e)) {\n        log(`Allowed propagation of ${e.type} from ${e.target} to ${e.currentTarget}`);\n    } else {\n        stopPropagation(e);\n    }\n}\n\n/** @param {Event} e */\nfunction stopPropagation(e) {\n    e.stopImmediatePropagation();\n    e.stopPropagation();\n    log(`Stopped propagation of ${e.type} from ${e.target}`);\n}\n\n/** @param {HTMLElement} target */\nfunction applyEventBlockers(target) {\n    target.addEventListener(\"mousedown\", restrictEventPropagation, true);\n    target.addEventListener(\"focusin\", stopPropagation, true);\n    target.addEventListener(\"focus\", restrictEventPropagation, true);\n    target.addEventListener(\"click\", restrictEventPropagation, true);\n    target.addEventListener(\"mouseup\", restrictEventPropagation, true);\n    target.addEventListener(\"focusout\", stopPropagation, true);\n    target.addEventListener(\"blur\", stopPropagation, true);\n}\n\n/** @param {Element} elem */\nfunction cleanAttrs(elem) {\n    for (let i = elem.attributes.length - 1; i >= 0; --i) {\n        const attr = elem.attributes[i];\n        if (attr.name !== \"class\" && !attr.name.startsWith(\"aria-\")) elem.removeAttribute(attr.name);\n    }\n}\n\n/** @param {string} label */\nfunction buildCollapsible(label) {\n    const content = document.createElement(\"summary\");\n    content.textContent = label;\n    content.classList.add(\"fbtrLabel\");\n\n    const collapsible = document.createElement(\"details\");\n    collapsible.classList.add(PROCESSED_CLASS);\n    collapsible.classList.add(COLLAPSED_SELECTOR.substring(1));\n    collapsible.appendChild(content);\n\n    return collapsible;\n}\n\n/**\n * @param {Element} node\n * @param {string} selector\n */\nfunction selectAllWithBase(node, selector) {\n    const nodeMatches = !node.classList.contains(PROCESSED_CLASS) && node.matches(selector);\n\n    const childResults = [];\n    for (const c of node.querySelectorAll(selector)) {\n        if (!c.classList.contains(PROCESSED_CLASS)) childResults.push(c);\n    }\n\n    const results = (function* () {\n        if (nodeMatches) yield node;\n        yield* childResults;\n    })();\n    results.length = childResults.length + nodeMatches;\n    return results;\n}\n\n/**\n * Replace all `use` elements with a copy of their referenced content.\n * @param {Element} target\n */\nfunction inlineUse(target) {\n    for (const use of selectAllWithBase(target, \"use\")) {\n        const used = document.querySelector(use.href.baseVal)?.cloneNode(true);\n        if (used) {\n            used.removeAttribute(\"id\");\n            use.replaceWith(used);\n        }\n    }\n}\n\n/** @param {HTMLElement} elem */\nfunction ariaText(elem) {\n    const labels = elem\n        .getAttribute(\"aria-labelledby\")\n        ?.split(\" \")\n        .map(id => document.getElementById(id))\n        .filter(e => e);\n\n    const text = [...new Set(labels || [])].map(e => e.textContent).join(\" \");\n    return text ? text : elem.getAttribute(\"aria-label\");\n}\n\n/** @param {HTMLElement} elem */\nfunction visibleText(elem) {\n    let text = elem.dataset.content ?? \"\";\n    const bounds = elem.getBoundingClientRect();\n    const children = [...elem.childNodes].reverse();\n\n    while (children.length > 0) {\n        const child = children.pop();\n        switch (child.nodeType) {\n            case Node.TEXT_NODE:\n                text += child.nodeValue;\n                break;\n            case Node.ELEMENT_NODE: {\n                if (!rectsIntersect(bounds, child.getBoundingClientRect())) continue;\n                text += child.dataset.content ?? \"\";\n                for (let c = child.lastChild; c !== null; c = c.previousSibling) children.push(c);\n                break;\n            }\n        }\n    }\n\n    return text;\n}\n\n/**\n * @param {DOMRect} a\n * @param {DOMRect} b\n */\nfunction rectsIntersect(a, b) {\n    return a.top < b.bottom && a.right > b.left && a.bottom > b.top && a.left < b.right;\n}\n"
  },
  {
    "path": "src/i18n.js",
    "content": "// Copyright (C) 2021-2024 Michael Ziminsky (Z)\n//\n// This file is part of FacebookTrackingRemoval, originally from ProxyTab.\n//\n// FacebookTrackingRemoval is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// FacebookTrackingRemoval is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n// GNU General Public License for more details.\n//\n// You should have received a copy of the GNU General Public License\n// along with FacebookTrackingRemoval.  If not, see <http://www.gnu.org/licenses/>.\n\n/**\n * @see {@link browser.i18n.getMessage}\n * @param {string} key\n */\nfunction getMessage(key, ...vars) {\n    const msg = browser.i18n.getMessage(key, vars);\n    if (!msg) throw `!! Missing Translation - ${key} !!`;\n\n    return msg;\n}\n\nfunction getMessageSafe(key, ...vars) {\n    try {\n        return getMessage(key, ...vars);\n    } catch (e) {\n        return e;\n    }\n}\n\n/**\n * Applies translations declared via attributes to elem\n * @param {HTMLElement} elem\n */\nfunction translate(elem) {\n    try {\n        const { i18n: key, i18nAttr: attr = \"title\", i18nVars: vars = \"\" } = elem.dataset;\n        elem.setAttribute(attr, getMessage(key, ...vars.split(\"||\")));\n    } catch (e) {\n        console.warn(\"Failed to apply translation to %o:\", elem, e);\n    }\n}\n\nwindow.customElements.define(\n    \"fbtr-i18n\",\n    class extends HTMLElement {\n        static get observedAttributes() {\n            return [\"key\"];\n        }\n\n        constructor() {\n            super();\n            for (const child of this.childNodes) {\n                if (child.nodeName !== \"PARAM\") child.remove();\n            }\n\n            // NOTE: Shadow DOM plays poorly with accessibility\n            this.text = this.attachShadow({ mode: \"open\" });\n\n            this.observer = new MutationObserver(this.update.bind(this));\n        }\n\n        get textContent() {\n            return this.text.textContent;\n        }\n\n        attributeChangedCallback() {\n            this.update();\n        }\n\n        connectedCallback() {\n            this.observer.observe(this, { childList: true, subtree: true, attributeFilter: [\"value\"] });\n        }\n\n        disconnectedCallback() {\n            this.observer.disconnect();\n        }\n\n        update() {\n            const key = this.getAttribute(\"key\");\n            const vars = [...this.getElementsByTagName(\"param\")].map(v => v.value);\n            try {\n                this.text.innerHTML = getMessage(key, ...vars);\n                this.classList.remove(\"error\");\n            } catch (e) {\n                this.text.textContent = e;\n                this.classList.add(\"error\");\n            }\n        }\n    },\n);\n\nconst I18N_SELECTOR = \"[data-i18n]\";\ndocument.querySelectorAll(I18N_SELECTOR).forEach(translate);\nnew MutationObserver(muts => {\n    for (const m of muts) {\n        if (m.type === \"attributes\") {\n            translate(m.target);\n        } else\n            for (const e of m.addedNodes) {\n                if (e.nodeType !== 1) continue;\n\n                if (e.matches(I18N_SELECTOR)) translate(e);\n                e.querySelectorAll(I18N_SELECTOR).forEach(translate);\n            }\n    }\n}).observe(document, {\n    attributeFilter: [\"data-i18n\", \"data-i18n-attr\", \"data-i18n-vars\"],\n    subtree: true,\n});\n\nexport default getMessageSafe;\n"
  },
  {
    "path": "src/options/options.css",
    "content": "@import url(./theme.css); /* Fallback for Chrome */\n@import url(chrome://global/skin/in-content/common.css); /* Actual theme in FF */\n\n\n:root {\n    --reset-btn-size: 16px;\n}\n\n*,\n*:before,\n*:after {\n    box-sizing: border-box;\n}\n\n\n#preview {\n    white-space: nowrap;\n}\n\n#btnRefresh.ctrl::before {\n    content: \"Force \";\n}\n\n#_hideMethod > span {\n    display: flex;\n    gap: 1.5rem;\n}\n\n.hidden {\n    display: none;\n}\n\n/* Make checkboxes visible from page action popup */\ninput {\n    display: initial !important;\n}\n\ninput[type=\"radio\"] {\n    margin-inline: initial;\n}\n\nbody {\n    width: max-content;\n}\n\nul {\n    list-style: none;\n    padding-inline-start: calc(1.5 * var(--reset-btn-size));\n}\n\nli {\n    margin: 10px;\n    position: relative;\n}\n\nli,\nlabel {\n    display: flex;\n    column-gap: 5px;\n    align-items: center;\n}\n\n.flex-col {\n    flex-direction: column;\n    flex-grow: 1;\n    align-items: initial;\n    row-gap: 5px;\n}\n\ntextarea {\n    display: block;\n    resize: vertical;\n    padding-right: calc(1.5 * var(--reset-btn-size));\n    min-height: 2rem;\n    flex-grow: 1;\n}\n\ndetails {\n    padding: 5px;\n    border: inset 1px;\n}\n\ndetails ul {\n    padding-inline-start: 0;\n}\n\ndetails>summary {\n    cursor: pointer;\n}\n\nbtn-reset {\n    position: absolute;\n    cursor: pointer;\n    height: var(--reset-btn-size);\n}\n\nbtn-reset:first-child {\n    left: calc(-1.5 * var(--reset-btn-size));\n}\n\nbtn-reset:last-child {\n    top: calc(.5 * var(--reset-btn-size));\n    right: calc(.5 * var(--reset-btn-size));\n}\n\n@media (prefers-color-scheme: dark) {\n    btn-reset {\n        filter: invert();\n    }\n}\n\n/* Timer */\n.resetDone {\n    animation: blank 1s 1;\n}\n\n@keyframes blank {}\n\n.resetDone btn-reset {\n    animation: spin .5s linear infinite;\n}\n\n@keyframes spin {\n    to {\n        transform: rotate(360deg);\n    }\n}\n\nli.resetDone {\n    animation: outline .25s alternate ease-in-out 4;\n}\n\n@keyframes outline {\n    to {\n        outline: dotted 2px seagreen;\n    }\n}\n"
  },
  {
    "path": "src/options/options.html",
    "content": "<!DOCTYPE html>\n<html>\n\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <link rel=\"stylesheet\" href=\"options.css\">\n    <script src=\"/browser-polyfill.min.js\"></script>\n    <script src=\"options.js\" type=\"module\"></script>\n</head>\n\n<body>\n    <fieldset>\n        <legend id=\"legend\">\n            <fbtr-i18n key=\"optsLegend\"></fbtr-i18n>\n        </legend>\n        <p><strong>**<fbtr-i18n key=\"optsReloadNotice\"></fbtr-i18n>**</strong></p>\n\n        <ul>\n            <li>\n                <label>\n                    <input type=\"checkbox\" id=\"enabled\" data-toggle=\"options\">\n                    <fbtr-i18n key=\"optsEnabled\"></fbtr-i18n>\n                </label>\n            </li>\n        </ul>\n        <hr>\n        <ul id=\"options\">\n            <li>\n                <btn-reset></btn-reset>\n                <label>\n                    <input type=\"checkbox\" id=\"fixLinks\">\n                    <fbtr-i18n key=\"optsFixLinks\"></fbtr-i18n>\n                </label>\n            </li>\n            <li>\n                <btn-reset></btn-reset>\n                <label>\n                    <input type=\"checkbox\" id=\"internalRefs\">\n                    <fbtr-i18n key=\"optsInternal\"></fbtr-i18n>\n                </label>\n            </li>\n            <li>\n                <btn-reset></btn-reset>\n                <label>\n                    <input type=\"checkbox\" id=\"inlineVids\" data-depends=\"fixLinks\">\n                    <fbtr-i18n key=\"optsInlineVids\"></fbtr-i18n>\n                </label>\n            </li>\n            <li>\n                <btn-reset></btn-reset>\n                <label>\n                    <input type=\"checkbox\" id=\"delPixeled\">\n                    <fbtr-i18n key=\"optsPixeled\"></fbtr-i18n>\n                </label>\n            </li>\n            <li>\n                <btn-reset></btn-reset>\n                <label>\n                    <input type=\"checkbox\" id=\"delSuggest\">\n                    <fbtr-i18n key=\"optsSuggest\"></fbtr-i18n>\n                </label>\n            </li>\n            <li>\n                <btn-reset></btn-reset>\n                <div class=\"flex-col\">\n                    <label>\n                        <input type=\"checkbox\" id=\"testCanvas\">\n                        <fbtr-i18n key=\"optsCanvas\"></fbtr-i18n>\n                    </label>\n                </div>\n            </li>\n            <li>\n                <btn-reset></btn-reset>\n                <label class=\"flex-col\">\n                    <fbtr-i18n key=\"optsSensitivity\"></fbtr-i18n>\n                    <input type=\"range\" id=\"canvasSensitivity\" data-depends=\"testCanvas\" min=\"0\" step=\"0.2\">\n                </label>\n            </li>\n            <li id=\"_hideMethod\">\n                <btn-reset></btn-reset>\n                <fbtr-i18n key=\"optsHideMethod\"></fbtr-i18n>\n                <span>\n                    <label>\n                        <input type=\"radio\" name=\"hideMethod\" value=\"collapse\">\n                        <fbtr-i18n key=\"optsCollapse\"></fbtr-i18n>\n                    </label>\n                    <label>\n                        <input type=\"radio\" name=\"hideMethod\" value=\"remove\">\n                        <fbtr-i18n key=\"optsRemove\"></fbtr-i18n>\n                    </label>\n                </span>\n            </li>\n            <li>\n                <btn-reset></btn-reset>\n                <label>\n                    <input type=\"checkbox\" id=\"useStyle\">\n                    <fbtr-i18n key=\"optsUseStyle\"></fbtr-i18n>\n                </label>\n            </li>\n            <li>\n                <details>\n                    <summary>\n                        <fbtr-i18n key=\"optsAdvanced\"></fbtr-i18n>\n                    </summary>\n                    <ul>\n                        <li>\n                            <label class=\"flex-col\">\n                                <span>\n                                    <fbtr-i18n key=\"optsStyleLabel\"></fbtr-i18n>\n                                    <fbtr-i18n id=\"preview\" key=\"optsStylePreview\"></fbtr-i18n>\n                                </span>\n                                <div style=\"position: relative; display: flex;\">\n                                    <textarea id=\"modStyle\" data-depends=\"useStyle\" rows=\"1\"></textarea>\n                                    <btn-reset></btn-reset>\n                                </div>\n                            </label>\n                        </li>\n                        <li>\n                            <label class=\"flex-col\">\n                                <fbtr-i18n key=\"optsUserRules\"></fbtr-i18n>\n                                <textarea id=\"userRules\" rows=\"3\"></textarea>\n                            </label>\n                        </li>\n                        <li>\n                            <label>\n                                <input type=\"checkbox\" id=\"pendingRules\">\n                                <fbtr-i18n key=\"optsPending\"></fbtr-i18n>\n                            </label>\n                            -\n                            <em>\n                                <a rel=\"noreferrer noopener\" target=\"_blank\"\n                                    href=\"https://github.com/mgziminsky/FacebookTrackingRemoval/blob/master/data/hide_rules/pending\">\n                                    <fbtr-i18n key=\"optsPendingLink\"></fbtr-i18n>\n                                </a>\n                            </em>\n                        </li>\n                        <li>\n                            <label title=\"For debugging only. Will impact performance when enabled\">\n                                <input type=\"checkbox\" id=\"logging\">\n                                <fbtr-i18n key=\"optsLogging\"></fbtr-i18n>\n                            </label>\n                        </li>\n                        <li>\n                            <label>\n                                <button type=\"button\" id=\"btnRefresh\"></button>\n                            </label>\n                        </li>\n                    </ul>\n                </details>\n            </li>\n        </ul>\n        <button type=\"button\" id=\"reset\" class=\"addon-control\">\n            <fbtr-i18n key=\"optsDefaults\"></fbtr-i18n>\n        </button>\n    </fieldset>\n</body>\n\n</html>\n"
  },
  {
    "path": "src/options/options.js",
    "content": "/*  This file is part of FacebookTrackingRemoval.\n\n    FacebookTrackingRemoval is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    FacebookTrackingRemoval is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with FacebookTrackingRemoval.  If not, see <http://www.gnu.org/licenses/>.\n\n    Copyright (C) 2016-2024 Michael Ziminsky\n*/\n\nimport { isChrome } from \"../common.js\";\nimport * as config from \"../config.js\";\nimport { CHROME_PORT, MSG, NOOP, RATE_LIMIT } from \"../consts.js\";\nimport getMessageSafe from \"../i18n.js\";\nimport { timeoutRemaining } from \"../rules_sync.js\";\n\n//\n/** @type {browser.runtime.Port} */\nlet bgPort;\nif (isChrome) bgPort = browser.runtime.connect({ name: CHROME_PORT });\n\n/** @type {Options} */\nconst changes = new Proxy(\n    {},\n    {\n        set(obj, key, val) {\n            if (config.options[key] === val) {\n                delete obj[key];\n            } else {\n                // Force undefined to null. undefined values don't get sent by postMessage\n                obj[key] = val ?? null;\n            }\n            if (bgPort) bgPort.postMessage(obj);\n            return true;\n        },\n    },\n);\n\n// Only works in FF... https://bugs.chromium.org/p/chromium/issues/detail?id=31262\nwindow.addEventListener(\"unload\", () => {\n    if (Object.keys(changes).length) Object.assign(config.options, changes);\n});\n\n// Expert Options\nconst modStyle = document.getElementById(\"modStyle\");\nconst preview = document.getElementById(\"preview\");\n\n// Set version text\ndocument.title = `${getMessageSafe(\"optsTitle\")} - v${browser.runtime.getManifest().version}`;\ndocument.getElementById(\"legend\").append(` - v${browser.runtime.getManifest().version}`);\n\n{\n    const userRules = document.getElementById(\"userRules\");\n    userRules.title = getMessageSafe(\"optsUserRulesHover\");\n    userRules.placeholder = getMessageSafe(\"optsUserRulesPlaceholder\");\n}\n\n// Set max value for sensitivity slider\n{\n    const slider = document.getElementById(\"canvasSensitivity\");\n    slider.max = config.MAX_CANVAS_SENSITIVITY;\n    slider.title = getMessageSafe(\"optsSenseHover\");\n}\n\n/** @param {Event} e */\nfunction handleChange(e) {\n    switch (e.target.type) {\n        case \"checkbox\":\n            changes[e.target.id] = e.target.checked;\n            break;\n        case \"radio\":\n            changes[e.target.name] = e.target.value;\n            break;\n        case \"text\":\n        case \"textarea\":\n            e.target.value = e.target.value.trim();\n            if (!e.target.value) {\n                changes[e.target.id] = undefined;\n            } else {\n                changes[e.target.id] = e.target.value;\n            }\n            break;\n        default:\n            changes[e.target.id] = e.target.value;\n            break;\n    }\n}\nfor (const text of document.querySelectorAll(\"input,textarea\")) {\n    text.addEventListener(\"change\", handleChange);\n}\n\ndocument\n    .getElementById(\"reset\")\n    .addEventListener(\"click\", _ => config.reset().then(() => document.body.classList.add(\"resetDone\")));\n\nmodStyle.addEventListener(\"input\", e => (preview.style.cssText = e.target.value));\n\n/** @param {Event} e */\nfunction handleToggle(e) {\n    document.getElementById(e.target.dataset.toggle).classList.toggle(\"hidden\", !e.target.checked);\n}\n\n/**\n * @param {Element} elem\n * @param {string} name\n * @param {*} value\n */\nfunction findRadio(elem, name, value) {\n    return elem.querySelector(`input[name=${name}][value=${value}]`);\n}\n\n// Per-option reset functionality\nwindow.customElements.define(\n    \"btn-reset\",\n    class extends HTMLElement {\n        constructor() {\n            super();\n            const img = this.attachShadow({ mode: \"open\" }).appendChild(document.createElement(\"img\"));\n            img.src = \"reset.svg\";\n            img.alt = getMessageSafe(\"optsResetAlt\");\n            img.title = getMessageSafe(\"optsResetTitle\");\n            this.addEventListener(\"click\", this.reset.bind(this));\n        }\n\n        /** @param {MouseEvent} e */\n        reset(e) {\n            e?.preventDefault();\n            const option = this.parentNode.querySelector(\"input[id],textarea[id],input[name]\");\n            const key = option.id || option.name;\n            changes[key] = null;\n            switch (option.type) {\n                case \"radio\":\n                    findRadio(this.parentNode, key, config.defaults[key]).checked = true;\n                    break;\n                case \"checkbox\":\n                    option.checked = config.defaults[key];\n                    break;\n                default:\n                    option.value = config.defaults[key];\n                    break;\n            }\n            this.parentNode.classList.add(\"resetDone\");\n        }\n    },\n);\ndocument.body.addEventListener(\"animationend\", e => e.target.classList.remove(\"resetDone\"));\n\n// Refresh button\n{\n    const btnRefresh = document.getElementById(\"btnRefresh\");\n    const btnText = getMessageSafe(\"optsRefresh\");\n    btnRefresh.title = browser.i18n.getMessage(\"optsRefreshHover\", [RATE_LIMIT / 1000 / 60]);\n\n    let timer;\n    let disabled = false;\n\n    const resetBtn = () => {\n        clearInterval(timer);\n        timer = null;\n        btnRefresh.textContent = btnText;\n        btnRefresh.disabled = disabled = false;\n    };\n\n    const btnRefreshTimer = () => {\n        resetBtn();\n        timeoutRemaining().then((timeout = 0) => {\n            if (timeout <= 0) return;\n\n            let remaining = Math.ceil(timeout / 1000);\n\n            btnRefresh.disabled = disabled = true;\n            btnRefresh.textContent = `${btnText} - ${remaining--} seconds`;\n\n            timer = setInterval(() => {\n                if (remaining <= 0) {\n                    resetBtn();\n                } else {\n                    btnRefresh.textContent = `${btnText} - ${remaining--} seconds`;\n                }\n            }, 1000);\n        });\n    };\n\n    btnRefreshTimer();\n    btnRefresh.addEventListener(\"click\", e => {\n        btnRefresh.disabled = disabled = true;\n        btnRefresh.classList.remove(\"ctrl\");\n        browser.runtime.sendMessage({ msg: MSG.rulesRefresh, force: e.ctrlKey }).then(btnRefreshTimer).catch(NOOP);\n    });\n\n    window.addEventListener(\"keydown\", e => {\n        if (!e.repeat && e.key === \"Control\") {\n            btnRefresh.classList.add(\"ctrl\");\n            btnRefresh.disabled = false;\n        }\n    });\n    window.addEventListener(\"keyup\", e => {\n        if (e.key === \"Control\") {\n            btnRefresh.classList.remove(\"ctrl\");\n            btnRefresh.disabled = disabled;\n        }\n    });\n}\n\n// Keep in sync with other options pages\nconfig.onChanged.addListener(init);\n\n// Avoid duplicated event listeners\nconst dependFuncs = new Map();\n\nfunction init() {\n    for (const key in changes) {\n        delete changes[key];\n    }\n\n    const opts = config.options;\n    for (const key in opts) {\n        const value = opts[key];\n        const item = document.getElementById(key);\n        if (item) {\n            if (item.type === \"checkbox\") {\n                item.checked = value;\n            } else if (item.type === \"text\" || item.tagName === \"TEXTAREA\") {\n                if (!item.placeholder) item.placeholder = config.defaults[key];\n                item.value = value;\n            } else {\n                item.value = value;\n            }\n        } else {\n            const radio = findRadio(document, key, value);\n            if (radio) radio.checked = true;\n        }\n    }\n\n    preview.style.cssText = modStyle.value;\n\n    for (const elem of document.querySelectorAll(\"[data-depends]\")) {\n        const source = document.getElementById(elem.dataset.depends);\n\n        if (!dependFuncs.has(elem)) dependFuncs.set(elem, () => (elem.disabled = !source.checked));\n\n        source.addEventListener(\"change\", dependFuncs.get(elem));\n        elem.disabled = !source.checked;\n    }\n\n    for (const checkbox of document.querySelectorAll(\"input[data-toggle]\")) {\n        checkbox.addEventListener(\"change\", handleToggle);\n        handleToggle.call(undefined, { target: checkbox });\n    }\n}\nconfig.READY.then(init);\n"
  },
  {
    "path": "src/options/theme.css",
    "content": "/* Relevant theme values taken from FF for use in chrome. Will be overridden by actual theme in FF */\n\n:root {\n    font: message-box;\n    appearance: none;\n    background-color: var(--in-content-page-background);\n    color: var(--in-content-page-color);\n}\n\nbody {\n    font-size: 15px;\n    font-weight: normal;\n    margin: 0;\n}\n\nbutton,\nselect,\ninput[type='color'] {\n    appearance: none;\n    min-height: 32px;\n    color: var(--in-content-button-text-color);\n    border: 1px solid var(--in-content-button-border-color);\n    border-radius: 4px;\n    background-color: var(--in-content-button-background);\n    font-weight: 400;\n    padding: 7px 15px;\n    text-decoration: none;\n    margin: 4px 8px;\n    font-size: 1em;\n}\n\ninput:is([type='email'], [type='tel'], [type='text'], [type='password'], [type='url'], [type='number']),\ntextarea {\n    appearance: none;\n    border: 1px solid var(--in-content-box-border-color);\n    border-radius: 4px;\n    color: inherit;\n    background-color: var(--in-content-box-background);\n}\n\n:disabled {\n    opacity: 0.4;\n}\n\n:host,\n:root {\n    --in-content-page-color: rgb(21, 20, 26);\n    --in-content-page-background: #fff;\n    --in-content-text-color: var(--in-content-page-color);\n    --in-content-deemphasized-text: rgb(91, 91, 102);\n    --in-content-box-background: #fff;\n    --in-content-box-background-odd: rgba(12, 12, 13, 0.05); /* grey 90 a05 */\n    --in-content-box-border-color: color-mix(in srgb, currentColor 41%, transparent);\n    --in-content-box-info-background: #f0f0f4;\n    --in-content-item-hover: color-mix(in srgb, var(--in-content-primary-button-background) 20%, transparent);\n    --in-content-item-hover-text: var(--in-content-page-color);\n    --in-content-item-selected: var(--in-content-primary-button-background);\n    --in-content-item-selected-text: var(--in-content-primary-button-text-color);\n    --in-content-icon-color: rgb(91, 91, 102);\n    --in-content-accent-color: var(--in-content-primary-button-background);\n    --in-content-accent-color-active: var(--in-content-primary-button-background-hover);\n    --in-content-border-hover: var(--grey-90-a50);\n    --in-content-border-invalid: var(--red-50);\n    --in-content-border-color: #d7d7db;\n    --in-content-error-text-color: #c50042;\n    --in-content-link-color: var(--in-content-primary-button-background);\n    --in-content-link-color-hover: var(--in-content-primary-button-background-hover);\n    --in-content-link-color-active: var(--in-content-primary-button-background-active);\n    --in-content-link-color-visited: var(--in-content-link-color);\n    /* button background states are also used for checkboxes and radiobuttons */\n    --in-content-button-text-color: var(--in-content-text-color);\n    --in-content-button-text-color-hover: var(--in-content-text-color);\n    --in-content-button-text-color-active: var(--in-content-button-text-color-hover);\n    --in-content-button-background: rgba(207, 207, 216, 0.33);\n    --in-content-button-background-hover: rgba(207, 207, 216, 0.66);\n    --in-content-button-background-active: rgb(207, 207, 216);\n    --in-content-button-border-color: transparent;\n    --in-content-button-border-color-hover: transparent;\n    --in-content-button-border-color-active: var(--in-content-button-border-color-hover);\n    --in-content-primary-button-text-color: rgb(251, 251, 254);\n    --in-content-primary-button-text-color-hover: var(--in-content-primary-button-text-color);\n    --in-content-primary-button-text-color-active: var(--in-content-primary-button-text-color);\n    --in-content-primary-button-background: #0061e0;\n    --in-content-primary-button-background-hover: #0250bb;\n    --in-content-primary-button-background-active: #053e94;\n    --in-content-primary-button-border-color: transparent;\n    --in-content-primary-button-border-hover: transparent;\n    --in-content-primary-button-border-active: transparent;\n    --in-content-danger-button-background: #e22850;\n    --in-content-danger-button-background-hover: #c50042;\n    --in-content-danger-button-background-active: #810220;\n    --in-content-focus-outline-color: var(--in-content-primary-button-background);\n    --in-content-focus-outline-width: 2px;\n    --in-content-focus-outline-offset: 2px;\n    --in-content-focus-outline-inset: calc(-1 * var(--in-content-focus-outline-width));\n    --in-content-focus-outline: var(--in-content-focus-outline-width) solid var(--in-content-focus-outline-color);\n\n    --in-content-table-background: #f8f8fa;\n    --in-content-table-border-color: var(--in-content-box-border-color);\n    --in-content-table-header-background: var(--in-content-primary-button-background);\n    --in-content-table-header-color: var(--in-content-primary-button-text-color);\n    --in-content-sidebar-width: 240px;\n\n    --dialog-warning-text-color: var(--red-60);\n\n    --checkbox-border-color: var(--in-content-box-border-color);\n    --checkbox-unchecked-bgcolor: var(--in-content-button-background);\n    --checkbox-unchecked-hover-bgcolor: var(--in-content-button-background-hover);\n    --checkbox-unchecked-active-bgcolor: var(--in-content-button-background-active);\n    --checkbox-checked-bgcolor: var(--in-content-primary-button-background);\n    --checkbox-checked-color: var(--in-content-primary-button-text-color);\n    --checkbox-checked-border-color: transparent;\n    --checkbox-checked-hover-bgcolor: var(--in-content-primary-button-background-hover);\n    --checkbox-checked-active-bgcolor: var(--in-content-primary-button-background-active);\n\n    --blue-40: #45a1ff;\n    --blue-50: #0a84ff;\n    --blue-60: #0060df;\n    --grey-30: #d7d7db;\n    --grey-60: #4a4a4f;\n    --grey-90-a10: rgba(12, 12, 13, 0.1);\n    --grey-90-a20: rgba(12, 12, 13, 0.2);\n    --grey-90-a30: rgba(12, 12, 13, 0.3);\n    --grey-90-a50: rgba(12, 12, 13, 0.5);\n    --grey-90-a60: rgba(12, 12, 13, 0.6);\n    --green-50: #30e60b;\n    --green-60: #12bc00;\n    --green-70: #058b00;\n    --green-80: #006504;\n    --green-90: #003706;\n    --orange-50: #ff9400;\n    --red-40: #ff4f5e;\n    --red-50: #ff0039;\n    --red-60: #d70022;\n    --red-70: #a4000f;\n    --red-80: #5a0002;\n    --red-90: #3e0200;\n    --yellow-50: #ffe900;\n    --yellow-60: #d7b600;\n    --yellow-60-a30: rgba(215, 182, 0, 0.3);\n    --yellow-70: #a47f00;\n    --yellow-80: #715100;\n    --yellow-90: #3e2800;\n\n    --shadow-10: 0 1px 4px var(--grey-90-a10);\n    --shadow-30: 0 4px 16px var(--grey-90-a10);\n\n    --card-padding: 16px;\n    --card-shadow: var(--shadow-10);\n    --card-outline-color: var(--grey-30);\n    --card-shadow-hover: var(--card-shadow), 0 0 0 5px var(--card-outline-color);\n\n    accent-color: var(--in-content-accent-color);\n    color-scheme: light dark;\n}\n\n@media (prefers-color-scheme: dark) {\n    :host,\n    :root {\n        --in-content-page-background: rgb(28, 27, 34);\n        --in-content-page-color: rgb(251, 251, 254);\n        --in-content-deemphasized-text: rgb(191, 191, 201);\n\n        --in-content-box-background: rgb(35, 34, 43);\n        --in-content-box-background-odd: rgba(249, 249, 250, 0.05);\n        --in-content-box-info-background: rgba(249, 249, 250, 0.15);\n\n        --in-content-border-color: rgba(249, 249, 250, 0.2);\n        --in-content-border-hover: rgba(249, 249, 250, 0.3);\n        --in-content-border-invalid: rgb(255, 132, 139);\n\n        --in-content-error-text-color: #ff9aa2;\n\n        --in-content-button-background: rgb(43, 42, 51);\n        --in-content-button-background-hover: rgb(82, 82, 94);\n        --in-content-button-background-active: rgb(91, 91, 102);\n        --in-content-icon-color: rgb(251, 251, 254);\n\n        --in-content-primary-button-text-color: rgb(43, 42, 51);\n        --in-content-primary-button-background: rgb(0, 221, 255);\n        --in-content-primary-button-background-hover: rgb(128, 235, 255);\n        --in-content-primary-button-background-active: rgb(170, 242, 255);\n\n        --in-content-danger-button-background: #ff848b;\n        --in-content-danger-button-background-hover: #ffbdc5;\n        --in-content-danger-button-background-active: #ffdfe7;\n\n        --in-content-table-background: rgb(35, 34, 43);\n\n        --card-outline-color: var(--grey-60);\n\n        --dialog-warning-text-color: var(--red-40);\n\n        scrollbar-color: rgba(249, 249, 250, 0.4) rgba(20, 20, 25, 0.3);\n    }\n}\n\n@media (prefers-contrast) {\n    :host,\n    :root {\n        --in-content-page-color: CanvasText;\n        --in-content-page-background: Canvas;\n        --in-content-deemphasized-text: GrayText;\n\n        --in-content-box-background: -moz-Dialog;\n        --in-content-box-background-odd: -moz-Dialog;\n        --in-content-box-border-color: -moz-DialogText;\n        --in-content-box-info-background: -moz-Dialog;\n\n        --in-content-item-hover: SelectedItem;\n        --in-content-item-hover-text: SelectedItemText;\n        --in-content-item-selected: SelectedItem;\n        --in-content-item-selected-text: SelectedItemText;\n        --in-content-icon-color: -moz-DialogText;\n\n        --in-content-accent-color: SelectedItem;\n        --in-content-accent-color-active: SelectedItem;\n\n        --in-content-border-hover: ThreeDShadow;\n        /* This is not great, but there is no suitable keyword for this.\n       * In theory, we shouldn't be conveying invalid state just with a colour\n       * change... */\n        --in-content-border-invalid: ThreeDShadow;\n        --in-content-border-color: ThreeDShadow;\n\n        --in-content-link-color: -moz-nativehyperlinktext;\n        --in-content-link-color-hover: -moz-nativehyperlinktext;\n        --in-content-link-color-active: -moz-nativehyperlinktext;\n        --in-content-link-color-visited: -moz-nativehyperlinktext;\n\n        --in-content-button-text-color: ButtonText;\n        --in-content-button-text-color-hover: SelectedItemText;\n        --in-content-button-text-color-active: SelectedItem;\n        --in-content-button-background: ButtonFace;\n        --in-content-button-background-hover: SelectedItem;\n        --in-content-button-background-active: SelectedItemText;\n        --in-content-button-border-color: ButtonText;\n        --in-content-button-border-color-hover: SelectedItemText;\n        --in-content-button-border-color-active: SelectedItem;\n\n        --in-content-primary-button-text-color: ButtonFace;\n        --in-content-primary-button-text-color-hover: SelectedItemText;\n        --in-content-primary-button-text-color-active: SelectedItem;\n        --in-content-primary-button-background: ButtonText;\n        --in-content-primary-button-background-hover: SelectedItem;\n        --in-content-primary-button-background-active: SelectedItemText;\n        --in-content-primary-button-border-color: ButtonFace;\n        --in-content-primary-button-border-hover: SelectedItemText;\n        --in-content-primary-button-border-active: SelectedItem;\n\n        --in-content-danger-button-background: var(--in-content-primary-button-background);\n        --in-content-danger-button-background-hover: var(--in-content-primary-button-background-hover);\n        --in-content-danger-button-background-active: var(--in-content-primary-button-background-active);\n\n        --in-content-focus-outline-color: -moz-DialogText;\n\n        --in-content-table-border-color: ThreeDDarkShadow;\n        --in-content-table-background: -moz-Dialog;\n        --in-content-table-header-background: -moz-Dialog;\n        --in-content-table-header-color: -moz-DialogText;\n\n        --dialog-warning-text-color: -moz-FieldText;\n\n        --checkbox-border-color: ThreeDShadow;\n        --checkbox-unchecked-bgcolor: -moz-Field;\n        --checkbox-unchecked-hover-bgcolor: -moz-Field;\n        --checkbox-unchecked-active-bgcolor: -moz-Field;\n        --checkbox-checked-bgcolor: SelectedItem;\n        --checkbox-checked-color: SelectedItemText;\n        --checkbox-checked-border-color: SelectedItem;\n        --checkbox-checked-hover-bgcolor: -moz-Field;\n        --checkbox-checked-active-bgcolor: -moz-Field;\n    }\n}\n\n@media not (prefers-contrast) {\n    button.semi-transparent:not(.ghost-button, .primary):enabled {\n        background-color: color-mix(in srgb, currentColor 10%, transparent);\n    }\n\n    button.semi-transparent:not(.primary):enabled:hover {\n        background-color: color-mix(in srgb, currentColor 20%, transparent);\n    }\n\n    button.semi-transparent:not(.primary):enabled:hover:active {\n        background-color: color-mix(in srgb, currentColor 30%, transparent);\n    }\n}\n"
  },
  {
    "path": "src/rules_sync.js",
    "content": "/*  This file is part of FacebookTrackingRemoval.\n\n    FacebookTrackingRemoval is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    FacebookTrackingRemoval is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with FacebookTrackingRemoval.  If not, see <http://www.gnu.org/licenses/>.\n\n    Copyright (C) 2016-2024 Michael Ziminsky\n*/\n\nimport { NOOP, RATE_LIMIT } from \"./consts.js\";\nimport { joinSelectors, parseHideRules, splitLines, stripComments } from \"./util.js\";\n\nexport { refreshRules, timeoutRemaining };\n\nconst SELECTOR_RULE_FILES = [\"article_wrapper\", \"unconditional\"];\nconst DYN_RULE_FILES = [\"pending\"];\nconst SPLIT_RULE_DIRS = [\"sponsored\", \"suggested\"];\nconst PARAM_CLEANING_FILES = [\"params\", \"prefix_patterns\", \"values\"];\nconst CLICK_WHITELIST_FILES = [\"elements\", \"roles\", \"selectors\"];\n\nasync function fetchRule(path, currentVal) {\n    const devMode = (await browser.management.getSelf()).installType === \"development\";\n    return fetch(`https://${devMode ? \"localhost\" : \"mgziminsky.gitlab.io\"}/FacebookTrackingRemoval/${path}`, {\n        mode: \"cors\",\n        signal: devMode ? AbortSignal.timeout(100) : undefined,\n    })\n        .then(resp => (resp.ok ? resp : Promise.reject()))\n        .catch(() =>\n            currentVal\n                ? Promise.reject(`Keeping current value: ${currentVal}`)\n                : fetch(browser.runtime.getURL(`data/${path}`)),\n        ) // Fallback to bundled copy\n        .then(resp => (resp.ok ? resp.text() : Promise.reject()));\n}\n\nasync function loadHideRules() {\n    const { hide_rules: currentRules = {} } = await browser.storage.local.get(\"hide_rules\");\n    const newRules = {};\n\n    for (const file of SELECTOR_RULE_FILES) {\n        await fetchRule(`hide_rules/${file}`, currentRules[file])\n            .then(joinSelectors)\n            .then(sel => (newRules[file] = sel))\n            .catch(e => console.warn(`Failed to load selectors file \"${file}\"\\n\\t`, e));\n    }\n\n    for (const file of DYN_RULE_FILES) {\n        await fetchRule(`hide_rules/${file}`, currentRules[file])\n            .then(parseHideRules)\n            .then(rule => Object.assign((newRules[file] ??= {}), rule))\n            .catch(e => console.warn(`Failed to load legacy rules from \"${file}\"\\n\\t`, e));\n    }\n\n    for (const dir of SPLIT_RULE_DIRS) {\n        await loadSplitRule(dir, currentRules[dir])\n            .then(rule => Object.assign((newRules[dir] ??= {}), rule))\n            .catch(e => console.warn(`Split rule \"${dir}\" failed to load\\n\\t`, e));\n    }\n\n    return Object.assign(currentRules, newRules);\n}\n\nasync function loadArrayData(key, files) {\n    const { [key]: currentRules = {} } = await browser.storage.local.get(key);\n\n    const newRules = {};\n    for (const file of files) {\n        await fetchRule(`${key}/${file}`, currentRules[file])\n            .then(stripComments)\n            .then(splitLines)\n            .then(data => (newRules[file] = data))\n            .catch(e => console.warn(`Failed to load array data from \"${key}/${file}\"\\n\\t`, e));\n    }\n\n    return Object.assign(currentRules, newRules);\n}\n\n/** @param {HideRule} currentRule */\nasync function loadSplitRule(dir, currentRule) {\n    const rule = {};\n\n    rule.selector = await fetchRule(`hide_rules/${dir}/selectors`, currentRule?.selector)\n        .then(joinSelectors)\n        .catch(e => console.warn(`Failed to load selectors for \"${dir}\"\\n\\t`, e));\n\n    // Selector required, fail if missing or empty\n    if (!rule.selector) return Promise.reject(\"Selector missing or empty\");\n\n    await fetchRule(`hide_rules/${dir}/texts`, currentRule?.texts)\n        .then(stripComments)\n        .then(splitLines)\n        .then(a => a.sort())\n        .then(texts => (rule.texts = texts))\n        .catch(e => console.warn(`Failed to load texts for \"${dir}\"\\n\\t`, e));\n\n    await fetchRule(`hide_rules/${dir}/patterns`, currentRule?.patterns)\n        .then(stripComments)\n        .then(splitLines)\n        .then(a => a.sort())\n        .then(patterns => (rule.patterns = patterns))\n        .catch(e => console.warn(`Failed to load patterns for \"${dir}\"\\n\\t`, e));\n\n    return rule;\n}\n\n/** @param {Function} func */\nasync function _try(func, ...args) {\n    try {\n        return await func(...args);\n    } catch (error) {\n        console.warn(error);\n    }\n}\n\nasync function timeoutRemaining() {\n    const { lastRuleRefresh } = await browser.storage.local.get(\"lastRuleRefresh\");\n    const timeout = !lastRuleRefresh ? 0 : RATE_LIMIT - (Date.now() - Date.parse(lastRuleRefresh));\n    return Math.max(0, timeout);\n}\n\nasync function refreshRules(force = false) {\n    const timeout = force ? 0 : await timeoutRemaining();\n\n    if (timeout > 0) return Promise.reject(timeout);\n\n    browser.storage.local\n        .set({\n            hide_rules: await _try(loadHideRules),\n            param_cleaning: await _try(loadArrayData, \"param_cleaning\", PARAM_CLEANING_FILES),\n            click_whitelist: await _try(loadArrayData, \"click_whitelist\", CLICK_WHITELIST_FILES),\n            lastRuleRefresh: new Date().toUTCString(),\n        })\n        .then(() => RATE_LIMIT);\n}\n\n// refresh rules every 12 hours\nbrowser.alarms.onAlarm.addListener(() => refreshRules().catch(NOOP));\nbrowser.alarms.create({ when: Date.now(), periodInMinutes: 60 * 12 });\n"
  },
  {
    "path": "src/types.d.ts",
    "content": "// This file is just for the IDE to provide code-assist\n\ninterface HideRule {\n    selector: string;\n    texts?: Map<string, string>;\n    patterns?: RegExp;\n}\n\ninterface HideRules {\n    article_wrapper: string;\n    sponsored: HideRule;\n    suggested: HideRule;\n    pending: HideRule;\n}\n\ninterface ParamCleaning {\n    params: string[];\n    prefix_patterns: string[];\n    values: string[];\n    pattern: RegExp;\n}\n\ninterface ClickWhitelist {\n    elements: string[];\n    roles: string[];\n    selectors: string[];\n    selector: string;\n}\n\ninterface Options {\n    enabled: boolean;\n    fixLinks: boolean;\n    internalRefs: boolean;\n    inlineVids: boolean;\n    fixVideos: boolean;\n    delPixeled: boolean;\n    delSuggest: boolean;\n    hideMethod: string;\n    useStyle: boolean;\n    logging: boolean;\n    modStyle: string;\n    userRules: string;\n    pendingRules: boolean;\n    testCanvas: boolean;\n    canvasSensitivity: number;\n}\n"
  },
  {
    "path": "src/util.js",
    "content": "/*  This file is part of FacebookTrackingRemoval.\n\n    FacebookTrackingRemoval is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    FacebookTrackingRemoval is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with FacebookTrackingRemoval.  If not, see <http://www.gnu.org/licenses/>.\n\n    Copyright (C) 2016-2024 Michael Ziminsky\n*/\n\nimport { param_cleaning } from \"./config.js\";\n\nexport { cleanLinkParams, joinSelectors, normalizeString, parseHideRules, splitLines, stripComments };\n\n/** @param {string} text */\nfunction splitLines(text) {\n    return text.trim().split(/\\s*$\\s*/m);\n}\n\n/** @param {string} text */\nfunction stripComments(text) {\n    return text.replace(/\\/\\*.*?\\*\\//g, \"\").trim();\n}\n\n/** @param {string} text */\nfunction joinSelectors(text) {\n    return stripComments(text)\n        .replace(/\\s*$\\s/gm, \",\")\n        .replace(/\\s+/g, \" \");\n}\n\nfunction parseHideRules(text) {\n    const selector = new Set();\n    const texts = new Set();\n    const patterns = new Set();\n\n    for (const line of splitLines(stripComments(text))) {\n        const [sel, ...filters] = line.split(\"||\");\n\n        sel.trim().replaceAll(/\\s+/g, \" \").split(\",\").forEach(selector.add.bind(selector));\n\n        for (const val of filters) {\n            if (/^\\/.*[^\\\\](?:\\\\\\\\)*\\/$/.test(val)) patterns.add(val.substring(1, val.length - 1));\n            else texts.add(val);\n        }\n    }\n\n    return {\n        selector: Array.from(selector).join(\",\"),\n        texts: Array.from(texts).sort(),\n        patterns: Array.from(patterns).sort(),\n    };\n}\n\n/** @param {string} str */\nfunction normalizeString(str) {\n    return Array.from(str.trim().toLowerCase()).sort().join(\"\");\n}\n\n/** @param {string} link */\nfunction cleanLinkParams(link, base = location.origin + location.pathname) {\n    try {\n        // Don't mess with anchor links\n        if (link.startsWith(\"#\")) return link;\n\n        const url = new URL(link, base);\n\n        // Nothing to do\n        if (url.search.length <= 1) return link;\n\n        const cleanParams = new URLSearchParams(url.search);\n\n        // Can't use bind in FF115+ due to addition of optional 2nd arg for matching on value\n        const deleteParam = p => cleanParams.delete(p);\n\n        /**@type {ParamCleaning}*/\n        const pc = param_cleaning;\n        pc.params.forEach(deleteParam);\n\n        // for..of loop stops early if items are removed\n        // .keys() doesn't work in FF... https://bugzilla.mozilla.org/show_bug.cgi?id=1414602\n        [...cleanParams]\n            .map(([key, _]) => key)\n            .filter(pc.pattern.test.bind(pc.pattern))\n            .forEach(deleteParam);\n\n        // Handle json encoded values\n        for (const name of pc.values.filter(v => cleanParams.has(v))) {\n            const val = JSON.parse(cleanParams.get(name));\n            for (const param of pc.params) delete val[param];\n            for (const key in val) {\n                if (pc.pattern.test(key)) delete val[key];\n            }\n            cleanParams.set(name, JSON.stringify(val));\n        }\n\n        const origLength = url.search.length;\n        url.search = cleanParams;\n        return origLength === url.search.length\n            ? link // No changes, avoid unintended modification\n            : // If link is the same host, use absolute pathname, otherwise use full URL\n              url.href.substring(url.host === location.host ? location.origin.length : 0);\n    } catch (e) {\n        return link;\n    }\n}\n"
  }
]