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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@biolibs/entrez

v1.1.1

Published

NCBI E-utilities client, verified against Biopython: efetch, esearch, esummary, elink, epost, einfo, espell and ecitmatch build the same requests, with the same rate limit and retries, and read and parse turn the XML that comes back into lists and diction

Readme

@biolibs/entrez

A client for NCBI's E-utilities — GenBank, PubMed, Protein, Taxonomy and the rest of Entrez — that sends the requests Biopython's Bio.Entrez sends, and reads the XML that comes back the way Entrez.read and Entrez.parse read it. It is the one @biolibs package that touches the network.

  • The eight E-utilities — efetch, esearch, esummary, elink, epost, einfo, espell, ecitmatch, with Biopython's names and arguments
  • The same request, byte for byte — the same parameter order, the same URL encoding, the same switch from GET to POST for long queries and long identifier lists
  • The same manners — at most three requests a second, ten with an API key; retries for server errors and dropped connections, none for a plain "not found"
  • Runs in a browser — NCBI's servers answer with Access-Control-Allow-Origin: *, so a page can fetch a record with no server of its own
  • One replaceable function touches the network — swap settings.transport to route requests through a proxy, add caching, or test without a connection
  • The XML read back — read and parse turn a reply into lists, dictionaries, strings and integers, deciding which is which from the DTD the reply names, as Biopython does
  • Every DTD Biopython ships, 291 of them, inside the package: nothing is downloaded to read a reply
  • Two dependencies, @biolibs/core and @biolibs/seqio, whose XML scanner this builds on

Sequence records come back as text for @biolibs/seqio; XML comes back as bytes for read.

What is verified

A generator drives the real Biopython with its network call replaced, and records what it would have sent: the method, the full URL, the POST body, the warning it gives when no email address is set, and the exception type and message where it raises. The tests replay those recordings.

| Upstream module | Items at parity | Checklist | |---|---|---| | Bio.Entrez | 10 / 10 | Bio.Entrez.md | | Bio.Entrez.Parser | 53 / 53 | Bio.Entrez.Parser.md |

The requests: 1,092 recorded cases against Biopython 1.88.

| Cases | What they record | |---|---| | 210 | the eight public functions, each under five combinations of email, tool and API key | | 240 | _build_request: every class of character in a query, lists, numbers, bytes, the GET/POST switch either side of both its limits | | 160 | _construct_params: what is added, what is dropped, and when it warns | | 237 | _has_api_key | | 206 | _open: the pause between requests, which errors are retried and how often, and the reply | | 24 | _format_ids | | 15 | _update_ecitmatch_variables |

Reading the replies: 1,791 recorded cases of read and parse, and under them 2,100 cases of the XML parser they stand on.

| Cases | What they record | |---|---| | 164 | a reply of each kind — esearch, esummary, einfo, elink, epost, espell, egquery, a PubMed article set with MathML, a taxonomy set, a JATS article, an XML Schema report — under every combination of validate, escape and ignore_errors | | 516 | what is not a good reply: not XML, no DTD, a DTD from somewhere it should not come from, a DTD that is not shipped, tags the DTD lacks, errors NCBI reports in the XML, malformed eSummary items, namespaces | | 1,019 | good replies broken one character at a time, or cut short | | 92 | long replies for parse, which reads 1,024 bytes at a time: which records are yielded before a late fault | | 291 | every DTD Biopython ships: what elementDecl decides each of its elements is | | 2,100 | the XML parser: every handler call real expat makes, in order, for documents and DTDs of every shape — 1,897 of them DTDs broken one character at a time, with the error and the line and column expat gives | | 291 | every shipped DTD again, through the XML parser: each element, attribute and entity declaration |

Each case holds every element Biopython built — its tag, attributes, key and the tags it allows — and the repr of the whole, or the exception with its message. For parse, the records it yielded before failing are part of the answer.

Where the claim stops:

  • Nothing is downloaded while parsing. Biopython fetches a DTD it does not have. read is not asynchronous and cannot, so a reply naming a DTD that is not among the 291 fails as Biopython fails with no network: RuntimeError: Failed to access …. Fetch it yourself and registerDtd it.
  • Expat is stood in for, not ported. Python's parser is expat, a C library. The stand-in is held to the 2,100 recorded cases, which cover what Biopython uses of it. Two things it does not do: follow a reference to an external general entity (NCBI's DTDs have none), and model expat's input buffer for anything but parse's 1,024-byte reads.
  • Text is refused, as in Python. read takes bytes or a handle. A string raises StreamModeError: XML names its own encoding, and a string has already been decoded by someone who did not ask it.
  • One order is chosen where Python's is random. A dictionary element starts with an empty list for each tag that may repeat, and Biopython makes them by walking a frozenset — so their order changes from one Python process to the next. Here they are alphabetical. Every other key is in document order.
  • DTD names are matched exactly. On a Mac Biopython finds eLink_101123.dtd under any capitals, because the file system does; on Linux it does not. This follows Linux.
  • The network itself is not recorded. fetchTransport, the default way of sending a request, is tested against a stand-in for fetch, not against Biopython: there is nothing reproducible to record. Everything up to the moment of sending, and everything done with the reply, is.
  • A reply is read in full before it is returned. Biopython hands back an open connection to read from; this hands back the bytes. For the size of reply the E-utilities give, the difference is memory, not behaviour.
  • Whole numbers and other numbers are one type here. 5 is written as Python writes the int 5. There is no way to pass the float 5.0, which Python would write as 5.0; pass the text "5.0".

Oddities that are Biopython's and are kept:

  • elink with a number for id raises AttributeError: 'int' object has no attribute 'count'. It does not join its identifiers, and then asks the number how many commas it has.
  • With maxTries set to 0 nothing is sent, and the result is UnboundLocalError.
  • A server error is retried at once; only a connection that got no answer waits sleepBetweenTries.

Install

npm install @biolibs/entrez
  • ESM only, Node 20 or later, TypeScript declarations included
  • Uses the platform's fetch: every current browser, and Node 20 or later
graph BT
  entrez["@biolibs/entrez"] --> core["@biolibs/core<br/><i>Python errors, warnings, UTF-8, inflate</i>"]
  entrez --> seqio["@biolibs/seqio<br/><i>the XML scanner; sequence text is for it too</i>"]

Say who you are

NCBI asks every client to give an email address, so that it can get in touch before blocking heavy use. Set it once. Biopython warns on every request made without one, and so does this.

import { settings } from "@biolibs/entrez";

settings.email = "[email protected]";   // Python: Entrez.email = "[email protected]"
settings.tool;                              // "biopython" — sent as-is unless you change it
settings.apiKey = "0123456789abcdef";       // optional: raises the limit from 3 requests a second to 10

Your email address is sent to NCBI with every request, in the URL. That is what NCBI asks for, and what Biopython does; it is worth knowing before using this in a page other people will open.

Fetching a record

efetch takes the database and then the rest of the parameters as an object, where Python takes keyword arguments.

import { efetch } from "@biolibs/entrez";
import { read } from "@biolibs/seqio";

const handle = await efetch("nucleotide", { id: "EU490707", rettype: "gb", retmode: "text" });

handle.url;        // the address the reply came from
handle.text;       // true — NCBI declared it plain text
const record = read(handle.readText(), "genbank");
record.id;         // "EU490707.1"

handle.read() does what Python's does: text for a plain-text reply, bytes for anything else, which is how XML arrives. handle.readText() always gives text, and handle.bytes always gives the bytes.

Searching

import { esearch } from "@biolibs/entrez";

const handle = await esearch("nucleotide", "Opuntia[orgn] AND rpl16", { retmax: 5, idtype: "acc" });
handle.readText();   // XML listing the matching identifiers

The reply is XML, and read makes sense of it.

Reading the XML back

read is Biopython's Entrez.read. Give it the handle, or the bytes:

import { type DictionaryElement, type ListElement, esearch, read } from "@biolibs/entrez";

const handle = await esearch("pubmed", "biopython[title]", { retmax: 3 });
const record = read(handle) as DictionaryElement;

record.get("Count")?.toString();                     // "3"
(record.get("IdList") as ListElement).map(String);   // ["19304878", "18606172", "16403221"]
record.repr();
// "{'Count': '3', 'RetMax': '3', 'RetStart': '0', 'IdList': ['19304878', '18606172', '16403221']}"

What comes back is ordinary data — a dictionary is a Map, a list is an Array, a string is a String — and each piece also remembers the element it came from:

const ids = record.get("IdList") as ListElement;
ids.tag;                // "IdList"
ids[0]!.tag;            // "Id"
ids[0]!.attributes;     // Map(0) {}

Which element is a list and which a dictionary is not in the XML. It is in the DTD the reply names, and the package carries every DTD Biopython does. repr() gives what Python would print.

parse is Entrez.parse, for a reply that is a list of records. It yields them one at a time:

import { type DictionaryElement, efetch, parse } from "@biolibs/entrez";

const handle = await efetch("taxonomy", { id: "9615,9685", retmode: "xml" });
const names: string[] = [];
for (const record of parse(handle)) names.push(String((record as DictionaryElement).get("ScientificName")));
names;   // ["Canis lupus familiaris", "Felis catus"]

Both take Biopython's three options, as an object:

read(handle, { validate: false });       // skip tags the DTD does not define, instead of ValidationError
read(handle, { escape: true });          // & < > in text become &amp; &lt; &gt;
read(handle, { ignoreErrors: true });    // keep an <ERROR> from NCBI as an ErrorElement, instead of RuntimeError

A reply that names a DTD the package does not have cannot be read until you supply it:

import { read, registerDtd } from "@biolibs/entrez";

registerDtd("mine.dtd", "<!ELEMENT Result (Id*)> <!ELEMENT Id (#PCDATA)>");

const xml = '<?xml version="1.0"?><!DOCTYPE Result SYSTEM "https://www.ncbi.nlm.nih.gov/dtd/mine.dtd"><Result><Id>1</Id><Id>2</Id></Result>';
read(new TextEncoder().encode(xml)).repr();   // "['1', '2']"

Only a DTD at https://…nlm.nih.gov/ is accepted, as in Biopython 1.88: a reply with an http:// DOCTYPE, which older saved replies have, is refused with ValueError: Expected secure URL to NCBI.

The request, without sending it

buildRequest is Biopython's _build_request: it returns what would be sent.

import { EUTILS, buildRequest, settings } from "@biolibs/entrez";

settings.email = "[email protected]";

const request = buildRequest(`${EUTILS}esearch.fcgi`, { db: "pubmed", term: "biopython[title]", retmax: 20 });
request.method;    // "GET"
request.fullUrl;
// "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term=biopython%5Btitle%5D&retmax=20&tool=biopython&email=a.n.other%40example.com"

It switches to POST by itself when the encoded parameters come to more than 1,000 characters, or when there are 200 or more identifiers, whichever happens first:

const ids = Array.from({ length: 200 }, (_, i) => 1000 + i);
const big = buildRequest(`${EUTILS}efetch.fcgi`, { db: "nucleotide", id: ids });

big.method;                                             // "POST"
big.fullUrl;                                            // ".../efetch.fcgi" — the parameters are in the body
new TextDecoder().decode(big.data!).slice(0, 30);       // "db=nucleotide&id=1000%2C1001%2"

buildRequest(`${EUTILS}efetch.fcgi`, { db: "nucleotide", id: ids.slice(0, 50) }).method;    // "GET"

Identifiers

A list of identifiers is joined with commas, and text is tidied, by formatIds:

import { formatIds } from "@biolibs/entrez";

formatIds(19304878);                 // "19304878"
formatIds(" 1 , 2 ,3 ");             // "1,2,3"
formatIds(["EU490707", 19304878]);   // "EU490707,19304878"

elink is the exception. It repeats id once per identifier, which asks NCBI for each one's links separately:

import { EUTILS, buildRequest } from "@biolibs/entrez";

// What elink sends for a list: joinIds is false.
buildRequest(`${EUTILS}elink.fcgi`, { dbfrom: "protein", db: "gene", id: ["15718680", "157427902"] }, null, false, false).fullUrl;
// ".../elink.fcgi?dbfrom=protein&db=gene&id=15718680&id=157427902&tool=biopython&email=a.n.other%40example.com"

URL encoding

Python's urlencode is not encodeURIComponent, and the differences change the bytes sent. quotePlus and urlencode are exported for anything else that has to match it.

import { quotePlus, urlencode } from "@biolibs/entrez";

quotePlus("Opuntia[orgn] AND rpl16");   // "Opuntia%5Borgn%5D+AND+rpl16" — a space is +
quotePlus("it's (here)!*~");            // "it%27s+%28here%29%21%2A~"   — only ~ survives
quotePlus("日本");                       // "%E6%97%A5%E6%9C%AC"

urlencode(new Map<string, unknown>([["id", [1, 2]], ["usehistory", true], ["retmax", null]]));
// "id=1&id=2&usehistory=True&retmax=None"

Pacing and retries

Requests are kept at least 0.37 seconds apart, or 0.1 with an API key. A reply that is a server error or "too many requests" is asked for again at once; a connection that gets no answer is retried after sleepBetweenTries seconds; any other 4xx is final.

import { HTTPError, settings } from "@biolibs/entrez";

settings.maxTries;            // 3
settings.sleepBetweenTries;   // 15  — seconds

try {
  await efetch("nucleotide", { id: "EU490707", rettype: "gb", retmode: "text" });
} catch (error) {
  if (error instanceof HTTPError) {
    error.code;      // the HTTP status, such as 429
    error.message;   // "HTTP Error 429: Too Many Requests"
  }
}

An identifier NCBI does not know is not an HTTP error: the reply has status 200 and says what was wrong in its body. Check what came back.

Replacing the network

Everything is sent through settings.transport. Replace it to add a cache, go through your own server, or run with no connection at all. It is given the request and returns the reply, or throws HTTPError or URLError.

import { efetch, settings, type Transport } from "@biolibs/entrez";

const canned: Transport = async (request) => ({
  url: request.fullUrl,
  contentType: "text/plain",
  body: new TextEncoder().encode(">made-up record\nACGT\n"),
});
settings.transport = canned;

const handle = await efetch("nucleotide", { id: "anything", rettype: "fasta", retmode: "text" });
handle.readText();   // ">made-up record\nACGT\n"

settings.now and settings.sleep are the clock and the wait, replaceable the same way, which is how the tests run 206 cases of pacing and retrying in a few milliseconds.

The other E-utilities

| Python | TypeScript | Notes | |---|---|---| | Entrez.efetch(db, **kw) | efetch(db, kw?) | records, in the format rettype and retmode ask for | | Entrez.esearch(db, term, **kw) | esearch(db, term, kw?) | identifiers matching a query | | Entrez.esummary(**kw) | esummary(kw?) | document summaries | | Entrez.elink(**kw) | elink(kw?) | related records; repeats id instead of joining it | | Entrez.epost(db, **kw) | epost(db, kw?) | upload identifiers to the history server; always a POST | | Entrez.einfo(**kw) | einfo(kw?) | the databases, or one database's fields | | Entrez.espell(**kw) | espell(kw?) | spelling suggestions | | Entrez.ecitmatch(**kw) | ecitmatch(kw?) | PubMed identifiers for citations | | Entrez.email, tool, api_key | settings.email, tool, apiKey | | | Entrez.max_tries, sleep_between_tries | settings.maxTries, sleepBetweenTries | | | Entrez.read(source, validate, escape, ignore_errors) | read(source, { validate, escape, ignoreErrors }) | not a promise: the reply is already in hand | | Entrez.parse(source, …) | parse(source, { … }) | a generator |

Each E-utility returns a promise. The request is built before the function returns, so a bad argument throws straight away, not when the promise is awaited.

Testing

npm test                 # the whole workspace
npx vitest run packages/entrez/test

| File | What it checks | |---|---| | test/entrez.test.ts | the 1,092 recorded requests from Biopython 1.88 | | test/entrez-parser.test.ts | the 1,791 recorded cases of read and parse, and elementDecl on all 291 DTDs | | test/expat.test.ts | the 2,100 recorded cases of the XML parser against real expat, and all 291 DTDs through it | | test/transport.test.ts | fetchTransport, against a stand-in for fetch | | test/readme.test.ts | every code block in this file |

No test touches the network.

Things to know

  • A browser cannot set a User-Agent, and does not need to: NCBI identifies clients by the tool and email parameters, which is what is sent.
  • Key order is the order sent. Parameters go out in the order you wrote them, then tool, email and api_key. JavaScript moves object keys that look like whole numbers to the front; if you have one, pass a Map or an array of pairs instead of an object.
  • null and undefined mean "leave it out", as None does in Python. Passing email: null drops the email for that request, and brings the warning back.
  • Rate limiting is per page or process. Two tabs, or two programs, each keep their own count.

License

MIT — see LICENSE.