# A volume of a collection, the series on its endpapers

> Volume XI of a twelve-volume hardcover series: two ISBNs by the barcode, a case design shared by every volume, and endpapers that show the whole collection.

- HTML version: https://postext.dev/en/cookbook/collection-volume-endpapers
- Recipe Nº 198 · Output & integration · Level 3 (Advanced) · Outputs: Canvas, PDF
- Genres: Fiction, drama & literary prose
- Requires postext ≥ 1.93.0, postext-pdf ≥ 1.93.0 · tested with 1.93.0, postext-pdf 1.93.0 on 2026-11-23
- Pages: [1](https://postext.dev/cookbook/collection-volume-endpapers/en/p01.webp?v=cada069a), [3](https://postext.dev/cookbook/collection-volume-endpapers/en/p03.webp?v=cada069a), [4](https://postext.dev/cookbook/collection-volume-endpapers/en/p04.webp?v=cada069a), [5](https://postext.dev/cookbook/collection-volume-endpapers/en/p05.webp?v=cada069a), [7](https://postext.dev/cookbook/collection-volume-endpapers/en/p07.webp?v=cada069a), [8](https://postext.dev/cookbook/collection-volume-endpapers/en/p08.webp?v=cada069a), [20](https://postext.dev/cookbook/collection-volume-endpapers/en/p20.webp?v=cada069a), [21](https://postext.dev/cookbook/collection-volume-endpapers/en/p21.webp?v=cada069a), [1](https://postext.dev/cookbook/collection-volume-endpapers/en/p27.webp?v=cada069a), [1](https://postext.dev/cookbook/collection-volume-endpapers/en/p28.webp?v=cada069a), [1](https://postext.dev/cookbook/collection-volume-endpapers/en/p29.webp?v=cada069a)
- PDF: https://postext.dev/cookbook/collection-volume-endpapers/en/collection-volume-endpapers.pdf?v=cada069a
- Open in Sandbox: https://postext.dev/en/sandbox#recipe=collection-volume-endpapers&lang=en (.postext: https://postext.dev/cookbook/collection-volume-endpapers/en/collection-volume-endpapers.postext)
- Last updated: 2026-11-23
- Other languages: [es](https://postext.dev/es/cookbook/collection-volume-endpapers.md), [ca](https://postext.dev/ca/cookbook/collection-volume-endpapers.md), [de](https://postext.dev/de/cookbook/collection-volume-endpapers.md), [fr](https://postext.dev/fr/cookbook/collection-volume-endpapers.md), [it](https://postext.dev/it/cookbook/collection-volume-endpapers.md), [pt](https://postext.dev/pt/cookbook/collection-volume-endpapers.md), [zh](https://postext.dev/zh/cookbook/collection-volume-endpapers.md), [ja](https://postext.dev/ja/cookbook/collection-volume-endpapers.md), [ar](https://postext.dev/ar/cookbook/collection-volume-endpapers.md)

## In short

One hardcover from a series of twelve, with its printer's sheets: the case in the series' colours with the volume's number, and the two endpapers inside its boards, which show the covers and titles of all twelve books.

## What you'll build

*The Deceitful Marriage*, the eleventh of Cervantes' twelve *Exemplary Novels*, as volume XI of a series that prints one novella per hardcover. The 26 pages are set in Crimson Pro 11/15.2 on a 120 × 185 mm page. `buildCover` then makes three sheets for the binder from them: the printed case, in the series' oxblood with a gold frame round the painting and the number in a gold ring, and the front and back endpapers, which share the collection between them: volumes I to VI open the book and VII to XII close it, each half as paintings on the pastedown and as a numbered list on the flyleaf. Beside the barcode, which carries the volume's ISBN, the case prints the ISBN of the complete work.

**This recipe answers:**

- How do I print a volume of a collection with the work's ISBN and its other titles on the endpapers?

## The short answer

The volume and its collection: two ISBNs and the series' catalogue.

```js
// script.js, lines 30–58
// The collection is data of the book, beside its versions. The volume's barcode carries its
// own ISBN, and the collection's `isbn` prints as a line above the bars. `catalogue` lists
// the twelve titles with their cover pictures, and `volume` names the one this book is: the
// endpapers set the list and the pictures from it (section 4), this volume marked in both.
const collection = {
  name: t({ en: 'Exemplary Novels', es: 'Novelas ejemplares' }),
  isbn: '978-84-0000-200-8',
  catalogue: [
    work('The Little Gipsy Girl', 'La gitanilla', 'gitanilla'),
    work('The Generous Lover', 'El amante liberal', 'amante'),
    work('Rinconete and Cortadillo', 'Rinconete y Cortadillo', 'rinconete'),
    work('The Spanish-English Lady', 'La española inglesa', 'espanola'),
    work('The Licentiate Vidriera', 'El licenciado Vidriera', 'vidriera'),
    work('The Force of Blood', 'La fuerza de la sangre', 'fuerza'),
    work('The Jealous Estremaduran', 'El celoso extremeño', 'celoso'),
    work('The Illustrious Scullery-Maid', 'La ilustre fregona', 'fregona'),
    work('The Two Damsels', 'Las dos doncellas', 'doncellas'),
    work('The Lady Cornelia', 'La señora Cornelia', 'cornelia'),
    work('The Deceitful Marriage', 'El casamiento engañoso', 'casamiento'),
    work('The Dialogue of the Dogs', 'El coloquio de los perros', 'coloquio'),
  ],
};
collection.volume = collection.catalogue[VOLUME - 1].id;
const production = {
  collection,
  // A printed case with a flat spine: the case sheet and two endpapers, no jacket.
  versions: [{ id: 'hardcover', name: t({ en: 'Hardcover', es: 'Tapa dura' }),
    binding: 'case-flat', isbn: '978-84-0000-198-8', isbnAddOn: '90000' }],
};
```

## Ingredients

**Teaches**

- [Print versions, ISBN and spine](https://postext.dev/en/docs/print-covers.md#versions-of-a-book): production.versions gives each binding of a book its binding profile and ISBN, printed as an EAN-13 barcode; the spine comes from the page count and the paper. production.collection adds the whole work's ISBN and a catalogue of its titles.
- [Print cover sheet](https://postext.dev/en/docs/print-covers.md#the-sheet-and-its-panels): buildCover lays out the sheet of a print version: back, spine and front, with flaps, a hardcover's case and dust jacket, and its endpapers, with bleed and fold marks. The cover setting designs it and a Markdown document of the book fills its panels.

**Also uses**

- [Covers, title pages and colophons](https://postext.dev/en/docs/configuration-styles.md#heading-styles)
- [Heading styles](https://postext.dev/en/docs/configuration-styles.md#heading-styles)
- [Designed openers](https://postext.dev/en/docs/configuration-headings.md#span-and-advanced-design)
- [Text, rules and boxes in page designs](https://postext.dev/en/docs/configuration-headers-footers.md#headers--footers)
- [Document metadata](https://postext.dev/en/docs/document-format.md#frontmatter)
- [Paragraph styles](https://postext.dev/en/docs/configuration-styles.md#paragraph-styles)
- [Running heads and folios](https://postext.dev/en/docs/configuration-headers-footers.md#headers--footers)
- [Figures and tables as resources](https://postext.dev/en/docs/document-format-resources.md#resources)
- [Semantic colour palette](https://postext.dev/en/docs/configuration-fonts-colors-viewers.md#color-palette)
- [PDF export](https://postext.dev/en/docs/configuration-pdf-output.md#generating-pdfs)
- [Pages on a canvas](https://postext.dev/en/docs/configuration-programmatic-usage.md#rendering-a-page-to-a-bitmap)
- [Paper, binding, desk and light (Folio)](https://postext.dev/en/docs/configuration-fonts-colors-viewers.md#folio-viewer-config)
- [Heading attributes](https://postext.dev/en/docs/document-format.md#heading-attributes)
- [Paper colour](https://postext.dev/en/docs/configuration-page-layout.md#page)
- [Heads by page role](https://postext.dev/en/docs/configuration-headers-footers.md#text-elements)
- [Fonts embedded in the PDF](https://postext.dev/en/docs/configuration-pdf-output.md#why-a-font-provider)
- [Running heads per section](https://postext.dev/en/docs/configuration-styles.md#heading-styles)
- [Unnumbered chapters](https://postext.dev/en/docs/configuration-styles.md#heading-styles)

**Config at a glance**

- [`bodyText`](https://postext.dev/en/docs/configuration-text.md#body-text), [`checks`](https://postext.dev/en/docs/configuration-fonts-colors-viewers.md#content-check-config), [`colorPalette`](https://postext.dev/en/docs/configuration-fonts-colors-viewers.md#color-palette), [`cover`](https://postext.dev/en/docs/print-covers.md#the-covers-design), [`folio`](https://postext.dev/en/docs/configuration-html-folio-epub.md#appearance), [`footer`](https://postext.dev/en/docs/configuration-headers-footers.md#headers--footers), [`header`](https://postext.dev/en/docs/configuration-headers-footers.md#headers--footers), [`headingStyles`](https://postext.dev/en/docs/configuration-styles.md#heading-styles), [`headings`](https://postext.dev/en/docs/configuration-headings.md#headings), [`layout`](https://postext.dev/en/docs/configuration-page-layout.md#layout), [`locale`](https://postext.dev/en/docs/configuration-language.md#hyphenation), [`page`](https://postext.dev/en/docs/configuration-page-layout.md#page), [`paragraphStyles`](https://postext.dev/en/docs/configuration-styles.md#paragraph-styles), [`production`](https://postext.dev/en/docs/print-covers.md#versions-of-a-book)

**APIs**

- [`buildCover`](https://postext.dev/en/docs/print-covers.md#from-code), [`buildDocumentWithFonts`](https://postext.dev/en/docs/configuration-programmatic-usage.md#loading-fonts-before-layout), [`decompressWoff2`](https://postext.dev/en/docs/configuration-pdf-output.md#browser-font-provider-fontsource--woff2), [`inlineSvgFonts`](https://postext.dev/en/docs/configuration-resources.md#fonts-in-svg-text), [`registerResourceImage`](https://postext.dev/en/docs/architecture.md#api-surface), [`renderPageToCanvas`](https://postext.dev/en/docs/configuration-programmatic-usage.md#rendering-a-page-to-a-bitmap), [`renderToPdf`](https://postext.dev/en/docs/configuration-pdf-output.md#generating-pdfs), `workIsbnCaption`

**Typefaces**

- Crimson Pro (OFL-1.1), Cormorant Garamond (OFL-1.1), Josefin Sans (OFL-1.1)

## Method

### 1 · The collection is data of the book

The code is [the short answer](https://postext.dev/en/cookbook/collection-volume-endpapers.md#the-short-answer) above. `production.collection` holds the series: its name, its ISBN, a `catalogue` with an id, a title and a picture for each volume, and `volume`, the id of the entry that is this book. The collection's `isbn` is what Postext prints beside the barcode: a line in black 6.5 pt over the bars, "ISBN of the complete work", in the book's language. A version that names a `workIsbn` of its own prints that one instead. Both ISBNs are sample numbers in the 978-84-0000 block, assigned to no book. The configuration checks report a `volume` that is not in the catalogue and a collection ISBN whose check digit is wrong.

### 2 · One livery for every volume

```js
// script.js, lines 63–80
// Every position is in mm from the top-left corner of its zone (the case's front is
// 116 × 191 mm: the 120 × 185 trim, set back 7 mm at the joint, 3 mm square round it).
const box = (id, zone, x, y, width, height, color, extra) => ({ id, kind: 'box', zone, x, y,
  width, height, color: col(color), ...extra });
const picture = (id, zone, x, y, width, height, resourceId, extra) => ({ id, kind: 'image', zone,
  x, y, width, height, resourceId, fit: 'cover', ...extra });
// `basis`: the spine drawn on; a thicker book stretches the bands and keeps the badge centred.
const spine = { basis: { width: 10, height: 191 } };
const livery = [
  box('frame', 'front', 11.2, 59.2, 93.6, 105.6, 'gold'),
  picture('art', 'front', 12, 60, 92, 104, 'cover-art'),
  picture('badge', 'front', 51.5, 169, 13, 13, 'badge', { fit: 'contain' }),
  box('head-band', 'spine', 0, 13, 10, 0.8, 'gold', spine),
  box('foot-band', 'spine', 0, 160, 10, 0.8, 'gold', spine),
  picture('spine-badge', 'spine', 1, 167, 8, 8, 'badge', { fit: 'contain', ...spine }),
  // A paper label for the barcode, whose caption is set in black.
  box('label', 'back', 53, 147, 61, 40, 'bone'),
];
```

The design of the case is the same object on every volume of the series; only `VOLUME`, the painting and the texts change. Each item is placed by the zone it stands in, so when another volume has more pages and a thicker spine the front moves with its panel. On the spine, `basis` records the 10 mm spine the bands were drawn on, and a spine of 8.3 mm or 14 mm stretches the bands to its width and keeps the badge on its centre line. The caption over the barcode is set in black, so the barcode sits on a pale label.

### 3 · Each endpaper has a design of its own

```js
// script.js, lines 84–99
// The case takes the livery; each endpaper names a design in `sheets`. At the front the
// pastedown is the left page, at the back the right one: volumes I–VI open the book,
// VII–XII close it, the pictures always on the pastedown, in the case's colour. A catalogue
// element grids the titles' pictures in its box; `stroke` outlines this volume's.
const shelf = (first, last) => ({ id: `shelf-${first}`, kind: 'catalogue', zone: 'pastedown',
  x: 26.5, y: 18, width: 67, height: 149, columns: 2, gap: 7, first, last,
  stroke: { color: col('gold'), width: 0.8 } });
const endpaper = (first, last) => ({ background: col('endpaper'),
  zones: { pastedown: col('case') }, elements: [shelf(first, last)],
  verticalAlign: { flyleaf: 'middle' } });
const cover = {
  background: col('case'),
  elements: livery,
  verticalAlign: { back: 'top' },
  sheets: { endpaperFront: endpaper(1, 6), endpaperBack: endpaper(7, 12) },
};
```

`cover.sheets` gives a sheet a design in place of the cover's: here `endpaperFront` and `endpaperBack`, each with its ground, the pastedown in the case's colour, and a `catalogue` element. The element is a box in a zone that the engine fills with the pictures of the titles from `first` to `last`, `columns` across with `gap` mm between them, each picture covering its cell. The title whose id is `collection.volume` is outlined with the element's `stroke`; on these endpapers that is the gold frame round volume XI. The livery stays off the endpapers, as each sheet draws only its own design. Opening the front of the book the pastedown is the left page, and at the back it is the right one, so the pictures always lie on the board.

The titles come from the cover's Markdown, which serves every sheet. A frame that names its sheets goes only on those:

```md
:::frame{slot="flyleaf" sheet="endpaperBack"}
:::paragraphs{style="ad-head"}
Exemplary Novels
:::

::catalogue{numbers="I" first=7 last=12}
:::
```

`::catalogue` stands for the titles of the catalogue, one paragraph each: the place in the counter style that `numbers` names, an en space and the title. The lines take the paragraph style `cover-catalogue`, and this volume's `cover-catalogue-current`; the pen restyles both, centred in Crimson Pro, the current one in dark red. The back cover's frame names `case jacket`, so the endpapers leave it out.

### 4 · Three sheets from one book

```js
// script.js, lines 421–432
const sheet = async (kind) => {
  const built = buildCover({ config, version: 'hardcover', pages: book.pages,
    markdown: coverText, metadata: book.metadata, resources, sheet: kind });
  if (!('config' in built)) throw new Error(built.issues.map((i) => i.kind).join(', '));
  // The barcode's digits name OCR-B, which no font server has: the label face sets them.
  for (const [id, bytes] of Object.entries(built.files)) {
    await loadSvg(id, new TextDecoder().decode(bytes)
      .replace(/font-family="[^"]*"/g, 'font-family="Josefin Sans"'));
  }
  return { built, doc: await buildDocumentWithFonts(built.content, built.config, kitFonts(FONTS)) };
};
const sheets = [await sheet('cover'), await sheet('endpaperFront'), await sheet('endpaperBack')];
```

The same call with `sheet: 'cover'`, `'endpaperFront'` and `'endpaperBack'` makes the case and the two endpapers, each a document of one page at its own size. The 26 pages round up to two 16-page signatures, 16 leaves of 240 µm; with 0.5 mm of allowance the block is 4.3 mm thick and the case spine 8.3 mm, two boards of 2 mm added. The lettering is checked against the case's spine, which is wider than the 6 mm minimum. The PDF holds the 26 pages, then the case and the endpapers.

## The whole recipe

One file, composed from the recipe's folder with the sample text and the Cookbook's shared kit inlined; it builds its own page. To run it, put it in a `<script type="module">` on an empty page, or paste it into the JS panel of a new CodePen (as a module). It imports postext from esm.sh, so there is nothing to install or build.

- Source folder: https://github.com/drnachio/postext/tree/main/cookbook/collection-volume-endpapers

### script.js

```js
// ═══ Postext Cookbook · Nº 198 · A volume of a collection, its endpapers the series ═══
// https://postext.dev/en/cookbook/collection-volume-endpapers
// Code: MIT · Text: Cervantes, tr. W. K. Kelly (public domain) · Art: diffusion models
// Fonts: Crimson Pro, Cormorant Garamond, Josefin Sans (SIL OFL 1.1) · Needs postext ≥ 1.93.0
//
// Volume XI of the twelve Exemplary Novels, one novella per hardcover: the series livery on
// the case, two ISBNs by the barcode, the twelve titles of the collection on the endpapers.
import {
  buildDocumentWithFonts, renderPageToCanvas, registerResourceImage, inlineSvgFonts,
} from 'https://esm.sh/postext';
import { buildCover, workIsbnCaption } from 'https://esm.sh/postext/production';
import { renderToPdf, decompressWoff2 } from 'https://esm.sh/postext-pdf';

const LANG = 'en'; // @lang: the language of the sample document ('en' | 'es')
const RECIPE = 'collection-volume-endpapers';

// ─── 1 · Design ─────────────────────────────────────────────────────────────
const palette = { ink: '#2a211c', accent: '#7a2a22', muted: '#6c6258', paper: '#fbf7ee',
  case: '#5e1c1a', gold: '#d2ae6a', bone: '#f1e8d4', endpaper: '#ece0c6' };
const col = (id) => ({ hex: palette[id], model: 'hex', paletteId: id });
const colorPalette = [
  ...Object.entries(palette).map(([id, hex]) => ({ id, name: id, value: { hex, model: 'hex' } })),
  { id: 'main-color', name: 'accent (defaults)', value: { hex: palette.accent, model: 'hex' } },
];
const VOLUME = 11; // this book's place in the collection
const roman = (n) => 'I II III IV V VI VII VIII IX X XI XII'.split(' ')[n - 1];
const work = (en, es, id) => ({ id, title: t({ en, es }), resource: `cat-${id}` });

// #region answer: the volume and its collection: two ISBNs and the series' catalogue
// The collection is data of the book, beside its versions. The volume's barcode carries its
// own ISBN, and the collection's `isbn` prints as a line above the bars. `catalogue` lists
// the twelve titles with their cover pictures, and `volume` names the one this book is: the
// endpapers set the list and the pictures from it (section 4), this volume marked in both.
const collection = {
  name: t({ en: 'Exemplary Novels', es: 'Novelas ejemplares' }),
  isbn: '978-84-0000-200-8',
  catalogue: [
    work('The Little Gipsy Girl', 'La gitanilla', 'gitanilla'),
    work('The Generous Lover', 'El amante liberal', 'amante'),
    work('Rinconete and Cortadillo', 'Rinconete y Cortadillo', 'rinconete'),
    work('The Spanish-English Lady', 'La española inglesa', 'espanola'),
    work('The Licentiate Vidriera', 'El licenciado Vidriera', 'vidriera'),
    work('The Force of Blood', 'La fuerza de la sangre', 'fuerza'),
    work('The Jealous Estremaduran', 'El celoso extremeño', 'celoso'),
    work('The Illustrious Scullery-Maid', 'La ilustre fregona', 'fregona'),
    work('The Two Damsels', 'Las dos doncellas', 'doncellas'),
    work('The Lady Cornelia', 'La señora Cornelia', 'cornelia'),
    work('The Deceitful Marriage', 'El casamiento engañoso', 'casamiento'),
    work('The Dialogue of the Dogs', 'El coloquio de los perros', 'coloquio'),
  ],
};
collection.volume = collection.catalogue[VOLUME - 1].id;
const production = {
  collection,
  // A printed case with a flat spine: the case sheet and two endpapers, no jacket.
  versions: [{ id: 'hardcover', name: t({ en: 'Hardcover', es: 'Tapa dura' }),
    binding: 'case-flat', isbn: '978-84-0000-198-8', isbnAddOn: '90000' }],
};
// #endregion
const folio = { paper: { type: 'bookWove', grammage: 100, bulk: 2.4, shade: '#f7f1e3' } };

// #region livery: the series design, the same on every volume but for its number
// Every position is in mm from the top-left corner of its zone (the case's front is
// 116 × 191 mm: the 120 × 185 trim, set back 7 mm at the joint, 3 mm square round it).
const box = (id, zone, x, y, width, height, color, extra) => ({ id, kind: 'box', zone, x, y,
  width, height, color: col(color), ...extra });
const picture = (id, zone, x, y, width, height, resourceId, extra) => ({ id, kind: 'image', zone,
  x, y, width, height, resourceId, fit: 'cover', ...extra });
// `basis`: the spine drawn on; a thicker book stretches the bands and keeps the badge centred.
const spine = { basis: { width: 10, height: 191 } };
const livery = [
  box('frame', 'front', 11.2, 59.2, 93.6, 105.6, 'gold'),
  picture('art', 'front', 12, 60, 92, 104, 'cover-art'),
  picture('badge', 'front', 51.5, 169, 13, 13, 'badge', { fit: 'contain' }),
  box('head-band', 'spine', 0, 13, 10, 0.8, 'gold', spine),
  box('foot-band', 'spine', 0, 160, 10, 0.8, 'gold', spine),
  picture('spine-badge', 'spine', 1, 167, 8, 8, 'badge', { fit: 'contain', ...spine }),
  // A paper label for the barcode, whose caption is set in black.
  box('label', 'back', 53, 147, 61, 40, 'bone'),
];
// #endregion

// #region endpapers: a design of their own, half the catalogue on each
// The case takes the livery; each endpaper names a design in `sheets`. At the front the
// pastedown is the left page, at the back the right one: volumes I–VI open the book,
// VII–XII close it, the pictures always on the pastedown, in the case's colour. A catalogue
// element grids the titles' pictures in its box; `stroke` outlines this volume's.
const shelf = (first, last) => ({ id: `shelf-${first}`, kind: 'catalogue', zone: 'pastedown',
  x: 26.5, y: 18, width: 67, height: 149, columns: 2, gap: 7, first, last,
  stroke: { color: col('gold'), width: 0.8 } });
const endpaper = (first, last) => ({ background: col('endpaper'),
  zones: { pastedown: col('case') }, elements: [shelf(first, last)],
  verticalAlign: { flyleaf: 'middle' } });
const cover = {
  background: col('case'),
  elements: livery,
  verticalAlign: { back: 'top' },
  sheets: { endpaperFront: endpaper(1, 6), endpaperBack: endpaper(7, 12) },
};
// #endregion

// #region cover-type: the paragraph styles the case and the endpapers are set in
const style = (id, fontFamily, size, lead, color, extra) => ({ id, fontFamily, fontSize: pt(size),
  lineHeight: pt(lead), color, italicColor: color, boldColor: color, firstLineIndent: mm(0),
  textAlign: 'left', hyphenation: false, ...extra });
const caps = (k) => ({ fontWeight: 600, textTransform: 'uppercase', letterSpacing: pt(k) });
const centre = { textAlign: 'center' };
const coverStyles = [
  style('cover-title', 'Cormorant Garamond', 42, 40, col('bone'), { fontWeight: 600,
    ...centre, marginTop: mm(5) }),
  style('cover-subtitle', 'Josefin Sans', 8, 11, col('gold'), { ...caps(1.8), ...centre,
    marginTop: pt(9) }),
  style('cover-author', 'Cormorant Garamond', 15, 18, col('bone'), { fontWeight: 500, italic: true,
    ...centre, marginTop: pt(3) }),
  style('cover-spine', 'Josefin Sans', 7, 8, col('bone'), { ...caps(1.1), ...centre }),
  style('back-series', 'Josefin Sans', 7.5, 10, col('gold'), { ...caps(1.4),
    marginBottom: pt(9) }),
  style('back-blurb', 'Crimson Pro', 10.5, 14.5, col('bone'), { marginBottom: pt(7) }),
  // The endpapers' lines: the series' name, a note, and the titles `::catalogue` sets in
  // `cover-catalogue`, this volume's in `cover-catalogue-current`.
  style('ad-head', 'Cormorant Garamond', 19, 22, col('accent'), { fontWeight: 600, ...centre }),
  style('ad-note', 'Crimson Pro', 9.5, 13, col('muted'), { italic: true, ...centre,
    marginTop: pt(4), marginBottom: pt(14) }),
  ...['cover-catalogue', 'cover-catalogue-current'].map((id, own) => style(id, 'Crimson Pro',
    11, 17, col(own ? 'accent' : 'ink'), { fontWeight: own ? 600 : 400, ...centre })),
];
// #endregion

const [W, H, TOP, FOOT, INNER, OUTER, LEAD] = [120, 185, 20, 22, 18, 15.5, 15.2]; // mm, pt
const at = (to, edge, x, y, size) => ({ anchor: { to, edge }, offset: { x: mm(x), y: mm(y) },
  ...(size && { size }) });
const text = (id, content, look, place) => ({ kind: 'text', id, content, align: 'center',
  overflow: 'wrap', placement: place, ...look });
const face = (fontFamily, fontSize, color, extra) => ({ fontFamily, fontSize: pt(fontSize), color,
  ...extra });
const label = (size, color = col('muted')) => face('Josefin Sans', size, color, caps(size / 5));
const serif = (size, extra) => face('Cormorant Garamond', size, col('ink'), extra);
const none = { header: { elements: [] }, footer: { elements: [] }, numbered: false, toc: false };
const design = (h, elements) => ({ enabled: true, minHeight: mm(h), slot: { elements } });
const page = (parity) => ({ breakBefore: { enabled: true, parity } });
const rule = (id, y, to = 'page') => ({ kind: 'rule', id, direction: 'horizontal',
  thickness: pt(0.6), color: col('accent'), placement: at(to, 'top', 0, y, { width: mm(10) }) });
const headingStyles = [
  { ...none, id: 'half-title', advancedDesign: design(60, [
    text('t', '{title}', serif(17, { fontWeight: 500 }), at('page', 'top', 0, 62))]) },
  { ...none, ...page('odd'), id: 'title-page', advancedDesign: design(H - TOP - FOOT, [
    text('s', '{subtitle}', label(7.5, col('accent')), at('page', 'top', 0, 36)),
    text('v', '{attr.volume}', face('Crimson Pro', 10, col('muted'), { italic: true }),
      at('page', 'top', 0, 41)),
    text('t', '{title}', serif(26, { fontWeight: 600 }), at('page', 'top', 0, 56,
      { width: mm(80) })),
    rule('r', 80),
    text('a', '{author}', label(8, col('accent')), at('page', 'top', 0, 85)),
    text('tr', '{attr.translators}', face('Crimson Pro', 9.5, col('muted'), { italic: true }),
      at('page', 'top', 0, 118, { width: mm(70) })),
    text('i', '{attr.imprint}', label(7), at('page', 'bottom', 0, -26)),
  ]) },
  { ...none, ...page('even'), id: 'rights',
    advancedDesign: design(80, [rule('r', 74, 'container')]) },
  // The novella opens on a recto, sunk under its number in the collection.
  { ...page('odd'), id: 'novella', numbered: false, toc: false, advancedDesign: design(62, [
    text('k', '{attr.kicker}', serif(30, { fontWeight: 600, color: col('accent') }),
      at('container', 'top', 0, 14)),
    text('t', '{titleText}', serif(19, { fontWeight: 500, italic: true }),
      at('container', 'top', 0, 33)),
    rule('r', 45, 'container')]) },
  { ...none, ...page('any'), id: 'colophon', advancedDesign: design(40, [
    rule('r', 30, 'container')]) },
];
const head = (id, content, parity) => text(id, content, { ...label(6.8), parity, pages: 'body' },
  at('page', 'top', 0, 11));

const config = {
  locale: t({ en: 'en-gb', es: 'es' }),
  colorPalette,
  page: { sizePreset: 'custom', width: mm(W), height: mm(H), dpi: 300,
    backgroundColor: col('paper'),
    margins: { top: mm(TOP), bottom: mm(FOOT), left: mm(INNER), right: mm(OUTER), mirror: true } },
  layout: { layoutType: 'single' },
  bodyText: { fontFamily: 'Crimson Pro', fontSize: pt(11), lineHeight: pt(LEAD), color: col('ink'),
    boldColor: col('ink'), italicColor: col('ink'), referenceColor: col('ink'),
    textAlign: 'justify',
    firstLineIndent: mm(4), indentAfterHeading: false, hyphenation: { enabled: true },
    optimalLineBreaking: true, avoidWidows: true, avoidOrphans: true },
  headings: { fontFamily: 'Cormorant Garamond', color: col('ink'), textAlign: 'center' },
  headingStyles,
  paragraphStyles: [
    style('rights', 'Crimson Pro', 8, 11, col('muted'), { spaceBetween: pt(5) }),
    style('colophon', 'Crimson Pro', 9.5, 13, col('muted'), { italic: true, ...centre }),
    ...coverStyles,
  ],
  header: { elements: [head('v', '{author}', 'even'), head('r', '{title}', 'odd')] },
  footer: { elements: [text('f', '{pageNumber}', { ...face('Crimson Pro', 9, col('ink')),
    pages: 'body' }, at('page', 'bottom', 0, -12))] },
  production, cover, folio,
  // The line buildCover prints over the barcode is the engine's own wording of the ISBN.
  checks: { contentInConfig: { allow: [workIsbnCaption(collection.isbn, LANG)] } },
};

// ─── 2 · Content ────────────────────────────────────────────────────────────
// The novella runs through three files; the cover's text, case and endpapers, is a fourth.
const markdown = String.raw`---
title: "The Deceitful Marriage"
subtitle: "Exemplary Novels"
author: "Miguel de Cervantes"
---

# The Deceitful Marriage {style="half-title"}

# The Deceitful Marriage {style="title-page" volume="Volume XI of twelve" translators="Translated from the Spanish by Walter K. Kelly" imprint="Espolón Editions · Valladolid"}

# Rights {style="rights"}

:::paragraphs{style="rights"}
*The Deceitful Marriage* is the eleventh of the twelve *Exemplary Novels*, published in Madrid by Juan de la Cuesta in 1613. Walter K. Kelly’s translation appeared in Bohn’s Standard Library (London, 1846; reprinted 1881) and is in the public domain; the text follows Project Gutenberg eBook 14420, with three misprints corrected and the translator’s two notes left out.

Exemplary Novels, volume XI · hardcover · ISBN 978-84-0000-198-8 · ISBN of the complete work 978-84-0000-200-8 · sample numbers, assigned to no book.

Paintings generated with diffusion models.

Set in Crimson Pro, Cormorant Garamond and Josefin Sans (SIL OFL) on 100 g/m² cream bulky book wove, bulk 2.4.
:::

# The Deceitful Marriage {style="novella" kicker="XI"}

From the Hospital of the Resurrection, which stands just beyond the Puerta del Campo, in Valladolid, there issued one day a soldier, who, by the excessive paleness of his countenance, and the weakness of his limbs, which obliged him to lean upon his sword, showed clearly to all who set eyes on him that, though the weather was not very warm, he must have sweated a good deal in the last few weeks. He had scarcely entered the gate of the city, with tottering steps, when he was accosted by an old friend who had not seen him for the last six months, and who approached the invalid, making signs of the cross as if he had seen a ghost. “What is all this?” he cried; “do I, indeed, behold the Señor Alferez Campuzano? Is it possible that I really see you in this country? Why, I thought you were in Flanders trailing a pike, instead of hobbling along with your sword for a walking-stick. How pale—how emaciated you look!”

“As to whether I am in this country or elsewhere, Señor Licentiate Peralta, the fact that you now see me is a sufficient answer,” replied Campuzano; “as for your other questions, all I can tell you is, that I have just come out of that hospital, where I have been confined for a long time in a dreadful state of health, brought upon me by the conduct of a woman I was indiscreet enough to make my wife.”

“You have been married, then?” said Peralta.

“Yes, Señor.”

“Married without benefit of clergy, I presume. Marriages of that sort bring their own penance with them.”

“Whether it was without benefit of clergy I cannot say,” replied the Alferez; “but I can safely aver that it was not without benefit of physic. Such were the torments of body and soul which my marriage brought upon me, that those of the body cost me forty sudations to cure them, and, as for those of the soul, there is no remedy at all that can relieve them. But excuse me, if I cannot hold a long conversation in the street; another day I will, with more convenience, relate to you my adventures, which are the strangest and most singular you ever heard in all the days of your life.”

“That will not do,” said the licentiate; “I must have you come to my lodgings, and there we will do penance together. You will have an olla, very fit for a sick man; and though it is scantly enough for two, we will make up the deficiency with a pie and a few slices of Rute ham, and, above all, with a hearty welcome, not only now, but whenever you choose to claim it.”

Campuzano accepted the polite invitation. They turned into the church of San Lorente and heard mass, and then Peralta took his friend home, treated him as he had promised, repeated his courteous offers, and requested him after dinner to relate his adventures. Campuzano, without more ado, began as follows:

You remember, Señor Licentiate Peralta, how intimate I was in this city with Captain Pedro de Herrera, who is now in Flanders. “I remember it very well,” replied Peralta. Well, one day when we had done dinner in the Posada della Solana, where we lived, there came in two ladies of genteel appearance, with two waiting women: one of the ladies entered into conversation with the Captain, both leaning against a window; the other sat down in a chair beside me, with her veil low down, so that I could not see her face, except so far as the thinness of the texture allowed. I entreated her to do me the favour to unveil, but I could not prevail, which the more inflamed my desire to have sight of her; but what especially increased my curiosity was that, whether on purpose, or by chance, the lady displayed a very white hand, with very handsome rings.

At that time I made a very gallant appearance with that great chain you have seen me wear, my hat with plumes and bands, my flame-coloured military garments, and, in the eyes of my own folly, I seemed so engaging that I imagined all the women must fall in love with me! Well, I implored her to unveil. “Be not importunate,” she replied; “I have a house; let a servant follow me; for though I am of more honourable condition than this reply of mine would indicate, yet for the sake of seeing whether your discretion corresponds to your gallant appearance, I will allow you to see me with less reserve.” I kissed her hand for the favour she granted me, in return for which I promised mountains of gold. The captain ended his conversation, the ladies went away, and a servant of mine followed them. The captain told me that what the lady had been asking of him was to take some letters to Flanders to another captain, who she said was her cousin, though he knew he was nothing but her gallant.

For my part I was all on fire for the snow-white hands I had seen, and dying for a peep at the face; so I presented myself next day at the door which my servant pointed out to me, and was freely admitted. I found myself in a house very handsomely decorated and furnished, in presence of a lady about thirty years of age, whom I recognised by her hands. Her beauty was not extraordinary, but of a nature well suited to fascinate in conversation; for she talked with a sweetness of tone that won its way through the ears to the soul. I had long *tête-à-têtes* with her, in which I made love with all my might: I bragged, bounced, swaggered, offered, promised, and made all the demonstrations I thought necessary to work myself into her good graces; but as she was accustomed to such offers and protestations, she listened to them with an attentive, but apparently far from credulous ear. In short, during the four days I continued to visit her, our intercourse amounted only to talking soft nonsense, without my being able to gather the tempting fruit.

In the course of my visits I always found the house free from intruders, and without a vestige of pretended relations or real gallants. She was waited on by a girl in whom there was more of the rogue than the simpleton. At last resolving to push my suit in the style of a soldier, who is about to shift his quarters, I came to the point with my fair one, Doña Estefania de Caycedo (for that is the name of my charmer), and this was the answer she gave me:”Señor Alferez Campuzano, I should be a simpleton if I sought to pass myself off on you for a saint; I have been a sinner, ay, and am one still, but not in a manner to become a subject of scandal in the neighbourhood or of notoriety in public. I have inherited no fortune either from my parents or any other relation; and yet the furniture of my house is worth a good two thousand five hundred ducats, and would fetch that sum it put up to auction at any moment. With this property I look for a husband to whom I may devote myself in all obedience, and with whom I may lead a better life, whilst I apply myself with incredible solicitude to the task of delighting and serving him; for there is no master cook who can boast of a more refined palate, or can turn out more exquisite ragouts and made-dishes than I can, when I choose to display my housewifery in that way. I can be the major domo in the house, the tidy wench in the kitchen, and the lady in the drawing room: in fact, I know how to command and make myself obeyed. I squander nothing and accumulate a great deal; my coin goes all the further for being spent under my own directions. My household linen, of which I have a large and excellent stock, did not come out of drapers’ shops or warehouses; these fingers and those of my maid servants stitched it all, and it would have been woven at home had that been possible. If I give myself these commendations, it is because I cannot incur your censure by uttering what it is absolutely necessary that you should know. In fine, I wish to say that I desire a husband to protect, command, and honour me, and not a gallant to flatter and abuse me: if you like to accept the gift that is offered you, here I am, ready and willing to put myself wholly at your disposal, without going into the public market with my hand, for it amounts to no less to place oneself at the mercy of match-makers’ tongues, and no one is so fit to arrange the whole affair as the parties themselves.”

My wits were not in my head at that moment, but in my heels. Delighted beyond imagination, and seeing before me such a quantity of property, which I already beheld by anticipation converted into ready money, without making any other reflections than those suggested by the longing that fettered my reason, I told her that I was fortunate and blest above all men since heaven had given me by a sort of miracle such a companion, that I might make her the lady of my affections and my fortune,—a fortune which was not so small, but that with that chain which I wore round my neck, and other jewels which I had at home, and by disposing of some military finery, I could muster more than two thousand ducats, which, with her two thousand five hundred, would be enough for us to retire upon to a village of which I was a native, and where I had relations and some patrimony. Its yearly increase, helped by our money, would enable us to lead a cheerful and unembarrassed life. In fine, our union was at once agreed on; the banns were published on three successive holidays (which happened to fall together), and on the fourth day, the marriage was celebrated in the presence of two friends of mine, and a youth who she said was her cousin, and to whom I introduced myself as a relation with words of great urbanity. Such, indeed, were all those which hitherto I had bestowed on my bride—with how crooked and treacherous an intention I would rather not say; for though I am telling truths, they are not truths under confession which must not be kept back.
`;
const part2 = String.raw`My servant removed my trunk from my lodgings to my wife’s house. I put by my magnificent chain in my wife’s presence; showed her three or four others, not so large, but of better workmanship, with three or four other trinkets of various kinds; laid before her my best dresses and my plumes, and gave her about four hundred reals, which I had, to defray the household expenses. For six days I tasted the bread of wedlock, enjoying myself like a beggarly bridegroom in the house of a rich father-in-law. I trod on rich carpets, lay in holland sheets, had silver candlesticks to light me, breakfasted in bed, rose at eleven o’clock, dined at twelve, and at two took my siesta in the drawing-room. Doña Estefania and the servant girl danced attendance upon me; my servant, whom I had always found lazy, was suddenly become nimble as a deer. If ever Doña Estefania quitted my side, it was to go to the kitchen and devote all her care to preparing fricassees to please my palate and quicken my appetite. My shirts, collars, and handkerchiefs were a very Aranjuez of flowers, so drenched they were with fragrant waters. Those days flew fast, like the years which are under the jurisdiction of time; and seeing myself so regaled and so well treated, I began to change for the better the evil intention with which I had begun this affair.

At the end of them, one morning, whilst I was still in bed with Doña Estefania, there was a loud knocking and calling at the street door. The servant girl put her head out of the window, and immediately popped it in again, saying,—“There she is, sure enough; she is come sooner than she mentioned in her letter the other day, but she is welcome!”

“Who’s come, girl?” said I.

“Who?” she replied; “why, my lady Doña Clementa Bueso, and with her señor Don Lope Melendez de Almendarez, with two other servants, and Hortigosa, the dueña she took with her.”

“Bless me! Run, wench, and open the door for them,” Doña Estefania now exclaimed; “and you, señor, as you love me, don’t put yourself out, or reply for me to anything you may hear said against me.”

“Why, who is to say anything to offend you, especially when I am by? Tell me, who are these people, whose arrival appears to have upset you?”

“I have no time to answer,” said Doña Estefania; “only be assured that whatever takes place here will be all pretended, and bears upon a certain design which you shall know by and by.”

Before I could make any reply to this, in walked Doña Clementa Bueso, dressed in lustrous green satin, richly laced with gold, a hat with green, white, and pink feathers, a gold hat-band, and a fine veil covering half her face. With her entered Don Lope Melendez de Almendarez in a travelling suit, no less elegant than rich. The dueña Hortigosa was the first who opened her lips, exclaiming, “Saints and angels, what is this! My lady Doña Clementa’s bed occupied, and by a man too! Upon my faith, the señora Doña Estefania has availed herself of my lady’s friendliness to some purpose!”

“That she has, Hortigosa,” replied Doña Clementa; “but I blame myself for never being on my guard against friends who can only be such when it is for their own advantage.”

To all this Doña Estefania replied: “Pray do not be angry, my lady Doña Clementa. I assure you there is a mystery in what you see; and when you are made acquainted with it you will acquit me of all blame.”

During this time I had put on my hose and doublet, and Doña Estefania, taking me by the hand, led me into another room. There she told me that this friend of hers wanted to play a trick on that Don Lope who was come with her, and to whom she expected to be married. The trick was to make him believe that the house and everything in it belonged to herself. Once married, it would matter little that the truth was discovered, so confident was the lady in the great love of Don Lope; the property would then be returned; and who could blame her, or any woman, for contriving to get an honourable husband, though it were by a little artifice? I replied that it was a very great stretch of friendship she thought of making, and that she ought to look well to it beforehand, for very probably she might be constrained to have recourse to justice to recover her effects. She gave me, however, so many reasons, and alleged so many obligations by which she was bound to serve Doña Clementa even in matters of more importance, that much against my will, and with sore misgivings, I complied with Doña Estefania’s wishes, on the assurance that the affair would not last more than eight days, during which we were to lodge with another friend of hers.

We finished dressing; she went to take her leave of the señora Doña Clementa Bueso and the señor Lope Melendez Almendarez, ordered my servant to follow her with my luggage, and I too followed without taking leave of any one. Doña Estefania stopped at a friend’s house, and stayed talking with her a good while, leaving us in the street, till at last a girl came out and told me and my servant to come in. We went up stairs to a small room in which there were two beds so close together that they seemed but one, for the bed-clothes actually touched each other. There we remained six days, during which not an hour passed in which we did not quarrel; for I was always telling her what a stupid thing she had done in giving up her house and goods, though it were to her own mother. One day, when Doña Estefania had gone out, as she said, to see how her business was going on, the woman of the house asked me what was the reason of my wrangling so much with my wife, and what had she done for which I scolded her so much, saying it was an act of egregious folly rather than of perfect friendship. I told her the whole story, how I had married Doña Estefania, the dower she had brought me, and the folly she had committed in leaving her house and goods to Doña Clementa, even though it was for the good purpose of catching such a capital husband as Don Lope. Thereupon the woman began to cross and bless herself at such a rate, and to cry out, “O, Lord! O, the jade!” that she put me into a great state of uneasiness. At last, “Señor Alferez,” said she, “I don’t know but I am going against my conscience in making known to you what I feel would lie heavy on it if I held my tongue. Here goes, however, in the name of God,—happen what may, the truth for ever, and lies to the devil! The truth is, that Doña Clementa Bueso is the real owner of the house and property which you have had palmed upon you for a dower; the lies are every word that Doña Estefania has told you, for she has neither house nor goods, nor any clothes besides those on her back. What gave her an opportunity for this trick was that Doña Clementa went to visit one of her relations in the city of Plasencia, and there to perform a novenary in the church of our Lady of Guadalupe, meanwhile leaving Doña Estefania to look after her house, for in fact they are great friends. And after all, rightly considered, the poor señora is not to blame, since she has had the wit to get herself such a person as the Señor Alferez for a husband.”

Here she came to an end, leaving me almost desperate; and without doubt I should have become wholly so, if my guardian angel had failed in the least to support me, and whisper to my heart that I ought to consider I was a Christian, and that the greatest sin men can be guilty of is despair, since it is the sin of devils. This consideration, or good inspiration, comforted me a little; not so much, however, but that I took my cloak and sword, and went out in search of Doña Estefania, resolved to inflict upon her an exemplary chastisement; but chance ordained, whether for my good or not I cannot tell, that she was not to be found in any of the places where I expected to fall in with her. I went to the church of San Lorente, commended me to our Lady, sat down on a bench, and in my affliction fell into so deep a sleep that I should not have awoke for a long time if others had not roused me. I went with a heavy heart to Doña Clementa’s, and found her as much at ease as a lady should be in her own house. Not daring to say a word to her, because Señor Don Lope was present, I returned to my landlady, who told me she had informed Doña Estefania that I was acquainted with her whole roguery; that she had asked how I had seemed to take the news; that she, the landlady, said I had taken it very badly, and had gone out to look for her, apparently with the worst intentions; whereupon Doña Estefania had gone away, taking with her all that was in my trunk, only leaving me one travelling coat. I flew to my trunk, and found it open, like a coffin waiting for a dead body; and well might it have been my own, if sense enough had been left me to comprehend the magnitude of my misfortune.

“Great it was, indeed,” observed the licentiate Peralta; “only to think that Doña Estefania carried off your fine chain and hat-band! Well, it is a true saying, ‘Misfortunes never come single.’”
`;
const part3 = String.raw`I do not so much mind that loss, replied the Alferez, since I may apply to myself the old saw, “My father-in-law thought to cheat me by putting off his squinting daughter upon me; and I myself am blind of an eye.”

“I don’t know in what respect you can say that?” replied Peralta.

Why, in this respect, that all that lot of chains and gewgaws might be worth some ten or twelve crowns.

“Impossible!” exclaimed the licentiate; “for that which the Señor Alferez wore on his neck must have weighed more than two hundred ducats.”

So it would have done, replied the Alferez, if the reality had corresponded with the appearance; but “All is not gold that glitters,” and my fine things were only imitations, but so well made that nothing but the touchstone or the fire could have detected that they were not genuine.

“So, then, it seems to have been a drawn game between you and the Señora Doña Estefania,” said the licentiate.

So much so that we may shuffle the cards and make a fresh deal. Only the mischief is, Señor Licentiate, that she may get rid of my mock chains, but I cannot get rid of the cheat she put upon me; for, in spite of my teeth, she remains my wife.

“You may thank God, Señor Campuzano,” said Peralta, “that your wife has taken to her heels, and that you are not obliged to go in search of her.”

Very true; but for all that, even without looking for her, I always find her—in imagination; and wherever I am, my disgrace is always present before me.

“I know not what answer to make you, except to remind you of these two verses of Petrarch:

“‘Che qui prende diletto di far frode, Non s’ha di lamentar s’altro l’inganna.’

That is to say, whoever makes it his practice and his pleasure to deceive others, has no right to complain when he is himself deceived.”

But I don’t complain, replied the Alferez; only I pity myself—for the culprit who knows his fault does not the less feel the pain of his punishment. I am well aware that I sought to deceive and that I was deceived, and caught in my own snare; but I cannot command my feelings so much as not to lament over myself. To come, however, to what more concerns my history (for I may give that name to the narrative of my adventures), I learned that Doña Estefania had been taken away by that cousin whom she brought to our wedding, who had been a lover of hers of long standing. I had no mind to go after her and bring back upon myself an evil I was rid of. I changed my lodgings and my skin too within a few days. My eyebrows and eyelashes began to drop; my hair left me by degrees; and I was bald before my time, and stripped of everything; for I had neither a beard to comb nor money to spend. My illness kept pace with my want; and as poverty bears down honour, drives some to the gallows, some to the hospital, and makes others enter their enemies’ doors with cringing submissiveness, which is one of the greatest miseries that can befall an unlucky man; that I might not expend upon my cure the clothes that should cover me respectably in health, I entered the Hospital of the Resurrection, where I took forty sudations. They say that I shall get well if I take care of myself. I have my sword; for the rest I trust in God.

The licentiate renewed his friendly offers, much wondering at the things he had heard.

If you are surprised at the little I have told you, Señor Peralta, said the Alferez, what will you say to the other things I have yet to relate, which exceed all imagination, since they pass all natural bounds? I can only tell you that they are such that I think it a full compensation for all my disasters that they were the cause of my entering the hospital, where I saw what I shall now relate to you; and what you can never believe; no; nor anybody else in the world.

All these preambles of the Alferez so excited Peralta’s curiosity, that he earnestly desired to hear, in detail, all that remained to be told.

You have no doubt seen, said the Alferez, two dogs going about by night with lanterns along with the Capuchin brethren, to give them light when they are collecting alms.

“I have,” replied Peralta.

You have also seen, or heard tell of them, that if alms are thrown from the windows, and happen to fall on the ground, they immediately help with the light and begin to look for what has fallen; that they stop of their own accord before the windows from which they know they are used to receive alms; and that with all their tameness on these occasions, so that they are more like lambs than dogs, they are lions in the hospital, keeping guard with great care and vigilance.

“I have heard that all this is as you say,” said Peralta; “but there is nothing in this to move my wonder.”

But what I shall now tell you of them, returned the Alferez, is enough to do so; yet, strange as it is, you must bring yourself to believe it. One night, the last but one of my sudation, I heard, and all but saw with my eyes those two dogs, one of which is called Scipio, the other Berganza, stretched on an old mat outside my room. In the middle of the night, lying awake in the dark, thinking of my past adventures and my present sorrows, I heard talking, and set myself to listen attentively, to see if I could make out who were the speakers and what they said. By degrees I did both, and ascertained that the speakers were the dogs Scipio and Berganza.

The words were hardly out of Campuzano’s mouth, when the licentiate jumped up and said: “Saving your favour, Señor Campuzano, till this moment I was in much doubt whether or not to believe what you have told me about your marriage; but what you now tell me of your having heard dogs talk, makes me decide upon not believing you at all. For God’s sake, Señor Alferez, do not relate such nonsense to any body, unless it be to one who is as much your friend as I am.”

Do not suppose I am so ignorant, replied Campuzano, as not to know that brutes cannot talk unless by a miracle. I well know that if starlings, jays, and parrots talk, it is only such words as they have learned by rote, and because they have tongues adapted to pronounce them; but they cannot, for all that, speak and reply with deliberate discourse as those dogs did. Many times, indeed, since I heard them I have been disposed not to believe myself, but to regard as a dream that which, being really awake, with all the five senses which our Lord was pleased to give me, I heard, marked, and finally wrote down without missing a word; whence you may derive proof enough to move and persuade you to believe this verity which I relate. The matters they talked of were various and weighty, such as might rather have been discussed by learned men than by the mouths of dogs; so that, since I could not have invented them out of my own head, I am come, in spite of myself, to believe that I did not dream, and that the dogs did talk.

“Body of me!” exclaimed the licentiate, “are the times of Æsop come back to us, when the cock conversed with the fox, and one beast with another?”

I should be one of them, and the greatest, replied the Alferez, if I believed that time had returned; and so I should be, too, if I did not believe what I have heard and seen, and what I am ready to swear to by any form of oath that can constrain incredulity itself to believe. But, supposing that I have deceived myself, and that this reality was a dream, and that to contend for it is an absurdity, will it not amuse you, Señor Peralta, to see, written in the form of a dialogue, the matters talked of by those dogs, or whoever the speakers may have been?

“Since you no longer insist on having me believe that you heard dogs talk,” replied Peralta, “with much pleasure I will hear this colloquy, of which I augur well, since it is reported by a gentleman of such talents as the Señor Alferez.”

Another thing I have to remark, said Campuzano, is, that, as I was very attentive, my apprehension very sensitive, and my memory very retentive (thanks to the many raisins and almonds I had swallowed), I got it all by heart, and wrote it down, word for word, the next day, without attempting to colour or adorn it, or adding or suppressing anything to make it attractive. The conversation took place not on one night only, but on two consecutive nights, though I have not written down more than one dialogue, that which contains the life of Berganza. His comrade Scipio’s life, which was the subject of the second night’s discourse, I intend to write out, if I find that the first one is believed, or at least not despised. I have thrown the matter into the form of a dialogue to avoid the cumbrous repetition of such phrases as, *said Scipio*, *replied Berganza*.

So saying, he took a roll of paper out of his breast pocket, and put it in the hands of the licentiate, who received it with a smile, as if he made very light of all he had heard, and was about to read.

I will recline on this sofa, said the Alferez, whilst you are reading those dreams or ravings, if you will, which have only this to recommend them, that you may lay them down when you grow tired of them.

“Make yourself comfortable,” said Peralta; “and I will soon despatch my reading.”

The Alferez lay down; the licentiate opened the scroll, and found it headed as follows:

# Colophon {style="colophon"}

:::paragraphs{style="colophon"}
The roll of paper Campuzano hands to Peralta is the *Dialogue of the Dogs*, volume XII of this collection.
:::
`;
const coverText = String.raw`:::frame{slot="back" sheet="case jacket"}
:::paragraphs{style="back-series"}
Exemplary Novels · XI
:::

:::paragraphs{style="back-blurb"}
An ensign leaves the hospital of Valladolid leaning on his sword. Over dinner he tells his friend Peralta how he married a lady with a furnished house and a chest of linen, and how both turned out to belong to someone else.
:::

:::paragraphs{style="back-blurb"}
At the end of his story he hands Peralta a roll of paper: two nights of talk he says he overheard between two dogs of the hospital, which is the twelfth and last volume of this collection.
:::
:::

:::frame{slot="flyleaf" sheet="endpaperFront"}
:::paragraphs{style="ad-head"}
Exemplary Novels
:::

:::paragraphs{style="ad-note"}
Twelve novellas by Miguel de Cervantes, first printed in Madrid in 1613, one to a volume in the order of that edition.
:::

::catalogue{numbers="I" first=1 last=6}
:::

:::frame{slot="flyleaf" sheet="endpaperBack"}
:::paragraphs{style="ad-head"}
Exemplary Novels
:::

:::paragraphs{style="ad-note"}
The second half of the collection. This book is volume XI.
:::

::catalogue{numbers="I" first=7 last=12}
:::
`;
const resources = [
  { id: 'cover-art', typeId: 'figure', kind: 'bitmap', createdAt: 0, updatedAt: 0,
    bitmap: { fileId: 'cover-art.jpg', format: 'jpeg', width: 1000, height: 1125 }, altText: t({
    en: 'A pale soldier leaning on his sword at a hospital gate; a man in black crosses himself.',
    es: 'Un soldado pálido apoyado en la espada a la puerta del hospital; otro se santigua.' }) },
  ...collection.catalogue.map((e) => ({ id: e.resource, typeId: 'figure', kind: 'bitmap',
    createdAt: 0, updatedAt: 0, altText: e.title,
    bitmap: { fileId: `${e.resource}.jpg`, format: 'jpeg', width: 320, height: 480 } })),
  { id: 'badge', typeId: 'figure', kind: 'svg', createdAt: 0, updatedAt: 0,
    svg: { fileId: 'badge.svg', width: 49, height: 49 }, altText: roman(VOLUME) },
];
await loadImage('cover-art.jpg', asset('casamiento-1000.jpg'));
const THUMBS = [asset('gitanilla-320.jpg'), asset('amante-320.jpg'), asset('rinconete-320.jpg'),
  asset('espanola-320.jpg'), asset('vidriera-320.jpg'), asset('fuerza-320.jpg'),
  asset('celoso-320.jpg'), asset('fregona-320.jpg'), asset('doncellas-320.jpg'),
  asset('cornelia-320.jpg'), asset('casamiento-320.jpg'), asset('coloquio-320.jpg')];
await Promise.all(collection.catalogue.map((e, i) => loadImage(`${e.resource}.jpg`, THUMBS[i])));
// #region art: the volume's badge, its number in a ring in the series' gold
await loadSvg('badge.svg', '<svg xmlns="http://www.w3.org/2000/svg" width="13mm" height="13mm" '
  + `viewBox="0 0 26 26" fill="none" stroke="${palette.gold}"><circle cx="13" cy="13" r="12.4" `
  + 'stroke-width="0.8"/><circle cx="13" cy="13" r="10.8" stroke-width="0.4"/><text x="13" '
  + `y="17.4" text-anchor="middle" stroke="none" fill="${palette.gold}" `
  + 'font-family="Cormorant Garamond" font-weight="600" font-size="12">'
  + `${roman(VOLUME)}</text></svg>`);
// #endregion

// ─── 3 · Fonts ──────────────────────────────────────────────────────────────
const FONTS = { 'Crimson Pro': ['400', '400i', '600'], 'Cormorant Garamond': ['500', '600', '500i'],
  'Josefin Sans': ['600'] };

// ─── 4 · Build & show ───────────────────────────────────────────────────────
const book = await buildDocumentWithFonts({ markdown: [markdown, part2, part3].join('\n\n'),
  resources }, config, kitFonts(FONTS));

// #region sheets: the case and both endpapers, from the pages just laid out
const sheet = async (kind) => {
  const built = buildCover({ config, version: 'hardcover', pages: book.pages,
    markdown: coverText, metadata: book.metadata, resources, sheet: kind });
  if (!('config' in built)) throw new Error(built.issues.map((i) => i.kind).join(', '));
  // The barcode's digits name OCR-B, which no font server has: the label face sets them.
  for (const [id, bytes] of Object.entries(built.files)) {
    await loadSvg(id, new TextDecoder().decode(bytes)
      .replace(/font-family="[^"]*"/g, 'font-family="Josefin Sans"'));
  }
  return { built, doc: await buildDocumentWithFonts(built.content, built.config, kitFonts(FONTS)) };
};
const sheets = [await sheet('cover'), await sheet('endpaperFront'), await sheet('endpaperBack')];
// #endregion

showPages([book, ...sheets.map((s) => s.doc)], { title: t({ en: 'Exemplary Novels XI · hardcover',
  es: 'Novelas ejemplares XI · tapa dura' }) });
// What buildCover worked out from the pages, above them.
const { sheets: made, sheet: caseSheet } = sheets[0].built;
document.getElementById('pages').before(`${book.pages.length} pp. · spine `
  + `${made.spine.caseSpine.toFixed(1)} mm · case ${caseSheet.width.toFixed(1)} mm wide`);

// One file for the printer: the pages, then the case and the two endpapers at their sizes.
offerPdf(() => renderToPdf([book, ...sheets.map((s) => s.doc)], { fontProvider: fontsourceProvider,
  resourceBytes: imageBytes }), `${RECIPE}.pdf`);

// ─── Kit ── helpers shared by every Cookbook recipe · postext.dev/cookbook ─────

// ─── Kit · core v1 ── the same in every recipe · postext.dev/cookbook
function mm(value) { return { value, unit: 'mm' }; }
function pt(value) { return { value, unit: 'pt' }; }
function em(value) { return { value, unit: 'em' }; }
/** The sample language's string: t({ en: 'Figure', es: 'Figura' }). */
function t(strings) { return strings[LANG] ?? Object.values(strings)[0]; }
/** A file in this recipe's assets folder, served from the Postext repo by jsDelivr. */
function asset(file) { return `https://cdn.jsdelivr.net/gh/drnachio/postext@main/cookbook/${RECIPE}/assets/${file}`; }

// ─── Kit · fonts v3 ── the same in every recipe · postext.dev/cookbook
// Postext loads the faces a config asks for before layout and asks the kit
// for Fontsource's files, the ones the PDF embeds too.

/** buildDocumentWithFonts' options: the resolver, and FONTS' faces loaded
 *  with the config's. FONTS = { 'Family Name': ['400', '400i', '700'] }. */
function kitFonts(FONTS = {}) {
  const faces = Object.entries(FONTS).flatMap(([family, specs]) => specs.map((spec) =>
    ({ family, weight: parseInt(spec, 10), style: spec.endsWith('i') ? 'italic' : 'normal' })));
  return { resolve: fontsourceResolver, faces };
}

/** A face's files with their ranges: latin, then latin-ext and greek when
 *  `text` needs them (kitSubsetsFor). Null for a face Fontsource lacks. */
async function fontsourceResolver(family, weight, style, { text = '' } = {}) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  if (meta && !(await fontsourceWeights(family, style)).includes(weight)) return null;
  kitStatus('Loading fonts…');
  const at = await fontsourceAt(id);
  return ['latin', ...kitSubsetsFor(text, meta)].map((subset) => ({
    source: `${at}files/${id}-${subset}-${weight}-${style}.woff2`,
    unicodeRange: kitRanges()[subset],
  }));
}

/** Each file's unicode-range (a function: the kit runs after the pen's code). */
function kitRanges() {
  return {
    latin: 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,'
      + 'U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD',
    'latin-ext': 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,'
      + 'U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF',
    greek: 'U+0370-03FF',
  };
}

/** For the cjk, arabic and comics blocks: loads `faces` (as FONTS) for the
 *  sample `text`; `optional` skips a face Fontsource lacks. Files are added in
 *  the order asked, the last winning a shared character. Resolves to the count. */
async function loadFonts(faces, text = '', { optional = false } = {}) {
  kitStatus('Loading fonts…');
  const ranges = kitRanges();
  const jobs = [];
  for (const [family, specs] of Object.entries(faces)) {
    const id = fontsourceId(family);
    const todo = [...new Set(specs)].map((spec) => [parseInt(spec, 10), spec.endsWith('i') ? 'italic' : 'normal'])
      .filter(([weight, style]) => !hasFace(family, weight, style)); // before any await
    const at = fontsourceAt(id);
    const meta = optional || /[^\0-ÿ]/u.test(text) ? await fontsourceMeta(family) : null;
    const subsets = ['latin', ...kitSubsetsFor(text, meta)];
    for (const [weight, style] of todo) {
      if (optional && !(meta && (await fontsourceWeights(family, style)).includes(weight))) continue;
      for (const subset of subsets) {
        const url = `${await at}files/${id}-${subset}-${weight}-${style}.woff2`;
        const face = new FontFace(family, `url(${url}) format('woff2')`,
          { weight: String(weight), style, unicodeRange: ranges[subset] });
        jobs.push(face.load().catch(() => {
          if (subset === 'latin' && !optional) throw new Error(`Fontsource has no ${family} ${weight} ${style}`);
        }));
      }
    }
  }
  const ready = await Promise.all(jobs).catch((error) => { kitFail(error); throw error; });
  return ready.filter((face) => face && document.fonts.add(face)).length;
}

/** A loaded FontFace covers this face (fonts.check() says yes to any family). */
function hasFace(family, weight, style) {
  for (const face of document.fonts) {
    if (face.status !== 'loaded' || face.style !== style) continue;
    if (face.family.replace(/^["']|["']$/g, '') !== family) continue;
    const [low, high = low] = face.weight.split(' ').map(Number);
    if (weight >= low && weight <= high) return true;
  }
  return false;
}

/** The files beyond latin `text` needs that `meta`'s family ships. */
function kitSubsetsFor(text, meta) {
  return [[/[Ā-˿ᴀ-ᶿḀ-ỿ†ℓⱠ-Ɀ꜠-ꟿ]/u, 'latin-ext'], [/[Ͱ-Ͽ]/u, 'greek']]
    .filter(([re, x]) => re.test(text) && meta?.subsets?.includes(x)).map(([, x]) => x);
}

/** Fontsource's id for a family: 'Source Serif 4' → 'source-serif-4'. */
function fontsourceId(family) { return family.toLowerCase().replace(/\s+/g, '-'); }

/** A package's folder at the one version @5 names now (#766). */
function fontsourceAt(id, u = `https://cdn.jsdelivr.net/npm/@fontsource/${id}@`) {
  return (fontsourceAt.c ??= {})[id] ??= fetch(u + '5/package.json').then((r) => r.json())
    .then((p) => p.version || 5, () => 5).then((v) => `${u}${v}/`);
}

/** The family's Fontsource metadata (weights, styles, subsets), or null. */
function fontsourceMeta(family, id = fontsourceId(family)) {
  return (fontsourceMeta.c ??= {})[id] ??= fetch(`https://api.fontsource.org/v1/fonts/${id}`)
    .then((res) => (res.ok ? res.json() : null), () => null);
}

/** The weights the package ships in `style`: the API pairs none (no Libre
 *  Caslon 700 italic file), so italics are read from latin-italic.css. */
function fontsourceWeights(family, style, id = fontsourceId(family)) {
  return (fontsourceWeights.c ??= {})[id + style] ??= fontsourceMeta(family).then(async (m) => {
    if (!m?.styles.includes(style)) return m ? [] : [400, 700];
    const css = style === 'italic' ? await fetch(`${await fontsourceAt(id)}latin-italic.css`).then((r) => (r.ok ? r.text() : ''), () => '') : '';
    const w = [...css.matchAll(/weight: (\d+)/g)].map((x) => +x[1]);
    return w.length ? w : m.weights;
  });
}

// ─── Kit · viewer v2 ── the same in every recipe · postext.dev/cookbook
/** The pages as spreads on a dark desk, page 1 alone, then verso | recto,
 *  each painted when it scrolls near. Other options go to renderPageToCanvas. */
function showPages(docs, { title, width = 460, ...render } = {}) {
  const root = viewer(title);
  const pages = [docs].flat().flatMap((doc) =>
    doc.pages.map((page) => ({ doc, page, n: (doc.pageIndexOffset ?? 0) + page.index })));
  const spreads = [];
  let verso = null;
  for (const p of pages) {
    if (p.n % 2 === 1) { if (verso) spreads.push([verso, null]); verso = p; }
    else { spreads.push([verso, p]); verso = null; }
  }
  if (verso) spreads.push([verso, null]);
  const density = Math.min(window.devicePixelRatio || 1, 2);
  showPages.painter?.disconnect();
  const painter = new IntersectionObserver((entries) => {
    for (const { isIntersecting, target } of entries) {
      if (!isIntersecting) continue;
      painter.unobserve(target);
      const { doc, page } = target.postext;
      renderPageToCanvas(page, doc, target, { ...render, scale: (width * density) / page.width });
    }
  }, { rootMargin: '800px' });
  showPages.painter = painter;
  root.replaceChildren(...spreads.map((pair) => {
    const spread = document.createElement('div');
    spread.className = 'pt-spread';
    for (const p of pair) {
      const figure = document.createElement('figure');
      if (p) {
        const label = p.page.pageLabel || String(p.n + 1);
        const canvas = document.createElement('canvas');
        canvas.postext = p;
        canvas.style.aspectRatio = `${p.page.width} / ${p.page.height}`;
        canvas.setAttribute('role', 'img');
        canvas.setAttribute('aria-label', `Page ${label}`);
        const folio = document.createElement('figcaption');
        folio.textContent = label;
        figure.append(canvas, folio);
        painter.observe(canvas);
      } else figure.className = 'pt-blank';
      spread.append(figure);
    }
    return spread;
  }));
  kitStatus(`${pages.length} ${pages.length === 1 ? 'page' : 'pages'}`);
  document.documentElement.dataset.postext = 'ready';
  return pages.length;
}

/** The desk, the bar and the error reporting, created once. */
function viewer(title) {
  if (!document.getElementById('pt-kit')) {
    document.head.insertAdjacentHTML('beforeend', `<style id="pt-kit">
      :root { color-scheme: dark; }
      body { margin: 0; background: #0e1014; color: #b9bcc4; font: 13px/1.45 system-ui, sans-serif; }
      #pt-bar { position: sticky; top: 0; z-index: 1; display: flex; flex-wrap: wrap; align-items: center;
        gap: 6px 16px; padding: 10px 16px; background: rgb(14 16 20 / .92); backdrop-filter: blur(6px);
        border-bottom: 1px solid #23262d; }
      #pt-bar strong { color: #f4f1ea; font-weight: 600; }
      #pt-actions { display: flex; gap: 12px; margin-left: auto; }
      #pt-actions a, #pt-actions button { color: #d8a21a; font: inherit; background: none; border: 0; padding: 0; cursor: pointer; }
      #pages { display: grid; justify-items: center; gap: 48px; padding: 32px 16px 72px; }
      .pt-spread { display: flex; }
      .pt-spread figure { margin: 0; width: min(460px, 44vw); }
      .pt-spread canvas { display: block; width: 100%; background: #fff;
        box-shadow: 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figure:first-child canvas { box-shadow: inset -14px 0 14px -14px rgb(0 0 0 / .18), 0 1px 2px rgb(0 0 0 / .5), 0 22px 44px -16px rgb(0 0 0 / .8); }
      .pt-spread figcaption { margin-top: 10px; text-align: center; font: 600 10px/1 system-ui, sans-serif;
        letter-spacing: .18em; text-transform: uppercase; color: #6c7079; }
      .pt-blank { visibility: hidden; }
      @media (max-width: 760px) {
        .pt-spread { flex-direction: column; gap: 32px; }
        .pt-spread figure { width: min(460px, 92vw); }
        .pt-blank { display: none; }
      }
    </style>`);
    document.body.insertAdjacentHTML('afterbegin',
      '<header id="pt-bar"><strong id="pt-title"></strong><span id="pt-status" role="status"></span><span id="pt-actions"></span></header>');
    document.getElementById('pt-title').textContent = document.title || 'Postext';
    addEventListener('error', (event) => kitFail(event.error ?? event.message));
    addEventListener('unhandledrejection', (event) => kitFail(event.reason));
  }
  if (title) document.getElementById('pt-title').textContent = title;
  return document.getElementById('pages')
    ?? document.body.appendChild(Object.assign(document.createElement('main'), { id: 'pages' }));
}

function kitStatus(text) {
  viewer();
  document.getElementById('pt-status').textContent = text;
}

function kitFail(error) {
  document.documentElement.dataset.postext = 'error';
  kitStatus(`Error: ${error?.message ?? error}`);
}

// ─── Kit · pdf v3 ── the same in every recipe that exports a PDF
/** The Fontsource files the screen used, as TrueType, with their range and
 *  place: the nearest weight the family ships in that style, upright with no italic;
 *  latin, then what its letters need (kitSubsetsFor). */
async function fontsourceProvider(family, weight, style, request) {
  const id = fontsourceId(family);
  const meta = await fontsourceMeta(family);
  const s = style === 'italic' && meta && !meta.styles.includes('italic') ? 'normal' : style;
  const shipped = meta ? await fontsourceWeights(family, s) : [];
  const weights = shipped.length ? shipped : [400, 700];
  const w = weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a));
  const text = String.fromCodePoint(...(request?.codePoints ?? []));
  const files = await Promise.all(['latin', ...kitSubsetsFor(text, meta)].map(async (subset, order) => {
    const res = await fetch(`${await fontsourceAt(id)}files/${id}-${subset}-${w}-${s}.woff2`);
    if (!res.ok) throw new Error(`Fontsource has no ${family} ${w} ${s} ${subset}`);
    return Object.assign(await decompressWoff2(new Uint8Array(await res.arrayBuffer())),
      { unicodeRange: kitRanges()[subset], order });
  }));
  return files.length === 1 ? files[0] : files;
}

/** A "Build the PDF" button; then "Open the PDF" (a new tab: CodePen's frame
 *  shows no PDFs) and a download link. */
function offerPdf(makePdf, filename) {
  viewer();
  const button = Object.assign(document.createElement('button'), { type: 'button', textContent: 'Build the PDF' });
  button.dataset.postextPdf = filename;
  button.addEventListener('click', async () => {
    button.disabled = true;
    button.textContent = 'Building the PDF…';
    try {
      const bytes = await makePdf();
      const url = URL.createObjectURL(new Blob([bytes], { type: 'application/pdf' }));
      const size = `${Math.max(1, Math.round(bytes.length / 1024))} KB`;
      button.replaceWith(
        Object.assign(document.createElement('a'), { href: url, target: '_blank', rel: 'noopener', textContent: 'Open the PDF ↗' }),
        Object.assign(document.createElement('a'), { href: url, download: filename, textContent: `Download ${filename} · ${size}` }));
    } catch (error) {
      button.disabled = false;
      button.textContent = 'Build the PDF';
      kitFail(error);
    }
  });
  document.getElementById('pt-actions').append(button);
}

// ─── Kit · images v3 ── recipes with pictures · postext.dev/cookbook
/** Registers a photo or PNG for the canvas and keeps its bytes for the PDF.
 *  fetch → ImageBitmap never taints the canvas (a plain cross-origin <img> would). */
async function loadImage(fileId, url) {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`Image not found (${res.status}): ${url}`);
  const bytes = new Uint8Array(await res.arrayBuffer());
  registerResourceImage(fileId, await createImageBitmap(new Blob([bytes])));
  (loadImage.bytes ??= new Map()).set(fileId, bytes);
}

/** Registers SVG markup as a vector image, its fonts inside (inlineSvgFonts, ≥ 1.25).
 *  `options` go to registerResourceImage: { singleInk: true } tints it on the canvas. */
async function loadSvg(fileId, svg, options) {
  if (typeof inlineSvgFonts === 'function') svg = await inlineSvgFonts(svg, svgFaces);
  const img = new Image();
  img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
  await img.decode();
  registerResourceImage(fileId, img, options);
  (loadImage.bytes ??= new Map()).set(fileId, new TextEncoder().encode(svg));
}

/** A face's Fontsource files: nearest weight; latin + what the SVG sets. */
async function svgFaces(family, weight, style, { codePoints = [] } = {}) {
  const [id, m] = [fontsourceId(family), await fontsourceMeta(family)];
  const w = m?.weights.reduce((a, b) => (Math.abs(b - weight) < Math.abs(a - weight) ? b : a)) ?? weight;
  const s = m?.styles.includes(style) === false ? 'normal' : style;
  return Promise.all(['latin', ...kitSubsetsFor(String.fromCodePoint(...codePoints), m)].map(async (x) => new Uint8Array(
    await (await fetch(`${await fontsourceAt(id)}files/${id}-${x}-${w}-${s}.woff2`)).arrayBuffer())));
}

/** renderToPdf({ resourceBytes: imageBytes }) */
function imageBytes(fileId) { return loadImage.bytes?.get(fileId); }

/** renderToHtml({ resourceImageUrl: imageUrl }) */
function imageUrl(fileId) {
  const bytes = imageBytes(fileId);
  if (!bytes) return undefined;
  imageUrl.urls ??= new Map();
  if (!imageUrl.urls.has(fileId)) {
    const type = /\.svg$/i.test(fileId) ? 'image/svg+xml' : /\.png$/i.test(fileId) ? 'image/png' : 'image/jpeg';
    imageUrl.urls.set(fileId, URL.createObjectURL(new Blob([bytes], { type })));
  }
  return imageUrl.urls.get(fileId);
}

// ─── /Kit ───────────────────────────────────────────────────────────────────────
```

## Variations

### Wrap the case in a dust jacket

On a case, `flaps` adds a jacket, a fourth sheet with flaps of its own. The barcode and the work's ISBN move to the jacket's back cover, and the blurb, whose frame names `jacket`, goes with them.

```diff
   versions: [{ id: 'hardcover', name: t({ en: 'Hardcover', es: 'Tapa dura' }),
-    binding: 'case-flat', isbn: '978-84-0000-198-8', isbnAddOn: '90000' }],
+    binding: 'case-flat', isbn: '978-84-0000-198-8', isbnAddOn: '90000', flaps: true }],
```

### Set the next volume

For volume XII the design stays as it is: `VOLUME` names the catalogue entry in `collection.volume`, so the badge, the gold frame on the endpapers and the highlighted title follow it. The cover's Markdown, the painting and the ISBN are that volume's.

```diff
-const VOLUME = 11; // this book's place in the collection
+const VOLUME = 12; // this book's place in the collection
```

## Pitfalls

- The sheets come after the book's pages in the captured list: the case is page 27, the book's count plus one. A change that adds a page to the book moves them.
- The Cookbook's `contentInConfig` check counts the line `buildCover` prints over the barcode as text kept in a design. The pen lists it in `checks.contentInConfig.allow`, worded by `workIsbnCaption`, the function the engine uses.
- A `catalogue` element draws the pictures only. The list of titles is the Markdown's `::catalogue`, so a sheet without that line shows the paintings with no names under them.
- The barcode's digits name OCR-B, which no font server has. Load the barcode with a `font-family` the pen already loads, or the PDF fails.

## Credits

- Recipe: Ignacio Ferro ([@drnachio](https://github.com/drnachio))
- Text: The Deceitful Marriage, translated by Walter K. Kelly, from The Exemplary Novels of Cervantes (London, Bohn’s Standard Library, 1846; 1881 reprint), Project Gutenberg eBook #14420: Miguel de Cervantes ([source](https://www.gutenberg.org/ebooks/14420)), public domain
- Text: El casamiento engañoso, from the Novelas ejemplares in the 1825 edition as transcribed on Wikisource: Miguel de Cervantes ([source](https://es.wikisource.org/wiki/El_casamiento_enga%C3%B1oso_(1825))), public domain
- Images: The front cover: a pale ensign leaning on his sword at the gate of the hospital of Valladolid, in oils: Generated With Diffusion Models, original
- Images: The cover painting of volume 1, The Little Gipsy Girl, on the endpapers, painted to match the front cover: Generated With Diffusion Models, original
- Images: The cover painting of volume 2, The Generous Lover, on the endpapers, painted to match the front cover: Generated With Diffusion Models, original
- Images: The cover painting of volume 3, Rinconete and Cortadillo, on the endpapers, painted to match the front cover: Generated With Diffusion Models, original
- Images: The cover painting of volume 4, The Spanish-English Lady, on the endpapers, painted to match the front cover: Generated With Diffusion Models, original
- Images: The cover painting of volume 5, The Licentiate Vidriera, on the endpapers, painted to match the front cover: Generated With Diffusion Models, original
- Images: The cover painting of volume 6, The Force of Blood, on the endpapers, painted to match the front cover: Generated With Diffusion Models, original
- Images: The cover painting of volume 7, The Jealous Estremaduran, on the endpapers, painted to match the front cover: Generated With Diffusion Models, original
- Images: The cover painting of volume 8, The Illustrious Scullery-Maid, on the endpapers, painted to match the front cover: Generated With Diffusion Models, original
- Images: The cover painting of volume 9, The Two Damsels, on the endpapers, painted to match the front cover: Generated With Diffusion Models, original
- Images: The cover painting of volume 10, The Lady Cornelia, on the endpapers, painted to match the front cover: Generated With Diffusion Models, original
- Images: The cover painting of volume 11, The Deceitful Marriage, on the endpapers, painted to match the front cover: Generated With Diffusion Models, original
- Images: The cover painting of volume 12, The Dialogue of the Dogs, on the endpapers, painted to match the front cover: Generated With Diffusion Models, original
- Type: Crimson Pro (OFL-1.1), Cormorant Garamond (OFL-1.1), Josefin Sans (OFL-1.1)
- Code: MIT · Sample content: CC-BY-4.0

## Related

- [Nº 196 · A paperback cover with flaps, its spine from the pages](https://postext.dev/en/cookbook/paperback-cover-with-flaps.md): A 120 × 190 mm paperback with 60 mm flaps: the pages are laid out first, and buildCover makes the cover sheet from them, with a spine as thick as their paper. · Level 3 (Advanced) · Fiction, drama & literary prose
- [Nº 200 · Cover text boxes anchored, chained and grown](https://postext.dev/en/cookbook/cover-text-boxes-anchored.md): A paperback of two Poe tales whose cover is set from six text boxes hung from the panels and from each other, a title that grows and a blurb that runs on. · Level 3 (Advanced) · Fiction, drama & literary prose
- [Nº 194 · A window cover that frames the title page](https://postext.dev/en/cookbook/die-cut-window-cover.md): An oval window cut through the cover with dieCuts, measured on the title-page painting so its edge falls on the gilt frame, plus the die line on its own plate. · Level 2 (Intermediate) · Fiction, drama & literary prose
