ochre-sdk
v1.3.9
Published
Node.js library for working with OCHRE (Online Cultural and Historical Research Environment) data
Maintainers
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-sdkUse 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. Passingcategoryas 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.containedItemCategorycontrols how nested Tree or Set contents are parsed. For large recursive item categories, passshouldOmitEmbeddedItems: trueto fetch the top-level item without its embedded item hierarchy.fetchItemChildren(uuid, options)fetches only the direct child items for an OCHRE item UUID. Passingcategorylets 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 holdOCHRE 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, andgetLeafPropertyValuesfor reading properties off a parsed item.flattenItemPropertiesandDEFAULT_PAGE_SIZEfor 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.
