@open-press/core 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +9 -5
  2. package/engine/cli.mjs +2 -5
  3. package/engine/commands/_shared.mjs +4 -4
  4. package/engine/commands/deploy.mjs +1 -1
  5. package/engine/commands/inspect.mjs +3 -3
  6. package/engine/commands/replace.mjs +1 -1
  7. package/engine/commands/search.mjs +1 -1
  8. package/engine/commands/upgrade.mjs +47 -5
  9. package/engine/commands/validate.mjs +2 -2
  10. package/engine/document-export.mjs +1 -1
  11. package/engine/{chrome-pdf.mjs → output/chrome-pdf.mjs} +1 -2
  12. package/engine/{deploy-sync.mjs → output/deploy-sync.mjs} +2 -2
  13. package/engine/{fonts.mjs → output/fonts.mjs} +1 -1
  14. package/engine/{public-assets.mjs → output/public-assets.mjs} +2 -2
  15. package/engine/{static-server.mjs → output/static-server.mjs} +2 -2
  16. package/engine/react/caption-numbering.mjs +73 -0
  17. package/engine/react/comment-marker.mjs +54 -10
  18. package/engine/react/document-entry.mjs +124 -64
  19. package/engine/react/document-export.mjs +266 -310
  20. package/engine/react/mdx-compile.mjs +214 -3
  21. package/engine/react/measurement-css.mjs +3 -3
  22. package/engine/react/pagination/allocator.mjs +122 -0
  23. package/engine/react/pagination/regions.mjs +81 -0
  24. package/engine/react/pagination.mjs +9 -121
  25. package/engine/react/pipeline/allocate.mjs +248 -0
  26. package/engine/react/pipeline/final-render.mjs +94 -0
  27. package/engine/react/pipeline/frame-measurement.mjs +300 -0
  28. package/engine/react/pipeline/press-tree.mjs +135 -0
  29. package/engine/react/project-asset-endpoint.mjs +2 -2
  30. package/engine/react/{chapter-css.mjs → section-css.mjs} +12 -9
  31. package/engine/react/sources/heading-numbering.mjs +132 -0
  32. package/engine/react/sources/mdx-resolver.mjs +441 -0
  33. package/engine/react/{workspace-discovery.mjs → style-discovery.mjs} +29 -40
  34. package/engine/{config.mjs → runtime/config.mjs} +15 -0
  35. package/engine/{file-utils.mjs → runtime/file-utils.mjs} +1 -1
  36. package/engine/{inspection.mjs → runtime/inspection.mjs} +3 -4
  37. package/engine/{source-text-tools.mjs → runtime/source-text-tools.mjs} +24 -7
  38. package/engine/runtime/source-workspace.mjs +186 -0
  39. package/engine/{validation.mjs → runtime/validation.mjs} +19 -17
  40. package/package.json +5 -2
  41. package/src/openpress/anchorMap.ts +27 -0
  42. package/src/openpress/core/Frame.tsx +80 -0
  43. package/src/openpress/core/FrameContext.tsx +19 -0
  44. package/src/openpress/core/MdxArea.tsx +35 -0
  45. package/src/openpress/core/Press.tsx +34 -0
  46. package/src/openpress/core/index.tsx +34 -15
  47. package/src/openpress/core/primitives.tsx +23 -0
  48. package/src/openpress/core/types.ts +131 -19
  49. package/src/openpress/core/useSource.ts +28 -0
  50. package/src/openpress/manuscript/index.tsx +196 -0
  51. package/src/openpress/mdx/index.ts +88 -0
  52. package/src/openpress/numbering/index.ts +294 -0
  53. package/src/openpress/publicPage.tsx +4 -186
  54. package/src/openpress/reactDocumentMetadata.ts +2 -16
  55. package/src/openpress/types.ts +0 -16
  56. package/src/openpress/workbench.tsx +2 -36
  57. package/src/styles/openpress/responsive.css +0 -14
  58. package/tsconfig.json +4 -1
  59. package/vite.config.ts +10 -3
  60. package/engine/commands/migrate-to-react.mjs +0 -27
  61. package/engine/page-renderer.mjs +0 -217
  62. package/engine/react/migrate-to-react.mjs +0 -355
  63. package/engine/source-workspace.mjs +0 -76
  64. package/src/openpress/core/basePages.tsx +0 -87
  65. package/src/openpress/pagination.ts +0 -845
  66. /package/engine/{chrome-pdf.d.mts → output/chrome-pdf.d.mts} +0 -0
  67. /package/engine/{katex-assets.mjs → output/katex-assets.mjs} +0 -0
  68. /package/engine/{page-block.mjs → output/page-block.mjs} +0 -0
  69. /package/engine/{pdf-media.mjs → output/pdf-media.mjs} +0 -0
  70. /package/engine/{config.d.mts → runtime/config.d.mts} +0 -0
  71. /package/engine/{issue-report.mjs → runtime/issue-report.mjs} +0 -0
@@ -0,0 +1,248 @@
1
+ // Layer 4 — Allocation.
2
+ //
3
+ // Per chain, fills MdxAreas with block IDs using the Phase 1 region allocator.
4
+ // Returns:
5
+ // - `allocation`: { [frameKey]: { [chainId]: blockIds[][] } } — areas per chain, area index → blockIds
6
+ // - `hints`: { totalPagesPerChain: { [chainId]: number } } — fed back to <Sections>
7
+ // - `warnings`: chain-overflowed, etc.
8
+
9
+ const SANITY_LIMIT = 200;
10
+
11
+ /**
12
+ * @param {object} opts
13
+ * @param {Array<FrameInstance>} opts.frames Layer 2 frame structure.
14
+ * @param {Array<MdxAreaMeasurement>} opts.mdxAreas Layer 3 MdxArea capacities.
15
+ * @param {Array<BlockMeasurement>} opts.blockHeights Layer 3 block heights.
16
+ * @param {Record<string, object>} opts.sources Resolved sources (for chain block lists).
17
+ * @returns {AllocationResult}
18
+ */
19
+ export function allocateChains({ frames, mdxAreas, blockHeights, sources }) {
20
+ // Group MdxAreas by chainId, sorted by (frame order, indexInFrame)
21
+ const chainAreas = groupAreasByChain(frames, mdxAreas);
22
+ // Group block heights by chainId
23
+ const blockHeightsByChain = groupBlockHeights(blockHeights);
24
+
25
+ const allocation = {};
26
+ const warnings = [];
27
+ const totalPagesPerChain = {};
28
+ // Track per-chain how many extension iterations the caller (orchestrator)
29
+ // should request. The actual *cloning* is done at the Press tree level
30
+ // by feeding hints back to <Sections>; here we just report how many
31
+ // frames each chain *should* have.
32
+
33
+ for (const [chainId, chainSource] of iterateChains(sources)) {
34
+ const areas = chainAreas.get(chainId) ?? [];
35
+ const blocks = buildBlockStream(chainSource, blockHeightsByChain.get(chainId));
36
+
37
+ const regions = areas.map((a) => ({
38
+ id: `${a.frameKey}#${a.indexInFrame}`,
39
+ capacity: a.capacity,
40
+ pageIndex: 0, // not used here; we keep our own mapping
41
+ columnIndex: a.indexInFrame,
42
+ __frameKey: a.frameKey,
43
+ __chainId: chainId,
44
+ __overflow: a.overflow,
45
+ }));
46
+
47
+ if (regions.length === 0 || blocks.length === 0) {
48
+ // No areas to fill, or no blocks to place.
49
+ if (blocks.length > 0 && !chainId.startsWith("toc:")) {
50
+ warnings.push({ code: "chain-has-no-area", chainId });
51
+ }
52
+ // Frames already correctly count to 0 for this chain.
53
+ // (Or it's a static-source chain like the cover, which doesn't allocate.)
54
+ // Skip.
55
+ // If chain has blocks but no areas, that's an authoring error.
56
+ const sourceFrameCount = frames.filter((f) => f.mdxAreas.some((a) => a.chainId === chainId)).length;
57
+ totalPagesPerChain[chainId] = Math.max(1, sourceFrameCount);
58
+ continue;
59
+ }
60
+
61
+ const { result, neededAreas } = greedyAllocate(blocks, regions);
62
+ const lastOverflow = regions[regions.length - 1].__overflow;
63
+ const sourceFramesForChain = uniqueFramesForChain(frames, chainId);
64
+
65
+ if (neededAreas > regions.length) {
66
+ // Overflow detected.
67
+ if (lastOverflow === "error") {
68
+ const remaining = blocks.slice(result.consumed).map((b) => b.id);
69
+ throw new Error(
70
+ `Chain "${chainId}" overflowed and the last MdxArea is overflow="error". ` +
71
+ `Remaining block IDs: ${remaining.slice(0, 5).join(", ")}${remaining.length > 5 ? `, ... (${remaining.length} total)` : ""}.`,
72
+ );
73
+ }
74
+ if (lastOverflow === "truncate") {
75
+ warnings.push({
76
+ code: "chain-overflowed",
77
+ chainId,
78
+ remainingBlocks: blocks.length - result.consumed,
79
+ });
80
+ // Don't grow totalPages; truncate at current capacity.
81
+ totalPagesPerChain[chainId] = sourceFramesForChain;
82
+ recordAllocation(allocation, result, regions);
83
+ continue;
84
+ }
85
+ // overflow="extend" (default): scale frame count up.
86
+ const areasPerFrame = Math.max(1, regions.length / Math.max(1, sourceFramesForChain));
87
+ const extraAreasNeeded = neededAreas - regions.length;
88
+ const extraFramesNeeded = Math.ceil(extraAreasNeeded / areasPerFrame);
89
+ const newTotal = sourceFramesForChain + extraFramesNeeded;
90
+ if (newTotal > SANITY_LIMIT) {
91
+ throw new Error(
92
+ `Chain "${chainId}" would require ${newTotal} frames after extension, exceeding the sanity limit of ${SANITY_LIMIT}. ` +
93
+ `Check that block content fits within the MdxArea capacity.`,
94
+ );
95
+ }
96
+ totalPagesPerChain[chainId] = newTotal;
97
+ // Don't record allocation yet — orchestrator will re-render with more
98
+ // frames and re-allocate.
99
+ continue;
100
+ }
101
+
102
+ totalPagesPerChain[chainId] = sourceFramesForChain;
103
+ recordAllocation(allocation, result, regions);
104
+ }
105
+
106
+ return {
107
+ allocation,
108
+ hints: { totalPagesPerChain },
109
+ warnings,
110
+ };
111
+ }
112
+
113
+ function greedyAllocate(blocks, regions) {
114
+ const filled = [];
115
+ let regionIndex = 0;
116
+ let currentBlockIds = [];
117
+ let currentHeight = 0;
118
+ let consumed = 0;
119
+ const flush = () => {
120
+ if (currentBlockIds.length === 0) return;
121
+ filled.push({
122
+ region: regions[regionIndex],
123
+ blockIds: currentBlockIds,
124
+ });
125
+ currentBlockIds = [];
126
+ currentHeight = 0;
127
+ };
128
+ for (let blockIndex = 0; blockIndex < blocks.length; blockIndex += 1) {
129
+ const block = blocks[blockIndex];
130
+ while (regionIndex < regions.length) {
131
+ const region = regions[regionIndex];
132
+ const nextBlock = blocks[blockIndex + 1];
133
+ const keepWithNextHeight = shouldKeepWithNext(block, nextBlock) ? block.height + nextBlock.height : 0;
134
+ if (
135
+ currentBlockIds.length > 0 &&
136
+ keepWithNextHeight > 0 &&
137
+ currentHeight + keepWithNextHeight > region.capacity
138
+ ) {
139
+ flush();
140
+ regionIndex += 1;
141
+ continue;
142
+ }
143
+ if (currentBlockIds.length === 0 || currentHeight + block.height <= region.capacity) {
144
+ currentBlockIds.push(block.id);
145
+ currentHeight += block.height;
146
+ consumed += 1;
147
+ break;
148
+ }
149
+ // Doesn't fit — flush current region and advance
150
+ flush();
151
+ regionIndex += 1;
152
+ }
153
+ if (regionIndex >= regions.length) break;
154
+ }
155
+ flush();
156
+ // neededAreas = total regions consumed if we had unlimited supply
157
+ // For overflow detection we estimate: if consumed < blocks.length, we need more areas.
158
+ let neededAreas = filled.length;
159
+ if (consumed < blocks.length) {
160
+ // Estimate how many more areas needed
161
+ const lastCap = regions[regions.length - 1].capacity;
162
+ const remainingBlocks = blocks.slice(consumed);
163
+ let h = 0;
164
+ let extra = 0;
165
+ let inExtra = false;
166
+ for (const b of remainingBlocks) {
167
+ if (!inExtra || h + b.height > lastCap) {
168
+ extra += 1;
169
+ h = b.height;
170
+ inExtra = true;
171
+ } else {
172
+ h += b.height;
173
+ }
174
+ }
175
+ neededAreas += extra;
176
+ }
177
+ return { result: { filled, consumed }, neededAreas };
178
+ }
179
+
180
+ function shouldKeepWithNext(block, nextBlock) {
181
+ if (!nextBlock) return false;
182
+ return /^h[1-6]$/.test(String(block?.name ?? ""));
183
+ }
184
+
185
+ function recordAllocation(allocation, result, regions) {
186
+ for (const fill of result.filled) {
187
+ const frameKey = fill.region.__frameKey;
188
+ const chainId = fill.region.__chainId;
189
+ const areaIndex = fill.region.columnIndex;
190
+ if (!allocation[frameKey]) allocation[frameKey] = {};
191
+ if (!allocation[frameKey][chainId]) allocation[frameKey][chainId] = [];
192
+ allocation[frameKey][chainId][areaIndex] = fill.blockIds;
193
+ }
194
+ }
195
+
196
+ function groupAreasByChain(frames, mdxAreas) {
197
+ // mdxAreas come from chromium in DOM order. We need to order by (frame
198
+ // sequence position in Press tree, indexInFrame). Use frames[] order.
199
+ const frameOrder = new Map();
200
+ frames.forEach((f, idx) => frameOrder.set(f.frameKey, idx));
201
+ const byChain = new Map();
202
+ const sorted = [...mdxAreas].sort((a, b) => {
203
+ const fa = frameOrder.get(a.frameKey) ?? Number.MAX_SAFE_INTEGER;
204
+ const fb = frameOrder.get(b.frameKey) ?? Number.MAX_SAFE_INTEGER;
205
+ if (fa !== fb) return fa - fb;
206
+ return a.indexInFrame - b.indexInFrame;
207
+ });
208
+ for (const area of sorted) {
209
+ if (!byChain.has(area.chainId)) byChain.set(area.chainId, []);
210
+ byChain.get(area.chainId).push(area);
211
+ }
212
+ return byChain;
213
+ }
214
+
215
+ function groupBlockHeights(blockHeights) {
216
+ const byChain = new Map();
217
+ for (const block of blockHeights) {
218
+ if (!byChain.has(block.chainId)) byChain.set(block.chainId, new Map());
219
+ byChain.get(block.chainId).set(block.id, block.height);
220
+ }
221
+ return byChain;
222
+ }
223
+
224
+ function buildBlockStream(chainSource, heightMap) {
225
+ if (!chainSource || !heightMap) return [];
226
+ return chainSource.map((block) => ({
227
+ id: block.id,
228
+ kind: block.kind,
229
+ name: block.name,
230
+ height: heightMap.get(block.id) ?? 0,
231
+ }));
232
+ }
233
+
234
+ function* iterateChains(sources) {
235
+ for (const source of Object.values(sources)) {
236
+ for (const [chainId, blocks] of Object.entries(source.chains)) {
237
+ yield [chainId, blocks];
238
+ }
239
+ }
240
+ }
241
+
242
+ function uniqueFramesForChain(frames, chainId) {
243
+ const set = new Set();
244
+ for (const f of frames) {
245
+ if (f.mdxAreas.some((a) => a.chainId === chainId)) set.add(f.frameKey);
246
+ }
247
+ return Math.max(1, set.size);
248
+ }
@@ -0,0 +1,94 @@
1
+ // Layer 5 — Final Render.
2
+ //
3
+ // Given the allocation map (frameKey -> chainId -> areaIndex -> blockIds),
4
+ // pre-compiles each MdxArea's block subset into React nodes, then renders
5
+ // the Press tree one more time with `PressContext.allocation` populated.
6
+ // The output HTML is parsed back into per-frame fragments for document.json.
7
+
8
+ import React from "react";
9
+ import { expandPressTree } from "./press-tree.mjs";
10
+ import { compileChainBlocks } from "../sources/mdx-resolver.mjs";
11
+
12
+ /**
13
+ * @returns {{ frames: Array<{ frameKey, role, chrome, html, blockIds, mdxAreas }>, html: string }}
14
+ */
15
+ export async function renderFinalPress({
16
+ Press,
17
+ PressContext,
18
+ sources,
19
+ hints,
20
+ toc,
21
+ allocation: blockAllocation, // chainId blockId allocator output: { [frameKey]: { [chainId]: blockIds[][] } }
22
+ renderRegistry,
23
+ }) {
24
+ // 1. Compile React nodes per (frameKey, chainId, areaIndex)
25
+ const reactAllocation = await buildReactAllocation(blockAllocation, sources, renderRegistry, toc);
26
+
27
+ // 2. Render Press tree with allocation in context
28
+ const { html, frames } = expandPressTree({
29
+ Press,
30
+ PressContext,
31
+ sources,
32
+ hints,
33
+ toc,
34
+ allocation: reactAllocation,
35
+ });
36
+
37
+ // 3. Annotate frame instances with blockIds (for document.json)
38
+ const framesWithBlocks = frames.map((frame) => {
39
+ const frameBlocks = blockAllocation[frame.frameKey] ?? {};
40
+ const blockIds = [];
41
+ const mdxAreas = frame.mdxAreas.map((area) => {
42
+ const ids = frameBlocks[area.chainId]?.[area.indexInFrame] ?? [];
43
+ blockIds.push(...ids);
44
+ return {
45
+ chainId: area.chainId,
46
+ indexInFrame: area.indexInFrame,
47
+ blockIds: ids,
48
+ };
49
+ });
50
+ return {
51
+ frameKey: frame.frameKey,
52
+ role: frame.role,
53
+ chrome: frame.chrome,
54
+ html: frame.html,
55
+ blockIds,
56
+ mdxAreas,
57
+ };
58
+ });
59
+
60
+ return { frames: framesWithBlocks, html };
61
+ }
62
+
63
+ async function buildReactAllocation(blockAllocation, sources, renderRegistry, toc) {
64
+ /** @type {Record<string, Record<string, React.ReactNode[]>>} */
65
+ const out = {};
66
+ const sourceOfChain = new Map();
67
+ for (const source of Object.values(sources)) {
68
+ for (const chainId of Object.keys(source.chains)) {
69
+ sourceOfChain.set(chainId, source.id);
70
+ }
71
+ }
72
+
73
+ for (const [frameKey, chainMap] of Object.entries(blockAllocation)) {
74
+ out[frameKey] = {};
75
+ for (const [chainId, areaArr] of Object.entries(chainMap)) {
76
+ const nodesByArea = [];
77
+ for (let areaIndex = 0; areaIndex < areaArr.length; areaIndex++) {
78
+ const blockIds = areaArr[areaIndex] ?? [];
79
+ if (blockIds.length === 0) {
80
+ nodesByArea[areaIndex] = null;
81
+ continue;
82
+ }
83
+ const sourceId = sourceOfChain.get(chainId);
84
+ const renderData = renderRegistry.get(sourceId);
85
+ const compiled = await compileChainBlocks({ renderData, chainId, blockIds, toc });
86
+ nodesByArea[areaIndex] = compiled.map(({ Content }, i) =>
87
+ React.createElement(Content, { key: `${areaIndex}-${i}` }),
88
+ );
89
+ }
90
+ out[frameKey][chainId] = nodesByArea;
91
+ }
92
+ }
93
+ return out;
94
+ }
@@ -0,0 +1,300 @@
1
+ // Layer 3 — Frame Measurement.
2
+ //
3
+ // Renders the Press tree (from Layer 2) plus a hidden "blocks zone" that
4
+ // contains every chain's full content, sends the combined document to
5
+ // Chromium, then queries the DOM for:
6
+ // - MdxArea capacities (per frameKey + chainId + indexInFrame)
7
+ // - Block heights (per chainId + blockId)
8
+ //
9
+ // The blocks zone uses the same `.page-body` CSS context as the live
10
+ // frames so widths and font metrics match.
11
+
12
+ import fs from "node:fs/promises";
13
+ import path from "node:path";
14
+ import React from "react";
15
+ import { renderToStaticMarkup } from "react-dom/server";
16
+ import { chromium } from "playwright";
17
+ import { createCaptionNumberingState, numberCaptionsInHtml } from "../caption-numbering.mjs";
18
+ import { compileChainBlocks } from "../sources/mdx-resolver.mjs";
19
+
20
+ const DEFAULT_VIEWPORT = { width: 794, height: 1123 };
21
+
22
+ // Safety inset applied to measured MdxArea capacities. A small reserve keeps
23
+ // content that visually fits "exactly" from clipping due to anti-aliasing,
24
+ // line breaks, and rounding.
25
+ const CAPACITY_SAFETY_RATIO = 0.04;
26
+ const CAPACITY_SAFETY_MAX_PX = 96;
27
+
28
+ /**
29
+ * @param {object} opts
30
+ * @param {string} opts.pressHtml Rendered Press tree HTML (Layer 2).
31
+ * @param {Record<string, object>} opts.sources Resolved sources keyed by sourceId.
32
+ * @param {Map<string, object>} opts.renderRegistry Internal render data per sourceId.
33
+ * @param {string} opts.css Combined CSS for measurement context.
34
+ * @param {string=} opts.baseHref Base URL for relative media paths in MDX.
35
+ * @param {string=} opts.mediaDir Local media dir for inlining /openpress/media/* assets.
36
+ * @param {object=} opts.captionNumbering Caption label formatter options.
37
+ * @param {{width:number,height:number}=} opts.viewport
38
+ */
39
+ export async function measureFrames({
40
+ pressHtml,
41
+ sources,
42
+ renderRegistry,
43
+ css = "",
44
+ baseHref = "",
45
+ mediaDir = "",
46
+ captionNumbering = {},
47
+ viewport = DEFAULT_VIEWPORT,
48
+ }) {
49
+ const chainContent = await buildChainContent(sources, renderRegistry, captionNumbering);
50
+ const html = await buildMeasurementDocument({ pressHtml, chainContent, css, baseHref, mediaDir });
51
+ return runChromiumMeasurement(html, viewport);
52
+ }
53
+
54
+ async function buildChainContent(sources, renderRegistry, captionNumbering) {
55
+ const out = new Map();
56
+ const captionState = createCaptionNumberingState();
57
+ for (const source of Object.values(sources)) {
58
+ for (const [chainId, blocks] of Object.entries(source.chains)) {
59
+ const blockIds = blocks.map((b) => b.id);
60
+ const renderData = renderRegistry.get(source.id);
61
+ const compiled = await compileChainBlocks({ renderData, chainId, blockIds });
62
+ const html = compiled
63
+ .map(({ Content }, idx) => renderToStaticMarkup(React.createElement(Content, { key: idx })))
64
+ .join("");
65
+ out.set(
66
+ chainId,
67
+ chainId.startsWith("toc:") ? html : numberCaptionsInHtml(html, captionNumbering, captionState),
68
+ );
69
+ }
70
+ }
71
+ return out;
72
+ }
73
+
74
+ async function buildMeasurementDocument({ pressHtml, chainContent, css, baseHref, mediaDir }) {
75
+ const normalizedPressHtml = await inlineMeasurementMediaUrls(pressHtml, mediaDir);
76
+ const blocksZoneParts = [];
77
+ for (const [chainId, contentHtml] of chainContent.entries()) {
78
+ const normalizedContentHtml = await inlineMeasurementMediaUrls(contentHtml, mediaDir);
79
+ const containerTag = chainId.startsWith("toc:") ? "ol" : "div";
80
+ const containerClass = chainId.startsWith("toc:") ? ' class="toc-list"' : "";
81
+ blocksZoneParts.push(`
82
+ <section class="reader-page reader-page--content" data-openpress-measure-frame="${escapeAttr(chainId)}" data-page-kind="content">
83
+ <div class="page-frame">
84
+ <main class="page-body">
85
+ <${containerTag}${containerClass} data-block-measurement-chain="${escapeAttr(chainId)}" style="overflow: visible;">
86
+ ${normalizedContentHtml}
87
+ </${containerTag}>
88
+ </main>
89
+ </div>
90
+ </section>
91
+ `);
92
+ }
93
+ const blocksZone = blocksZoneParts.join("\n");
94
+
95
+ return `<!doctype html>
96
+ <html>
97
+ <head>
98
+ <meta charset="utf-8">
99
+ ${baseHref ? `<base href="${escapeAttr(baseHref)}">` : ""}
100
+ <style>
101
+ body { margin: 0; }
102
+ ${css}
103
+ /* Reader-page is hidden by default in the workspace theme (only the
104
+ is-active page is shown). Override visibility in measurement zones
105
+ but do not touch the page-frame display, because the theme uses
106
+ CSS grid with grid-template-rows reserving page-header and
107
+ page-footer space; we must preserve that layout so MdxArea
108
+ inherits the real page-body cell height. */
109
+ [data-openpress-frames-zone] .reader-page,
110
+ [data-openpress-blocks-zone] .reader-page {
111
+ display: block !important;
112
+ }
113
+ /* MdxArea fills its grid/flex parent so we measure the layout slot,
114
+ not the inserted content. */
115
+ [data-openpress-frames-zone] [data-openpress-mdx-area="true"] {
116
+ display: block;
117
+ box-sizing: border-box;
118
+ min-height: 0;
119
+ align-self: stretch;
120
+ overflow: visible;
121
+ }
122
+ [data-openpress-frames-zone] { position: relative; }
123
+ [data-openpress-blocks-zone] { position: fixed; left: -200000px; top: 0; visibility: hidden; pointer-events: none; }
124
+ </style>
125
+ </head>
126
+ <body>
127
+ <div data-openpress-frames-zone>${normalizedPressHtml}</div>
128
+ <div data-openpress-blocks-zone>${blocksZone}</div>
129
+ </body>
130
+ </html>`;
131
+ }
132
+
133
+ async function runChromiumMeasurement(html, viewport) {
134
+ const browser = await chromium.launch();
135
+ try {
136
+ const page = await browser.newPage({ viewport });
137
+ await page.setContent(html, { waitUntil: "load" });
138
+ // Match the print-ready settle: fonts first (font metrics affect image
139
+ // alt-text fallback boxes), then await every image's `complete` AND
140
+ // `decode()` so intrinsic sizes are committed before layout, then two
141
+ // animation frames so the chromium layout pass observes the final box
142
+ // model. Without this, `getBoundingClientRect()` on figures that hold
143
+ // images can race the decode and return collapsed heights, causing the
144
+ // allocator to pack too many blocks per page.
145
+ await page.evaluate(async () => {
146
+ if (document.fonts?.ready) await document.fonts.ready;
147
+ await Promise.all(Array.from(document.images).map(async (img) => {
148
+ if (!img.complete) {
149
+ await new Promise((resolve) => {
150
+ const settle = () => {
151
+ img.removeEventListener("load", settle);
152
+ img.removeEventListener("error", settle);
153
+ resolve(undefined);
154
+ };
155
+ img.addEventListener("load", settle, { once: true });
156
+ img.addEventListener("error", settle, { once: true });
157
+ });
158
+ }
159
+ await img.decode?.().catch(() => undefined);
160
+ }));
161
+ await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
162
+ });
163
+
164
+ const mdxAreas = await page.evaluate((safety) => {
165
+ const zone = document.querySelector("[data-openpress-frames-zone]");
166
+ if (!zone) return [];
167
+ const areas = Array.from(zone.querySelectorAll("[data-openpress-mdx-area]"));
168
+ const out = [];
169
+ for (const el of areas) {
170
+ const frame = el.closest("[data-openpress-frame-key]");
171
+ if (!frame) continue;
172
+ const frameKey = frame.getAttribute("data-openpress-frame-key") || "";
173
+ const chainId = el.getAttribute("data-openpress-mdx-area-chain") || "";
174
+ const overflow = el.getAttribute("data-openpress-mdx-area-overflow") || "extend";
175
+ // Index within this frame's same-chain areas
176
+ const sameInFrame = Array.from(frame.querySelectorAll(`[data-openpress-mdx-area][data-openpress-mdx-area-chain="${chainId}"]`));
177
+ const indexInFrame = sameInFrame.indexOf(el);
178
+ const rect = measuredMdxAreaRect(el);
179
+ const inset = Math.min(safety.maxPx, Math.max(0, rect.height * safety.ratio));
180
+ const capacity = Math.max(1, rect.height - inset);
181
+ out.push({
182
+ frameKey,
183
+ chainId,
184
+ overflow,
185
+ indexInFrame,
186
+ capacity,
187
+ rawHeight: rect.height,
188
+ width: rect.width,
189
+ });
190
+ }
191
+ return out;
192
+
193
+ function measuredMdxAreaRect(el) {
194
+ const rect = el.getBoundingClientRect();
195
+ if (rect.height > 1) return rect;
196
+ const candidates = [
197
+ el.parentElement,
198
+ el.closest(".page-body"),
199
+ el.closest("[data-openpress-frame-key]")?.querySelector(".page-body"),
200
+ ];
201
+ for (const candidate of candidates) {
202
+ if (!candidate) continue;
203
+ const fallback = candidate.getBoundingClientRect();
204
+ if (fallback.height > rect.height) {
205
+ return {
206
+ height: fallback.height,
207
+ width: rect.width > 0 ? rect.width : fallback.width,
208
+ };
209
+ }
210
+ }
211
+ return rect;
212
+ }
213
+ }, { ratio: CAPACITY_SAFETY_RATIO, maxPx: CAPACITY_SAFETY_MAX_PX });
214
+
215
+ const blockHeights = await page.evaluate(() => {
216
+ const zone = document.querySelector("[data-openpress-blocks-zone]");
217
+ if (!zone) return [];
218
+ const out = [];
219
+ for (const chain of zone.querySelectorAll("[data-block-measurement-chain]")) {
220
+ const chainId = chain.getAttribute("data-block-measurement-chain") ?? "";
221
+ const parentTop = chain.parentElement?.getBoundingClientRect().top ?? chain.getBoundingClientRect().top;
222
+ let previousBottom = parentTop;
223
+ for (const el of Array.from(chain.querySelectorAll("[data-openpress-block-id]"))) {
224
+ const rect = el.getBoundingClientRect();
225
+ out.push({
226
+ id: el.getAttribute("data-openpress-block-id"),
227
+ height: Math.max(rect.height, rect.bottom - previousBottom),
228
+ chainId,
229
+ });
230
+ previousBottom = Math.max(previousBottom, rect.bottom);
231
+ }
232
+ }
233
+ return out;
234
+ });
235
+
236
+ return { mdxAreas, blockHeights };
237
+ } finally {
238
+ await browser.close();
239
+ }
240
+ }
241
+
242
+ function escapeAttr(value) {
243
+ return String(value).replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
244
+ }
245
+
246
+ async function inlineMeasurementMediaUrls(html, mediaDir) {
247
+ if (!mediaDir || !html) return html;
248
+ let out = String(html);
249
+ const matches = new Set();
250
+ for (const match of out.matchAll(/\bsrc=(['"])([^\1]*?)\1/g)) {
251
+ const src = match[2];
252
+ if (!src) continue;
253
+ if (src.startsWith('/openpress/media/')) {
254
+ matches.add(src.slice('/openpress/media/'.length));
255
+ continue;
256
+ }
257
+ if (src.startsWith('media/')) {
258
+ matches.add(src.slice('media/'.length));
259
+ continue;
260
+ }
261
+ if (src.startsWith('./media/')) {
262
+ matches.add(src.slice('./media/'.length));
263
+ }
264
+ }
265
+ for (const rawName of matches) {
266
+ const dataUrl = await mediaDataUrl(mediaDir, rawName);
267
+ if (!dataUrl) continue;
268
+ out = out.replaceAll(`/openpress/media/${rawName}`, dataUrl);
269
+ out = out.replaceAll(`media/${rawName}`, dataUrl);
270
+ out = out.replaceAll(`./media/${rawName}`, dataUrl);
271
+ }
272
+ return out;
273
+ }
274
+
275
+ async function mediaDataUrl(mediaDir, rawName) {
276
+ let fileName;
277
+ try {
278
+ fileName = decodeURIComponent(String(rawName));
279
+ } catch {
280
+ fileName = String(rawName);
281
+ }
282
+ if (!fileName || fileName !== path.basename(fileName)) return null;
283
+ const filePath = path.join(mediaDir, fileName);
284
+ let bytes;
285
+ try {
286
+ bytes = await fs.readFile(filePath);
287
+ } catch {
288
+ return null;
289
+ }
290
+ return `data:${mediaMimeType(fileName)};base64,${bytes.toString("base64")}`;
291
+ }
292
+
293
+ function mediaMimeType(fileName) {
294
+ const ext = path.extname(fileName).toLowerCase();
295
+ if (ext === ".svg") return "image/svg+xml";
296
+ if (ext === ".jpg" || ext === ".jpeg") return "image/jpeg";
297
+ if (ext === ".gif") return "image/gif";
298
+ if (ext === ".webp") return "image/webp";
299
+ return "image/png";
300
+ }