postext 1.88.1 → 1.89.0

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 (117) hide show
  1. package/dist/__tests__/bundle/parallelBundle.test.d.ts +2 -0
  2. package/dist/__tests__/bundle/parallelBundle.test.d.ts.map +1 -0
  3. package/dist/__tests__/bundle/parallelBundle.test.js +105 -0
  4. package/dist/__tests__/bundle/parallelBundle.test.js.map +1 -0
  5. package/dist/__tests__/exports.test.js +2 -0
  6. package/dist/__tests__/exports.test.js.map +1 -1
  7. package/dist/__tests__/fonts/glyphFallback.test.js +16 -1
  8. package/dist/__tests__/fonts/glyphFallback.test.js.map +1 -1
  9. package/dist/__tests__/freezeMeasured.d.ts +2 -0
  10. package/dist/__tests__/freezeMeasured.d.ts.map +1 -0
  11. package/dist/__tests__/freezeMeasured.js +8 -0
  12. package/dist/__tests__/freezeMeasured.js.map +1 -0
  13. package/dist/__tests__/measure/measureCache.test.js +26 -8
  14. package/dist/__tests__/measure/measureCache.test.js.map +1 -1
  15. package/dist/__tests__/measure/segmentWidthsOnly.test.d.ts +2 -0
  16. package/dist/__tests__/measure/segmentWidthsOnly.test.d.ts.map +1 -0
  17. package/dist/__tests__/measure/segmentWidthsOnly.test.js +64 -0
  18. package/dist/__tests__/measure/segmentWidthsOnly.test.js.map +1 -0
  19. package/dist/__tests__/parse/annotationScan.test.d.ts +2 -0
  20. package/dist/__tests__/parse/annotationScan.test.d.ts.map +1 -0
  21. package/dist/__tests__/parse/annotationScan.test.js +34 -0
  22. package/dist/__tests__/parse/annotationScan.test.js.map +1 -0
  23. package/dist/__tests__/parse/memos.test.js +22 -1
  24. package/dist/__tests__/parse/memos.test.js.map +1 -1
  25. package/dist/__tests__/pipeline/text/characterStyles.test.js +21 -0
  26. package/dist/__tests__/pipeline/text/characterStyles.test.js.map +1 -1
  27. package/dist/__tests__/pipeline/text/spaceBreaks.test.js +20 -0
  28. package/dist/__tests__/pipeline/text/spaceBreaks.test.js.map +1 -1
  29. package/dist/__tests__/vertical/verticalWidthKept.test.d.ts +2 -0
  30. package/dist/__tests__/vertical/verticalWidthKept.test.d.ts.map +1 -0
  31. package/dist/__tests__/vertical/verticalWidthKept.test.js +71 -0
  32. package/dist/__tests__/vertical/verticalWidthKept.test.js.map +1 -0
  33. package/dist/bundle/book.d.ts +82 -8
  34. package/dist/bundle/book.d.ts.map +1 -1
  35. package/dist/bundle/book.js +373 -181
  36. package/dist/bundle/book.js.map +1 -1
  37. package/dist/bundle/index.d.ts +3 -3
  38. package/dist/bundle/index.d.ts.map +1 -1
  39. package/dist/bundle/index.js +1 -1
  40. package/dist/bundle/index.js.map +1 -1
  41. package/dist/bundle/layoutCache.d.ts +18 -5
  42. package/dist/bundle/layoutCache.d.ts.map +1 -1
  43. package/dist/bundle/layoutCache.js +24 -19
  44. package/dist/bundle/layoutCache.js.map +1 -1
  45. package/dist/fonts/glyphFallback.d.ts +3 -0
  46. package/dist/fonts/glyphFallback.d.ts.map +1 -1
  47. package/dist/fonts/glyphFallback.js +45 -12
  48. package/dist/fonts/glyphFallback.js.map +1 -1
  49. package/dist/fonts/glyphPlaces.d.ts.map +1 -1
  50. package/dist/fonts/glyphPlaces.js +46 -19
  51. package/dist/fonts/glyphPlaces.js.map +1 -1
  52. package/dist/index.d.ts +2 -2
  53. package/dist/index.d.ts.map +1 -1
  54. package/dist/index.js +1 -1
  55. package/dist/index.js.map +1 -1
  56. package/dist/knuthPlass/breakpoints.d.ts.map +1 -1
  57. package/dist/knuthPlass/breakpoints.js +4 -0
  58. package/dist/knuthPlass/breakpoints.js.map +1 -1
  59. package/dist/knuthPlass/spaceBreaks.d.ts.map +1 -1
  60. package/dist/knuthPlass/spaceBreaks.js +114 -12
  61. package/dist/knuthPlass/spaceBreaks.js.map +1 -1
  62. package/dist/knuthPlass/wasm/bytes.generated.d.ts +1 -1
  63. package/dist/knuthPlass/wasm/bytes.generated.d.ts.map +1 -1
  64. package/dist/knuthPlass/wasm/bytes.generated.js +555 -529
  65. package/dist/knuthPlass/wasm/bytes.generated.js.map +1 -1
  66. package/dist/marks/characterStyles.d.ts.map +1 -1
  67. package/dist/marks/characterStyles.js +7 -3
  68. package/dist/marks/characterStyles.js.map +1 -1
  69. package/dist/marks/highlightMarks.d.ts.map +1 -1
  70. package/dist/marks/highlightMarks.js +7 -3
  71. package/dist/marks/highlightMarks.js.map +1 -1
  72. package/dist/measure/cache.d.ts.map +1 -1
  73. package/dist/measure/cache.js +46 -20
  74. package/dist/measure/cache.js.map +1 -1
  75. package/dist/measure/index.d.ts.map +1 -1
  76. package/dist/measure/index.js +4 -3
  77. package/dist/measure/index.js.map +1 -1
  78. package/dist/measure/plain.d.ts.map +1 -1
  79. package/dist/measure/plain.js +9 -3
  80. package/dist/measure/plain.js.map +1 -1
  81. package/dist/measure/pretextLanguage.d.ts +13 -1
  82. package/dist/measure/pretextLanguage.d.ts.map +1 -1
  83. package/dist/measure/pretextLanguage.js +19 -3
  84. package/dist/measure/pretextLanguage.js.map +1 -1
  85. package/dist/measure/vertical.d.ts.map +1 -1
  86. package/dist/measure/vertical.js +22 -2
  87. package/dist/measure/vertical.js.map +1 -1
  88. package/dist/parse/annotations/scan.d.ts +4 -3
  89. package/dist/parse/annotations/scan.d.ts.map +1 -1
  90. package/dist/parse/annotations/scan.js +33 -21
  91. package/dist/parse/annotations/scan.js.map +1 -1
  92. package/dist/parse/annotations/source.js +1 -1
  93. package/dist/parse/annotations/source.js.map +1 -1
  94. package/dist/parse/blockParser.d.ts +10 -0
  95. package/dist/parse/blockParser.d.ts.map +1 -1
  96. package/dist/parse/blockParser.js +33 -4
  97. package/dist/parse/blockParser.js.map +1 -1
  98. package/dist/parse/sourceMapping.d.ts.map +1 -1
  99. package/dist/parse/sourceMapping.js +69 -44
  100. package/dist/parse/sourceMapping.js.map +1 -1
  101. package/dist/pipeline/build/balanced.d.ts.map +1 -1
  102. package/dist/pipeline/build/balanced.js +2 -0
  103. package/dist/pipeline/build/balanced.js.map +1 -1
  104. package/dist/pipeline/build/drivers.d.ts.map +1 -1
  105. package/dist/pipeline/build/drivers.js +8 -0
  106. package/dist/pipeline/build/drivers.js.map +1 -1
  107. package/dist/pipeline/build/pass.d.ts.map +1 -1
  108. package/dist/pipeline/build/pass.js +8 -0
  109. package/dist/pipeline/build/pass.js.map +1 -1
  110. package/dist/pipeline/sections/partPalette/recolor.d.ts.map +1 -1
  111. package/dist/pipeline/sections/partPalette/recolor.js +20 -11
  112. package/dist/pipeline/sections/partPalette/recolor.js.map +1 -1
  113. package/dist/util/perfTap.d.ts +29 -0
  114. package/dist/util/perfTap.d.ts.map +1 -0
  115. package/dist/util/perfTap.js +48 -0
  116. package/dist/util/perfTap.js.map +1 -0
  117. package/package.json +1 -1
@@ -14,6 +14,8 @@ import { configUsesPlaceholder } from '../design/placeholders.js';
14
14
  import { blankChapterFrontmatter } from '../defaults/chapterStyles.js';
15
15
  import { bundleStart } from './manifest.js';
16
16
  import { beginLayoutBuild, createBundleLayoutCache, jsonKey } from './layoutCache.js';
17
+ import { perfLap, perfTimed } from '../util/perfTap.js';
18
+ import { holdParseMemo } from '../parse/blockParser.js';
17
19
  /** How many times the book is laid out at most while the contents' page
18
20
  * numbers settle. */
19
21
  const MAX_ROUNDS = 3;
@@ -95,6 +97,26 @@ function chapterKey(markdown, continuation, outlineText, citations, laterIds) {
95
97
  const head = jsonKey([continuation ?? null, localCitationKey(citations), laterIds ?? null]);
96
98
  return head === undefined ? undefined : `${head}\u0000${outlineText}\u0000${markdown}`;
97
99
  }
100
+ /** Lay one chapter of a book out: its document, and what the book's chain
101
+ * and outline read from it. What `buildBundle` does for each chapter, and
102
+ * what a worker of `buildBundleParallel` does for the chapters it is
103
+ * sent. */
104
+ export function layOutChapter(job, context) {
105
+ const { markdown, metadata, continuation, outline, citations, laterPageIds } = job;
106
+ const { config, resources } = context;
107
+ const doc = buildDocument({ markdown, metadata, resources, ...(continuation ? { continuation } : {}), ...(outline ? { outline } : {}), ...(citations ? { citations } : {}), ...(laterPageIds ? { laterPageIds } : {}) }, config, context.cache, context.options);
108
+ const last = doc.pages[doc.pages.length - 1];
109
+ const firstContent = firstContentPage(doc);
110
+ return {
111
+ doc,
112
+ ...(doc.pendingJumps ? { jumps: doc.pendingJumps } : {}),
113
+ pageCount: doc.pages.length,
114
+ ...(last ? { next: { startAt: last.pageNumberValue + 1, format: last.pageNumberFormat } } : {}),
115
+ outline: perfTimed('bundle.chapterOutline', () => outlineFromDoc(doc, contentOutline({ markdown }, config, continuation).outline)),
116
+ ...(doc.carriedOutline ? { carried: carriedPlaces(doc) } : {}),
117
+ ...(firstContent ? { firstContent } : {}),
118
+ };
119
+ }
98
120
  /** Lay out every chapter of `bundle`, in order; returns one `VDTDocument`
99
121
  * per chapter. Hand the array to `renderToPdf` for the whole book, or
100
122
  * paint `docs[i]` for one chapter. A bundle that holds part of a longer
@@ -102,196 +124,366 @@ function chapterKey(markdown, continuation, outlineText, citations, laterIds) {
102
124
  * that continuation, as `buildDocument({ markdown, continuation: start },
103
125
  * config)` would, and the chapters after it chained from it. */
104
126
  export function buildBundle(bundle, options = {}) {
127
+ // Each chapter is parsed once for the whole build (#1604).
128
+ const release = holdParseMemo();
129
+ try {
130
+ const { context, steps } = bundleLayout(bundle, options, false);
131
+ let step = steps.next();
132
+ while (!step.done)
133
+ step = steps.next(step.value.map((job) => layOutChapter(job, context)));
134
+ return step.value;
135
+ }
136
+ finally {
137
+ release();
138
+ }
139
+ }
140
+ /**
141
+ * {@link buildBundle} with the chapters laid out several at a time
142
+ * (#1611): the same documents, from an executor that may spread the
143
+ * chapters over worker threads.
144
+ *
145
+ * A chapter reads the pages of the chapters before it (its page offset
146
+ * and numbering), so a round hands the executor every chapter at once,
147
+ * each with the continuation the chain gives from the layouts known so
148
+ * far, and the rounds end when every chapter stands on the continuation
149
+ * the chain gives it — the layout `buildBundle` reaches chapter by
150
+ * chapter. A book with stories that jump between chapters (#943) is laid
151
+ * out one chapter at a time, as `buildBundle` does.
152
+ */
153
+ export async function buildBundleParallel(bundle, options) {
154
+ const { layOutChapters, pageHints, ...rest } = options;
155
+ const release = holdParseMemo();
156
+ try {
157
+ const { steps } = bundleLayout(bundle, rest, true, pageHints);
158
+ let step = steps.next();
159
+ while (!step.done) {
160
+ const jobs = step.value;
161
+ const records = await layOutChapters(jobs);
162
+ if (records.length !== jobs.length)
163
+ throw new Error(`layOutChapters: ${jobs.length} chapters asked, ${records.length} returned`);
164
+ step = steps.next(records);
165
+ }
166
+ return step.value;
167
+ }
168
+ finally {
169
+ release();
170
+ }
171
+ }
172
+ /** How many times a round of {@link buildBundleParallel} hands the
173
+ * executor every chapter not settled yet before it goes on one chapter
174
+ * at a time. */
175
+ const MAX_SPECULATIONS = 12;
176
+ /** The blank page a chapter that opens on a fixed side starts with (0 or
177
+ * 1), as `guess` was laid out. */
178
+ function leadingBlank(guess) {
179
+ const first = guess.record.firstContent;
180
+ return first && first.pageIndex - guess.physical === 1 ? 1 : 0;
181
+ }
182
+ /**
183
+ * What a chapter is taken to give the chain when it starts after
184
+ * `physical` pages numbered from `next`, from its layout elsewhere in the
185
+ * book (`guess`; none: what `hint` says of it, else two pages). Its pages
186
+ * are those it had, less the
187
+ * blank page before its opener when it had one and now starts on the
188
+ * other side, and its numbering goes on from the new start when it went
189
+ * on from the old one. A wrong guess costs a layout, never a page: the
190
+ * chapter is laid out again from the records that settle.
191
+ */
192
+ function linkFrom(guess, physical, next, hint) {
193
+ if (!guess && hint) {
194
+ const last = hint.lastPage;
195
+ // (A chapter handed no numbering counts from 1.)
196
+ const numbering = last ? { startAt: ('value' in last.number ? last.number.value : (next?.startAt ?? 1) + last.number.delta) + 1, format: last.format } : undefined;
197
+ return { pageCount: hint.pageCount, ...(numbering ? { next: numbering } : {}) };
198
+ }
199
+ if (!guess)
200
+ return { pageCount: 2, ...(next ? { next: { startAt: next.startAt + 2, format: next.format } } : {}) };
201
+ const { record } = guess;
202
+ const blank = leadingBlank(guess);
203
+ const flipped = (physical - guess.physical) % 2 !== 0;
204
+ const pageCount = flipped && blank === 1 ? record.pageCount - 1 : record.pageCount;
205
+ // The numbers went on through the chapter, in the format it was handed
206
+ // (one handed no numbering counts from 1 in the book's own format): they
207
+ // go on from the new start. Numbers that start again inside the chapter
208
+ // end where they ended.
209
+ const ran = record.next !== undefined && next !== undefined
210
+ && record.next.startAt === (guess.startAt ?? 1) + record.pageCount
211
+ && (guess.format === undefined || record.next.format === guess.format);
212
+ const numbering = ran ? { startAt: next.startAt + pageCount, format: next.format } : record.next;
213
+ return { pageCount, ...(numbering ? { next: numbering } : {}), ...(record.jumps ? { jumps: record.jumps } : {}) };
214
+ }
215
+ /** A book's layout as steps: each yields the chapters to lay out now and
216
+ * takes their records, and the last returns the documents. `speculate`:
217
+ * a step may hold every chapter whose layout is not known, the ones after
218
+ * the first laid out on a guess of the pages before them. */
219
+ function bundleLayout(bundle, options, speculate, pageHints) {
105
220
  const { config: configOverride, cache: sharedCache, onChapter, metadata: givenMetadata, layoutCache, ...buildOptions } = options;
106
221
  const config = configOverride ?? bundle.config;
107
222
  const resources = [...(bundle.resources ?? [])];
108
223
  const cache = sharedCache ?? createMeasurementCache();
109
- const chapters = bundle.chapters;
110
- // The book's metadata: the first chapter's front matter over the given
111
- // values. Later chapters' front matter is not the book's.
112
- const first = chapters[0];
113
- const metadata = { ...(givenMetadata ?? {}), ...(first ? extractFrontmatter(first.markdown).metadata : {}) };
114
- const sources = chapters.map((c, index) => (index === 0 ? c.markdown : blankFrontmatter(c.markdown)));
115
- // Without a cache of its own, the build still keeps the chapters a round
116
- // of the contents leaves as they were for the next round.
117
- const build = beginLayoutBuild(layoutCache ?? createBundleLayoutCache(), jsonKey([config, resources.map(layoutFields), metadata]));
118
- // A chapter printing the contents (`:::toc`) or the index (`:::index`)
119
- // reads the whole book's outline; so does one whose references name
120
- // anchors, which may lie in another chapter (#262).
121
- const hasToc = sources.map((markdown) => build.derive(`toc\u0000${markdown}`, () => {
122
- const { hasToc: toc, hasIndex, hasRefs } = contentOutline({ markdown, resources }, config);
123
- return toc || hasIndex || hasRefs;
124
- }));
125
- const anyToc = hasToc.some(Boolean);
126
- // The page fences of the chapters after each chapter (#943): where a
127
- // story of a composed page may jump to. A book whose configuration names
128
- // no `page:` target keeps none, and a chapter without a composed page
129
- // does not depend on them.
130
- const jumpsPossible = (jsonKey(config) ?? '').includes('page:');
131
- let chain;
132
- // Where the book starts: the pages before it and the numbering in effect
133
- // are the first chapter's alone (the chain supplies them from then on),
134
- // the counters and the open part are what every chapter after it counts
135
- // on from.
136
- const start = bundleStart(bundle.start);
137
- const { pageIndexOffset: startOffset = 0, pageNumbering: _startNumbering, ...startCounters } = start ?? {};
138
- void _startNumbering;
139
- // A chapter's page fences are read in its own style: the one it names,
140
- // or the one of the part it is in (#1521), which may give it the
141
- // templates its pages name.
142
- const laterIds = jumpsPossible
143
- ? laterPageIdsOf(sources.map((markdown, index) => {
144
- if (!hasComposedPage(markdown))
145
- return [];
146
- const before = inherited(index);
147
- return build.derive(`ids\u0000${before?.part?.style ?? ''}\u0000${markdown}`, () => pageFenceIds(markdown, config, before));
148
- }))
149
- : undefined;
150
- /** What each chapter needs of `laterIds` to be laid out: only the
151
- * chapters with a composed page jump. */
152
- const laterIdsOf = (index) => laterIds && hasComposedPage(sources[index]) && Object.keys(laterIds[index]).length > 0 ? laterIds[index] : undefined;
153
- // Citations are numbered and listed across the book (#272): each chapter
154
- // is formatted against the book's references and citations.
155
- // Every chapter's front matter counts here (its references), not only
156
- // the first's.
157
- const citationSources = chapters.map((c, index) => build.derive(`cite\u0000${index === 0 ? 1 : 0}\u0000${c.markdown}`, () => {
158
- try {
159
- return citationSourceOf(c.markdown);
224
+ const context = { config, resources, cache, options: buildOptions };
225
+ return { context, steps: steps() };
226
+ function* steps() {
227
+ const chapters = bundle.chapters;
228
+ // The book's metadata: the first chapter's front matter over the given
229
+ // values. Later chapters' front matter is not the book's.
230
+ const first = chapters[0];
231
+ const metadata = { ...(givenMetadata ?? {}), ...(first ? extractFrontmatter(first.markdown).metadata : {}) };
232
+ const sources = chapters.map((c, index) => (index === 0 ? c.markdown : blankFrontmatter(c.markdown)));
233
+ // Without a cache of its own, the build still keeps the chapters a round
234
+ // of the contents leaves as they were for the next round.
235
+ const build = beginLayoutBuild(layoutCache ?? createBundleLayoutCache(), jsonKey([config, resources.map(layoutFields), metadata]));
236
+ // A chapter printing the contents (`:::toc`) or the index (`:::index`)
237
+ // reads the whole book's outline; so does one whose references name
238
+ // anchors, which may lie in another chapter (#262).
239
+ const lap = perfLap();
240
+ const hasToc = sources.map((markdown) => build.derive(`toc\u0000${markdown}`, () => {
241
+ const { hasToc: toc, hasIndex, hasRefs } = contentOutline({ markdown, resources }, config);
242
+ return toc || hasIndex || hasRefs;
243
+ }));
244
+ const anyToc = hasToc.some(Boolean);
245
+ lap('bundle.flags');
246
+ // The page fences of the chapters after each chapter (#943): where a
247
+ // story of a composed page may jump to. A book whose configuration names
248
+ // no `page:` target keeps none, and a chapter without a composed page
249
+ // does not depend on them.
250
+ const jumpsPossible = (jsonKey(config) ?? '').includes('page:');
251
+ let chain;
252
+ // Where the book starts: the pages before it and the numbering in effect
253
+ // are the first chapter's alone (the chain supplies them from then on),
254
+ // the counters and the open part are what every chapter after it counts
255
+ // on from.
256
+ const start = bundleStart(bundle.start);
257
+ const { pageIndexOffset: startOffset = 0, pageNumbering: _startNumbering, ...startCounters } = start ?? {};
258
+ void _startNumbering;
259
+ // A chapter's page fences are read in its own style: the one it names,
260
+ // or the one of the part it is in (#1521), which may give it the
261
+ // templates its pages name.
262
+ const laterIds = jumpsPossible
263
+ ? laterPageIdsOf(sources.map((markdown, index) => {
264
+ if (!hasComposedPage(markdown))
265
+ return [];
266
+ const before = inherited(index);
267
+ return build.derive(`ids\u0000${before?.part?.style ?? ''}\u0000${markdown}`, () => pageFenceIds(markdown, config, before));
268
+ }))
269
+ : undefined;
270
+ /** What each chapter needs of `laterIds` to be laid out: only the
271
+ * chapters with a composed page jump. */
272
+ const laterIdsOf = (index) => laterIds && hasComposedPage(sources[index]) && Object.keys(laterIds[index]).length > 0 ? laterIds[index] : undefined;
273
+ lap('bundle.pageIds');
274
+ // Citations are numbered and listed across the book (#272): each chapter
275
+ // is formatted against the book's references and citations.
276
+ // Every chapter's front matter counts here (its references), not only
277
+ // the first's.
278
+ const citationSources = chapters.map((c, index) => build.derive(`cite\u0000${index === 0 ? 1 : 0}\u0000${c.markdown}`, () => {
279
+ try {
280
+ return citationSourceOf(c.markdown);
281
+ }
282
+ catch {
283
+ // Front matter the YAML reader rejects counts for nothing.
284
+ return citationSourceOf(sources[index]);
285
+ }
286
+ }));
287
+ const citations = citationSources.some((s) => needsCitationContext(s.blocks, s.metadata))
288
+ ? bookCitationContexts(citationSources, resources)
289
+ : undefined;
290
+ build.bookInputs(jsonKey(sharedCitationKey(citations?.[0])));
291
+ lap('bundle.citations');
292
+ // `{bookTotalPages}` needs the page count of the whole book, known once
293
+ // every chapter is laid out: the book goes round once more with it. It
294
+ // never moves a page break, so one more round settles it.
295
+ const usesBookTotal = configUsesPlaceholder(config, 'bookTotalPages');
296
+ // The contents before any chapter is laid out (#787): every chapter's
297
+ // headings, parts and anchors, numbered as the book numbers them, without
298
+ // their pages. A contents chapter set with it takes, but for its page
299
+ // labels, the room it takes in the end, so the chapters after it are laid
300
+ // out at their final pages on the first round instead of once short of
301
+ // them and again (Terapia Ocupacional laid 120 chapters out for its 62).
302
+ // The rounds then settle the labels as before.
303
+ let outline = anyToc ? provisionalOutline() : undefined;
304
+ lap('bundle.provisionalOutline');
305
+ let bookPageCount;
306
+ /** The last record each chapter was given in a walk laid out several
307
+ * chapters at a time: what the chapters after it take it to give until
308
+ * it is laid out on the chain. */
309
+ /** By chapter, for each side it may start on (the pages before it even
310
+ * or odd): a chapter's pages may depend on the side in ways no rule
311
+ * here knows (a float that falls on another page), so the layout on
312
+ * the same side is the one read when there is one. */
313
+ const guesses = [];
314
+ const guessFor = (index, physical) => guesses[index]?.[physical % 2] ?? guesses[index]?.[1 - (physical % 2)];
315
+ /** Each chapter as the last settled walk asked for it. */
316
+ let lastJobs = [];
317
+ for (let round = 0;; round++) {
318
+ if (round > 0)
319
+ build.nextRound();
320
+ const outlineText = outline ? jsonKey(outline) : '';
321
+ const total = bookPageCount !== undefined ? { bookPageCount } : {};
322
+ const roundOutline = outline;
323
+ /** Chapters with no key, laid out on the round's settled chain: their
324
+ * record stands for the rest of the round. */
325
+ const unkeyed = new Map();
326
+ // Stories that jump between chapters are sent on by the chapter laid
327
+ // out, not by a guess of it.
328
+ const guessing = speculate && !laterIds;
329
+ let records = [];
330
+ let settled = [];
331
+ // The chain, walked until every chapter stands on a record laid out
332
+ // with the continuation the chain gives it. A walk of `buildBundle`
333
+ // lays each chapter out as it reaches it, so its first is its last.
334
+ for (let walk = 0;; walk++) {
335
+ records = [];
336
+ settled = [];
337
+ const jobs = [];
338
+ const asked = [];
339
+ let counters = Object.keys(startCounters).length > 0 ? startCounters : undefined;
340
+ let physical = startOffset;
341
+ /** Stories that jump to a later chapter, by the chapter that has the
342
+ * page, in the order they were sent (#943). */
343
+ const incoming = new Map();
344
+ let next;
345
+ for (let index = 0; index < sources.length; index++) {
346
+ const markdown = sources[index];
347
+ const continuation = index === 0
348
+ ? (start || bookPageCount !== undefined ? { ...start, ...total } : undefined)
349
+ : { ...counters, pageIndexOffset: physical, ...(next ? { pageNumbering: next } : {}), ...(incoming.has(index) ? { jumps: incoming.get(index) } : {}), ...total };
350
+ // A story that came in refers to anchors of the book (#943).
351
+ const printsOutline = (hasToc[index] || (incoming.get(index) ?? []).some((j) => j.outline)) && roundOutline !== undefined;
352
+ const laterOf = laterIdsOf(index);
353
+ const key = printsOutline && outlineText === undefined ? undefined : chapterKey(markdown, continuation, printsOutline ? outlineText : '', citations?.[index], laterOf);
354
+ const job = {
355
+ index, markdown, metadata,
356
+ ...(continuation ? { continuation } : {}),
357
+ ...(printsOutline ? { outline: roundOutline } : {}),
358
+ ...(citations ? { citations: citations[index] } : {}),
359
+ ...(laterOf ? { laterPageIds: laterOf } : {}),
360
+ };
361
+ asked.push(job);
362
+ // Whether the chapters before this one all stand on their records.
363
+ const exact = jobs.length === 0;
364
+ let record = build.peek(key) ?? (exact ? unkeyed.get(index) : undefined);
365
+ let link = record;
366
+ if (!record) {
367
+ if (exact && (!guessing || walk >= MAX_SPECULATIONS || key === undefined)) {
368
+ // Laid out now, alone: the chain goes on from its record.
369
+ const [made] = yield [job];
370
+ link = record = build.put(key, made);
371
+ if (key === undefined)
372
+ unkeyed.set(index, record);
373
+ }
374
+ else if (guessing && key !== undefined && walk < MAX_SPECULATIONS) {
375
+ // Laid out with the others of this walk; the chapters after
376
+ // it go on from what its last layout says of it.
377
+ jobs.push({ job, key, physical, startAt: next?.startAt, format: next?.format });
378
+ link = linkFrom(guessFor(index, physical), physical, next, pageHints?.[index]);
379
+ }
380
+ else {
381
+ // A chapter that cannot wait for the others: the walk ends
382
+ // here and the next one reaches it on settled records.
383
+ break;
384
+ }
385
+ }
386
+ if (record) {
387
+ if (jobs.length === 0)
388
+ settled.push({ key, record });
389
+ records.push(record);
390
+ }
391
+ // The stories this chapter sends to a page of a later one.
392
+ for (const jump of link.jumps ?? []) {
393
+ const to = laterIds?.[index] && Object.prototype.hasOwnProperty.call(laterIds[index], jump.target) ? laterIds[index][jump.target] : undefined;
394
+ if (to === undefined)
395
+ continue;
396
+ const list = incoming.get(to) ?? [];
397
+ list.push({ ...jump, chapter: jump.chapter ?? index, fromChapter: index });
398
+ incoming.set(to, list);
399
+ }
400
+ physical += link.pageCount;
401
+ if (link.next)
402
+ next = link.next;
403
+ const before = counters;
404
+ const beforeKey = jsonKey(before);
405
+ counters = build.derive(beforeKey === undefined ? undefined : `next\u0000${beforeKey}\u0000${markdown}`, () => perfTimed('bundle.continuation', () => continuationAfter({ markdown, resources }, config, before)));
406
+ }
407
+ if (jobs.length === 0 && records.length === sources.length) {
408
+ lastJobs = asked;
409
+ break;
410
+ }
411
+ const made = yield jobs.map((j) => j.job);
412
+ jobs.forEach((j, i) => {
413
+ const guess = { record: build.put(j.key, made[i]), physical: j.physical, startAt: j.startAt, format: j.format };
414
+ (guesses[j.job.index] ??= [undefined, undefined])[j.physical % 2] = guess;
415
+ });
416
+ }
417
+ build.settle(settled);
418
+ const physical = startOffset + records.reduce((n, r) => n + r.pageCount, 0);
419
+ // Another round for the contents while their page labels move (at
420
+ // most MAX_ROUNDS layouts), and for the book's page count while the
421
+ // one printed is not the one laid out (at most one more).
422
+ let outlineMoved = false;
423
+ if (anyToc) {
424
+ // The index marks, anchors and headings written in the part of a story
425
+ // that went on in a page of a later chapter are listed where they
426
+ // stand (#988).
427
+ const outlines = laterIds ? mergeCarriedOutline(records.map((r) => r.outline), records.map((r) => r.carried)) : records.map((r) => r.outline);
428
+ const bookOutline = records.flatMap((record, index) => {
429
+ const entries = outlines[index];
430
+ // A part that reached no page of its chapter — set without a
431
+ // divider page (`parts.page: false`) by a fence closing the
432
+ // chapter — starts with the next chapter's content, as its running
433
+ // heads do.
434
+ if (!entries.some((e) => e.kind === 'part' && e.pageIndex === undefined))
435
+ return entries;
436
+ const next = records.slice(index + 1).map((r) => r.firstContent).find((p) => p !== undefined);
437
+ return next ? entries.map((e) => (e.kind === 'part' && e.pageIndex === undefined ? { ...e, ...next } : e)) : entries;
438
+ });
439
+ outlineMoved = !outline || outlineKey(outline) !== outlineKey(bookOutline);
440
+ // The first round laid the contents out from the provisional outline,
441
+ // which has no pages: always lay the book out once more with them.
442
+ if (outlineMoved)
443
+ outline = bookOutline;
444
+ }
445
+ const totalMoved = usesBookTotal && bookPageCount !== physical;
446
+ if (usesBookTotal)
447
+ bookPageCount = physical;
448
+ const again = (outlineMoved && round + 1 < MAX_ROUNDS) || (totalMoved && round + 1 < MAX_ROUNDS + 1);
449
+ if (!again)
450
+ break;
160
451
  }
161
- catch {
162
- // Front matter the YAML reader rejects counts for nothing.
163
- return citationSourceOf(sources[index]);
452
+ // A record kept from an earlier round without its document.
453
+ const lost = build.lost();
454
+ if (lost.length > 0) {
455
+ const again = yield lost.map((index) => lastJobs[index]);
456
+ lost.forEach((index, i) => build.putBack(index, again[i]));
164
457
  }
165
- }));
166
- const citations = citationSources.some((s) => needsCitationContext(s.blocks, s.metadata))
167
- ? bookCitationContexts(citationSources, resources)
168
- : undefined;
169
- build.bookInputs(jsonKey(sharedCitationKey(citations?.[0])));
170
- // `{bookTotalPages}` needs the page count of the whole book, known once
171
- // every chapter is laid out: the book goes round once more with it. It
172
- // never moves a page break, so one more round settles it.
173
- const usesBookTotal = configUsesPlaceholder(config, 'bookTotalPages');
174
- // The contents before any chapter is laid out (#787): every chapter's
175
- // headings, parts and anchors, numbered as the book numbers them, without
176
- // their pages. A contents chapter set with it takes, but for its page
177
- // labels, the room it takes in the end, so the chapters after it are laid
178
- // out at their final pages on the first round instead of once short of
179
- // them and again (Terapia Ocupacional laid 120 chapters out for its 62).
180
- // The rounds then settle the labels as before.
181
- let outline = anyToc ? provisionalOutline() : undefined;
182
- let bookPageCount;
183
- for (let round = 0;; round++) {
184
- if (round > 0)
185
- build.nextRound();
186
- const records = [];
187
- const outlineText = outline ? jsonKey(outline) : '';
188
- let counters = Object.keys(startCounters).length > 0 ? startCounters : undefined;
189
- let physical = startOffset;
190
- /** Stories that jump to a later chapter, by the chapter that has the
191
- * page, in the order they were sent (#943). */
192
- const incoming = new Map();
193
- let next;
194
- const total = bookPageCount !== undefined ? { bookPageCount } : {};
195
- sources.forEach((markdown, index) => {
196
- const continuation = index === 0
197
- ? (start || bookPageCount !== undefined ? { ...start, ...total } : undefined)
198
- : { ...counters, pageIndexOffset: physical, ...(next ? { pageNumbering: next } : {}), ...(incoming.has(index) ? { jumps: incoming.get(index) } : {}), ...total };
199
- // A story that came in refers to anchors of the book (#943).
200
- const printsOutline = (hasToc[index] || (incoming.get(index) ?? []).some((j) => j.outline)) && outline !== undefined;
201
- const laterOf = laterIdsOf(index);
202
- const key = printsOutline && outlineText === undefined ? undefined : chapterKey(markdown, continuation, printsOutline ? outlineText : '', citations?.[index], laterOf);
203
- const record = build.chapter(key, () => {
204
- const doc = buildDocument({ markdown, metadata, resources, ...(continuation ? { continuation } : {}), ...(printsOutline ? { outline } : {}), ...(citations ? { citations: citations[index] } : {}), ...(laterOf ? { laterPageIds: laterOf } : {}) }, config, cache, buildOptions);
205
- const last = doc.pages[doc.pages.length - 1];
206
- const firstContent = firstContentPage(doc);
207
- return {
208
- doc,
209
- ...(doc.pendingJumps ? { jumps: doc.pendingJumps } : {}),
210
- pageCount: doc.pages.length,
211
- ...(last ? { next: { startAt: last.pageNumberValue + 1, format: last.pageNumberFormat } } : {}),
212
- outline: outlineFromDoc(doc, contentOutline({ markdown }, config, continuation).outline),
213
- ...(doc.carriedOutline ? { carried: carriedPlaces(doc) } : {}),
214
- ...(firstContent ? { firstContent } : {}),
215
- };
216
- });
217
- records.push(record);
218
- // The stories this chapter sends to a page of a later one.
219
- for (const jump of record.jumps ?? []) {
220
- const to = laterIds?.[index] && Object.prototype.hasOwnProperty.call(laterIds[index], jump.target) ? laterIds[index][jump.target] : undefined;
221
- if (to === undefined)
222
- continue;
223
- const list = incoming.get(to) ?? [];
224
- list.push({ ...jump, chapter: jump.chapter ?? index, fromChapter: index });
225
- incoming.set(to, list);
226
- }
227
- physical += record.pageCount;
228
- if (record.next)
229
- next = record.next;
230
- const before = counters;
231
- const beforeKey = jsonKey(before);
232
- counters = build.derive(beforeKey === undefined ? undefined : `next\u0000${beforeKey}\u0000${markdown}`, () => continuationAfter({ markdown, resources }, config, before));
233
- });
234
- // Another round for the contents while their page labels move (at
235
- // most MAX_ROUNDS layouts), and for the book's page count while the
236
- // one printed is not the one laid out (at most one more).
237
- let outlineMoved = false;
238
- if (anyToc) {
239
- // The index marks, anchors and headings written in the part of a story
240
- // that went on in a page of a later chapter are listed where they
241
- // stand (#988).
242
- const outlines = laterIds ? mergeCarriedOutline(records.map((r) => r.outline), records.map((r) => r.carried)) : records.map((r) => r.outline);
243
- const bookOutline = records.flatMap((record, index) => {
244
- const entries = outlines[index];
245
- // A part that reached no page of its chapter — set without a
246
- // divider page (`parts.page: false`) by a fence closing the
247
- // chapter — starts with the next chapter's content, as its running
248
- // heads do.
249
- if (!entries.some((e) => e.kind === 'part' && e.pageIndex === undefined))
250
- return entries;
251
- const next = records.slice(index + 1).map((r) => r.firstContent).find((p) => p !== undefined);
252
- return next ? entries.map((e) => (e.kind === 'part' && e.pageIndex === undefined ? { ...e, ...next } : e)) : entries;
253
- });
254
- outlineMoved = !outline || outlineKey(outline) !== outlineKey(bookOutline);
255
- // The first round laid the contents out from the provisional outline,
256
- // which has no pages: always lay the book out once more with them.
257
- if (outlineMoved)
258
- outline = bookOutline;
458
+ const docs = build.finish();
459
+ // Stories that jump from one chapter to a page of another (#943): the
460
+ // marks that name the page print its number.
461
+ if (laterIds)
462
+ resolveJumpMarks(docs);
463
+ if (onChapter)
464
+ docs.forEach((doc, index) => onChapter(index, doc));
465
+ return docs;
466
+ /** Every chapter's outline entries as its text gives them, the counters
467
+ * chained from chapter to chapter as the rounds chain them. */
468
+ function provisionalOutline() {
469
+ return sources.flatMap((markdown, index) => contentOutline({ markdown, resources }, config, inherited(index)).outline);
259
470
  }
260
- const totalMoved = usesBookTotal && bookPageCount !== physical;
261
- if (usesBookTotal)
262
- bookPageCount = physical;
263
- const again = (outlineMoved && round + 1 < MAX_ROUNDS) || (totalMoved && round + 1 < MAX_ROUNDS + 1);
264
- if (!again)
265
- break;
266
- }
267
- const docs = build.finish();
268
- // Stories that jump from one chapter to a page of another (#943): the
269
- // marks that name the page print its number.
270
- if (laterIds)
271
- resolveJumpMarks(docs);
272
- if (onChapter)
273
- docs.forEach((doc, index) => onChapter(index, doc));
274
- return docs;
275
- /** Every chapter's outline entries as its text gives them, the counters
276
- * chained from chapter to chapter as the rounds chain them. */
277
- function provisionalOutline() {
278
- return sources.flatMap((markdown, index) => contentOutline({ markdown, resources }, config, inherited(index)).outline);
279
- }
280
- /** What chapter `index` inherits from the chapters before it, as the
281
- * first round chains it (the same keys, so the round finds them): its
282
- * counters and the part it is in. Chained once, on first use. */
283
- function inherited(index) {
284
- if (!chain) {
285
- chain = [];
286
- let before = Object.keys(startCounters).length > 0 ? startCounters : undefined;
287
- for (const markdown of sources) {
288
- const prior = before;
289
- chain.push(prior);
290
- const priorKey = jsonKey(prior);
291
- before = build.derive(priorKey === undefined ? undefined : `next\u0000${priorKey}\u0000${markdown}`, () => continuationAfter({ markdown, resources }, config, prior));
471
+ /** What chapter `index` inherits from the chapters before it, as the
472
+ * first round chains it (the same keys, so the round finds them): its
473
+ * counters and the part it is in. Chained once, on first use. */
474
+ function inherited(index) {
475
+ if (!chain) {
476
+ chain = [];
477
+ let before = Object.keys(startCounters).length > 0 ? startCounters : undefined;
478
+ for (const markdown of sources) {
479
+ const prior = before;
480
+ chain.push(prior);
481
+ const priorKey = jsonKey(prior);
482
+ before = build.derive(priorKey === undefined ? undefined : `next\u0000${priorKey}\u0000${markdown}`, () => continuationAfter({ markdown, resources }, config, prior));
483
+ }
292
484
  }
485
+ return chain[index];
293
486
  }
294
- return chain[index];
295
487
  }
296
488
  }
297
489
  //# sourceMappingURL=book.js.map