Skip to content

Auto-transform the Bible HTML from getPassage so the consumer doesn't have extra steps#216

Open
cameronapak wants to merge 5 commits intomainfrom
transform-bible-html
Open

Auto-transform the Bible HTML from getPassage so the consumer doesn't have extra steps#216
cameronapak wants to merge 5 commits intomainfrom
transform-bible-html

Conversation

@cameronapak
Copy link
Copy Markdown
Collaborator

@cameronapak cameronapak commented Apr 20, 2026

Summary

Auto-transforms Bible HTML inside getPassage so consumers never need to call transformBibleHtml manually. Uses native DOMParser in browser, dynamic import('linkedom') on server. Added data-yv-transformed idempotency marker so double-transforms are a no-op.

5 files changed across core and ui: bible.ts (getHtmlAdapters + transform in getPassage), bible-html-transformer.ts (idempotency guard), bible-html-transformer.test.ts (3 idempotency tests), bible.test.ts (updated assertions for transformed output), verse.tsx (kept transform as XSS safety net for direct callers).

Verse.Html retains its transformBibleHtml call as defense-in-depth — the idempotency marker makes it a no-op for HTML that already went through getPassage.

All 609 tests pass (290 core, 258 hooks, 61 ui). Build, typecheck, lint green.

Context: Why transformBibleHtml Exists — And Where It May Not Be Needed

Test plan

  • Verify getPassage with format: 'html' returns transformed content (data-yv-transformed present)
  • Verify getPassage with format: 'text' returns raw content (no transformation)
  • Verify double-transform produces identical output (idempotency)
  • Verify footnotes are extracted into data-verse-footnote attributes
  • Verify Verse.Html still sanitizes raw HTML passed directly (XSS protection)

🤖 Generated with Claude Code

Greptile Summary

This PR auto-transforms Bible HTML inside getPassage so consumers no longer call transformBibleHtml manually, with a transform: false escape hatch for raw-HTML or server-only use cases. The data-yv-transformed idempotency marker makes Verse.Html's existing sanitization call a no-op for pre-transformed content, and a clear error is thrown when linkedom is absent on the server.

Confidence Score: 4/5

Safe to merge after addressing the two P2 items; no P0/P1 issues introduced in this PR

Both remaining findings are P2: the idempotency marker fallback is an edge case that doesn't affect the Bible API's always-wrapped HTML in practice, and the CSS :has() compatibility gap only impacts transform: false consumers on Firefox < 121. Score of 4 rather than 5 to signal these are worth a quick fix before shipping, but neither is blocking.

packages/core/src/bible-html-transformer.ts (marker placement fallback) and packages/core/src/styles/bible-reader.css (:has() browser support)

Important Files Changed

Filename Overview
packages/core/src/bible.ts Adds getHtmlAdapters() and auto-transform logic in getPassage; linkedom missing now throws a clear error (previous concern resolved); transform parameter defaults via !== false semantics
packages/core/src/bible-html-transformer.ts Adds idempotency guard (data-yv-transformed) and marker placement; fallback to doc.body when firstElementChild is null means marker isn't serialized via innerHTML, breaking the idempotency guarantee for element-less HTML
packages/core/src/styles/bible-reader.css Adds CSS :has() fallback for verse label spacing in untransformed HTML; :has() is unsupported in Firefox < 121, which could silently omit spacing for transform: false users on older Firefox
packages/ui/src/components/verse.tsx Comment update only; logic unchanged — SSR still returns raw HTML, browser still calls transformBibleHtml, idempotency guard makes it a no-op for pre-transformed content
packages/core/src/bible-html-transformer.test.ts Adds three idempotency tests covering: marker presence after transform, short-circuit on re-transform, and full double-transform equality
packages/core/src/tests/bible.test.ts Updated assertions to match auto-transformed output; adds transform: false opt-out test and data-verse-footnote assertions
.changeset/auto-transform-bible-html.md Minor-version bump across all three packages; accurately documents auto-transform behaviour and the transform: false escape hatch

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A["getPassage(versionId, usfm, format)"] --> B{"format == html\nAND transform !== false?"}
    B -- No --> C[Return raw API response]
    B -- Yes --> D[getHtmlAdapters]
    D --> E{"DOMParser available\nin globalThis?"}
    E -- Yes --> F[Browser: native DOMParser adapter]
    E -- No --> G["Server: dynamic import linkedom"]
    G -- error --> H["Throw: install linkedom\nor use transform: false"]
    G -- ok --> I[linkedom DOMParser adapter]
    F --> J[transformBibleHtml]
    I --> J
    J --> K{"doc.querySelector\ndata-yv-transformed?"}
    K -- Found --> L[sanitize only, return early]
    K -- Not found --> M["sanitize → wrapVerseContent\n→ footnotes → nbsp → tables"]
    M --> N["Set data-yv-transformed on\nfirstElementChild"]
    N --> O[Return transformed passage]
    L --> O
    P["Verse.Html browser"] --> Q["transformBibleHtml via useMemo"]
    Q --> K
Loading

Fix All in Claude Code Fix All in Cursor

Prompt To Fix All With AI
This is a comment left during a code review.
Path: packages/core/src/bible-html-transformer.ts
Line: 358-360

Comment:
Idempotency marker lost when HTML has no element children. `doc.body?.firstElementChild` is `null` for bare-text or comment-only HTML, so `root` falls back to `doc.body` itself. The attribute is then set on `<body>`, but `serializeHtml` returns `doc.body.innerHTML` — the inner content — so the `data-yv-transformed` attribute on `<body>` is never serialized. The marker is silently dropped, and a subsequent call re-runs the full transform. Bible API responses always have a root `<div>`, so this won't bite in production today, but `transformBibleHtml` is a public API and the fallback undermines the guarantee for consumers who pass arbitrary HTML fragments.

```suggestion
  // Mark as transformed for idempotency
  const root = doc.body?.firstElementChild;
  if (root) {
    root.setAttribute(TRANSFORMED_ATTR, '');
  } else {
    // No element root — wrap content so the marker is serializable
    const wrapper = doc.createElement('div');
    wrapper.setAttribute(TRANSFORMED_ATTR, '');
    while (doc.body?.firstChild) {
      wrapper.appendChild(doc.body.firstChild);
    }
    doc.body?.appendChild(wrapper);
  }
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: packages/core/src/styles/bible-reader.css
Line: 93-97

Comment:
`:has()` landed in Firefox 121 (December 2023). Browsers older than that silently drop this rule, so verse labels in `transform: false` content would render without a spacing character. The primary path (auto-transformed HTML) is unaffected since `addNbspToVerseLabels` injects `\u00A0` directly into the DOM. Consider the fallback below to cover older engines.

```suggestion
  /* When content hasn't been JS-transformed, add spacing after verse labels via CSS.
     Transformed HTML already has a \u00A0 inserted by addNbspToVerseLabels().
     Note: :has() requires Firefox 121+ / Safari 15.4+ / Chrome 105+. */
  & .yv-vlbl::after {
    content: "\00A0";
  }

  /* Remove the CSS-added space when JS transformation has already done it */
  &:has([data-yv-transformed]) .yv-vlbl::after {
    content: none;
  }
```

How can I resolve this? If you propose a fix, please make it concise.

Reviews (3): Last reviewed commit: "chore: update changeset with transform o..." | Re-trigger Greptile

getPassage now automatically sanitizes and transforms HTML content
before returning — verse wrapping, footnote extraction, nbsp, and
table fixes all happen at the root. Uses native DOMParser in browser,
dynamic import('linkedom') on server. Added data-yv-transformed
idempotency marker so double-transforms are a no-op.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented Apr 20, 2026

🦋 Changeset detected

Latest commit: 20c1599

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 4 packages
Name Type
@youversion/platform-core Minor
@youversion/platform-react-hooks Minor
@youversion/platform-react-ui Minor
vite-react Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@cameronapak cameronapak changed the title feat(core): auto-transform Bible HTML in getPassage Auto-transform the Bible HTML from getPassage so the consumer doesn't have extra steps Apr 20, 2026
Comment thread packages/core/src/bible-html-transformer.ts Outdated
Comment thread packages/core/src/bible.ts Outdated
cameronapak and others added 2 commits April 20, 2026 14:10
Run XSS sanitization before idempotency check so data-yv-transformed
cannot bypass sanitizeBibleHtmlDocument. Add clear error message when
linkedom is missing on server instead of opaque module-not-found error.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

expect(result.html).not.toContain('onclick');
expect(result.html).toContain('<p>');
expect(result.html).toContain('<p');
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note: if you're wondering why this tag is seemingly cut off, it's because the tags would contain a data attribute in this new PR, which would then make it where the tag is something like <p data-yv-attribute> versus <p> standalone

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can this expect() call do regular expressions? we don't have pre tags yet, that I know of, but still... it'd be great to tighten this up if that's not too difficult.

Copy link
Copy Markdown
Member

@davidfedor davidfedor left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Big picture: I love the idea of being helpful, without requiring the developer to have to make another call. My comments and questions are around whether this is the best way to do that. (Maybe it is! I'm not sure yet.)
I notice this would be blurring the lines between Core being merely an API helper-layer, but now it would be doing some of the prep-work of the UI (visualization layer). So at the least having that be optional seems wise.
I'm wondering if that parameter should default to do the transformation, or not... or whether we need to force the dev to make a choice (to attempt to force them to make an informed choice).

} catch {
throw new Error(
'Server-side HTML transformation requires "linkedom". ' +
'Install it as a dependency or pass format: "text" to skip transformation.',
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This might be better if there was a supported way to get raw html (untransformed), for people who don't want to import linkedom or who (for whatever reason) want the original data. How about a new format option, "rawhtml" or something like that?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(I'm writing this here because this error path is not something a builder will probably be excited to be in. The fix would mostly be elsewhere.)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

... or add another parameter so that the format can stay "html". That feels like a better idea to me.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like what you're processing. I've added a new commit to have the escape hatch allowing users to intentionally seek raw html versus transformed: aece62a

This PR is ready for re-review and re-consideration @davidfedor

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few things:

  • I'm curious, why linkedom as opposed to a more widely supported library like jsdom? Is there any risk of supply chain pollution with the newer library?
  • Have the docs been updated to reflect the need for a third party dependency?
  • Can the dependency be added as an optional peer dependency so it shows up in install logs?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I ask as someone who is doing RSC data loading, and will need to have this work server-side :)

@davidfedor
Copy link
Copy Markdown
Member

(FYI I've asked for thoughts from Bryson H; not sure if he's got cycles to contribute or not)

cameronapak and others added 2 commits April 24, 2026 11:23
Add `transform` param to `getPassage` (default: true) so consumers can
receive untransformed HTML without needing linkedom on the server.
CSS now handles verse label spacing for raw HTML via ::after pseudo-element.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@cameronapak cameronapak requested a review from davidfedor April 24, 2026 16:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants