npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@adguard/api

v2.1.4

Published

This is a TypeScript library that implements AdGuard's extension API

Downloads

20

Readme

AdGuard API

[!NOTE] Version: v2.1.0

AdGuard API is a filtering library that provides the following features:

  • Request and content filtering, using @adguard/tswebextension.
  • Filtering rules list management (downloading, caching, and auto updates).
  • Content blocking via AdGuard Assistant UI.
  • Auto-detecting language filters.
  • Logging request processing.

Table of contents

Installation

  1. Install the @adguard/api module via npm or yarn
npm install @adguard/api

or

yarn add @adguard/api
  1. Import the AdguardApi class to the background script
import { AdguardApi } from "@adguard/api";
  1. Import adguard-contents at the top of your content script entry
import '@adguard/api/content-script';
  1. Import adguard-assistant at the top of your assistant script entry
import '@adguard/api/assistant';

Required web accessible resources

AdGuard API requires web accessible resources from the AdGuard Scriptlets library to be able to redirect web requests to a local "resource" using the $redirect rule modifier. You can use @adguard/tswebextension CLI to download it.

Configuration

Syntax:

type Configuration = {
    filters: number[],
    filteringEnabled: boolean,
    allowlist?: string[],
    blocklist?: string[],
    rules?: string[],
    filtersMetadataUrl: string,
    filterRulesUrl: string,
    documentBlockingPageUrl?: string,
};

Properties:

  • filters (mandatory) - An array of filters identifiers. You can look for possible filters identifiers in the filters metadata file.

  • filteringEnabled (mandatory) - Enable/disable filtering engine.

  • allowlist (optional) - An array of domains, for which AdGuard won't work.

  • blocklist (optional) - This property completely changes AdGuard behavior. If it is defined, Adguard will work for domains from the blocklist only. All other domains will be ignored. If blocklist is defined, allowlist will be ignored.

  • rules (optional) - An array of custom filtering rules. Here is an article describing filtering rules syntax. These custom rules might be created by a user via AdGuard Assistant UI.

  • filtersMetadataUrl (mandatory) - An absolute path to a file, containing filters metadata. Once started, AdGuard will periodically check filters updates by downloading this file. Example: https://filters.adtidy.org/extension/chromium/filters.json.

  • filterRulesUrl (mandatory) - URL mask used for fetching filters rules. {filter_id} parameter will be replaced with an actual filter identifier. Example: https://filters.adtidy.org/extension/chromium/filters/{filter_id}.txt (English filter (filter id = 2) will be loaded from: https://filters.adtidy.org/extension/chromium/2.txt)

  • documentBlockingPageUrl (optional) - Path to the document blocking page. If not specified, the default browser page will be shown.

Example:

const configuration: Configuration = {
    filters: [],
    allowlist: [],
    blocklist: [],
    rules: [],
    filtersMetadataUrl: 'https://filters.adtidy.org/extension/chromium/filters.json',
    filterRulesUrl: 'https://filters.adtidy.org/extension/chromium/filters/{filter_id}.txt'
};

![!WARNING] Please note, that we do not allow using filters.adtidy.org other than for testing purposes. You have to use your own server for storing filter files. You can (and actually should) use filters.adtidy.org for periodically updating files on your side.

Static methods

Creates a new AdguardApi instance.

AdguardApi.create

Syntax:

public static async create(): Promise<AdguardApi>

Example:

const adguardApi = await AdguardApi.create();

Methods

adguardApi.getMessageHandler

Gets the message handler for API content script messages.

The API message handler name is a constant that can be exported as MESSAGE_HANDLER_NAME from @adguard/api.

Syntax:

public getMessageHandler(): MessageHandlerMV2

Example:

// get tswebextension message handler
const handleApiMessage = adguardApi.getMessageHandler();

const handleAppMessage = async (message: Message) => {
  // handle your app messages here
};

// route message depending on handler name
browser.runtime.onMessage.addListener(async (message, sender) => {
  if (message?.handlerName === MESSAGE_HANDLER_NAME) {
    return Promise.resolve(handleApiMessage(message, sender));
  }
  return handleAppMessage(message);
});

Returns:

A message handler that will listen to internal messages. For example: messages for get computed css for content-script.

adguardApi.start

Initializes AdGuard API and starts it immediately.

Syntax:

public async start(configuration: Configuration): Promise<Configuration>

Example:

const appliedConfiguration = await adguardApi.start(configuration);

Parameters:

Returns:

A Promise, resolved with applied API Configuration when api is initialized and filtering started

adguardApi.stop

Completely stops AdGuard API.

Syntax:

public async stop(): Promise<void>

Example:

await adguardApi.stop();

Returns:

Promise, resolved when API is completely stopped

adguardApi.configure

This method modifies AdGuard configuration.

Note, that Adguard must be already started (see adguardApi.start).

Syntax:

public async configure(configuration: Configuration): Promise<Configuration>

Example:

const updatedConfiguration = await adguardApi.configure(configuration);

Parameters:

Returns:

A Promise object that is getting resolved with applied API Configuration when the API config is updated.

adguardApi.setFilteringEnabled

Enables or disables filtering without engine re-initialization.

Syntax:

public async setFilteringEnabled(value: boolean): Promise<void>

Example:

await adguardApi.setFilteringEnabled(false);

Parameters:

  • value - boolean value that indicates the filtering engine state.

Returns:

A Promise object that is getting resolved when filtering engine state is updated.

adguardApi.openAssistant

Opens the AdGuard Assistant UI in the specified tab. You must also subscribe on onAssistantCreateRule event channel for applying rules that are created by Adguard Assistant.

Syntax:

public async openAssistant(tabId: number): Promise<void>

Example:

await adguardApi.openAssistant(tabId);

Parameters:

Returns:

A Promise object that is getting resolved when the Assistant UI is opened in the specified tab.

adguardApi.closeAssistant

Closes AdGuard Assistant in the specified tab.

Syntax:

public async openAssistant(tabId: number): Promise<void>

Example:

await adguardApi.closeAssistant(tabId);

Parameters:

Returns:

A Promise object that is getting resolved when Assistant UI id closed in the specified tab.

adguardApi.getRulesCount

Gets currently loaded rules count.

Syntax:

public getRulesCount(): number

Example:

adguardApi.getRulesCount();

Returns:

rules count number

adguardApi.onAssistantCreateRule

TsWebExtension event channel that receives events when a rule is created via AdGuard Assistant.

Syntax:

public onAssistantCreateRule: EventChannel<string>;

Example:


// update config on Assistant rule apply
const applyRule = async (rule): Promise<void> => {
  console.log(`Rule ${rule} was created by Adguard Assistant`);
  configuration.rules!.push(rule);
  await adguardApi.configure(configuration);
};

// add listener
adguardApi.onAssistantCreateRule.subscribe(applyRule);

// remove listener
adguardApi.onAssistantCreateRule.unsubscribe(applyRule);

adguardApi.onFiltersDeletion

TsWebExtension Event channel, which fires event on obsoleted filters deletion. It can be fired after checking an update for filters in the FiltersUpdateService.

Syntax:

public onFiltersDeletion: EventChannel<number[]>;

Example:


// update config on filter deletion
const removeObsoletedFilterId = async (filterIds: number[]): Promise<void> => {
  console.log(`Filters with ids ${filterIds} deleted because they became obsoleted.`);
  configuration.filters = configuration.filters.filter((id) => !filterIds.includes(id));

  await adguardApi.configure(configuration);
};

// add listener
adguardApi.onFiltersDeletion.subscribe(removeObsoletedFilterId);

// remove listener
adguardApi.onFiltersDeletion.unsubscribe(removeObsoletedFilterId);

adguardApi.onRequestBlocking

API for adding and removing listeners for request blocking events.

Syntax:

export interface RequestBlockingLoggerInterface {
    addListener(listener: EventChannelListener<RequestBlockingEvent>): void;
    removeListener(listener: EventChannelListener<RequestBlockingEvent>): void;
}

Example:

// Registers an event listener
adguardApi.onRequestBlocked.addListener(
  callback // function, mandatory
)
// Removes specified event listener
adguardApi.onRequestBlocked.removeListener(
  callback // function, mandatory
)

Callback parameter properties:

  • tabId - Tab identifier.
  • requestUrl - URL of the blocked request.
  • referrerUrl - Referrer URL.
  • rule - Filtering rule that has been applied to this request.
  • filterId - ID of the filter list the rule belongs to.
  • requestType - Request mime type. Possible values are listed below:

Request types:

  • DOCUMENT - top-level frame document.
  • SUBDOCUMENT - document loaded in a nested frame.
  • SCRIPT
  • STYLESHEET
  • OBJECT
  • IMAGE
  • XMLHTTPREQUEST
  • MEDIA
  • FONT
  • WEBSOCKET
  • OTHER

Usage

See full sample app project in examples/adguard-api

import { AdguardApi, Configuration, RequestBlockingEvent } from "@adguard/api";

(async (): Promise<void> => {
    // create new AdguardApi instance
    const adguardApi = AdguardApi.create();

    const configuration: Configuration = {
        filters: [2],
        allowlist: ["www.example.com"],
        rules: ["example.org##h1"],
        filterRulesUrl: "https://filters.adtidy.org/extension/chromium/filters/{filter_id}.txt",
        filtersMetadataUrl: "https://filters.adtidy.org/extension/chromium/filters.json",
    };

    // console log event on request blocking
    const onRequestBlocked = (event: RequestBlockingEvent) => {
        console.log(event);
    };

    // console log current rules count, loaded in engine
    const logTotalCount = (): void => {
        console.log("Total rules count:", adguardApi.getRulesCount());
    };

    adguardApi.onRequestBlocked.addListener(onRequestBlocked);

    await adguardApi.start(configuration);

    console.log("Finished Adguard API initialization.");
    logTotalCount();

    configuration.allowlist!.push("www.google.com");

    await adguardApi.configure(configuration);

    console.log("Finished Adguard API re-configuration");
    logTotalCount();

    // update config on Assistant rule apply
    adguardApi.onAssistantCreateRule.subscribe(async (rule) => {
        console.log(`Rule ${rule} was created by Adguard Assistant`);
        configuration.rules!.push(rule);
        await adguardApi.configure(configuration);
        console.log("Finished Adguard API re-configuration");
        logTotalCount();
    });

    chrome.runtime.onMessage.addListener(async (message) => {
        switch (message.type) {
            case "OPEN_ASSISTANT": {
                chrome.tabs.query({ active: true }, async (res) => {
                    if (res[0]?.id) {
                        await adguardApi.openAssistant(res[0].id);
                    }
                });
                break;
            }
            default:
            // do nothing
        }
    });

    // Disable Adguard in 1 minute
    setTimeout(async () => {
        adguardApi.onRequestBlocked.removeListener(onRequestBlocked);
        await adguardApi.stop();
        console.log("Adguard API has been disabled.");
    }, 60 * 1000);
})();

Minimum supported browser versions

| Browser | Version | |------------------------- |:---------:| | Chromium Based Browsers | 79 | | Firefox | 78 | | Opera | 66 | | Edge | 79 |