From f4f3c8d4d10345b023b4cfc1210aec80dd755aed Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 30 May 2024 13:01:39 -0500 Subject: [PATCH] Remove empty tag filters --- src/filter.ts | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/filter.ts b/src/filter.ts index fd698c4..f9288c8 100644 --- a/src/filter.ts +++ b/src/filter.ts @@ -1,6 +1,5 @@ -import { NostrEvent, NostrFilter, NSchema as n } from '@nostrify/nostrify'; +import { NKinds, NostrEvent, NostrFilter, NSchema as n } from '@nostrify/nostrify'; import stringifyStable from 'fast-stable-stringify'; -import { getFilterLimit } from 'nostr-tools'; import { z } from 'zod'; /** Microfilter to get one specific event by ID. */ @@ -65,6 +64,25 @@ function normalizeFilters(filters: F[]): F[] { }, []); } +/** Calculate the intrinsic limit of a filter. This function may return `Infinity`. */ +function getFilterLimit(filter: NostrFilter): number { + if (filter.ids && !filter.ids.length) return 0; + if (filter.kinds && !filter.kinds.length) return 0; + if (filter.authors && !filter.authors.length) return 0; + + for (const [key, value] of Object.entries(filter)) { + if (key[0] === '#' && Array.isArray(value) && !value.length) return 0; + } + + return Math.min( + Math.max(0, filter.limit ?? Infinity), + filter.ids?.length ?? Infinity, + filter.authors?.length && filter.kinds?.every((kind) => NKinds.replaceable(kind)) + ? filter.authors.length * filter.kinds.length + : Infinity, + ); +} + export { type AuthorMicrofilter, canFilter,