UNPKG

@adguard/agtree

Version:
65 lines (62 loc) 2.66 kB
/* * AGTree v3.2.2 (build date: Tue, 08 Jul 2025 13:39:47 GMT) * (c) 2025 Adguard Software Ltd. * Released under the MIT license * https://github.com/AdguardTeam/tsurlfilter/tree/master/packages/agtree#readme */ import { NULL, COMMA, PIPE } from '../../utils/constants.js'; import { isUndefined } from '../../utils/type-guards.js'; import { BaseSerializer } from '../base-serializer.js'; import { ListItemsSerializer } from './list-items-serializer.js'; import { DomainListMarshallingMap } from '../../marshalling-utils/misc/domain-list-common.js'; import { BinaryTypeMarshallingMap } from '../../marshalling-utils/misc/binary-type-common.js'; /** * Value map for binary serialization. This helps to reduce the size of the serialized data, * as it allows us to use a single byte to represent frequently used values. * * ! IMPORTANT: If you change values here, please update the {@link BINARY_SCHEMA_VERSION}! * * @note Only 256 values can be represented this way. */ const SEPARATOR_SERIALIZATION_MAP = new Map([ [COMMA, 0], [PIPE, 1], ]); /** * `DomainListSerializer` is responsible for serializing a domain list. * * @example * - If the rule is `example.com,~example.net##.ads`, the domain list is `example.com,~example.net`. * - If the rule is `ads.js^$script,domains=example.com|~example.org`, the domain list is `example.com|~example.org`. * This serializer is responsible for serializing these domain lists. * @see {@link https://help.eyeo.com/adblockplus/how-to-write-filters#elemhide_domains} */ class DomainListSerializer extends BaseSerializer { /** * Serializes a domain list node to binary format. * * @param node Node to serialize. * @param buffer ByteBuffer for writing binary data. */ static serialize(node, buffer) { buffer.writeUint8(BinaryTypeMarshallingMap.DomainListNode); const separator = SEPARATOR_SERIALIZATION_MAP.get(node.separator); if (isUndefined(separator)) { throw new Error(`Invalid separator: ${node.separator}`); } buffer.writeUint8(DomainListMarshallingMap.Separator); buffer.writeUint8(separator); buffer.writeUint8(DomainListMarshallingMap.Children); ListItemsSerializer.serialize(node.children, buffer); if (!isUndefined(node.start)) { buffer.writeUint8(DomainListMarshallingMap.Start); buffer.writeUint32(node.start); } if (!isUndefined(node.end)) { buffer.writeUint8(DomainListMarshallingMap.End); buffer.writeUint32(node.end); } buffer.writeUint8(NULL); } } export { DomainListSerializer };