ochre-sdk 1.3.32 → 1.3.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -57,8 +57,7 @@ present and `error` is `null`; on failure, the parsed value is `null` and
57
57
  `category` lets the XQuery search only the matching OCHRE collection.
58
58
  - `fetchItemLinks(uuid, options)` fetches items linked from a source item and
59
59
  parses them as embedded OCHRE items.
60
- - `fetchItemOcrData(uuid, value, options)` fetches the positioned OCR strings of
61
- an item that match a search value, for drawing hit boxes over a scanned page.
60
+ - `fetchItemOcrData(uuid, value, options)` searches the OCR text of an item and returns each match with its page, the positioned words you need to draw hit boxes over the scanned page, and, if you ask for it, the words around the match for a result snippet.
62
61
  - `fetchGallery(params, options)` fetches paginated resource galleries with an
63
62
  optional label filter.
64
63
  - `fetchWebsite(abbreviation, options)` fetches an OCHRE website presentation
@@ -221,23 +220,36 @@ Set item projections do not carry the OCR layer, so an `ocr` leaf is resolved by
221
220
 
222
221
  ## OCR Data
223
222
 
224
- 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.
223
+ A Resource can carry an `<ocr>` layer with the positioned output of an OCR run, and a multi-page document usually keeps one layer on each of its child Resources, one per page. The node hierarchy inside a 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` or `string` in any namespace, and its text comes from the `CONTENT` attribute rather than from the element's text content.
225
224
 
226
225
  ```ts
227
226
  import { fetchItemOcrData } from "ochre-sdk";
228
227
 
229
- const result = await fetchItemOcrData("<item-uuid>", "Artifact", {
230
- matchMode: "exact",
228
+ const result = await fetchItemOcrData("<item-uuid>", "Madeline", {
229
+ contextWordCount: 8,
231
230
  });
232
231
 
233
- for (const ocrString of result.ocrStrings ?? []) {
234
- console.log(ocrString.content, ocrString.x, ocrString.y, ocrString.vertices);
232
+ for (const match of result.ocrMatches ?? []) {
233
+ console.log(
234
+ match.pageNumber,
235
+ match.context?.before,
236
+ match.text,
237
+ match.context?.after,
238
+ );
235
239
  }
236
240
  ```
237
241
 
238
- `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.
242
+ Because a word node holds a single OCR word, matching runs against each word, which defaults to case-insensitive `includes`, and the search value is split on whitespace and matched as a phrase. A match is a run of consecutive words in which the first word matches the first term, the second word matches the second term, and so on. With `includes`, each word only has to contain its term, so searching for `"whitman madeline"` finds `Whitman, Madeline` despite the comma, while `exact` requires each word to equal its term. Searching for `"Chicago University"` does not match `University of Chicago`, and a single-term search matches every word that matches the term, each as its own match. Matches come back in document order, and an item with no OCR layer, or with no matches, returns an empty array, though requesting an item that does not exist is an error.
239
243
 
240
- 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.
244
+ Every match has an `id` that is unique among the matches of the requested item and stays the same for the same match on every fetch, as long as the page's OCR layer is unchanged. It is built from where the match sits in the document, not from its geometry or text, which means you can use it as a key for a list of results or to remember a selected match; treat it as opaque and don't parse it.
245
+
246
+ `resourceUuid` names the Resource that owns the page's OCR layer, which differs from the requested item when the OCR lives on a child Resource, and `pageNumber` gives the 1-based position of that Resource among its sibling Resources. You can use `resourceUuid` to navigate to the page and `pageNumber` to label it.
247
+
248
+ Pass `contextWordCount` to get that many words on either side of each match in `context.before` and `context.after`. The context crosses lines and blocks but never leaves the page, and `context.isTruncatedBefore` and `context.isTruncatedAfter` tell you whether the page has more words beyond it, so you know when to draw an ellipsis. The context is counted in whole words, and if you need snippets of an even length, you can trim it to a character budget in your UI. Without `contextWordCount`, `context` is null and the search skips the extra work.
249
+
250
+ `strings` holds the positioned words of the match, and `x` and `y` come from `HPOS` and `VPOS` and give the top-left corner of each box, `width` and `height` give 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, in which case `vertices` is empty.
251
+
252
+ A word hyphenated across two lines is matched by its whole form from `SUBS_CONTENT`, so it counts as one word in both a phrase and the context, and searching for `"He conceived of"` finds `He con-` at the end of one line and `ceived of` at the start of the next, with the match holding both halves in `strings` (one box on each line) and its `text` and context showing the word whole.
241
253
 
242
254
  ## Helpers And Types
243
255
 
package/dist/errors.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { isObject, readEntries } from "./reflection.mjs";
2
1
  import * as v from "valibot";
2
+ import { isObject, readEntries } from "./reflection.mjs";
3
3
  // src/errors.ts
4
4
  /**
5
5
  The shape a valibot issue has to have for this module to render it
@@ -1,3 +1,4 @@
1
+ import * as v from "valibot";
1
2
  import { getErrorOutput } from "../errors.mjs";
2
3
  import { requestOchre } from "./request.mjs";
3
4
  import { parseGallery } from "../parsers/index.mjs";
@@ -5,7 +6,6 @@ import { parseRequestedLanguages, resolveContentLanguages } from "../parsers/lan
5
6
  import { gallerySchema } from "../schemas.mjs";
6
7
  import { XMLGalleryData } from "../xml/schemas.mjs";
7
8
  import { OCHRE_RESPONSE_PADDING, compileOchreQuery, getContentLanguage, stringLiteral } from "../xquery.mjs";
8
- import * as v from "valibot";
9
9
  // src/fetchers/gallery.ts
10
10
  function buildXQuery(parameters) {
11
11
  const { uuid, filter, page, perPage, contentLanguage } = parameters;
@@ -1,3 +1,4 @@
1
+ import * as v from "valibot";
1
2
  import { OCHRE_COLLECTION_CATEGORIES } from "../categories.mjs";
2
3
  import { getErrorOutput } from "../errors.mjs";
3
4
  import { requestOchre } from "./request.mjs";
@@ -6,7 +7,6 @@ import { parseRequestedLanguages, resolveContentLanguages } from "../parsers/lan
6
7
  import { uuidSchema } from "../schemas.mjs";
7
8
  import { XMLItemLinksData } from "../xml/schemas.mjs";
8
9
  import { OCHRE_RESPONSE_PADDING, compileOchreQuery, getContentLanguage, stringLiteral } from "../xquery.mjs";
9
- import * as v from "valibot";
10
10
  // src/fetchers/item-children.ts
11
11
  function buildXQuery(uuid, category, contentLanguage) {
12
12
  const categories = category == null ? OCHRE_COLLECTION_CATEGORIES : typeof category === "string" ? [category] : category;
@@ -1,3 +1,4 @@
1
+ import * as v from "valibot";
1
2
  import { ITEM_CATEGORY_ALIASES, OCHRE_COLLECTION_CATEGORIES } from "../categories.mjs";
2
3
  import { getErrorOutput } from "../errors.mjs";
3
4
  import { requestOchre } from "./request.mjs";
@@ -6,7 +7,6 @@ import { parseRequestedLanguages, resolveContentLanguages } from "../parsers/lan
6
7
  import { uuidSchema } from "../schemas.mjs";
7
8
  import { XMLItemLinksData } from "../xml/schemas.mjs";
8
9
  import { OCHRE_RESPONSE_PADDING, compileOchreQuery, getContentLanguage, stringLiteral } from "../xquery.mjs";
9
- import * as v from "valibot";
10
10
  // src/fetchers/item-links.ts
11
11
  /**
12
12
  Build an XQuery string to fetch linked items from the OCHRE API.
@@ -1,3 +1,4 @@
1
+ import * as v from "valibot";
1
2
  import { normalizeItemCategory } from "../categories.mjs";
2
3
  import { getErrorOutput } from "../errors.mjs";
3
4
  import { requestOchre } from "./request.mjs";
@@ -9,7 +10,6 @@ import { compileContainerItemsQuery } from "../query.mjs";
9
10
  import { itemLocationsParametersSchema } from "../schemas.mjs";
10
11
  import { XMLItemLocationsData } from "../xml/schemas.mjs";
11
12
  import { getContentLanguage, stringLiteral } from "../xquery.mjs";
12
- import * as v from "valibot";
13
13
  // src/fetchers/item-locations.ts
14
14
  function parseViewContexts(scopes, languages) {
15
15
  const viewContexts = /* @__PURE__ */ new Map();
@@ -1,37 +1,41 @@
1
1
  import { OchreRequestOptions } from "./request.mjs";
2
- import { OcrString } from "../types/index.mjs";
2
+ import { OcrMatch } from "../types/index.mjs";
3
3
  /**
4
- Fetches and parses the OCR strings of an OCHRE item that match a search value
4
+ Fetches the OCR matches of an OCHRE item for a search value
5
5
 
6
6
  Resources may carry an `<ocr>` layer whose internal hierarchy is irregular
7
- and therefore not parsed. Only its word nodes are returned, wherever they
8
- occur in that subtree, in document order. A word node is any element whose
9
- name is `string` in any casing and any namespace, and matching reads its
10
- `CONTENT` attribute rather than its text content.
7
+ and therefore not parsed. Only its word nodes are read, wherever they occur
8
+ in that subtree. A word node is any element named `String` or `string` in
9
+ any namespace, and matching reads its `CONTENT` attribute, or its
10
+ `SUBS_CONTENT` attribute when the word is hyphenated across two lines.
11
11
 
12
- Each word node holds a single OCR word, so a multi-word search value is split
13
- on whitespace and a node is returned when it matches any one term. Nested
14
- child Resources are searched too, with `resourceUuid` naming the Resource
15
- each match belongs to.
12
+ Each word node holds a single OCR word, so the search value is split on
13
+ whitespace and read as a phrase: a match is a run of consecutive words in
14
+ which each word matches its term, so a single-term search matches every word
15
+ that matches the term. Every OCR layer is one page, and nested child Resources are
16
+ searched too, with `resourceUuid` and `pageNumber` naming the page each
17
+ match is on. Matches are returned in document order.
16
18
 
17
19
  @param uuid - The UUID of the OCHRE item to read the OCR layer of
18
- @param value - The search value to match against each OCR string's content
20
+ @param value - The search value, matched as a phrase of whitespace-separated terms
19
21
  @param options - Options for the fetch
20
- @param options.matchMode - Whether a term has to be contained in a string's content ("includes", the default) or equal it ("exact")
22
+ @param options.matchMode - Whether each term has to be contained in its word ("includes", the default) or equal it ("exact")
21
23
  @param options.isCaseSensitive - Whether matching is case sensitive, defaulting to false
24
+ @param options.contextWordCount - The number of words of context to return on either side of each match, within its page, defaulting to 0 for no context
22
25
  @param options.fetch - The fetch function to use
23
- @returns The matching OCR strings, an empty array when the item has no OCR
24
- layer or nothing matches, and a null output on fetch/parse errors
26
+ @returns The OCR matches, an empty array when the item has no OCR layer or
27
+ nothing matches, and a null output on fetch/parse errors
25
28
  */
26
29
  export declare function fetchItemOcrData(uuid: string, value: string, options?: OchreRequestOptions & {
27
30
  matchMode?: "includes" | "exact";
28
31
  isCaseSensitive?: boolean;
32
+ contextWordCount?: number;
29
33
  }): Promise<{
30
- ocrStrings: Array<OcrString>;
34
+ ocrMatches: Array<OcrMatch>;
31
35
  error: null;
32
36
  detailedError: null;
33
37
  } | {
34
- ocrStrings: null;
38
+ ocrMatches: null;
35
39
  error: string;
36
40
  detailedError: string;
37
41
  }>;
@@ -1,16 +1,15 @@
1
+ import * as v from "valibot";
1
2
  import { getErrorOutput } from "../errors.mjs";
2
3
  import { requestOchre } from "./request.mjs";
3
- import { buildOcrWordPath } from "../ocr.mjs";
4
+ import { buildOcrLayerPath, buildOcrWordPath } from "../ocr.mjs";
4
5
  import { itemOcrDataParametersSchema } from "../schemas.mjs";
5
6
  import { OCHRE_RESPONSE_PADDING, stringLiteral } from "../xquery.mjs";
6
- import * as v from "valibot";
7
7
  // src/fetchers/item-ocr-data.ts
8
8
  const OCR_STRING_VERTEX_REGEX = /\(\s*(-?\d+(?:\.\d+)?)\s*,\s*(-?\d+(?:\.\d+)?)\s*\)/g;
9
9
  /**
10
- Schema for a single matched OCR string in the OCHRE API response
10
+ Schema for a single OCR string of a match in the OCHRE API response
11
11
  */
12
12
  const ocrStringSchema = v.object({
13
- resourceUuid: v.optional(v.string(), ""),
14
13
  content: v.optional(v.string(), ""),
15
14
  x: v.optional(v.string(), ""),
16
15
  y: v.optional(v.string(), ""),
@@ -19,11 +18,25 @@ const ocrStringSchema = v.object({
19
18
  vertices: v.optional(v.string(), "")
20
19
  });
21
20
  /**
21
+ Schema for a single OCR match in the OCHRE API response
22
+ */
23
+ const ocrMatchSchema = v.object({
24
+ id: v.string(),
25
+ resourceUuid: v.optional(v.string(), ""),
26
+ pageNumber: v.optional(v.string(), ""),
27
+ text: v.optional(v.string(), ""),
28
+ before: v.optional(v.string(), ""),
29
+ after: v.optional(v.string(), ""),
30
+ isTruncatedBefore: v.optional(v.string(), "false"),
31
+ isTruncatedAfter: v.optional(v.string(), "false"),
32
+ ocrString: v.optional(v.union([v.array(ocrStringSchema), ocrStringSchema]))
33
+ });
34
+ /**
22
35
  Schema for the item OCR data OCHRE API response
23
36
  */
24
- const responseSchema = v.object({ result: v.object({ ochre: v.object({ ocrStrings: v.object({
37
+ const responseSchema = v.object({ result: v.object({ ochre: v.object({ ocrMatches: v.object({
25
38
  found: v.optional(v.string(), "false"),
26
- ocrString: v.optional(v.union([v.array(ocrStringSchema), ocrStringSchema]))
39
+ ocrMatch: v.optional(v.union([v.array(ocrMatchSchema), ocrMatchSchema]))
27
40
  }) }) }) });
28
41
  function getSearchTerms(parameters) {
29
42
  const { value, isCaseSensitive } = parameters;
@@ -31,7 +44,7 @@ function getSearchTerms(parameters) {
31
44
  for (const term of value.split(/\s+/u)) if (term !== "") terms.push(isCaseSensitive ? term : term.toLocaleLowerCase("en-US"));
32
45
  return terms;
33
46
  }
34
- function parseOcrStringNumber(value) {
47
+ function parseOcrNumber(value) {
35
48
  const trimmedValue = value.trim();
36
49
  if (trimmedValue === "") return null;
37
50
  const numericValue = Number(trimmedValue);
@@ -49,74 +62,144 @@ function parseOcrStringVertices(value) {
49
62
  }
50
63
  return vertices;
51
64
  }
65
+ function toArray(value) {
66
+ if (value == null) return [];
67
+ return Array.isArray(value) ? value : [value];
68
+ }
52
69
  /**
53
- Build an XQuery string to fetch matching OCR strings from the OCHRE API
70
+ Build an XQuery string to fetch the OCR matches of an item from the OCHRE API
54
71
 
55
72
  The `<ocr>` layer is marked supplemental, so it is deliberately read without
56
73
  the supplemental stripping the other fetchers apply. Word nodes are projected
57
74
  at any depth, because OCHRE does not guarantee the shape of the surrounding
58
75
  hierarchy.
59
76
 
60
- Both the container and the word nodes are matched on a case-folded
61
- `local-name()` rather than a name test, because OCHRE varies the casing of
62
- these elements and may serve them in a namespace. A plain `//ocr//string`
63
- name test silently matches nothing in either of those cases.
77
+ Each layer is one page. A layer is skipped unless every term occurs somewhere
78
+ in its joined word text, which is a superset of every phrase match, so pages
79
+ without a match never pay for word-by-word matching. On the remaining pages
80
+ the words are read into a sequence once, a phrase is matched only from the
81
+ words matching its first term, and the context is sliced out of the sequence
82
+ by position rather than walked along the `preceding` and `following` axes.
83
+
84
+ A hyphenated word is split over two word nodes that both carry the whole
85
+ form in `SUBS_CONTENT`. The two nodes are read as one word, so a phrase
86
+ spanning a hyphenated word still lines up term by term, and the hyphenation
87
+ check only runs on pages that carry a `SUBS_TYPE` at all.
88
+
89
+ A match's ID joins the requested UUID, the position of its layer in the item,
90
+ and the position of its first word node in that layer. A phrase starts at
91
+ most one match per word, so the ID is unique, and it reads only document
92
+ positions, so it holds for any OCR source and repeats on every fetch.
64
93
 
65
- The matches are wrapped in an `<ocrStrings>` element carrying a `found`
94
+ The matches are wrapped in an `<ocrMatches>` element carrying a `found`
66
95
  flag, which tells "no such item" apart from "no matches".
67
96
  @param parameters - The parameters for the fetch
68
97
  @param parameters.uuid - The UUID of the OCHRE item to read the OCR layer of
69
- @param parameters.terms - The whitespace-separated search terms to match against, already lowercased for case-insensitive matching
70
- @param parameters.matchMode - Whether a term has to be contained in a string's content or equal it
98
+ @param parameters.terms - The search terms to match, in phrase order, already lowercased for case-insensitive matching
99
+ @param parameters.matchMode - Whether a term has to be contained in its word or equal it
71
100
  @param parameters.isCaseSensitive - Whether matching is case sensitive
101
+ @param parameters.contextWordCount - The number of words of context to return on either side of a match, or 0 for none
72
102
  @returns An XQuery string
73
103
  */
74
104
  function buildXQuery(parameters) {
75
- const { uuid, terms, matchMode, isCaseSensitive } = parameters;
76
- const termValues = terms.map((term) => stringLiteral(term));
77
- const contentExpression = isCaseSensitive ? "string($string/@CONTENT)" : "lower-case(string($string/@CONTENT))";
78
- const matchExpression = matchMode === "exact" ? `normalize-space(${contentExpression}) = $term` : `contains(${contentExpression}, $term)`;
105
+ const { uuid, terms, matchMode, isCaseSensitive, contextWordCount } = parameters;
106
+ const fold = (expression) => isCaseSensitive ? expression : `lower-case(${expression})`;
107
+ const keyExpression = matchMode === "exact" ? `normalize-space(${fold("$text")})` : fold("$text");
108
+ const matchExpression = matchMode === "exact" ? "$keys[$index + $offset - 1] eq $terms[$offset]" : "contains($keys[$index + $offset - 1], $terms[$offset])";
109
+ const contextAttributes = contextWordCount > 0 ? `
110
+ before="{string-join(subsequence($texts, max(($index - ${contextWordCount}, 1)), min(($index - 1, ${contextWordCount}))), " ")}"
111
+ after="{string-join(subsequence($texts, $last + 1, ${contextWordCount}), " ")}"
112
+ isTruncatedBefore="{$index - ${contextWordCount} gt 1}"
113
+ isTruncatedAfter="{$last + ${contextWordCount} lt $textCount}"` : "";
79
114
  return `xquery version "1.0-ml";
80
115
 
81
- declare variable $terms := (${termValues.join(", ")});
116
+ declare variable $terms := (${terms.map((term) => stringLiteral(term)).join(", ")});
117
+ declare variable $termCount := count($terms);
118
+
119
+ declare function local:joins-previous($words as element()*, $index as xs:integer) as xs:boolean {
120
+ let $word := $words[$index]
121
+ let $previous := $words[$index - 1]
122
+ let $whole := string($word/@SUBS_CONTENT)
123
+ return $whole ne ""
124
+ and string($word/@SUBS_TYPE) eq "HypPart2"
125
+ and string($previous/@SUBS_TYPE) eq "HypPart1"
126
+ and string($previous/@SUBS_CONTENT) eq $whole
127
+ };
82
128
 
83
129
  let $ochre := doc(${stringLiteral(uuid)})/ochre
84
- let $ocrStrings :=
85
- for $string in ${buildOcrWordPath("$ochre")}
86
- where (some $term in $terms satisfies ${matchExpression})
87
- return <ocrString
88
- resourceUuid="{string($string/ancestor::*[local-name(.) = "resource"][1]/@uuid)}"
89
- content="{string($string/@CONTENT)}"
90
- x="{string($string/@HPOS)}"
91
- y="{string($string/@VPOS)}"
92
- width="{string($string/@WIDTH)}"
93
- height="{string($string/@HEIGHT)}"
94
- vertices="{string($string/@VERTICES)}"/>
130
+ let $ocrMatches :=
131
+ for $layer at $layerIndex in ${buildOcrLayerPath("$ochre")}
132
+ let $words := ${buildOcrWordPath("$layer")}
133
+ let $layerText := ${fold("string-join(($words/@CONTENT, $words/@SUBS_CONTENT), \" \")")}
134
+ where (every $term in $terms satisfies contains($layerText, $term))
135
+ return
136
+ let $wordCount := count($words)
137
+ let $heads :=
138
+ if (exists($words/@SUBS_TYPE))
139
+ then
140
+ for $index in (1 to $wordCount)
141
+ where not(local:joins-previous($words, $index))
142
+ return $index
143
+ else (1 to $wordCount)
144
+ let $texts :=
145
+ for $head in $heads
146
+ let $word := $words[$head]
147
+ return string(($word/@SUBS_CONTENT[. ne ""], $word/@CONTENT)[1])
148
+ let $keys := for $text in $texts return ${keyExpression}
149
+ let $textCount := count($texts)
150
+ let $owner := $layer/ancestor::*[local-name(.) = "resource"][1]
151
+ let $pageNumber :=
152
+ if (exists($owner))
153
+ then count($owner/preceding-sibling::*[local-name(.) = "resource"]) + 1
154
+ else ()
155
+ for $index in (1 to $textCount - $termCount + 1)
156
+ where (every $offset in (1 to $termCount) satisfies ${matchExpression})
157
+ return
158
+ let $last := $index + $termCount - 1
159
+ let $firstWord := $heads[$index]
160
+ let $lastWord := if ($last lt $textCount) then $heads[$last + 1] - 1 else $wordCount
161
+ return <ocrMatch
162
+ id="{concat(${stringLiteral(uuid)}, ":", $layerIndex, ":", $firstWord)}"
163
+ resourceUuid="{string($owner/@uuid)}"
164
+ pageNumber="{$pageNumber}"
165
+ text="{string-join(subsequence($texts, $index, $termCount), " ")}"${contextAttributes}>{
166
+ for $string in subsequence($words, $firstWord, $lastWord - $firstWord + 1)
167
+ return <ocrString
168
+ content="{string($string/@CONTENT)}"
169
+ x="{string($string/@HPOS)}"
170
+ y="{string($string/@VPOS)}"
171
+ width="{string($string/@WIDTH)}"
172
+ height="{string($string/@HEIGHT)}"
173
+ vertices="{string($string/@VERTICES)}"/>
174
+ }</ocrMatch>
95
175
 
96
- return <ochre>${OCHRE_RESPONSE_PADDING}<ocrStrings found="{exists($ochre)}">{$ocrStrings}</ocrStrings></ochre>`;
176
+ return <ochre>${OCHRE_RESPONSE_PADDING}<ocrMatches found="{exists($ochre)}">{$ocrMatches}</ocrMatches></ochre>`;
97
177
  }
98
178
  /**
99
- Fetches and parses the OCR strings of an OCHRE item that match a search value
179
+ Fetches the OCR matches of an OCHRE item for a search value
100
180
 
101
181
  Resources may carry an `<ocr>` layer whose internal hierarchy is irregular
102
- and therefore not parsed. Only its word nodes are returned, wherever they
103
- occur in that subtree, in document order. A word node is any element whose
104
- name is `string` in any casing and any namespace, and matching reads its
105
- `CONTENT` attribute rather than its text content.
182
+ and therefore not parsed. Only its word nodes are read, wherever they occur
183
+ in that subtree. A word node is any element named `String` or `string` in
184
+ any namespace, and matching reads its `CONTENT` attribute, or its
185
+ `SUBS_CONTENT` attribute when the word is hyphenated across two lines.
106
186
 
107
- Each word node holds a single OCR word, so a multi-word search value is split
108
- on whitespace and a node is returned when it matches any one term. Nested
109
- child Resources are searched too, with `resourceUuid` naming the Resource
110
- each match belongs to.
187
+ Each word node holds a single OCR word, so the search value is split on
188
+ whitespace and read as a phrase: a match is a run of consecutive words in
189
+ which each word matches its term, so a single-term search matches every word
190
+ that matches the term. Every OCR layer is one page, and nested child Resources are
191
+ searched too, with `resourceUuid` and `pageNumber` naming the page each
192
+ match is on. Matches are returned in document order.
111
193
 
112
194
  @param uuid - The UUID of the OCHRE item to read the OCR layer of
113
- @param value - The search value to match against each OCR string's content
195
+ @param value - The search value, matched as a phrase of whitespace-separated terms
114
196
  @param options - Options for the fetch
115
- @param options.matchMode - Whether a term has to be contained in a string's content ("includes", the default) or equal it ("exact")
197
+ @param options.matchMode - Whether each term has to be contained in its word ("includes", the default) or equal it ("exact")
116
198
  @param options.isCaseSensitive - Whether matching is case sensitive, defaulting to false
199
+ @param options.contextWordCount - The number of words of context to return on either side of each match, within its page, defaulting to 0 for no context
117
200
  @param options.fetch - The fetch function to use
118
- @returns The matching OCR strings, an empty array when the item has no OCR
119
- layer or nothing matches, and a null output on fetch/parse errors
201
+ @returns The OCR matches, an empty array when the item has no OCR layer or
202
+ nothing matches, and a null output on fetch/parse errors
120
203
  */
121
204
  async function fetchItemOcrData(uuid, value, options) {
122
205
  try {
@@ -124,42 +207,58 @@ async function fetchItemOcrData(uuid, value, options) {
124
207
  uuid,
125
208
  value,
126
209
  matchMode: options?.matchMode,
127
- isCaseSensitive: options?.isCaseSensitive
128
- });
129
- const terms = getSearchTerms({
130
- value: parameters.value,
131
- isCaseSensitive: parameters.isCaseSensitive
210
+ isCaseSensitive: options?.isCaseSensitive,
211
+ contextWordCount: options?.contextWordCount
132
212
  });
133
213
  const xquery = buildXQuery({
134
214
  uuid: parameters.uuid,
135
- terms,
215
+ terms: getSearchTerms({
216
+ value: parameters.value,
217
+ isCaseSensitive: parameters.isCaseSensitive
218
+ }),
136
219
  matchMode: parameters.matchMode,
137
- isCaseSensitive: parameters.isCaseSensitive
220
+ isCaseSensitive: parameters.isCaseSensitive,
221
+ contextWordCount: parameters.contextWordCount
138
222
  });
139
- const { found, ocrString } = (await requestOchre({
223
+ const { found, ocrMatch } = (await requestOchre({
140
224
  xquery,
141
225
  schema: responseSchema,
142
226
  label: "OCHRE item OCR data",
143
227
  options
144
- })).result.ochre.ocrStrings;
228
+ })).result.ochre.ocrMatches;
145
229
  if (found !== "true") throw new Error(`No OCHRE item found for UUID: ${parameters.uuid}`, { cause: parameters.uuid });
146
- const parsedOcrStrings = ocrString == null ? [] : Array.isArray(ocrString) ? ocrString : [ocrString];
147
- return {
148
- ocrStrings: Array.from(parsedOcrStrings, (parsedOcrString) => ({
149
- resourceUuid: parsedOcrString.resourceUuid !== "" ? parsedOcrString.resourceUuid : null,
230
+ const ocrMatches = [];
231
+ for (const parsedOcrMatch of toArray(ocrMatch)) {
232
+ const strings = Array.from(toArray(parsedOcrMatch.ocrString), (parsedOcrString) => ({
150
233
  content: parsedOcrString.content,
151
- x: parseOcrStringNumber(parsedOcrString.x),
152
- y: parseOcrStringNumber(parsedOcrString.y),
153
- width: parseOcrStringNumber(parsedOcrString.width),
154
- height: parseOcrStringNumber(parsedOcrString.height),
234
+ x: parseOcrNumber(parsedOcrString.x),
235
+ y: parseOcrNumber(parsedOcrString.y),
236
+ width: parseOcrNumber(parsedOcrString.width),
237
+ height: parseOcrNumber(parsedOcrString.height),
155
238
  vertices: parseOcrStringVertices(parsedOcrString.vertices)
156
- })),
239
+ }));
240
+ ocrMatches.push({
241
+ id: parsedOcrMatch.id,
242
+ resourceUuid: parsedOcrMatch.resourceUuid !== "" ? parsedOcrMatch.resourceUuid : null,
243
+ pageNumber: parseOcrNumber(parsedOcrMatch.pageNumber),
244
+ text: parsedOcrMatch.text,
245
+ strings,
246
+ context: parameters.contextWordCount > 0 ? {
247
+ before: parsedOcrMatch.before,
248
+ after: parsedOcrMatch.after,
249
+ isTruncatedBefore: parsedOcrMatch.isTruncatedBefore === "true",
250
+ isTruncatedAfter: parsedOcrMatch.isTruncatedAfter === "true"
251
+ } : null
252
+ });
253
+ }
254
+ return {
255
+ ocrMatches,
157
256
  error: null,
158
257
  detailedError: null
159
258
  };
160
259
  } catch (error) {
161
260
  return {
162
- ocrStrings: null,
261
+ ocrMatches: null,
163
262
  ...getErrorOutput(error, "Failed to fetch item OCR data")
164
263
  };
165
264
  }
@@ -1,3 +1,4 @@
1
+ import * as v from "valibot";
1
2
  import { ITEM_CATEGORIES_WITH_EMBEDDED_ITEMS, ITEM_CONTAINER_CATEGORIES, isItemCategoryWithEmbeddedItems, isItemContainerCategory } from "../categories.mjs";
2
3
  import { getErrorOutput } from "../errors.mjs";
3
4
  import { requestOchre } from "./request.mjs";
@@ -7,7 +8,6 @@ import { parseWebpageView } from "../parsers/website/index.mjs";
7
8
  import { uuidSchema } from "../schemas.mjs";
8
9
  import { XMLData } from "../xml/schemas.mjs";
9
10
  import { OCHRE_RESPONSE_PADDING, compileOchreQuery, getContentLanguage, stringLiteral } from "../xquery.mjs";
10
- import * as v from "valibot";
11
11
  // src/fetchers/item.ts
12
12
  function isItemWithEmbeddedItems(item) {
13
13
  return isItemCategoryWithEmbeddedItems(item.category);
@@ -1,3 +1,4 @@
1
+ import * as v from "valibot";
1
2
  import { getErrorOutput } from "../errors.mjs";
2
3
  import { requestOchre } from "./request.mjs";
3
4
  import { parseIdentification } from "../parsers/index.mjs";
@@ -5,7 +6,6 @@ import { parseRequestedLanguages, resolveContentLanguages } from "../parsers/lan
5
6
  import { uuidSchema } from "../schemas.mjs";
6
7
  import { XMLMapSourcesData } from "../xml/schemas.mjs";
7
8
  import { OCHRE_RESPONSE_PADDING, compileOchreQuery, getContentLanguage, stringLiteral } from "../xquery.mjs";
8
- import * as v from "valibot";
9
9
  // src/fetchers/map-layers.ts
10
10
  const REGEX_TILE_TEMPLATE_LEVEL = /\{(?:level|z)\}/i;
11
11
  const REGEX_TILE_TEMPLATE_ROW = /\{(?:row|y)\}/i;
@@ -1,5 +1,5 @@
1
- import { FetchFunction } from "../parsers/helpers.mjs";
2
1
  import * as v from "valibot";
2
+ import { FetchFunction } from "../parsers/helpers.mjs";
3
3
  export type OchreRequestOptions = {
4
4
  fetch?: FetchFunction;
5
5
  signal?: AbortSignal;
@@ -1,8 +1,8 @@
1
+ import { XMLParser } from "fast-xml-parser";
2
+ import * as v from "valibot";
1
3
  import { OCHRE_ENDPOINT, XML_PARSER_OPTIONS } from "../constants.mjs";
2
4
  import { createSchemaValidationError } from "../errors.mjs";
3
5
  import { restoreXMLMetadata } from "../xml/metadata.mjs";
4
- import * as v from "valibot";
5
- import { XMLParser } from "fast-xml-parser";
6
6
  // src/fetchers/request.ts
7
7
  const OCHRE_XQUERY_ENDPOINT = `${OCHRE_ENDPOINT}?xquery&xsl=none&lang="*"`;
8
8
  const xmlParser = new XMLParser(XML_PARSER_OPTIONS);
@@ -1,7 +1,7 @@
1
+ import * as v from "valibot";
1
2
  import { getErrorOutput } from "../../errors.mjs";
2
3
  import { fetchContainerItems } from "../container-items.mjs";
3
4
  import { setItemsParametersSchema } from "../../schemas.mjs";
4
- import * as v from "valibot";
5
5
  // src/fetchers/set/items.ts
6
6
  async function fetchSetItems(parameters, containedItemCategories, options) {
7
7
  try {
@@ -1,3 +1,4 @@
1
+ import * as v from "valibot";
1
2
  import { DEFAULT_LANGUAGES } from "../../constants.mjs";
2
3
  import { getErrorOutput } from "../../errors.mjs";
3
4
  import { requestOchre } from "../request.mjs";
@@ -6,7 +7,6 @@ import { parseXMLContent } from "../../parsers/string.mjs";
6
7
  import { compileContainerItemsQuery, getItemFilterQueries, getPropertyFacetSelectors } from "../../query.mjs";
7
8
  import { setPropertyValuesParametersSchema } from "../../schemas.mjs";
8
9
  import { stringLiteral } from "../../xquery.mjs";
9
- import * as v from "valibot";
10
10
  // src/fetchers/set/property-values.ts
11
11
  function getLabelContentLanguages(content) {
12
12
  const languages = [];
@@ -1,7 +1,7 @@
1
+ import * as v from "valibot";
1
2
  import { getErrorOutput } from "../../errors.mjs";
2
3
  import { fetchContainerItems } from "../container-items.mjs";
3
4
  import { treeItemsParametersSchema } from "../../schemas.mjs";
4
- import * as v from "valibot";
5
5
  // src/fetchers/tree/items.ts
6
6
  async function fetchTreeItems(parameters, containedItemCategories, options) {
7
7
  try {
package/dist/index.d.mts CHANGED
@@ -16,6 +16,6 @@ import { flattenItemProperties } from "./helpers.mjs";
16
16
  import { OCHRE_LANGUAGES, OchreLanguage, OchreLanguageCode, OchreLanguageKind, OchreLanguageStandard, getOchreLanguage, getOchreLanguageCode, isOchreLanguageCode } from "./languages.mjs";
17
17
  import { defineLanguages } from "./parsers/languages.mjs";
18
18
  import { MultilingualOptions, MultilingualString, MultilingualStringEntries, MultilingualStringEntry, MultilingualStringInput, MultilingualStringJSON, MultilingualStringObject, MultilingualStringText } from "./parsers/multilingual.mjs";
19
- import { AnyBibliography, AnyConcept, AnyItem, AnyPeriod, AnyPerson, AnyPropertyValue, AnyPropertyVariable, AnyResource, AnySet, AnySpatialUnit, AnyText, AnyTree, BaseItem, BaseItemLink, BelongsTo, Bibliography, BibliographyEntryInfo, BibliographyItemLink, BibliographySourceDocument, Concept, ConceptItemLink, ContainedItemCategory, ContainedItemCategoryFromOption, ContainedItemCategoryOption, Context, ContextItem, ContextItemCategory, ContextNode, Coordinates, CoordinatesSource, DictionaryUnitItemLink, DownloadOption, EmbeddedBibliography, EmbeddedConcept, EmbeddedItem, EmbeddedPeriod, EmbeddedPerson, EmbeddedPropertyValue, EmbeddedPropertyVariable, EmbeddedResource, EmbeddedSet, EmbeddedSpatialUnit, EmbeddedText, EmbeddedTree, Event, Gallery, Heading, HeadingItemCategory, Identification, Image, ImageMap, ImageMapArea, Interpretation, Item, ItemCategory, ItemCategoryFromOption, ItemCategoryOption, ItemCategoryWithEmbeddedItems, ItemContainerCategory, ItemLink, ItemLinkCategory, ItemLinks, ItemLocation, ItemPayloadKind, ItemProperty, ItemWithoutEmbeddedItems, LanguageCodes, License, MapLayer, Metadata, Note, Observation, OcrString, PartialDate, PartialDateBound, PartialDateQualifier, PartialDateSeason, PartialDateValue, Period, PeriodItemLink, Person, PersonItemLink, Property, PropertyLike, PropertyRelation, PropertyValue, PropertyValueContent, PropertyValueDataType, PropertyValueItemLink, PropertyValueQueryItem, PropertyVariable, PropertyVariableItemLink, Query, QueryGroup, QueryLeaf, QueryablePropertyValueDataType, RecursiveItemCategory, Resource, ResourceItemLink, Section, Set, SetAttributeValueQueryItem, SetBibliography, SetConcept, SetItem, SetItemCategory, SetItemLink, SetItemProperty, SetItemSimplifiedProperty, SetItemsSort, SetItemsSortDirection, SetPeriod, SetResource, SetSpatialUnit, SetStyle, SetStyleProperty, SetTree, SimplifiedProperty, SpatialUnit, SpatialUnitItemLink, Text, TextItemLink, TopLevelItem, Tree, TreeItemCategory, TreeItemLink } from "./types/index.mjs";
19
+ import { AnyBibliography, AnyConcept, AnyItem, AnyPeriod, AnyPerson, AnyPropertyValue, AnyPropertyVariable, AnyResource, AnySet, AnySpatialUnit, AnyText, AnyTree, BaseItem, BaseItemLink, BelongsTo, Bibliography, BibliographyEntryInfo, BibliographyItemLink, BibliographySourceDocument, Concept, ConceptItemLink, ContainedItemCategory, ContainedItemCategoryFromOption, ContainedItemCategoryOption, Context, ContextItem, ContextItemCategory, ContextNode, Coordinates, CoordinatesSource, DictionaryUnitItemLink, DownloadOption, EmbeddedBibliography, EmbeddedConcept, EmbeddedItem, EmbeddedPeriod, EmbeddedPerson, EmbeddedPropertyValue, EmbeddedPropertyVariable, EmbeddedResource, EmbeddedSet, EmbeddedSpatialUnit, EmbeddedText, EmbeddedTree, Event, Gallery, Heading, HeadingItemCategory, Identification, Image, ImageMap, ImageMapArea, Interpretation, Item, ItemCategory, ItemCategoryFromOption, ItemCategoryOption, ItemCategoryWithEmbeddedItems, ItemContainerCategory, ItemLink, ItemLinkCategory, ItemLinks, ItemLocation, ItemPayloadKind, ItemProperty, ItemWithoutEmbeddedItems, LanguageCodes, License, MapLayer, Metadata, Note, Observation, OcrMatch, OcrString, PartialDate, PartialDateBound, PartialDateQualifier, PartialDateSeason, PartialDateValue, Period, PeriodItemLink, Person, PersonItemLink, Property, PropertyLike, PropertyRelation, PropertyValue, PropertyValueContent, PropertyValueDataType, PropertyValueItemLink, PropertyValueQueryItem, PropertyVariable, PropertyVariableItemLink, Query, QueryGroup, QueryLeaf, QueryablePropertyValueDataType, RecursiveItemCategory, Resource, ResourceItemLink, Section, Set, SetAttributeValueQueryItem, SetBibliography, SetConcept, SetItem, SetItemCategory, SetItemLink, SetItemProperty, SetItemSimplifiedProperty, SetItemsSort, SetItemsSortDirection, SetPeriod, SetResource, SetSpatialUnit, SetStyle, SetStyleProperty, SetTree, SimplifiedProperty, SpatialUnit, SpatialUnitItemLink, Text, TextItemLink, TopLevelItem, Tree, TreeItemCategory, TreeItemLink } from "./types/index.mjs";
20
20
  import { AccordionWebBlock, ContextTree, ContextTreeFilterLevel, ContextTreeFilterVariant, ContextTreeLevel, ContextTreeLevelItem, ProtectedWebsite, ResponsiveStyles, Scope, Style, StylesheetCategory, StylesheetItem, WebAccordionItem, WebBlock, WebBlockByLayout, WebBlockItem, WebBlockLayout, WebCollectionVariant, WebElement, WebElementComponent, WebElementComponentName, WebElementComponentOf, WebElementOf, WebIiifViewer, WebImage, WebLoadingVariant, WebOptions, WebRelationVariant, WebSectionDisplay, WebSectionVariant, WebSidebar, WebTitle, Webpage, Website, WebsiteMetadata, WebsitePrivacy, WebsitePropertyQuery, WebsitePropertyQueryNode, WebsiteSegment, WebsiteType } from "./types/website.mjs";
21
- export { type AccordionWebBlock, type AnyBibliography, type AnyConcept, type AnyItem, type AnyPeriod, type AnyPerson, type AnyPropertyValue, type AnyPropertyVariable, type AnyResource, type AnySet, type AnySpatialUnit, type AnyText, type AnyTree, type BaseItem, type BaseItemLink, type BelongsTo, type Bibliography, type BibliographyEntryInfo, type BibliographyItemLink, type BibliographySourceDocument, type Concept, type ConceptItemLink, type ContainedItemCategory, type ContainedItemCategoryFromOption, type ContainedItemCategoryOption, type Context, type ContextItem, type ContextItemCategory, type ContextNode, type ContextTree, type ContextTreeFilterLevel, type ContextTreeFilterVariant, type ContextTreeLevel, type ContextTreeLevelItem, type Coordinates, type CoordinatesSource, DEFAULT_PAGE_SIZE, type DictionaryUnitItemLink, type DownloadOption, type EmbeddedBibliography, type EmbeddedConcept, type EmbeddedItem, type EmbeddedPeriod, type EmbeddedPerson, type EmbeddedPropertyValue, type EmbeddedPropertyVariable, type EmbeddedResource, type EmbeddedSet, type EmbeddedSpatialUnit, type EmbeddedText, type EmbeddedTree, type Event, type Gallery, type Heading, type HeadingItemCategory, type Identification, type Image, type ImageMap, type ImageMapArea, type Interpretation, type Item, type ItemCategory, type ItemCategoryFromOption, type ItemCategoryOption, type ItemCategoryWithEmbeddedItems, type ItemContainerCategory, type ItemLink, type ItemLinkCategory, type ItemLinks, type ItemLocation, type ItemPayloadKind, type ItemProperty, type ItemWithoutEmbeddedItems, type LanguageCodes, type License, type MapLayer, type Metadata, type MultilingualOptions, MultilingualString, type MultilingualStringEntries, type MultilingualStringEntry, type MultilingualStringInput, type MultilingualStringJSON, type MultilingualStringObject, type MultilingualStringText, type Note, OCHRE_LANGUAGES, type Observation, type OchreLanguage, type OchreLanguageCode, type OchreLanguageKind, type OchreLanguageStandard, type OcrString, type PartialDate, type PartialDateBound, type PartialDateQualifier, type PartialDateSeason, type PartialDateValue, type Period, type PeriodItemLink, type Person, type PersonItemLink, type Property, type PropertyLike, type PropertyOptions, type PropertyRelation, type PropertySelector, type PropertyValue, type PropertyValueContent, type PropertyValueDataType, type PropertyValueItemLink, type PropertyValueQueryItem, type PropertyVariable, type PropertyVariableItemLink, type ProtectedWebsite, type Query, type QueryGroup, type QueryLeaf, type QueryablePropertyValueDataType, type RecursiveItemCategory, type Resource, type ResourceItemLink, type ResponsiveStyles, type Scope, type Section, type Set, type SetAttributeValueQueryItem, type SetBibliography, type SetConcept, type SetItem, type SetItemCategory, type SetItemLink, type SetItemProperty, type SetItemSimplifiedProperty, type SetItemsSort, type SetItemsSortDirection, type SetPeriod, type SetResource, type SetSpatialUnit, type SetStyle, type SetStyleProperty, type SetTree, type SimplifiedProperty, type SpatialUnit, type SpatialUnitItemLink, type Style, type StylesheetCategory, type StylesheetItem, type Text, type TextItemLink, type TopLevelItem, type Tree, type TreeItemCategory, type TreeItemLink, type WebAccordionItem, type WebBlock, type WebBlockByLayout, type WebBlockItem, type WebBlockLayout, type WebCollectionVariant, type WebElement, type WebElementComponent, type WebElementComponentName, type WebElementComponentOf, type WebElementOf, type WebIiifViewer, type WebImage, type WebLoadingVariant, type WebOptions, type WebRelationVariant, type WebSectionDisplay, type WebSectionVariant, type WebSidebar, type WebTitle, type Webpage, type Website, type WebsiteMetadata, type WebsitePrivacy, type WebsitePropertyQuery, type WebsitePropertyQueryNode, type WebsiteSegment, type WebsiteType, defineLanguages, fetchGallery, fetchItem, fetchItemChildren, fetchItemLinks, fetchItemLocations, fetchItemOcrData, fetchMapLayers, fetchSetItems, fetchSetPropertyValues, fetchTreeItems, fetchWebsite, fetchWebsiteMetadata, flattenItemProperties, getLeafPropertyValues, getOchreLanguage, getOchreLanguageCode, getProperty, getPropertyValue, getPropertyValues, getUniqueProperties, getUniquePropertyVariableLabels, isOchreLanguageCode, isPropertyMatchingFilter, normalizePropertyVariableLabel };
21
+ export { type AccordionWebBlock, type AnyBibliography, type AnyConcept, type AnyItem, type AnyPeriod, type AnyPerson, type AnyPropertyValue, type AnyPropertyVariable, type AnyResource, type AnySet, type AnySpatialUnit, type AnyText, type AnyTree, type BaseItem, type BaseItemLink, type BelongsTo, type Bibliography, type BibliographyEntryInfo, type BibliographyItemLink, type BibliographySourceDocument, type Concept, type ConceptItemLink, type ContainedItemCategory, type ContainedItemCategoryFromOption, type ContainedItemCategoryOption, type Context, type ContextItem, type ContextItemCategory, type ContextNode, type ContextTree, type ContextTreeFilterLevel, type ContextTreeFilterVariant, type ContextTreeLevel, type ContextTreeLevelItem, type Coordinates, type CoordinatesSource, DEFAULT_PAGE_SIZE, type DictionaryUnitItemLink, type DownloadOption, type EmbeddedBibliography, type EmbeddedConcept, type EmbeddedItem, type EmbeddedPeriod, type EmbeddedPerson, type EmbeddedPropertyValue, type EmbeddedPropertyVariable, type EmbeddedResource, type EmbeddedSet, type EmbeddedSpatialUnit, type EmbeddedText, type EmbeddedTree, type Event, type Gallery, type Heading, type HeadingItemCategory, type Identification, type Image, type ImageMap, type ImageMapArea, type Interpretation, type Item, type ItemCategory, type ItemCategoryFromOption, type ItemCategoryOption, type ItemCategoryWithEmbeddedItems, type ItemContainerCategory, type ItemLink, type ItemLinkCategory, type ItemLinks, type ItemLocation, type ItemPayloadKind, type ItemProperty, type ItemWithoutEmbeddedItems, type LanguageCodes, type License, type MapLayer, type Metadata, type MultilingualOptions, MultilingualString, type MultilingualStringEntries, type MultilingualStringEntry, type MultilingualStringInput, type MultilingualStringJSON, type MultilingualStringObject, type MultilingualStringText, type Note, OCHRE_LANGUAGES, type Observation, type OchreLanguage, type OchreLanguageCode, type OchreLanguageKind, type OchreLanguageStandard, type OcrMatch, type OcrString, type PartialDate, type PartialDateBound, type PartialDateQualifier, type PartialDateSeason, type PartialDateValue, type Period, type PeriodItemLink, type Person, type PersonItemLink, type Property, type PropertyLike, type PropertyOptions, type PropertyRelation, type PropertySelector, type PropertyValue, type PropertyValueContent, type PropertyValueDataType, type PropertyValueItemLink, type PropertyValueQueryItem, type PropertyVariable, type PropertyVariableItemLink, type ProtectedWebsite, type Query, type QueryGroup, type QueryLeaf, type QueryablePropertyValueDataType, type RecursiveItemCategory, type Resource, type ResourceItemLink, type ResponsiveStyles, type Scope, type Section, type Set, type SetAttributeValueQueryItem, type SetBibliography, type SetConcept, type SetItem, type SetItemCategory, type SetItemLink, type SetItemProperty, type SetItemSimplifiedProperty, type SetItemsSort, type SetItemsSortDirection, type SetPeriod, type SetResource, type SetSpatialUnit, type SetStyle, type SetStyleProperty, type SetTree, type SimplifiedProperty, type SpatialUnit, type SpatialUnitItemLink, type Style, type StylesheetCategory, type StylesheetItem, type Text, type TextItemLink, type TopLevelItem, type Tree, type TreeItemCategory, type TreeItemLink, type WebAccordionItem, type WebBlock, type WebBlockByLayout, type WebBlockItem, type WebBlockLayout, type WebCollectionVariant, type WebElement, type WebElementComponent, type WebElementComponentName, type WebElementComponentOf, type WebElementOf, type WebIiifViewer, type WebImage, type WebLoadingVariant, type WebOptions, type WebRelationVariant, type WebSectionDisplay, type WebSectionVariant, type WebSidebar, type WebTitle, type Webpage, type Website, type WebsiteMetadata, type WebsitePrivacy, type WebsitePropertyQuery, type WebsitePropertyQueryNode, type WebsiteSegment, type WebsiteType, defineLanguages, fetchGallery, fetchItem, fetchItemChildren, fetchItemLinks, fetchItemLocations, fetchItemOcrData, fetchMapLayers, fetchSetItems, fetchSetPropertyValues, fetchTreeItems, fetchWebsite, fetchWebsiteMetadata, flattenItemProperties, getLeafPropertyValues, getOchreLanguage, getOchreLanguageCode, getProperty, getPropertyValue, getPropertyValues, getUniqueProperties, getUniquePropertyVariableLabels, isOchreLanguageCode, isPropertyMatchingFilter, normalizePropertyVariableLabel };
package/dist/ocr.d.mts CHANGED
@@ -21,15 +21,26 @@ narrowing misses is a document the search silently drops.
21
21
  */
22
22
  export declare const OCR_WORD_QNAMES: string;
23
23
  /**
24
- Build an XQuery path selecting every OCR word element beneath a node
24
+ Build an XQuery path selecting every OCR layer beneath a node
25
25
 
26
- Matches the layer and the word elements on a case-folded `local-name()`
27
- rather than a name test, because a name test silently matches nothing when
28
- OCHRE varies the casing or serves the elements in a namespace. Word elements
29
- are selected at any depth, because the hierarchy between the layer and its
30
- words is irregular and is not parsed.
26
+ Matches on `local-name()` so that a layer is selected in any namespace.
31
27
  @param rootExpression - The XQuery expression to select from
32
28
  @returns The XQuery path
33
29
  @internal
34
30
  */
35
- export declare function buildOcrWordPath(rootExpression: string): string;
31
+ export declare function buildOcrLayerPath(rootExpression: string): string;
32
+ /**
33
+ Build an XQuery path selecting every OCR word element beneath an OCR layer
34
+
35
+ Matches on `local-name()` so that both the ALTO-namespaced and the
36
+ unnamespaced elements are selected, against exactly the local names
37
+ {@link OCR_WORD_QNAMES} narrows on, so the path and the narrowing always
38
+ agree. Comparing against a literal list measures around three times faster
39
+ than case-folding every element name. Word elements are selected at any
40
+ depth, because the hierarchy between the layer and its words is irregular
41
+ and is not parsed.
42
+ @param layerExpression - The XQuery expression selecting the OCR layers, as built by {@link buildOcrLayerPath}
43
+ @returns The XQuery path
44
+ @internal
45
+ */
46
+ export declare function buildOcrWordPath(layerExpression: string): string;
package/dist/ocr.mjs CHANGED
@@ -10,7 +10,6 @@ of them: an `xs:QName("String")` narrowing matches 2 of the 18,446 documents
10
10
  carrying an OCR layer, while the ALTO-namespaced `String` matches 14,650.
11
11
  */
12
12
  const OCR_WORD_LOCAL_NAMES = ["String", "string"];
13
- const OCR_WORD_CASE_FOLDED_LOCAL_NAME = "string";
14
13
  /**
15
14
  The name of the element wrapping an OCR layer inside an OCHRE document
16
15
  @internal
@@ -34,18 +33,31 @@ narrowing misses is a document the search silently drops.
34
33
  */
35
34
  const OCR_WORD_QNAMES = `(${[...OCR_WORD_LOCAL_NAMES.map((localName) => `fn:QName(${stringLiteral(ALTO_NAMESPACE)}, ${stringLiteral(localName)})`), ...OCR_WORD_LOCAL_NAMES.map((localName) => `xs:QName(${stringLiteral(localName)})`)].join(", ")})`;
36
35
  /**
37
- Build an XQuery path selecting every OCR word element beneath a node
36
+ Build an XQuery path selecting every OCR layer beneath a node
38
37
 
39
- Matches the layer and the word elements on a case-folded `local-name()`
40
- rather than a name test, because a name test silently matches nothing when
41
- OCHRE varies the casing or serves the elements in a namespace. Word elements
42
- are selected at any depth, because the hierarchy between the layer and its
43
- words is irregular and is not parsed.
38
+ Matches on `local-name()` so that a layer is selected in any namespace.
44
39
  @param rootExpression - The XQuery expression to select from
45
40
  @returns The XQuery path
46
41
  @internal
47
42
  */
48
- function buildOcrWordPath(rootExpression) {
49
- return `${rootExpression}//*[lower-case(local-name(.)) = ${stringLiteral("ocr")}]//*[lower-case(local-name(.)) = ${stringLiteral(OCR_WORD_CASE_FOLDED_LOCAL_NAME)}][@${OCR_WORD_CONTENT_ATTRIBUTE}]`;
43
+ function buildOcrLayerPath(rootExpression) {
44
+ return `${rootExpression}//*[local-name(.) = ${stringLiteral("ocr")}]`;
50
45
  }
51
- export { OCR_LAYER_ELEMENT_NAME, OCR_WORD_CONTENT_ATTRIBUTE, OCR_WORD_QNAMES, buildOcrWordPath };
46
+ /**
47
+ Build an XQuery path selecting every OCR word element beneath an OCR layer
48
+
49
+ Matches on `local-name()` so that both the ALTO-namespaced and the
50
+ unnamespaced elements are selected, against exactly the local names
51
+ {@link OCR_WORD_QNAMES} narrows on, so the path and the narrowing always
52
+ agree. Comparing against a literal list measures around three times faster
53
+ than case-folding every element name. Word elements are selected at any
54
+ depth, because the hierarchy between the layer and its words is irregular
55
+ and is not parsed.
56
+ @param layerExpression - The XQuery expression selecting the OCR layers, as built by {@link buildOcrLayerPath}
57
+ @returns The XQuery path
58
+ @internal
59
+ */
60
+ function buildOcrWordPath(layerExpression) {
61
+ return `${layerExpression}//*[local-name(.) = (${OCR_WORD_LOCAL_NAMES.map((localName) => stringLiteral(localName)).join(", ")})][@${OCR_WORD_CONTENT_ATTRIBUTE}]`;
62
+ }
63
+ export { OCR_LAYER_ELEMENT_NAME, OCR_WORD_CONTENT_ATTRIBUTE, OCR_WORD_QNAMES, buildOcrLayerPath, buildOcrWordPath };
@@ -1,3 +1,4 @@
1
+ import * as v from "valibot";
1
2
  import { CONTEXT_CATEGORY_ALIASES, ITEM_CATEGORY_BY_ALIAS, ITEM_CATEGORY_FACTS, SET_ITEM_CATEGORIES, isHeadingItemCategory, normalizeItemCategory } from "../categories.mjs";
2
3
  import { getParserOptions, multilingualFromText, parseContentLike, parseContentLikeText, parseLicense, parseRequiredContentLike, parseStringLike } from "./helpers.mjs";
3
4
  import { parseMetadataLanguages, resolveDefaultLanguage, resolveLanguages } from "./languages.mjs";
@@ -7,7 +8,6 @@ import { readPropertyValueText } from "./property-token.mjs";
7
8
  import { parseXMLString, transformPermanentIdentificationUrl } from "./string.mjs";
8
9
  import { readEntries, readProperty } from "../reflection.mjs";
9
10
  import { getXMLSourceIndex } from "../xml/metadata.mjs";
10
- import * as v from "valibot";
11
11
  // src/parsers/index.ts
12
12
  function isXMLContextGroup(context) {
13
13
  return "context" in context;
@@ -1,8 +1,8 @@
1
+ import * as v from "valibot";
1
2
  import { DEFAULT_LANGUAGES } from "../constants.mjs";
2
3
  import { parseStringLike } from "./helpers.mjs";
3
4
  import { readArrayProperty, readEntries } from "../reflection.mjs";
4
5
  import { ochreLanguageCodeSchema } from "../schemas.mjs";
5
- import * as v from "valibot";
6
6
  // src/parsers/languages.ts
7
7
  /**
8
8
  A content entry carrying a language tag
@@ -1,3 +1,4 @@
1
+ import * as v from "valibot";
1
2
  import { OCHRE_ENDPOINT, PERMANENT_IDENTIFICATION_URL_PREFIX, TEXT_ANNOTATION_UUID, getOchreItemUrl } from "../constants.mjs";
2
3
  import { normalizePropertyVariableLabel } from "../getters.mjs";
3
4
  import { serializeMDXContent, serializeMDXText } from "./mdx.mjs";
@@ -5,7 +6,6 @@ import { MultilingualString } from "./multilingual.mjs";
5
6
  import { readPropertyValueText, readPropertyValueUuid } from "./property-token.mjs";
6
7
  import { renderOptionsSchema } from "../schemas.mjs";
7
8
  import { getXMLSourceIndex } from "../xml/metadata.mjs";
8
- import * as v from "valibot";
9
9
  // src/parsers/string.ts
10
10
  const TEXT_ANNOTATION_TOKEN = "text-annotation";
11
11
  const TEXT_STYLING_TOKEN = "text-styling";
@@ -1,3 +1,4 @@
1
+ import * as v from "valibot";
1
2
  import { normalizeItemCategory } from "../../categories.mjs";
2
3
  import { getProperty } from "../../getters.mjs";
3
4
  import { parseStringContent } from "../helpers.mjs";
@@ -11,7 +12,6 @@ import { websitePresentationReader } from "./reader.mjs";
11
12
  import { parseResponsiveCssStyles } from "./styles.mjs";
12
13
  import { normalizeWebsiteResources } from "./walk.mjs";
13
14
  import { collectionVariantSchema, componentSchema } from "../../schemas.mjs";
14
- import * as v from "valibot";
15
15
  // src/parsers/website/components.ts
16
16
  /**
17
17
  Default values for a collection's display properties, shared between the
package/dist/query.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { BELONGS_TO_COLLECTION_UUID } from "./constants.mjs";
2
- import { OCR_WORD_CONTENT_ATTRIBUTE, OCR_WORD_QNAMES, buildOcrWordPath } from "./ocr.mjs";
2
+ import { OCR_WORD_CONTENT_ATTRIBUTE, OCR_WORD_QNAMES, buildOcrLayerPath, buildOcrWordPath } from "./ocr.mjs";
3
3
  import { OCHRE_RESPONSE_PADDING, compileOchreQuery, stringLiteral } from "./xquery.mjs";
4
4
  // src/query.ts
5
5
  const CTS_INCLUDES_STOP_WORDS = /* @__PURE__ */ new Set([
@@ -580,7 +580,7 @@ function registerOcrPhraseHelper(context) {
580
580
  context.helperNamesByKey.set(helperName, helperName);
581
581
  context.helperDeclarations.push(`declare function ${helperName}($resource as node(), $terms as xs:string*, $isCaseSensitive as xs:boolean) as xs:boolean {
582
582
  let $contents :=
583
- for $word in ${buildOcrWordPath("$resource")}
583
+ for $word in ${buildOcrWordPath(buildOcrLayerPath("$resource"))}
584
584
  return if ($isCaseSensitive) then string($word/@${OCR_WORD_CONTENT_ATTRIBUTE}) else lower-case(string($word/@${OCR_WORD_CONTENT_ATTRIBUTE}))
585
585
  let $needles :=
586
586
  for $term in $terms
@@ -1,5 +1,5 @@
1
- import { Query } from "./types/index.mjs";
2
1
  import * as v from "valibot";
2
+ import { Query } from "./types/index.mjs";
3
3
  /**
4
4
  Validates a pseudo-UUID string
5
5
  @param value - The string to validate
@@ -72,6 +72,7 @@ export declare const itemOcrDataParametersSchema: v.ObjectSchema<{
72
72
  readonly value: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "A search value is required">]>;
73
73
  readonly matchMode: v.OptionalSchema<v.PicklistSchema<["includes", "exact"], undefined>, "includes">;
74
74
  readonly isCaseSensitive: v.OptionalSchema<v.BooleanSchema<undefined>, false>;
75
+ readonly contextWordCount: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, "Context word count must be an integer">, v.MinValueAction<number, 0, "Context word count must not be negative">]>, 0>;
75
76
  }, undefined>;
76
77
  export declare const setItemsParametersSchema: v.ObjectSchema<{
77
78
  readonly belongsToCollectionScopeUuids: v.OptionalSchema<v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "Invalid pseudo-UUID">]>, undefined>, readonly []>;
package/dist/schemas.mjs CHANGED
@@ -1,6 +1,6 @@
1
+ import * as v from "valibot";
1
2
  import "./constants.mjs";
2
3
  import { getOchreLanguageCode, isOchreLanguageCode } from "./languages.mjs";
3
- import * as v from "valibot";
4
4
  // src/schemas.ts
5
5
  const PSEUDO_UUID_REGEX = /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i;
6
6
  /**
@@ -268,7 +268,8 @@ const itemOcrDataParametersSchema = v.object({
268
268
  uuid: uuidSchema,
269
269
  value: v.pipe(v.string(), v.check((value) => value.trim() !== "", "A search value is required")),
270
270
  matchMode: v.optional(v.picklist(["includes", "exact"]), "includes"),
271
- isCaseSensitive: defaultFalseSchema
271
+ isCaseSensitive: defaultFalseSchema,
272
+ contextWordCount: v.optional(v.pipe(v.number(), v.integer("Context word count must be an integer"), v.minValue(0, "Context word count must not be negative")), 0)
272
273
  });
273
274
  /**
274
275
  Schema for validating Set items parameters
@@ -335,7 +335,7 @@ Positioned OCR string in OCHRE
335
335
 
336
336
  OCHRE gives no guarantee about the node hierarchy inside a Resource's
337
337
  `<ocr>` layer, so only its word nodes are parsed, at whatever depth they
338
- occur. A word node is any element named `string` in any casing and any
338
+ occur. A word node is any element named `String` or `string` in any
339
339
  namespace, and its text is read from the `CONTENT` attribute.
340
340
 
341
341
  `x` and `y` come from `HPOS` and `VPOS` and locate the top-left corner of
@@ -343,12 +343,8 @@ the word's box, while `vertices` comes from `VERTICES` and is its full
343
343
  bounding polygon, which is not necessarily rectangular. Every geometry
344
344
  attribute is optional in the source, so each one is null when absent or
345
345
  unparseable, and `vertices` is then empty.
346
-
347
- `resourceUuid` is the Resource that owns the OCR layer, which differs from
348
- the requested item when the OCR lives on a child Resource.
349
346
  */
350
347
  export type OcrString = {
351
- resourceUuid: string | null;
352
348
  content: string;
353
349
  x: number | null;
354
350
  y: number | null;
@@ -360,6 +356,43 @@ export type OcrString = {
360
356
  }>;
361
357
  };
362
358
  /**
359
+ OCR search match in OCHRE
360
+
361
+ A match is one occurrence of the search phrase on one page: a run of
362
+ consecutive words in which each word matches its term. `strings` holds the
363
+ positioned words of the run, and a word hyphenated across two lines
364
+ contributes both halves.
365
+
366
+ `text` is the run as it reads, with hyphenated words rejoined from their
367
+ `SUBS_CONTENT`, which also count as one word in the phrase and in the
368
+ context. `context` holds the words on either side, within the same
369
+ page, and is null unless context was requested. Its `isTruncatedBefore` and
370
+ `isTruncatedAfter` flags are true when the page has more words beyond the
371
+ context.
372
+
373
+ `id` is unique among the matches of the requested item and is the same for
374
+ the same match on every fetch while its OCR layer is unchanged, so it can key
375
+ a list or a selection. It is opaque and is not meant to be parsed.
376
+
377
+ `resourceUuid` is the Resource that owns the page's OCR layer, which differs
378
+ from the requested item when the OCR lives on a child Resource.
379
+ `pageNumber` is the 1-based position of that Resource among its sibling
380
+ Resources, which is the page order of a multi-page document.
381
+ */
382
+ export type OcrMatch = {
383
+ id: string;
384
+ resourceUuid: string | null;
385
+ pageNumber: number | null;
386
+ text: string;
387
+ strings: Array<OcrString>;
388
+ context: {
389
+ before: string;
390
+ after: string;
391
+ isTruncatedBefore: boolean;
392
+ isTruncatedAfter: boolean;
393
+ } | null;
394
+ };
395
+ /**
363
396
  Note in OCHRE
364
397
  */
365
398
  export type Note<T extends LanguageCodes = LanguageCodes> = {
@@ -1,5 +1,5 @@
1
- import { isObject, readEntries, readProperty } from "../reflection.mjs";
2
1
  import { XMLParser } from "fast-xml-parser";
2
+ import { isObject, readEntries, readProperty } from "../reflection.mjs";
3
3
  // src/xml/metadata.ts
4
4
  const XML_METADATA_SYMBOL = XMLParser.getMetaDataSymbol();
5
5
  /**
@@ -1,5 +1,5 @@
1
- import { XMLBibliography, XMLData as XMLData$1, XMLDataItem as XMLDataItem$1, XMLItemLinksData as XMLItemLinksData$1, XMLLink as XMLLink$1, XMLPeriod, XMLPerson, XMLProperty, XMLResource, XMLSetItemsData as XMLSetItemsData$1, XMLString, XMLWebsiteResource, XMLWebsiteResourceItem } from "./types.mjs";
2
1
  import * as v from "valibot";
2
+ import { XMLBibliography, XMLData as XMLData$1, XMLDataItem as XMLDataItem$1, XMLItemLinksData as XMLItemLinksData$1, XMLLink as XMLLink$1, XMLPeriod, XMLPerson, XMLProperty, XMLResource, XMLSetItemsData as XMLSetItemsData$1, XMLString, XMLWebsiteResource, XMLWebsiteResourceItem } from "./types.mjs";
3
3
  export declare const XMLLink: v.GenericSchema<unknown, XMLLink$1>;
4
4
  export declare const XMLDataItem: v.GenericSchema<unknown, XMLDataItem$1>;
5
5
  export declare const XMLItemLinksData: v.GenericSchema<unknown, XMLItemLinksData$1>;
@@ -1,7 +1,7 @@
1
+ import * as v from "valibot";
1
2
  import { readArrayProperty } from "../reflection.mjs";
2
3
  import { isPseudoUuid } from "../schemas.mjs";
3
4
  import { parseDateTime } from "./dates.mjs";
4
- import * as v from "valibot";
5
5
  // src/xml/schemas.ts
6
6
  function getXMLStringPayload(value) {
7
7
  return typeof value === "string" ? value : value.payload ?? null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ochre-sdk",
3
- "version": "1.3.32",
3
+ "version": "1.3.34",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "Node.js library for working with OCHRE (Online Cultural and Historical Research Environment) data",
@@ -46,23 +46,23 @@
46
46
  ],
47
47
  "dependencies": {
48
48
  "@nodable/entities": "^3.1.0",
49
- "fast-equals": "^6.2.2",
50
- "fast-xml-parser": "^5.12.0",
49
+ "fast-equals": "^6.4.2",
50
+ "fast-xml-parser": "^5.12.1",
51
51
  "valibot": "^1.5.0"
52
52
  },
53
53
  "devDependencies": {
54
54
  "@antfu/eslint-config": "^10.0.0",
55
- "@types/node": "^26.6.6",
55
+ "@types/node": "^26.6.11",
56
56
  "bumpp": "^12.3.0",
57
- "eslint": "^10.14.0",
58
- "eslint-plugin-erasable-syntax-only": "^0.7.2",
57
+ "eslint": "^10.16.0",
58
+ "eslint-plugin-erasable-syntax-only": "^0.7.3",
59
59
  "eslint-plugin-slop": "^0.1.3",
60
- "eslint-plugin-sonarjs": "^4.2.2",
61
- "knip": "^6.45.1",
62
- "oxfmt": "^0.78.0",
60
+ "eslint-plugin-sonarjs": "^4.2.3",
61
+ "knip": "^6.49.0",
62
+ "oxfmt": "^0.81.0",
63
63
  "tsdown": "^0.23.7",
64
64
  "typescript": "^6.0.3",
65
- "vitest": "^5.1.0"
65
+ "vitest": "^5.1.2"
66
66
  },
67
67
  "scripts": {
68
68
  "dev": "tsdown src/index.ts --watch",