Release EPUB Tools 0.2.0
Verify / verify (push) Canceled after 0s

This commit is contained in:
2026-09-02 08:53:49 +02:00
parent f68dcfe4ea
commit efd80eb18a
41 changed files with 3250 additions and 614 deletions
+60 -6
View File
@@ -33,13 +33,19 @@ async function epubFixture(): Promise<Buffer> {
await writer.add(
"EPUB/package.opf",
new TextReader(
`<?xml version="1.0"?><package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="id"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:identifier id="id">urn:browser:test</dc:identifier><dc:title>Browser Fixture</dc:title><dc:language>en</dc:language><dc:creator>Local Author</dc:creator></metadata><manifest><item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/><item id="cover" href="cover.png" media-type="image/png" properties="cover-image"/></manifest><spine><itemref idref="chapter"/></spine></package>`,
`<?xml version="1.0"?><package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="id"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:identifier id="id">urn:browser:test</dc:identifier><dc:title>Browser Fixture</dc:title><dc:language>en</dc:language><dc:creator>Local Author</dc:creator></metadata><manifest><item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/><item id="title-page" href="title.xhtml" media-type="application/xhtml+xml"/><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/><item id="cover" href="cover.png" media-type="image/png" properties="cover-image"/></manifest><spine><itemref idref="title-page"/><itemref idref="chapter"/></spine></package>`,
),
);
await writer.add(
"EPUB/nav.xhtml",
new TextReader(
`<?xml version="1.0"?><html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"><body><nav epub:type="toc"><ol><li><a href="chapter.xhtml">A safe chapter</a></li></ol></nav></body></html>`,
`<?xml version="1.0"?><html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"><body><nav epub:type="toc"><ol><li><a href="title.xhtml">Cover</a></li><li><a href="chapter.xhtml">A safe chapter</a></li></ol></nav></body></html>`,
),
);
await writer.add(
"EPUB/title.xhtml",
new TextReader(
`<?xml version="1.0"?><html xmlns="http://www.w3.org/1999/xhtml"><head><title>Cover</title></head><body><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="100%" height="100%" viewBox="0 0 1283 1920" preserveAspectRatio="none"><image width="1283" height="1920" xlink:href="cover.png"></image></svg></body></html>`,
),
);
await writer.add(
@@ -85,17 +91,45 @@ test("serves the release identity and hardened headers", async ({
const manifest = await request.get("/deep/nested/epub/toolbox-app.json");
await expect(manifest.json()).resolves.toMatchObject({
id: "de.add-ideas.epub-tools",
version: "0.1.0",
version: "0.2.0",
entry: "./",
});
});
test("adapts Markdown locally and reports the resulting EPUB workspace", async ({
page,
}) => {
const external = await localOnly(page);
await page.goto("/deep/nested/epub/");
await page.getByLabel("Choose publication").setInputFiles({
name: "local-notes.md",
mimeType: "text/markdown",
buffer: Buffer.from("# Local notes\n\nA **private** chapter."),
});
await expect(
page.getByText("Local notes", { exact: true }).first(),
).toBeVisible({
timeout: 30_000,
});
await expect(page.getByText("MARKDOWN → EPUB workspace")).toBeVisible();
await expect(
page
.frameLocator("iframe[title^='Safe EPUB preview']")
.getByRole("heading", { name: "Local notes" }),
).toBeVisible();
await page.getByRole("button", { name: "Validation" }).click();
await expect(page.getByText(/was converted locally into/iu)).toBeVisible();
expect(external).toEqual([]);
});
test("opens, sanitizes, edits, rebuilds, and reopens a real EPUB", async ({
page,
}) => {
const external = await localOnly(page);
await page.goto("/deep/nested/epub/");
await page.getByLabel("Choose EPUB").setInputFiles({
await page.getByRole("button", { name: "Personalize" }).click();
await page.getByRole("button", { name: "Dark" }).click();
await page.getByLabel("Choose publication").setInputFiles({
name: "fixture.epub",
mimeType: "application/epub+zip",
buffer: await epubFixture(),
@@ -104,13 +138,33 @@ test("opens, sanitizes, edits, rebuilds, and reopens a real EPUB", async ({
page.getByText("Browser Fixture", { exact: true }).first(),
).toBeVisible({ timeout: 30_000 });
const reader = page.frameLocator("iframe[title^='Safe EPUB preview']");
const titleImage = reader.locator("svg image");
await expect(titleImage).toBeVisible();
expect(
await titleImage.evaluate((element) =>
element.getAttributeNS("http://www.w3.org/1999/xlink", "href"),
),
).toMatch(/^blob:/u);
await expect(reader.locator("html")).toHaveAttribute(
"data-epub-reader-theme",
"dark",
);
await expect
.poll(() =>
reader.locator("body").evaluate((element) => {
const style = getComputedStyle(element);
return [style.backgroundColor, style.color];
}),
)
.toEqual(["rgb(23, 29, 45)", "rgb(237, 241, 251)"]);
await page.getByRole("button", { name: /A safe chapter/u }).click();
await expect(
reader.getByRole("heading", { name: "Hello from EPUB" }),
).toBeVisible();
await expect(reader.locator("script")).toHaveCount(0);
await page.getByRole("tab", { name: "Metadata" }).click();
await page.getByRole("button", { name: "Metadata" }).click();
await page.getByLabel("Title").fill("Updated in browser");
await page.getByRole("tab", { name: "Export & rebuild" }).click();
await page.getByRole("button", { name: "Export & rebuild" }).click();
const downloadPromise = page.waitForEvent("download");
await page.getByRole("button", { name: "Create updated EPUB" }).click();
const download = await downloadPromise;
+18
View File
@@ -0,0 +1,18 @@
import { expect, test } from "@playwright/test";
test("keeps the primary workspace inside a narrow viewport", async ({
page,
}) => {
await page.goto("/deep/nested/epub/");
await expect(page.locator("main").first()).toBeVisible();
await expect(
page.locator("main .loading, main .workbench-loading"),
).toHaveCount(0);
const widths = await page.evaluate(() => ({
content: document.documentElement.scrollWidth,
viewport: document.documentElement.clientWidth,
}));
expect(widths.viewport).toBeLessThanOrEqual(430);
expect(widths.content).toBeLessThanOrEqual(widths.viewport + 1);
});
+36 -2
View File
@@ -1,4 +1,4 @@
import { render, screen } from "@testing-library/react";
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { App } from "../../src/App";
@@ -13,7 +13,41 @@ describe("EPUB Tools", () => {
await screen.findByRole("heading", { name: "EPUB Tools" }),
).toBeVisible();
expect(
await screen.findByText("Sandboxed reader · local files"),
await screen.findByText("Sandboxed reader · local files", undefined, {
timeout: 4_000,
}),
).toBeVisible();
});
it("shows the selected filename and progress before archive work starts", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () => new Response("Not found", { status: 404 })),
);
vi.stubGlobal(
"requestAnimationFrame",
vi.fn(() => 1),
);
render(<App />);
const input = await screen.findByLabelText(
"Choose publication",
undefined,
{ timeout: 4_000 },
);
fireEvent.change(input, {
target: {
files: [
new File(["not read yet"], "large-publication.epub", {
type: "application/epub+zip",
}),
],
},
});
const status = await screen.findByRole("status");
expect(status).toHaveTextContent("large-publication.epub");
expect(status).toHaveTextContent("Preparing the local file");
expect(
screen.getByRole("progressbar", { name: "EPUB opening progress" }),
).toHaveValue(0);
});
});
+330 -2
View File
@@ -1,10 +1,33 @@
import { Blob as NodeBlob, File as NodeFile } from "node:buffer";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { closeBook, openEpub } from "../../src/epub/archive";
import { patchPackageMetadata, rebuildEpub } from "../../src/epub/export";
import {
openPublication,
publicationAdapterForFile,
} from "../../src/epub/adapters";
import {
readEntryText,
readPublicationResourceBytes,
} from "../../src/epub/entries";
import {
exportMarkdown,
exportReadingOrderHtml,
patchPackageMetadata,
rebuildEpub,
} from "../../src/epub/export";
import {
exportReadingNotes,
importReadingNotes,
type EpubReadingNotes,
} from "../../src/epub/annotations";
import { resolvePackageHref, validateEntryPath } from "../../src/epub/paths";
import { renderChapter, revokeRenderedChapter } from "../../src/epub/reader";
import {
applyReaderTheme,
renderChapter,
revokeRenderedChapter,
} from "../../src/epub/reader";
import type { EpubBook } from "../../src/epub/types";
import { searchPublication } from "../../src/epub/search";
import { createEpubFixture } from "./fixture";
let opened: EpubBook[] = [];
@@ -31,6 +54,51 @@ describe("EPUB path policy", () => {
});
describe("EPUB package inspection", () => {
it("adapts bounded Markdown, HTML and plain text into explicit EPUB workspaces", async () => {
expect(publicationAdapterForFile({ name: "notes.md", type: "" })).toBe(
"markdown",
);
const markdown = await openPublication(
new File(["# Adapter title\n\nA **local** paragraph."], "notes.md", {
type: "text/markdown",
}),
);
opened.push(markdown);
expect(markdown.adapter).toMatchObject({
kind: "markdown",
sourceFilename: "notes.md",
});
expect(markdown.package.metadata.title).toBe("Adapter title");
expect(await readEntryText(markdown, "EPUB/content.xhtml")).toContain(
"<strong>local</strong>",
);
expect(markdown.issues).toContainEqual(
expect.objectContaining({ code: "adapted-publication" }),
);
const html = await openPublication(
new File(
[
"<!doctype html><title>Safe source</title><style>body{color:red}</style><h1 onclick='bad()'>Heading</h1><script>bad()</script><a href='https://example.invalid'>external</a>",
],
"source.html",
{ type: "text/html" },
),
);
opened.push(html);
const adaptedHtml = await readEntryText(html, "EPUB/content.xhtml");
expect(adaptedHtml).toContain("<h1>Heading</h1>");
expect(adaptedHtml).not.toMatch(/script|onclick|example\.invalid/iu);
const text = await openPublication(
new File(["first\nsecond"], "plain.txt", { type: "text/plain" }),
);
opened.push(text);
expect(await readEntryText(text, "EPUB/content.xhtml")).toContain(
"<pre>first\nsecond</pre>",
);
});
it("opens metadata, navigation, spine, and bounded inventory", async () => {
const book = await openEpub(await createEpubFixture());
opened.push(book);
@@ -52,6 +120,34 @@ describe("EPUB package inspection", () => {
expect(book.issues.filter((item) => item.severity === "error")).toEqual([]);
});
it("reports monotonic, named opening phases", async () => {
const updates: Array<{ phase: string; progress: number }> = [];
const book = await openEpub(await createEpubFixture(), (progress) =>
updates.push(progress),
);
opened.push(book);
expect(updates.map((update) => update.phase)).toEqual(
expect.arrayContaining([
"archive",
"entries",
"container",
"package",
"navigation",
"validation",
"ready",
]),
);
expect(updates.at(-1)).toMatchObject({ phase: "ready", progress: 0.96 });
for (const [index, update] of updates.entries()) {
expect(update.progress).toBeGreaterThanOrEqual(0);
expect(update.progress).toBeLessThanOrEqual(1);
if (index > 0)
expect(update.progress).toBeGreaterThanOrEqual(
updates[index - 1]?.progress ?? 0,
);
}
});
it("reports active content and broken resources", async () => {
const book = await openEpub(
await createEpubFixture({ activeContent: true, brokenLink: true }),
@@ -61,6 +157,22 @@ describe("EPUB package inspection", () => {
expect.arrayContaining(["active-content", "broken-link"]),
);
});
it("parses direction, page progression, and fixed-layout metadata", async () => {
const book = await openEpub(
await createEpubFixture({ direction: "rtl", fixedLayout: true }),
);
opened.push(book);
expect(book.package).toMatchObject({
direction: "rtl",
pageProgressionDirection: "rtl",
rendition: {
layout: "pre-paginated",
orientation: "portrait",
spread: "none",
},
});
});
});
describe("safe rendering and editing", () => {
@@ -82,6 +194,186 @@ describe("safe rendering and editing", () => {
revokeRenderedChapter(chapter);
});
it("resolves SVG XLink images, disables XLink navigation, and caches repeats", async () => {
const createObjectURL = vi.fn(() => "blob:fixture-cover");
vi.stubGlobal("URL", {
...URL,
createObjectURL,
revokeObjectURL: vi.fn(),
});
const book = await openEpub(
await createEpubFixture({ svgTitlePage: true, repeatedImages: 100 }),
);
opened.push(book);
const chapter = await renderChapter(book, "EPUB/title.svg");
const document = new DOMParser().parseFromString(chapter.html, "text/html");
const image = document.querySelector("svg image");
const anchor = document.querySelector("svg a");
expect(image?.getAttributeNS("http://www.w3.org/1999/xlink", "href")).toBe(
"blob:fixture-cover",
);
expect(
anchor?.getAttributeNS("http://www.w3.org/1999/xlink", "href"),
).toBeNull();
expect(anchor?.getAttribute("href")).toBe("#");
expect(anchor?.getAttribute("data-epub-href")).toBe(
"https://example.invalid/tracker",
);
revokeRenderedChapter(chapter);
const repeated = await renderChapter(book, "EPUB/chapter.xhtml");
expect(repeated.objectUrls).toHaveLength(1);
expect(createObjectURL).toHaveBeenCalledTimes(2);
revokeRenderedChapter(repeated);
});
it("reports missing SVG XLink resources and removes them from rendering", async () => {
vi.stubGlobal("URL", {
...URL,
createObjectURL: vi.fn(),
revokeObjectURL: vi.fn(),
});
const book = await openEpub(
await createEpubFixture({
svgTitlePage: true,
svgImageHref: "missing-cover.jpeg",
}),
);
opened.push(book);
expect(book.issues).toContainEqual(
expect.objectContaining({
code: "broken-link",
path: "EPUB/title.svg",
}),
);
const chapter = await renderChapter(book, "EPUB/title.svg");
const document = new DOMParser().parseFromString(chapter.html, "text/html");
const image = document.querySelector("svg image");
expect(image?.getAttribute("href")).toBeNull();
expect(
image?.getAttributeNS("http://www.w3.org/1999/xlink", "href"),
).toBeNull();
});
it("applies an explicit reader theme independently of the operating system", () => {
const source = "<!doctype html><html><head></head><body>Text</body></html>";
expect(applyReaderTheme(source, "dark")).toContain(
'<html data-epub-reader-theme="dark">',
);
expect(applyReaderTheme(source, "light")).toContain(
'<html data-epub-reader-theme="light">',
);
});
it("loads bounded packaged CSS/fonts, blocks network URLs, and records internal links", async () => {
let url = 0;
vi.stubGlobal("URL", {
...URL,
createObjectURL: vi.fn(() => `blob:fixture-${++url}`),
revokeObjectURL: vi.fn(),
});
const book = await openEpub(
await createEpubFixture({
packagedStyles: true,
secondChapter: true,
direction: "rtl",
fixedLayout: true,
}),
);
opened.push(book);
const chapter = await renderChapter(book, "EPUB/chapter.xhtml");
expect(chapter).toMatchObject({
direction: "rtl",
layout: "pre-paginated",
});
expect(chapter.html).toContain("data-epub-publisher-stylesheet");
expect(chapter.html).toMatch(/font-family:\s*Fixture/iu);
expect(chapter.html).toContain("blob:fixture-");
expect(chapter.html).not.toContain("example.invalid/tracker.png");
expect(chapter.links).toContainEqual(
expect.objectContaining({
path: "EPUB/chapter-two.xhtml",
fragment: "answer",
external: false,
}),
);
});
it("decodes standardized IDPF-obfuscated fonts without treating them as DRM", async () => {
const book = await openEpub(
await createEpubFixture({ obfuscatedFont: true }),
);
opened.push(book);
expect(book.summary).toMatchObject({
encryptedResources: false,
obfuscatedFontCount: 1,
});
expect(book.issues).toContainEqual(
expect.objectContaining({ code: "font-obfuscation-supported" }),
);
const font = await readPublicationResourceBytes(
book,
"EPUB/fonts/book.woff2",
1024,
);
expect(new TextDecoder().decode(font.slice(0, 4))).toBe("wOF2");
});
it("searches bounded reading-order text and exports safe derived formats", async () => {
const book = await openEpub(
await createEpubFixture({ secondChapter: true, activeContent: true }),
);
opened.push(book);
const progress: number[] = [];
const results = await searchPublication(
book,
"searchable phrase",
(value) => progress.push(value.current),
);
expect(results).toHaveLength(2);
expect(results[0]).toMatchObject({
path: "EPUB/chapter-two.xhtml",
occurrences: 2,
});
expect(progress.at(-1)).toBe(2);
const markdown = await (await exportMarkdown(book)).text();
const html = await (await exportReadingOrderHtml(book)).text();
expect(markdown).toContain("# Second chapter");
expect(html).toContain("Content-Security-Policy");
expect(html).not.toContain("<script");
expect(html).not.toContain('http-equiv="refresh"');
expect(html).not.toContain("<template");
expect(html).not.toContain("example.invalid");
});
it("round-trips bounded publication-scoped bookmarks and annotations", () => {
const notes: EpubReadingNotes = {
schemaVersion: 1,
publication: { identifier: "urn:test:book", title: "Fixture Book" },
bookmarks: [
{ id: "bookmark-1", path: "EPUB/chapter.xhtml", label: "Opening" },
],
annotations: [
{
id: "note-1",
path: "EPUB/chapter-two.xhtml",
fragment: "answer",
label: "Answer",
note: "Review",
quote: "searchable phrase",
},
],
};
const output = exportReadingNotes(notes);
expect(importReadingNotes(output, notes.publication)).toEqual(notes);
expect(() =>
importReadingNotes(output, {
identifier: "urn:other",
title: "Other",
}),
).toThrow(/different publication/u);
});
it("patches metadata and rebuilds a readable normalized EPUB", async () => {
const book = await openEpub(await createEpubFixture());
opened.push(book);
@@ -111,4 +403,40 @@ describe("safe rendering and editing", () => {
mimetypeStored: true,
});
});
it("re-keys standardized obfuscated fonts when the identifier changes", async () => {
const book = await openEpub(
await createEpubFixture({ obfuscatedFont: true }),
);
opened.push(book);
const metadata = {
...book.package.metadata,
identifier: "urn:test:updated-book",
creators: [...book.package.metadata.creators],
subjects: [...book.package.metadata.subjects],
};
const rebuilt = await rebuildEpub(book, { metadata });
expect(rebuilt.changes).toContain(
"Re-keyed 1 standardized obfuscated font(s)",
);
const reopened = await openEpub(
new File([rebuilt.blob], "re-keyed.epub", {
type: "application/epub+zip",
}),
);
opened.push(reopened);
expect(reopened.package.uniqueIdentifierValue).toBe(
"urn:test:updated-book",
);
expect(reopened.summary).toMatchObject({
encryptedResources: false,
obfuscatedFontCount: 1,
});
const font = await readPublicationResourceBytes(
reopened,
"EPUB/fonts/book.woff2",
1024,
);
expect(new TextDecoder().decode(font.slice(0, 4))).toBe("wOF2");
});
});
+53 -3
View File
@@ -10,8 +10,17 @@ export async function createEpubFixture(
brokenLink?: boolean;
activeContent?: boolean;
compressedMimetype?: boolean;
svgTitlePage?: boolean;
svgImageHref?: string;
repeatedImages?: number;
packagedStyles?: boolean;
obfuscatedFont?: boolean;
secondChapter?: boolean;
direction?: "ltr" | "rtl";
fixedLayout?: boolean;
} = {},
): Promise<File> {
const packagedStyles = options.packagedStyles || options.obfuscatedFont;
const writer = new ZipWriter(new BlobWriter("application/epub+zip"));
await writer.add("mimetype", new TextReader("application/epub+zip"), {
level: options.compressedMimetype ? 6 : 0,
@@ -22,24 +31,65 @@ export async function createEpubFixture(
`<?xml version="1.0"?><container xmlns="urn:oasis:names:tc:opendocument:xmlns:container"><rootfiles><rootfile full-path="EPUB/package.opf" media-type="application/oebps-package+xml"/></rootfiles></container>`,
),
);
if (options.obfuscatedFont)
await writer.add(
"META-INF/encryption.xml",
new TextReader(
`<?xml version="1.0" encoding="UTF-8"?><encryption xmlns="urn:oasis:names:tc:opendocument:xmlns:container" xmlns:enc="http://www.w3.org/2001/04/xmlenc#"><enc:EncryptedData><enc:EncryptionMethod Algorithm="http://www.idpf.org/2008/embedding"/><enc:CipherData><enc:CipherReference URI="EPUB/fonts/book.woff2"/></enc:CipherData></enc:EncryptedData></encryption>`,
),
);
await writer.add(
"EPUB/package.opf",
new TextReader(
`<?xml version="1.0" encoding="UTF-8"?><package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="book-id"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:identifier id="book-id">urn:test:book</dc:identifier><dc:title>Fixture Book</dc:title><dc:language>en</dc:language><dc:creator>Ada Example</dc:creator></metadata><manifest><item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/><item id="cover" href="cover.png" media-type="image/png" properties="cover-image"/></manifest><spine><itemref idref="chapter"/></spine></package>`,
`<?xml version="1.0" encoding="UTF-8"?><package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="book-id"${options.direction ? ` dir="${options.direction}"` : ""}><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:identifier id="book-id">urn:test:book</dc:identifier><dc:title>Fixture Book</dc:title><dc:language>en</dc:language><dc:creator>Ada Example</dc:creator>${options.fixedLayout ? '<meta property="rendition:layout">pre-paginated</meta><meta property="rendition:orientation">portrait</meta><meta property="rendition:spread">none</meta>' : ""}</metadata><manifest><item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/><item id="chapter" href="chapter.xhtml" media-type="application/xhtml+xml"/>${options.secondChapter ? '<item id="chapter-two" href="chapter-two.xhtml" media-type="application/xhtml+xml"/>' : ""}<item id="cover" href="cover.png" media-type="image/png" properties="cover-image"/>${packagedStyles ? '<item id="style" href="styles/book.css" media-type="text/css"/><item id="font" href="fonts/book.woff2" media-type="font/woff2"/>' : ""}${options.svgTitlePage ? '<item id="title-page" href="title.svg" media-type="image/svg+xml"/>' : ""}</manifest><spine${options.direction ? ` page-progression-direction="${options.direction}"` : ""}>${options.svgTitlePage ? '<itemref idref="title-page"/>' : ""}<itemref idref="chapter"/>${options.secondChapter ? '<itemref idref="chapter-two"/>' : ""}</spine></package>`,
),
);
await writer.add(
"EPUB/nav.xhtml",
new TextReader(
`<?xml version="1.0"?><html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"><head><title>Contents</title></head><body><nav epub:type="toc"><ol><li><a href="chapter.xhtml">Opening chapter</a></li></ol></nav></body></html>`,
`<?xml version="1.0"?><html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"><head><title>Contents</title></head><body><nav epub:type="toc"><ol><li><a href="chapter.xhtml">Opening chapter</a>${options.secondChapter ? '<ol><li><a href="chapter-two.xhtml#answer">Second chapter</a></li></ol>' : ""}</li></ol></nav></body></html>`,
),
);
await writer.add(
"EPUB/chapter.xhtml",
new TextReader(
`<?xml version="1.0"?><html xmlns="http://www.w3.org/1999/xhtml"><head><title>Opening chapter</title></head><body><h1>Hello</h1><p>Local reading.</p>${options.activeContent ? "<script>globalThis.pwned=true</script><form><input/></form>" : ""}<img src="cover.png"/><a href="${options.brokenLink ? "missing.xhtml" : "nav.xhtml"}">Next</a></body></html>`,
`<?xml version="1.0"?><html xmlns="http://www.w3.org/1999/xhtml"${options.direction ? ` dir="${options.direction}"` : ""}><head><title>Opening chapter</title>${packagedStyles ? '<link rel="stylesheet" href="styles/book.css"/>' : ""}</head><body><h1 id="opening">Hello</h1><p>Local reading and searchable phrase.</p>${options.activeContent ? '<script>globalThis.pwned=true</script><form><input/></form><meta http-equiv="refresh" content="0;url=https://example.invalid/export-leak"/><template><iframe src="https://example.invalid/template-leak"></iframe></template>' : ""}${Array.from({ length: options.repeatedImages ?? 1 }, () => '<img src="cover.png"/>').join("")}<a href="${options.brokenLink ? "missing.xhtml" : options.secondChapter ? "chapter-two.xhtml#answer" : "nav.xhtml"}">Next</a></body></html>`,
),
);
if (options.secondChapter)
await writer.add(
"EPUB/chapter-two.xhtml",
new TextReader(
`<?xml version="1.0"?><html xmlns="http://www.w3.org/1999/xhtml"><head><title>Second chapter</title></head><body><h1 id="answer">Answer</h1><p>The searchable phrase appears twice: searchable phrase.</p></body></html>`,
),
);
if (packagedStyles) {
await writer.add(
"EPUB/styles/book.css",
new TextReader(
`@font-face{font-family:Fixture;src:url("../fonts/book.woff2")}body{font-family:Fixture;background-image:url("https://example.invalid/tracker.png")}h1{color:rebeccapurple}`,
),
);
const fontBytes = new Uint8Array([0x77, 0x4f, 0x46, 0x32, 0, 0, 0, 0]);
if (options.obfuscatedFont) {
const key = new Uint8Array(
await crypto.subtle.digest(
"SHA-1",
new TextEncoder().encode("urn:test:book"),
),
);
for (let index = 0; index < fontBytes.length; index += 1)
fontBytes[index] = fontBytes[index]! ^ key[index % key.length]!;
}
await writer.add("EPUB/fonts/book.woff2", new Uint8ArrayReader(fontBytes));
}
if (options.svgTitlePage)
await writer.add(
"EPUB/title.svg",
new TextReader(
`<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="100%" height="100%" viewBox="0 0 1283 1920" preserveAspectRatio="none"><a xlink:href="https://example.invalid/tracker"><image width="1283" height="1920" xlink:href="${options.svgImageHref ?? "cover.png"}"/></a></svg>`,
),
);
await writer.add(
"EPUB/cover.png",
new Uint8ArrayReader(