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

ochre-sdk

v1.3.9

Published

Node.js library for working with OCHRE (Online Cultural and Historical Research Environment) data

Readme

OCHRE SDK

ochre-sdk is a TypeScript package for reading data from OCHRE (Online Cultural and Historical Research Environment). It fetches OCHRE XML/XQuery responses, validates the payloads, and parses them into typed objects that are easier to use in web applications, digital collections, and research tools.

The package focuses on the public OCHRE v2 API and exposes higher-level helpers for items, linked items, galleries, Set search results, Set facets, website presentation records, multilingual text, and property access.

Installation

npm install ochre-sdk

Use the equivalent command for your package manager if you do not use npm.

ochre-sdk is published as an ESM package. The runtime must provide fetch, or you can pass a custom fetch implementation through each fetcher's options.fetch field.

Quick Start

import { fetchItem } from "ochre-sdk";

const result = await fetchItem("<item-uuid>", {
  category: "resource",
  languages: ["eng"],
});

if (result.error != null) {
  throw new Error("Failed to fetch item", { cause: result.error });
}

console.log(result.item.identification.label.getText("eng"));

Every fetcher returns a success/error object. On success, the parsed value is present and error is null; on failure, the parsed value is null and error contains the message.

Core API

  • fetchItem(uuid, options) fetches and parses a single OCHRE item. Passing category as a single category narrows the returned TypeScript type to that category; passing an array narrows it to any category in that list and lets the parser resolve the actual category from the payload. containedItemCategory controls how nested Tree or Set contents are parsed. For large recursive item categories, pass shouldOmitEmbeddedItems: true to fetch the top-level item without its embedded item hierarchy.
  • fetchItemChildren(uuid, options) fetches only the direct child items for an OCHRE item UUID. Passing category lets the XQuery search only the matching OCHRE collection.
  • fetchItemLinks(uuid, options) fetches items linked from a source item and parses them as embedded OCHRE items.
  • fetchItemOcrData(uuid, value, options) fetches the positioned OCR strings of an item that match a search value, for drawing hit boxes over a scanned page.
  • fetchGallery(params, options) fetches paginated resource galleries with an optional label filter.
  • fetchWebsite(abbreviation, options) fetches an OCHRE website presentation record, including pages, segments, components, navigation, footer, sidebar, style, collection, and item-page configuration.
  • fetchSetItems(params, containedItemCategories, options) fetches paginated Set search results with typed query and sort support.
  • fetchSetItemLocations(params, options) fetches the identification, coordinates and chosen property values of every Set item matching a query, without paging, for drawing all results on a map while a list pages through them.
  • fetchTreeItems(params, containedItemCategories, options) is the same for a Tree, and is how to read a Tree too large to fetch whole. Items nested under headings come back flat, in document order.
  • fetchSetPropertyValues(params, options) fetches Set property-value facets and optional bibliography/period attribute facets for the same query model.

Multilingual Text

OCHRE text fields are represented with MultilingualString. It preserves plain text and rich text renderings, supports language fallback, and exposes helpers for exact-language access when consumers need stricter behavior.

const title = result.item.identification.label;

title.getText("eng");
title.getRichText("eng");
title.getExactText("tur");
title.getAvailableLanguages();

Reads come in three widths. getText and getRichText resolve one entry through the language fallback, getExactText and getExactRichText skip the fallback, and getEntries, getTexts and getExactTexts return every entry when OCHRE carried more than one for a language.

Two questions look alike and are not the same. isEmpty() asks whether any language carries an entry at all. hasContent() asks whether any entry in any language holds text that is not whitespace, which is what a caller deciding whether to render something wants, because OCHRE does serve fields holding a single blank entry.

title.isEmpty();
title.hasContent();
title.hasLanguage("tur");
title.hasAliases();
title.isNonLinguistic();

title.getAvailableLanguages(); // languages that carry content
title.getSupportedLanguages(); // languages the string was built to hold

OCHRE publishes zxx content in two senses, and the string tells them apart by the only thing that distinguishes them: whether another language stands beside it. Beside a field's languages, zxx content names the same thing again, so it is read as aliases (getAliases()). Standing alone, it is the text itself in no language, such as an identifier, so it is read as non-linguistic text: isNonLinguistic() is true, every language reads it through getText, and it has no aliases. Every string, however it is built or edited, follows the same rule, so adding a language to a non-linguistic string turns its text into aliases, as the same content would be read.

Writes return a new string and never mutate the original.

title.with("tur", "Başlık");
title.with("tur", "another entry", { shouldAppend: true });
title.without("tur");
title.withAliases(["ABC"]);

title.mapText((text) => text.trim());
title.filterEntries((entry) => entry.isPrimary);

mapText runs against plain text and rebuilds each entry's rich text from the result, so a transform cannot corrupt the markup OCHRE wrote. A transform that needs to keep or rewrite markup returns { text, richText } instead of a string.

For reusable language tuples, use defineLanguages to keep runtime validation and literal TypeScript inference together.

import { defineLanguages, fetchWebsite } from "ochre-sdk";

const languages = defineLanguages("eng", "tur");
const result = await fetchWebsite("uchicago-node", { languages });

Language Codes

OCHRE publishes ISO 639-2 language codes in their bibliographic (B) form, the Library of Congress MARC convention, and every language the SDK reads or accepts uses them: per for Persian, not ISO 639-3 fas, and likewise fre, chi and ger. There are three exceptions: the ISO 639-3 identifier where ISO 639-2 has no code (yua, lzh), the terminology (T) form for Dutch (nld, not dut), and a few codes of OCHRE's own for transliterations and vocabularies (ota-xlt, rel), some of which collide with unrelated ISO 639-3 languages. Requests in any other code are rejected, with the OCHRE code to use when one exists.

OCHRE_LANGUAGES maps every code OCHRE publishes to its name, what it tags (a language, a transliteration, a vocabulary or non-linguistic content), the standard the code itself is taken from (iso639-2b, or one of the exceptions: iso639-3, iso639-2t or ochre), its ISO 639-3 identifier and the BCP 47 tag to give Intl or an HTML lang attribute. Either standard is null when none fits.

import { getOchreLanguage, getOchreLanguageCode } from "ochre-sdk";

getOchreLanguage("per"); // { name: "Persian", kind: "language", standard: "iso639-2b", iso639_3: "fas", bcp47: "fa" }
getOchreLanguage("ota-xlt")?.bcp47; // "ota-Latn-t-ota-arab"
getOchreLanguageCode("fas"); // "per"

Set Queries

Set fetchers accept a recursive Query tree. Leaf queries can target full text, specific fields, property values, bibliographies, periods, notes, images, and other supported OCHRE search surfaces.

import { fetchSetItems, type Query } from "ochre-sdk";

const queries: Query = {
  target: "string",
  value: "Chicago",
  matchMode: "includes",
  isCaseSensitive: false,
  language: "eng",
};

const result = await fetchSetItems(
  { setScopeUuids: ["<set-uuid>"], queries, page: 1, pageSize: 48 },
  ["resource", "bibliography"],
  { languages: ["eng"] },
);

Use fetchSetPropertyValues with the same query shape when you need facet data for a filtered result set.

Sort by distance from a point with { target: "distance", latitude, longitude }. Items are ordered by their first point, or the center of their first plane, and items without coordinates come last.

fetchTreeItems takes the same Query tree and the same sort options, because both fetchers compile the same query model against their container's searchable path. The difference is what the payload carries: OCHRE publishes Tree items as identification-only stubs unless the Tree is published with item properties, so a property query or a propertyValue sort only works on a Tree that carries them.

import { fetchTreeItems } from "ochre-sdk";

const result = await fetchTreeItems(
  { treeScopeUuids: ["<tree-uuid>"], sort: { target: "title" }, page: 1 },
  ["concept"],
  { languages: ["eng"] },
);

OCR Text Queries

The ocr target searches the OCR text layer of the Resource items in a Set. It takes no language, because OCR text carries none.

const queries: Query = {
  and: [
    {
      target: "ocr",
      value: "Cappaert",
      matchMode: "includes",
      isCaseSensitive: false,
    },
    {
      target: "title",
      value: "Convocation",
      matchMode: "includes",
      isCaseSensitive: false,
      language: "eng",
    },
  ],
};

Every word node in that layer holds a single OCR word in its CONTENT attribute, so includes matches each search term as its own word anywhere in the layer, in any order, with * and ? wildcards supported. exact instead matches the terms as a run of adjacent whole words, so "THE COLLEGE" matches a page carrying that phrase but not one where the two words merely appear apart. An item matches when the OCR layer of the item itself or of any of its child Resources matches.

Set item projections do not carry the OCR layer, so an ocr leaf is resolved by an extra index-only search over the Resource documents whose matching UUIDs are then joined back onto the Set items. It still composes with and, or, and isNegated like any other leaf, and repeating the same OCR search inside one tree only costs one search.

OCR Data

A Resource may carry an <ocr> layer holding the positioned output of an OCR run. The node hierarchy inside that layer is irregular and is not parsed, but any word node within it, at any depth, is read as one positioned OCR string. A word node is any element named string in any casing and any namespace, and its text comes from the CONTENT attribute rather than from the element's text content.

import { fetchItemOcrData } from "ochre-sdk";

const result = await fetchItemOcrData("<item-uuid>", "Artifact", {
  matchMode: "exact",
});

for (const ocrString of result.ocrStrings ?? []) {
  console.log(ocrString.content, ocrString.x, ocrString.y, ocrString.vertices);
}

x and y come from HPOS and VPOS and give the top-left corner of the box, width and height its size, and vertices comes from VERTICES and is its full bounding polygon, which is not always rectangular. Each geometry field is null when the source attribute is absent or unparseable, and vertices is then empty. resourceUuid names the Resource that owns the OCR layer, which differs from the requested item when the OCR lives on a child Resource.

Matching defaults to case-insensitive includes and runs against each string's CONTENT. Because a <string> holds a single OCR word, a multi-word search value is split on whitespace and a string is returned when it matches any one term. Requesting an item that does not exist is an error; an item with no OCR layer, or no matches, returns an empty array.

Helpers And Types

The root export includes the SDK's public TypeScript model, website component types, query types, property getters, and small data helpers:

  • Item, SetItem, ItemLink, Website, WebElementOf, WebElementComponentOf, WebBlockByLayout, Query, and related types.
  • getProperty, getPropertyValues, getPropertyValue, getUniqueProperties, getUniquePropertyVariableLabels, isPropertyMatchingFilter, and getLeafPropertyValues for reading properties off a parsed item.
  • flattenItemProperties and DEFAULT_PAGE_SIZE for common collection UI workflows.

Property Access

Every property lookup takes a PropertySelector, which names a property either by its variable UUID or by its variable label. A label can be narrowed by the values the property carries.

import { getProperty, getPropertyValue, getPropertyValues } from "ochre-sdk";

const properties = result.item.properties;

getProperty(properties, { uuid: "<variable-uuid>" });
getProperty(properties, { label: "Material" });
getProperty(properties, { label: "Material", valueContent: "Ceramic" });

getPropertyValues(properties, { label: "Material" });
getPropertyValue(properties, { label: "Material" })?.content;

Labels are matched case-insensitively, and spaces and underscores are treated as hyphens, so "Media type", "media_type" and "media-type" all name the same property.

Pass { includeNestedProperties: true } to descend into nested properties, and { limitToLeafPropertyValues: false } to keep non-leaf values. Leaf filtering applies to getPropertyValues and getPropertyValue; getProperty returns a property exactly as the item carries it.

Development

The package source lives in src/, and src/index.ts is the public entrypoint. Published files are generated into dist/. See package.json for the available repository scripts.

License

MIT