diff --git a/AGENTS.md b/AGENTS.md index 7881615..278fb0f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -35,7 +35,12 @@ consumer in `src/study_builder/contract.py` must continue to verify: - a supported header contract and `success: true` footer. Never use a `utf8` convenience field as the authoritative value. Decode `base64`, -verify it, then create the public text projection. Unknown additive fields must be +verify it, then create the public text projection. Prefer the optional +`normalized_raw` and `normalized_stripped` byte envelopes from GetBible SWORD 0.4.0; +validate them as strict UTF-8 without reapplying the source encoding or stripping +U+FEFF. A nonnull normalized strip requires a nonnull normalized source. Continue +validating the legacy byte envelopes and projection availability even when they are +not used for display. Unknown additive fields must be retained in the internal source record. Validated entries remain disk-backed and writers stream them; do not restore whole-module entry or commentary collections in memory. Composed documents are streamed from the documents they embed, never built @@ -94,8 +99,17 @@ named `html`) is not guaranteed to be HTML; it can still contain source markup. Never use that name to infer its format. These rules apply to dictionaries and commentaries alike; shared projection changes need both resources' smoke builds. Preserve source wording and scripts without per-entry replacements or language -filters. Every text is normalised the same way. Module bytes UTF-8 cannot read are -decoded as Windows-1252, never replaced. Public schemas and paths stay unchanged. +filters. Every text is normalised the same way. An explicit null normalized source +must not fall back to guessed decoding: retain its warning diagnostics, fail that +module's display projection, and continue independent modules. A null normalized +strip still permits source-aware rendering from valid normalized source. Never +substitute unsafe legacy render/strip output for these new projections. The previous +Windows-1252 compatibility decoder applies only to older streams omitting both +normalized fields. SWORD keys have their own index/verse encoding, independent of +the source body. Retain the existing key compatibility decoder for UTF-8/single-byte +modules so their IDs and URLs stay stable; do not apply SCSU or UTF-16 body decoding +to those keys. This does not relax normalized source-body decoding. Public +schemas and paths stay unchanged. Dictionary Strong's keys remain compatible with Bible API v3 (`G3056`, `H0430`). Repeated dictionary keys retain the unsuffixed direct path for their first diff --git a/README.md b/README.md index 2592417..b0b6c30 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ same sources every other GetBible service reads. ## Extraction dependency -`conf/getbiblesword.json` pins release `v0.1.1`, contract +`conf/getbiblesword.json` pins release `v0.4.0`, contract `getbiblesword.ndjson/v1`, and the exact x86-64/ARM64 Linux asset names and SHA-256 digests. On first use the builder: @@ -46,7 +46,7 @@ SHA-256 digests. On first use the builder: 3. verifies it against the SHA-256 digest committed in the manifest; 4. safely extracts only `usr/bin/getbiblesword`; 5. checks the executable's reported version and contract; -6. caches it under `.work/tools/getbiblesword/0.1.1/`. +6. caches it under `.work/tools/getbiblesword/0.4.0/`. The `getbible/getbiblesword` repository and its pinned release are public, so installation requires no repository token or GitHub API request. The automated @@ -99,13 +99,16 @@ and independently checks all of the rules that protect publication: - `getbiblesword.ndjson/v1` header and extract command; - canonical top-level member order and zero-based monotonic sequence values; - base64 decoding, byte size, SHA-256, and matching UTF-8 convenience fields; +- strict UTF-8 in normalized projections and their source/strip relationship; +- legacy projection availability and byte envelopes, even when not selected for display; - entry/configuration ordinals and module classification; - artifact identifiers, chunk indexes, reconstructed size, and SHA-256; - exact stream SHA-256 over every line before the footer, including LF; - exact footer record/entry/artifact/byte counts and `success: true`. Raw bytes remain authoritative. The adapter derives the public plain text only -after verification and retains the original contract records internally. +after verification and retains the original contract records internally, including +legacy projections, official attributes, annotation segments, and additive fields. Validated entries are held in a compressed, disk-backed spool. Commentary entries are then normalized into disk-backed chapter buckets, collapsed so that a comment attached to a verse range is stored once rather than once per verse, and emitted in @@ -324,12 +327,19 @@ clients that would otherwise read every word individually. ## Plain text -Every document is plain text. For ThML, TEI, and OSIS modules, the builder projects the -verified source markup into readable text. SWORD's stripped projections can discard +Every document is plain text. GetBible SWORD 0.4.0 supplies `normalized_raw`, source +markup strictly decoded to UTF-8, and `normalized_stripped`, SWORD's plain-text view +of that source. The builder verifies each byte envelope and reads these projections +as UTF-8 without reapplying the module's original encoding. The original source bytes +remain in the validated record. + +For ThML, TEI, and OSIS modules, the builder projects the verified UTF-8 source markup +into readable text. SWORD's stripped projections can discard line breaks and character references: a TEI `` can disappear between words, and a Greek letter written as `α` can be lost. The source-aware projections preserve paragraphs, line breaks, senses, notes, reference labels, and Unicode characters for -both dictionaries and commentaries. Other source formats retain SWORD's stripped text. +both dictionaries and commentaries. Other source formats use the verified normalized +stripped text. Character references are decoded once, when markup is read. Text that is already plain is only whitespace-normalised, so literal ampersands and entity-like examples are not @@ -344,8 +354,19 @@ space between words, no leading or trailing space on a line, and at most one bla line between blocks. Standalone documents and the corresponding entries embedded in complete downloads contain identical text. -Bytes the module wrote in Windows-1252 — the `’` of "David’s", the non-breaking space of -"1 Chronicles" — are read as such rather than replaced with `�`. +An explicitly unavailable `normalized_raw` is reported as a module failure after +stream verification; the builder preserves its diagnostics and continues independent +modules under the existing recovery policy. It does not guess another encoding. +If only `normalized_stripped` is unavailable, the source-aware readers can still +derive text from the intact source. Legacy render/strip output cannot override that +decision. Older v1 streams omitting both normalized fields retain the previous decoder +and its Windows-1252 compatibility behavior. + +The extractor does not normalize SWORD index or verse keys. The builder retains its +existing key decoder for UTF-8 and single-byte modules, including legacy index bytes, +to preserve published dictionary IDs and URLs. SCSU and UTF-16 body encodings are not +applied to ASCII or UTF-8 lookup keys. This key compatibility rule does not affect the +strict normalized source-body decoding. The upgrade adds no public fields or API version. ## Scripture references diff --git a/conf/getbiblesword.json b/conf/getbiblesword.json index b2ecb62..8883ec0 100644 --- a/conf/getbiblesword.json +++ b/conf/getbiblesword.json @@ -1,16 +1,16 @@ { "repository": "getbible/getbiblesword", - "version": "0.1.1", - "tag": "v0.1.1", + "version": "0.4.0", + "tag": "v0.4.0", "contract": "getbiblesword.ndjson/v1", "assets": { "linux-x86_64": { - "name": "getbiblesword-0.1.1-linux-x86_64.tar.gz", - "sha256": "ef8f698e77918be439a39973f6d3d2307951ec6054bee389f4f3ef0c148a063d" + "name": "getbiblesword-0.4.0-linux-x86_64.tar.gz", + "sha256": "58f8c1d1c0e23af0e121ce8ec192ab5d8d3da5fba9f832d7c678eceba5c7fbf5" }, "linux-arm64": { - "name": "getbiblesword-0.1.1-linux-arm64.tar.gz", - "sha256": "e90ab9afd69ff7d6204cf93121bfa6a22bd97d6a312a1e2cdb400e5ae89c821b" + "name": "getbiblesword-0.4.0-linux-arm64.tar.gz", + "sha256": "03476d274f09638653cb770b304483b57fb49532499a37765cce89fed9c4e968" } } } diff --git a/schemas/getbiblesword-ndjson-v1.schema.json b/schemas/getbiblesword-ndjson-v1.schema.json index c88192e..ec74e29 100644 --- a/schemas/getbiblesword-ndjson-v1.schema.json +++ b/schemas/getbiblesword-ndjson-v1.schema.json @@ -87,6 +87,14 @@ "properties": { "type": { "const": "entry" }, "key": { "$ref": "#/$defs/byteValue" }, + "normalized_raw": { + "description": "Optional UTF-8 source markup projection; null when the declared encoding cannot be decoded strictly. Never replaces authoritative raw bytes.", + "oneOf": [{ "$ref": "#/$defs/byteValue" }, { "type": "null" }] + }, + "normalized_stripped": { + "description": "Optional SWORD stripText projection of normalized_raw, encoded in UTF-8; null when unavailable.", + "oneOf": [{ "$ref": "#/$defs/byteValue" }, { "type": "null" }] + }, "raw": { "$ref": "#/$defs/byteValue" } } } diff --git a/src/study_builder/content.py b/src/study_builder/content.py index 562e355..a3bc6a3 100644 --- a/src/study_builder/content.py +++ b/src/study_builder/content.py @@ -491,6 +491,11 @@ class ContentProjectionError(ValueError): def public_content(entry: dict[str, Any], *, source_type: str = "") -> dict[str, str]: """Project a validated contract entry onto the unchanged v1 text-only shape.""" + if error := entry.get("_text_error"): + raise ContentProjectionError( + f"Entry {entry.get('key', 'unknown')!r} " + f"({source_type or 'unspecified SourceType'}): {error}" + ) projector = {"thml": thml_text, "tei": tei_text, "osis": osis_text}.get( source_type.strip().casefold() ) diff --git a/src/study_builder/contract.py b/src/study_builder/contract.py index 1c03307..f5b5c2a 100644 --- a/src/study_builder/contract.py +++ b/src/study_builder/contract.py @@ -143,6 +143,38 @@ def _text(value: Any, context: str, encoding: str = "") -> str: return decode_module_text(decode_byte_value(value, context), encoding) +def _normalized_text(value: Any, context: str) -> str: + """Validate an extractor UTF-8 projection without reapplying its source codec.""" + payload = decode_byte_value(value, context) + try: + # A BOM in this projection is source content, not a decoding instruction. + return payload.decode("utf-8", errors="strict") + except UnicodeDecodeError as error: + raise ContractError(f"{context} must contain valid UTF-8") from error + + +def _normalized_entry_key(value: Any, context: str, encoding: str) -> str: + """Read SWORD's index/verse key independently of the source-body encoding. + + SWORD generates verse keys and uses UTF-8 dictionary key operations even when + the body is SCSU or UTF-16. The new extractor does not normalize keys, so keep + the existing key decoder for previously supported UTF-8/single-byte modules. + Real indexes such as Easton's contain legacy bytes despite declaring UTF-8; + changing their decoding would change existing dictionary IDs and URLs. + """ + payload = decode_byte_value(value, context) + declared = encoding.strip().casefold().replace("_", "-") + if declared in _UTF8_ENCODINGS | _SINGLE_BYTE_ENCODINGS: + return decode_module_text(payload, encoding) + try: + return payload.decode("utf-8", errors="strict") + except UnicodeDecodeError as error: + raise ContractError( + f"{context} is not a supported UTF-8 SWORD key; " + f"the source-body encoding {encoding!r} cannot be applied to index keys" + ) from error + + class GetBibleSwordContractReader: def __init__(self, schema_path: Path, expected_contract: str) -> None: schema = read_json(schema_path) @@ -364,10 +396,64 @@ def _adapt_module( @staticmethod def _adapt_entry(record: dict[str, Any], sequence: int, encoding: str = "") -> dict[str, Any]: - key = _text(record["key"], f"record[{sequence}].key", encoding) - raw = _text(record["raw"], f"record[{sequence}].raw", encoding) - rendered = record.get("rendered_default") - stripped = record.get("stripped") + context = f"record[{sequence}]" + available = record.get("projections_available") + if not isinstance(available, bool): + raise ContractError(f"{context}.projections_available must be a boolean") + for name in ("rendered_default", "stripped"): + if name not in record: + raise ContractError(f"{context}.{name} is missing") + if available: + # Unused legacy projections must still satisfy the byte contract. + decode_byte_value(record[name], f"{context}.{name}") + elif record[name] is not None: + raise ContractError( + f"{context}.{name} must be null when projections are unavailable" + ) + normalized = "normalized_raw" in record or "normalized_stripped" in record + text_error: dict[str, str] = {} + if normalized: + key = _normalized_entry_key(record["key"], f"{context}.key", encoding) + projections = { + name: ( + _normalized_text(record[name], f"{context}.{name}") + if record.get(name) is not None + else None + ) + for name in ("normalized_raw", "normalized_stripped") + } + raw = projections["normalized_raw"] + plain = projections["normalized_stripped"] + if plain is not None and raw is None: + raise ContractError(f"{context}.normalized_stripped requires normalized_raw") + if raw is None: + # Null is a declared decoding failure, not permission to guess a + # codec. Defer display failure until after complete verification + # so the pipeline retains the extractor's warning diagnostics. + text_error["_text_error"] = ( + "entry.encoding.unavailable: the extractor could not decode the source " + f"using Encoding={encoding or 'Latin-1 (default)'!r}; " + "normalized_raw is unavailable and the original bytes are retained" + ) + raw = raw or "" + plain = plain or "" + # Legacy render/strip results have no UTF-8 guarantee. Never let an + # unsafe fallback override an explicitly unavailable projection. + rendered = "" + else: + # Older NDJSON v1 streams may omit both optional projections. + key = _text(record["key"], f"{context}.key", encoding) + raw = _text(record["raw"], f"{context}.raw", encoding) + rendered = ( + _text(record["rendered_default"], f"{context}.rendered_default", encoding) + if record.get("rendered_default") is not None + else "" + ) + plain = ( + _text(record["stripped"], f"{context}.stripped", encoding) + if record.get("stripped") is not None + else "" + ) scope = record.get("scope") or {} verse: dict[str, Any] = {} if scope.get("type") == "verse_key": @@ -386,18 +472,11 @@ def _adapt_entry(record: dict[str, Any], sequence: int, encoding: str = "") -> d # Historical internal name: rendered_default can still be source # markup when the extractor has no display filter installed. Select # the public projection using SourceType, never this field's name. - "html": ( - _text(rendered, f"record[{sequence}].rendered_default", encoding) - if rendered is not None - else "" - ), - "plain": ( - _text(stripped, f"record[{sequence}].stripped", encoding) - if stripped is not None - else "" - ), + "html": rendered, + "plain": plain, "verse": verse, "_getbiblesword": record, + **text_error, } @staticmethod diff --git a/tests/test_engine.py b/tests/test_engine.py index e474d3c..7639030 100644 --- a/tests/test_engine.py +++ b/tests/test_engine.py @@ -14,15 +14,24 @@ from study_builder.engine import EngineManifest, GetBibleSwordManager -def test_manifest_pins_release_and_architectures(project_root: Path, monkeypatch) -> None: +@pytest.mark.parametrize( + ("architecture", "sha256"), + [ + ("x86_64", "58f8c1d1c0e23af0e121ce8ec192ab5d8d3da5fba9f832d7c678eceba5c7fbf5"), + ("arm64", "03476d274f09638653cb770b304483b57fb49532499a37765cce89fed9c4e968"), + ], +) +def test_manifest_pins_release_and_architectures( + project_root: Path, monkeypatch, architecture: str, sha256: str +) -> None: manifest = EngineManifest.load(project_root / "conf/getbiblesword.json") - assert manifest.version == "0.1.1" - assert manifest.tag == "v0.1.1" + assert manifest.version == "0.4.0" + assert manifest.tag == "v0.4.0" monkeypatch.setattr("study_builder.engine.platform.system", lambda: "Linux") - monkeypatch.setattr("study_builder.engine.platform.machine", lambda: "x86_64") + monkeypatch.setattr("study_builder.engine.platform.machine", lambda: architecture) asset = manifest.platform_asset() - assert asset.name == "getbiblesword-0.1.1-linux-x86_64.tar.gz" - assert asset.sha256 == "ef8f698e77918be439a39973f6d3d2307951ec6054bee389f4f3ef0c148a063d" + assert asset.name == f"getbiblesword-0.4.0-linux-{architecture}.tar.gz" + assert asset.sha256 == sha256 def test_release_asset_url_is_scoped_to_pinned_repository( @@ -31,13 +40,13 @@ def test_release_asset_url_is_scoped_to_pinned_repository( manager = GetBibleSwordManager(project_root / "conf/getbiblesword.json", tmp_path) manager._validate_asset_url( "https://github.com/getbible/getbiblesword/releases/download/" - "v0.1.1/getbiblesword-0.1.1-linux-x86_64.tar.gz", - "getbiblesword-0.1.1-linux-x86_64.tar.gz", + "v0.4.0/getbiblesword-0.4.0-linux-x86_64.tar.gz", + "getbiblesword-0.4.0-linux-x86_64.tar.gz", ) with pytest.raises(RuntimeError, match="outside github.com"): manager._validate_asset_url( "https://example.com/archive.tar.gz", - "getbiblesword-0.1.1-linux-x86_64.tar.gz", + "getbiblesword-0.4.0-linux-x86_64.tar.gz", ) @@ -72,7 +81,7 @@ def get_bytes(self, url, headers=None): def download(self, url, target, expected_sha256=None, headers=None): self.urls.append(url) assert url.startswith( - "https://github.com/getbible/getbiblesword/releases/download/v0.1.1/" + "https://github.com/getbible/getbiblesword/releases/download/v0.4.0/" ) assert "api.github.com" not in url assert expected_sha256 == archive_sha256 diff --git a/tests/test_normalized_contract.py b/tests/test_normalized_contract.py new file mode 100644 index 0000000..a0264f2 --- /dev/null +++ b/tests/test_normalized_contract.py @@ -0,0 +1,341 @@ +# SPDX-License-Identifier: GPL-2.0-only +from __future__ import annotations + +import io +import json +from dataclasses import replace +from pathlib import Path +from typing import Any + +import pytest +from test_contract import base_records, byte_value, stream + +from study_builder.books import BookRegistry +from study_builder.commentaries import CommentaryWriter +from study_builder.content import ContentProjectionError, public_content +from study_builder.contract import ContractError, GetBibleSwordContractReader +from study_builder.dictionaries import DictionaryWriter + + +@pytest.fixture +def reader(project_root: Path) -> GetBibleSwordContractReader: + return GetBibleSwordContractReader( + project_root / "schemas/getbiblesword-ndjson-v1.schema.json", + "getbiblesword.ndjson/v1", + ) + + +def normalized_records( + *, encoding: str | None = "UTF-8", raw: str = "

λόγος

", plain: str = "λόγος" +) -> list[dict[str, Any]]: + records = base_records() + records[0]["producer_version"] = "0.4.0" + records[2].update( + normalized_raw=byte_value(raw), + normalized_stripped=byte_value(plain), + raw=byte_value(b"legacy source\x92"), + stripped=byte_value("legacy stripped text"), + rendered_default=byte_value("

legacy rendered text

"), + ) + if encoding is not None: + records.insert( + 2, + { + "name": byte_value("Encoding"), + "ordinal": 0, + "type": "config_entry", + "value": byte_value(encoding), + }, + ) + return records + + +def test_verified_normalized_bytes_supply_text_and_preserve_complete_source(reader) -> None: + records = normalized_records(encoding="Latin-1") + record = records[-1] + record["official_attributes"] = [{"name": byte_value("Lemma"), "value": byte_value("G3056")}] + record["annotation_segments"] = [{"text": byte_value("λ"), "offset": 3}] + record["future_projection"] = {"source": byte_value(b"\x00\xff")} + exported = reader.read(io.BytesIO(stream(records))) + try: + entry = exported.entries[0] + assert entry["raw"] == "

λόγος

" + assert entry["plain"] == "λόγος" + assert entry["html"] == "" + assert public_content(entry, source_type="OSIS") == {"text": "λόγος"} + assert entry["_getbiblesword"] == {**record, "sequence": len(records) - 1} + finally: + exported.close() + + +@pytest.mark.parametrize("field", ["normalized_raw", "normalized_stripped"]) +def test_normalized_bytes_are_strict_utf8_even_without_convenience_text(reader, field) -> None: + records = normalized_records(encoding="Latin-1") + records[-1][field] = byte_value(b"caf\xe9") + with pytest.raises(ContractError, match="UTF-8|UTF8|utf-8"): + reader.read(io.BytesIO(stream(records))) + + +@pytest.mark.parametrize("field", ["normalized_raw", "normalized_stripped", "raw", "stripped"]) +def test_every_byte_envelope_remains_verified_when_normalized_text_exists(reader, field) -> None: + records = normalized_records() + records[-1][field]["sha256"] = "0" * 64 + with pytest.raises(ContractError, match="sha256"): + reader.read(io.BytesIO(stream(records))) + + +@pytest.mark.parametrize("field", ["rendered_default", "stripped"]) +@pytest.mark.parametrize("state", ["string", "missing", "null"]) +def test_available_legacy_projections_require_valid_envelopes_with_normalized_text( + reader, field, state +) -> None: + records = normalized_records() + if state == "missing": + del records[-1][field] + else: + records[-1][field] = "broken" if state == "string" else None + with pytest.raises(ContractError): + reader.read(io.BytesIO(stream(records))) + + +@pytest.mark.parametrize("flag", ["true", 1, None, "missing"]) +def test_normalized_entries_require_a_boolean_legacy_projection_flag(reader, flag) -> None: + records = normalized_records() + if flag == "missing": + del records[-1]["projections_available"] + else: + records[-1]["projections_available"] = flag + with pytest.raises(ContractError): + reader.read(io.BytesIO(stream(records))) + + +@pytest.mark.parametrize("field", ["rendered_default", "stripped"]) +def test_unavailable_legacy_projections_cannot_carry_nonnull_values(reader, field) -> None: + records = normalized_records() + records[-1].update(projections_available=False, rendered_default=None, stripped=None) + records[-1][field] = byte_value("unexpected legacy projection") + with pytest.raises(ContractError): + reader.read(io.BytesIO(stream(records))) + + +def test_normalized_text_is_usable_when_both_legacy_projections_are_unavailable(reader) -> None: + records = normalized_records() + records[-1].update(projections_available=False, rendered_default=None, stripped=None) + exported = reader.read(io.BytesIO(stream(records))) + try: + entry = exported.entries[0] + assert entry["raw"] == "

λόγος

" + assert entry["plain"] == "λόγος" + assert public_content(entry, source_type="OSIS") == {"text": "λόγος"} + assert entry["_getbiblesword"] == {**records[-1], "sequence": len(records) - 1} + finally: + exported.close() + + +@pytest.mark.parametrize("field", ["normalized_raw", "normalized_stripped"]) +def test_normalized_convenience_text_cannot_override_authoritative_bytes(reader, field) -> None: + records = normalized_records() + records[-1][field]["utf8"] = "forged convenience text" + with pytest.raises(ContractError, match="utf8"): + reader.read(io.BytesIO(stream(records))) + + +@pytest.mark.parametrize("raw_state", ["missing", "null"]) +def test_normalized_stripped_requires_a_nonnull_normalized_raw(reader, raw_state) -> None: + records = normalized_records() + if raw_state == "missing": + del records[-1]["normalized_raw"] + else: + records[-1]["normalized_raw"] = None + with pytest.raises(ContractError): + reader.read(io.BytesIO(stream(records))) + + +def test_null_normalization_preserves_warning_but_blocks_legacy_text_fallback(reader) -> None: + records = normalized_records(encoding="SCSU") + records[-1]["normalized_raw"] = None + records[-1]["normalized_stripped"] = None + records.append( + { + "code": "normalization.text_unavailable", + "message": byte_value("The source cannot be decoded strictly."), + "severity": "warning", + "type": "diagnostic", + } + ) + exported = reader.read(io.BytesIO(stream(records))) + try: + entry = exported.entries[0] + assert entry["_text_error"] + assert entry["raw"] == entry["plain"] == entry["html"] == "" + assert exported.diagnostics[0]["code"] == "normalization.text_unavailable" + assert exported.diagnostics[0]["message_text"] == "The source cannot be decoded strictly." + assert exported.footer["success"] is True + with pytest.raises(ContentProjectionError, match="John 1:1"): + public_content(entry, source_type="OSIS") + finally: + exported.close() + + +@pytest.mark.parametrize("source_type", ["TEI", "OSIS", "ThML"]) +@pytest.mark.parametrize("stripped_state", ["missing", "null"]) +def test_source_markup_projects_when_normalized_stripped_is_unavailable( + reader, source_type, stripped_state +) -> None: + records = normalized_records(raw="

λ α

") + if stripped_state == "missing": + del records[-1]["normalized_stripped"] + else: + records[-1]["normalized_stripped"] = None + exported = reader.read(io.BytesIO(stream(records))) + try: + entry = exported.entries[0] + assert entry["plain"] == entry["html"] == "" + assert public_content(entry, source_type=source_type) == {"text": "λ α"} + finally: + exported.close() + + +def test_normalized_plain_is_not_decoded_as_markup_or_legacy_module_encoding(reader) -> None: + records = normalized_records(encoding="Latin-1", plain="café & λ") + exported = reader.read(io.BytesIO(stream(records))) + try: + assert public_content(exported.entries[0]) == {"text": "café & λ"} + finally: + exported.close() + + +def test_normalized_utf8_bom_is_retained_as_source_content(reader) -> None: + records = normalized_records(raw="\ufeff

λόγος

", plain="\ufeffλόγος") + exported = reader.read(io.BytesIO(stream(records))) + try: + entry = exported.entries[0] + assert entry["raw"] == "\ufeff

λόγος

" + assert entry["plain"] == "\ufeffλόγος" + finally: + exported.close() + + +@pytest.mark.parametrize( + ("encoding", "key", "expected"), + [ + # Keys remain authoritative index bytes, not normalized body text. Keep + # the legacy decoder's values so upgrading does not rename v1 paths. + ("Latin-1", "café".encode(), "café"), + ("Latin-1", b"caf\xe9\x92", "café’"), + (None, b"caf\xe9\x92", "café’"), + ("UTF-8", b"Caf\xe9", "Café"), + # Easton's original index key differs from its valid normalized body. + ("UTF-8", b"ABRAHAM\xc2\x80\x99S BOSOM", "ABRAHAM\u0080\u2122S BOSOM"), + ("UTF-8", "café λόγος".encode(), "café λόγος"), + ("SCSU", b"G03056", "G03056"), + ("SCSU", "λόγος".encode(), "λόγος"), + ("UTF-16", b"John 1:1", "John 1:1"), + ("UTF-16", "λόγος".encode(), "λόγος"), + ], +) +def test_normalized_entries_preserve_compatible_keys_without_redecoding_body_text( + reader, encoding, key, expected +) -> None: + records = normalized_records(encoding=encoding) + records[-1]["key"] = byte_value(key) + exported = reader.read(io.BytesIO(stream(records))) + try: + entry = exported.entries[0] + assert entry["key"] == expected + assert entry["raw"] == "

λόγος

" + assert entry["_getbiblesword"]["raw"] == records[-1]["raw"] + finally: + exported.close() + + +def test_both_normalized_fields_absent_preserves_legacy_projection(reader) -> None: + records = base_records() + records[2]["raw"] = byte_value(b"

Moses\x92 caf\xc3\xa9

") + records[2]["stripped"] = byte_value(b"Moses\x92 caf\xc3\xa9") + exported = reader.read(io.BytesIO(stream(records))) + try: + entry = exported.entries[0] + assert entry["raw"] == "

Moses’ café

" + assert entry["plain"] == "Moses’ café" + assert entry["html"] == "

Word

" + assert "_text_error" not in entry + assert public_content(entry, source_type="OSIS") == {"text": "Moses’ café"} + finally: + exported.close() + + +@pytest.mark.parametrize("resource", ["dictionaries", "commentaries"]) +@pytest.mark.parametrize( + ("source_type", "markup"), + [ + ("TEI", 'λόγοςJohn 1:1'), + ("OSIS", '

λόγοςJohn 1:1

'), + ("ThML", '

λόγος
John 1:1

'), + ], +) +def test_normalized_reader_to_writer_preserves_public_v1_text_and_references( + reader, + tmp_path, + project_root, + reference_engine, + greek_dictionary_module, + commentary_module, + resource, + source_type, + markup, +) -> None: + records = normalized_records(encoding="SCSU", raw=markup) + records[-1]["normalized_stripped"] = None + records[-1]["raw"] = byte_value(b"\x0e\xff\xfe opaque source bytes") + if resource == "dictionaries": + records[-1]["key"] = byte_value("03056") + records[1]["classification"] = "dictionary" + records[1]["name"] = byte_value("StrongsGreek") + records[1]["sword_type"] = byte_value("Lexicons / Dictionaries") + module = greek_dictionary_module + writer_type = DictionaryWriter + else: + module = commentary_module + writer_type = CommentaryWriter + module = replace(module, fields={**module.fields, "sourcetype": (source_type,)}) + exported = reader.read(io.BytesIO(stream(records))) + try: + writer = writer_type( + tmp_path, + BookRegistry(project_root / "conf/book_registry.json"), + project_root / "schemas", + references=reference_engine, + ) + writer.write(module, exported) + finally: + exported.close() + if resource == "dictionaries": + document = json.loads((tmp_path / "strongsgreek/G3056.json").read_text()) + complete = json.loads((tmp_path / "strongsgreek.json").read_text()) + assert complete["entries"][0] == document + assert document["id"] == "G3056" + assert document["aliases"] == ["03056", "G3056"] + assert document["schema"] == "getbible-dictionary-entry-v1" + else: + chapter = json.loads((tmp_path / "testcom/43/1.json").read_text()) + complete = json.loads((tmp_path / "testcom.json").read_text()) + assert complete["books"][0]["chapters"][0] == chapter + document = chapter["entries"][0] + assert document["osis"] == "John.1.1" + assert document["verse"] == 1 + assert chapter["schema"] == "getbible-commentary-chapter-v1" + assert document["text"] == "λόγος\nJohn 1:1" + assert "html" not in document + assert "normalized_raw" not in document + assert "_getbiblesword" not in document + assert document["references"] == [ + { + "ref": "John 1:1", + "osis": "John.1.1", + "book": 43, + "chapter": 1, + "verse": 1, + "text": "John 1:1", + } + ]