@adguard/tsurlfilter

中文文档
6.0.4发布于 2026/10/15GPL-3.0-onlyTypeScriptESM + CJS近 30 天下载 3126

这是一个执行 AdGuard 内容屏蔽规则的 TypeScript 库

中文使用文档
文档目录6 节
  1. 思想
  2. 安装
  3. API 描述
  4. 公共财产
  5. 公共课程
  6. 文档

TSUrlFilter 服务器

npm-badge license-badge

这是一个执行AdGuard内容屏蔽规则的TypeScript库.

思想

想法是有一个单一的库,我们可以重复用于以下任务:

  • 在 Chrome 和 Firefox 扩展中屏蔽内容( 显然)
  • 使用此库来解析规则并转换为 Safari 兼容 内容封禁列表 (见 萨法里守护, (中文(简体) ), IOS 的守护(中文(简体) )
  • 使用此库验证和显示过滤列表 (见 过滤器记录, (中文(简体) ), 守护符(中文(简体) )

安装

您可以通过 :

API 描述

公共财产

TSURLFILTER_VERSION

类型 : string

图书馆版本.

公共课程

发动机

引擎是这个库的主要类. 它代表了已装入规则的过滤功能

工厂

你可以通过工厂制造引擎. 有两种模式:同步和同步.

重要编号: content 输入 EngineFactoryOptions 接受其中之一 一个生字符串或一个 FilterList 举个例子. 如果您提供了字符串, 它会自动被包裹 在一个 FilterList 并转会. 如果你提供 FilterList 实例,您完全控制 以可选方式提供转换数据取代转换进程 页:1 FilterList 建筑师.

说明数字 : tsurlfilter 只支持 AdGuard 过滤语法. 如果您需要从其他语法转换规则 (例如:uBlock Origin, Adblock Plus),使用 FilterList 类 将规则自动转换为 AdGuard 格式 通过 RawRuleConverter.convertToAdg()。 。 。 . 此转换应在过滤列表级别进行 在引擎处理规则之前.

同步模式

创建引擎同步 .

/**
 * Creates an instance of the network engine in sync mode.
 *
 * @param options Engine factory options.
 *
 * @returns An instance of the network engine.
 */
public static createSync(options: EngineFactoryOptions): Engine;
同步模式

同步创建引擎 。 我们在AdGuard浏览器扩展中使用了这种方法来避免UI的滞后.

/**
 * Creates an instance of the network engine in async mode.
 *
 * @param options Engine factory options.
 *
 * @returns An instance of the network engine.
 */
public static createAsync(options: EngineFactoryOptions): Promise<Engine>;
示例
const engine = await Engine.createAsync({
    filters: [
        {
            id: 1,
            content: '||example.com^',
        },
    ],
});
匹配请求
/**
 * Matches the specified request against the filtering engine and returns the matching result.
 * In case frameRules parameter is not specified, frame rules will be selected matching request.sourceUrl.
 *
 * @param request - request to check
 * @param frameRules - source rules or undefined
 * @returns matching result
 */
matchRequest(request: Request, frameRule: NetworkRule | null = null): MatchingResult;
匹配图像
/**
  * Matches current frame and returns document-level allowlist rule if found.
  *
  * @param frameUrl
  */
matchFrame(frameUrl: string): NetworkRule | null;
启动引擎
import { Engine, setConfiguration } from '@adguard/tsurlfilter';

const rawFilter = [
  '[AdGuard]',
  '! Title: Example filter',
  '! Description: This is just an example filter.',
  'example.com##h1',
].join('\n');

const config = {
    engine: 'extension',
    version: '1.0.0',
    verbose: true,
};

setConfiguration(config);

// Create engine using the factory method
const engine = Engine.createSync({
    filters: [
        {
            id: 0,
            content: rawFilter,
        },
    ],
});

console.log(`Engine loaded with ${engine.getRulesCount()} rule(s)`);
匹配请求
const request = new Request(url, sourceUrl, RequestType.Document);
const result = engine.matchRequest(request);
获取化妆品数据
const cosmeticResult = engine.getCosmeticResult(request, CosmeticOption.CosmeticOptionAll);

匹配结果

匹配Result包含所有匹配网络请求的规则, 并提供了定义网络请求的方法 应处理

获取基本结果
/**
 * GetBasicResult returns a rule that should be applied to the web request.
 * Possible outcomes are:
 * returns null -- bypass the request.
 * returns a allowlist rule -- bypass the request.
 * returns a blocking rule -- block the request.
 *
 * @returns basic result rule
 */
getBasicResult(): NetworkRule | null;
获取文档锁定结果
/**
 * Returns a rule that should block a document request.
 *
 * @returns Document blocking rule if any, null otherwise.
 */
getDocumentBlockingResult(): NetworkRule | null;
获得可选择性

此旗帜应用于 getCosmeticResult(request: Request, option: CosmeticOption)

/**
  * Returns a bit-flag with the list of cosmetic options
  *
  * @returns {CosmeticOption} mask
  */
getCosmeticOption(): CosmeticOption;
其他规则
/**
  * Return an array of replace rules
  */
getReplaceRules(): NetworkRule[]

/**
  * Returns an array of csp rules
  */
getCspRules(): NetworkRule[]

/**
  * Returns an array of cookie rules
  */
getCookieRules(): NetworkRule[]

化妆品

化妆品的结果是代表相匹配的化妆品规则. 它包含以下属性:

/**
 * Storage of element hiding rules
 */
public elementHiding: CosmeticStylesResult;

/**
 * Storage of CSS rules
 */
public CSS: CosmeticStylesResult;

/**
 * Storage of JS rules
 */
public JS: CosmeticScriptsResult;

/**
 * Storage of Html filtering rules
 */
public Html: CosmeticHtmlResult;

/**
 * Script rules
 */
public getScriptRules(): CosmeticRule[];
应用化妆品结果 - CSS
const css = [...cosmeticResult.elementHiding.generic, ...cosmeticResult.elementHiding.specific]
        .map((rule) => `${rule.getContent()} { display: none!important; }`);

const styleText = css.join('\n');
const injectDetails = {
    code: styleText,
    runAt: 'document_start',
};

chrome.tabs.insertCSS(tabId, injectDetails);
应用化妆品结果 - 脚本
const cosmeticRules = cosmeticResult.getScriptRules();
const scriptsCode = cosmeticRules.map((x) => x.getScript()).join('\r\n');
const toExecute = buildScriptText(scriptsCode);

chrome.tabs.executeScript(tabId, {
    code: toExecute,
});

DnsEngine (英语)

DNSEngine结合了主机规则和网络规则,并且应该迅速找到主机名的匹配规则.

构造器
/**
  * Builds an instance of dns engine
  *
  * @param storage
  */
constructor(storage: RuleStorage);
匹配
/**
 * Match searches over all filtering and host rules loaded to the engine
 *
 * @param hostname to check
 * @returns dns result object
 */
public match(hostname: string): DnsResult;
匹配主机名
const dnsResult = dnsEngine.match(hostname);
if (dnsResult.basicRule && !dnsResult.basicRule.isAllowlist()) {
    // blocking rule found
    ...
}

if (dnsResult.hostRules.length > 0) {
    // hosts rules found
    ...
}

规则语法Utils

此模块不直接用于引擎, 但可用于其他库

公共方法
/**
 * Checks if rule can be matched by domain
 *
 * @param ruleText Rule text
 * @param domain Domain to check
 */
public static isRuleForDomain(ruleText: string, domain: string): boolean
/**
 * Checks if rule can be matched by URL
 *
 * @param ruleText Rule text
 * @param url URL to check
 */
public static isRuleForUrl(ruleText: string, url: string): boolean;

过滤列表

FilterList 是代表已转换过滤器列表的类 能够有效访问转换后和原规则内容.

关键特性
  • 自动规则转换: 使用 AdGuard 格式转换过滤规则 RawRuleConverter.convertToAdg()
  • O(1) 访问:通过转换数据提供对原始过滤规则的经常性访问
  • 双向绘图: 维持转换规则和原规则之间的映射
  • 内容恢复: 从已转换的内容恢复原始过滤列表
构造器
/**
 * Creates a new FilterList instance.
 *
 * @param content Filter list content.
 * @param data Optional conversion data. If not provided, the filter list will be prepared.
 */
constructor(content: string, data?: ConversionData)
转换数据结构

这个 ConversionData 界面跟踪已转换规则和原规则之间的关系 :

interface ConversionData {
    /**
     * Original filter list rules that were converted.
     */
    originals: string[];

    /**
     * Conversion map.
     * Maps line start offsets in the converted content to indexes in the originals array.
     * Keys are 0-based line start offsets, values are 0-based indexes in originals array.
     */
    conversions: Record<number, number>;
}
主要方法
获取转换内容
/**
 * Returns the converted content.
 */
public getContent(): string;
获取规则文本
/**
 * Returns the rule text for a given offset in the converted content.
 * This may be a converted rule.
 *
 * @param offset Line start offset in the converted content.
 * @returns Rule as string, or null if not found.
 */
public getRuleText(offset: number): string | null;
获取原始规则文本
/**
 * Returns the original rule text for a given offset.
 * If the rule was converted, returns the original from conversion data.
 * If not converted, returns the rule text (which is already the original).
 *
 * @param offset Line start offset in the converted content.
 * @returns Original rule text, or null if offset is invalid.
 */
public getOriginalRuleText(offset: number): string | null;
正在转换规则正本( Strict)
/**
 * Returns the original rule text only if the rule was actually converted.
 * Unlike getOriginalRuleText(), this returns null for unconverted rules.
 *
 * @param offset Line start offset in the converted content.
 * @returns Original rule text if converted, or null if not converted or invalid offset.
 */
public getConvertedRuleOriginal(offset: number): string | null;
恢复原始内容
/**
 * Restores the original filter list content from the converted content.
 *
 * @returns Original filter list content.
 */
public getOriginalContent(): string;
静态方法
/**
 * Creates an empty converted filter list.
 */
public static createEmpty(): FilterList;

/**
 * Creates an empty conversion data.
 */
public static createEmptyConversionData(): ConversionData;
用法示例
import { FilterList } from '@adguard/tsurlfilter';

// Create a filter list (automatically converts rules)
const filterList = new FilterList('||example.com^$third-party');

// Get converted content
const converted = filterList.getContent();

// Get rule at specific offset
const rule = filterList.getRuleText(0);

// Get original rule if it was converted
const original = filterList.getOriginalRuleText(0);

// Restore full original content
const originalContent = filterList.getOriginalContent();

// Create from existing conversion data (no re-conversion)
const data = filterList.getConversionData();
const filterList2 = new FilterList(converted, data);

文档

版本与发布记录

@adguard/tsurlfilter 共发布 248 个版本,首次发布于 2020/07/15;过去 12 个月发布了 16 个版本。

版本发布日期距今
6.0.4latest2026/10/1523 天前
6.0.32026/08/252 个月前
6.0.22026/07/293 个月前
5.0.12026/04/276 个月前
5.0.0-beta.1beta2026/04/176 个月前
5.0.0-beta2026/04/166 个月前

其他发布通道:alpha → 3.3.0-alpha.0,beta → 5.0.0-beta.1。

关于 @adguard/tsurlfilter 的常见问题

@adguard/tsurlfilter 是什么?

这是一个执行 AdGuard 内容屏蔽规则的 TypeScript 库

如何安装 @adguard/tsurlfilter?

在项目目录运行 npm install @adguard/tsurlfilter,或使用 pnpm add / yarn add / bun add。

@adguard/tsurlfilter 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@adguard/tsurlfilter 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@adguard/tsurlfilter 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@adguard/tsurlfilter 可以商用吗?

@adguard/tsurlfilter 使用 GPL-3.0-only 许可。强 Copyleft:分发包含该代码的软件时,整个作品需以 GPL-3.0 兼容许可开源,并附带专利与反锁定条款。仅内部使用不触发此义务。以上为概括,不构成法律意见,请以许可原文为准。

@adguard/tsurlfilter 的下载量有多少?

根据 npm 官方下载统计,@adguard/tsurlfilter 在 2026/10/05 – 2026/11/03 这 30 天内被下载 3,126 次,日均约 104 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@adguard/tsurlfilter 还在维护吗?

最新版本 6.0.4 发布于 2026/10/15(23 天前);至今共发布 248 个版本,其中过去 12 个月发布了 16 个;首次发布于 2020/07/15。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。