pretext-pdf 1.0.8 → 1.1.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 (43) hide show
  1. package/CHANGELOG.md +945 -869
  2. package/README.md +1 -1
  3. package/UPSTREAM.md +112 -0
  4. package/dist/cli.js +19 -19
  5. package/dist/measure-text.d.ts +1 -1
  6. package/dist/measure-text.d.ts.map +1 -1
  7. package/dist/measure-text.js +1 -1
  8. package/dist/measure-text.js.map +1 -1
  9. package/dist/rich-text.js +1 -1
  10. package/dist/rich-text.js.map +1 -1
  11. package/dist/vendor/pretext/analysis.d.ts +35 -0
  12. package/dist/vendor/pretext/analysis.d.ts.map +1 -0
  13. package/dist/vendor/pretext/analysis.js +1162 -0
  14. package/dist/vendor/pretext/analysis.js.map +1 -0
  15. package/dist/vendor/pretext/bidi.d.ts +2 -0
  16. package/dist/vendor/pretext/bidi.d.ts.map +1 -0
  17. package/dist/vendor/pretext/bidi.js +176 -0
  18. package/dist/vendor/pretext/bidi.js.map +1 -0
  19. package/dist/vendor/pretext/generated/bidi-data.d.ts +5 -0
  20. package/dist/vendor/pretext/generated/bidi-data.d.ts.map +1 -0
  21. package/dist/vendor/pretext/generated/bidi-data.js +980 -0
  22. package/dist/vendor/pretext/generated/bidi-data.js.map +1 -0
  23. package/dist/vendor/pretext/layout.d.ts +75 -0
  24. package/dist/vendor/pretext/layout.d.ts.map +1 -0
  25. package/dist/vendor/pretext/layout.js +448 -0
  26. package/dist/vendor/pretext/layout.js.map +1 -0
  27. package/dist/vendor/pretext/line-break.d.ts +43 -0
  28. package/dist/vendor/pretext/line-break.d.ts.map +1 -0
  29. package/dist/vendor/pretext/line-break.js +908 -0
  30. package/dist/vendor/pretext/line-break.js.map +1 -0
  31. package/dist/vendor/pretext/line-text.d.ts +5 -0
  32. package/dist/vendor/pretext/line-text.d.ts.map +1 -0
  33. package/dist/vendor/pretext/line-text.js +69 -0
  34. package/dist/vendor/pretext/line-text.js.map +1 -0
  35. package/dist/vendor/pretext/measurement.d.ts +31 -0
  36. package/dist/vendor/pretext/measurement.d.ts.map +1 -0
  37. package/dist/vendor/pretext/measurement.js +251 -0
  38. package/dist/vendor/pretext/measurement.js.map +1 -0
  39. package/dist/vendor/pretext/rich-inline.d.ts +53 -0
  40. package/dist/vendor/pretext/rich-inline.d.ts.map +1 -0
  41. package/dist/vendor/pretext/rich-inline.js +327 -0
  42. package/dist/vendor/pretext/rich-inline.js.map +1 -0
  43. package/package.json +212 -208
package/CHANGELOG.md CHANGED
@@ -1,869 +1,945 @@
1
- # Changelog
2
-
3
- <!-- markdownlint-disable MD024 -->
4
-
5
- All notable changes to pretext-pdf are documented here.
6
- Format: [Keep a Changelog 1.1.0](https://keepachangelog.com/en/1.1.0/)
7
-
8
- ---
9
-
10
- ## [1.0.8] — 2026-05-06
11
-
12
- Public API contract integrity: the `RenderOptions.logger` option now actually does what
13
- its JSDoc has always promised, and `@napi-rs/canvas` no longer auto-installs.
14
-
15
- ### Fixed
16
-
17
- - **`RenderOptions.logger` now routes warnings from asset loading and rendering** —
18
- Previously only validation warnings respected the `logger` option. Now all advisory
19
- warnings from `loadImages` (image load, image embed, QR/barcode/chart skipped, plugin
20
- loadAsset failed, watermark image skipped 7 call sites) and `renderDocument` (form
21
- field render failure) flow through `logger.warn` when one is provided. Bidi-js fallback
22
- warnings from RTL reordering remain on `console.warn`; the JSDoc on `RenderOptions.logger`
23
- has been updated to document the actual scope honestly.
24
-
25
- - **Missing `[pretext-pdf]` log prefix on bidi-js error path** — One `console.warn` in
26
- `measure-text.ts` was logging without the canonical `[pretext-pdf]` prefix, making it
27
- hard to identify the library as the source in consumer logs. Now consistent.
28
-
29
- ### Changed
30
-
31
- - **`@napi-rs/canvas` removed from `optionalDependencies`** Was double-listed in both
32
- `peerDependencies` (with `optional: true`) and `optionalDependencies`. The latter caused
33
- npm to attempt installing the native canvas binary on every install, including in
34
- edge/serverless environments where the platform may not be supported and the dep is
35
- not needed. Now only listed under `peerDependencies` — install it explicitly when you
36
- need SVG/QR/barcode/chart rasterization in Node.
37
-
38
- ### Documentation
39
-
40
- - **README — security callout for `allowedFileDirs`** — Added a prominent callout in the
41
- Quick Start section. The default behavior allows `image.src` and `svg.src` to read any
42
- absolute file path, which is a path-traversal vector when document JSON originates from
43
- user input or an LLM. The callout now appears immediately after the first `render()`
44
- example.
45
-
46
- ---
47
-
48
- ## [1.0.7] — 2026-05-05
49
-
50
- Picks up pretext fork v0.0.6-patched.2: 8 additional upstream PRs (11 total).
51
-
52
- ### Fixed
53
-
54
- - **German low opening quote `„` no longer breaks at line-start on hyphenation path** —
55
- `KINSOKU_START_FORBIDDEN` in `src/measure-text.ts` now includes U+201E (`„`), matching
56
- pretext PR #165 which fixed the non-hyphenation path. Previously `„` could appear
57
- at the start of a wrapped line when hyphenation was active.
58
-
59
- - **Currency symbols stay glued to adjacent numbers** — Upstream PR #105 (cherry-picked in
60
- `v0.0.6-patched.2`) prevents `$`, `€`, `£`, `₹` etc. from line-breaking away from
61
- the number they annotate.
62
-
63
- - **Trailing collapsible-space reconstruction fixed** Upstream PR #29 fix (extended in
64
- v0.0.6-patched.2): a word followed by a space that exactly fills `maxWidth` no longer
65
- drops the space from line boundary cursors, preventing Arabic/mixed-script text from
66
- losing inter-word spaces during reconstruction.
67
-
68
- ### Changed
69
-
70
- - **`@chenglou/pretext` dependency** Bumped from `v0.0.6-patched` to `v0.0.6-patched.2`
71
- (GitHub fork, 11 upstream PRs total). Adds: CJK overflow prevention (PR #132),
72
- fit-advance cache fix (PR #161), rich inline stats unification (PR #138),
73
- chunk layout side table O(1) lookup (PR #140), bidi surrogate handling (PR #3),
74
- skip no-op merge passes (PR #119), currency stickiness (PR #105),
75
- German quote fix (PR #165), and trailing-space reconstruction (PR #29).
76
-
77
- ---
78
-
79
- ## [1.0.6] — 2026-05-04
80
-
81
- Audit bug fixes: validator correctness, internal export hygiene, schema gaps, README accuracy.
82
-
83
- ### Fixed
84
-
85
- - **lineHeight upper-bound cap removed** — `validate()` no longer rejects `lineHeight > 20`. The
86
- field is in points (pt), not a multiplier; 36pt is valid for a large heading. The `> 20` cap in
87
- `paragraph`, `heading`, and `defaultParagraphStyle` validators has been removed. The lower-bound
88
- check (lineHeight >= fontSize) is preserved.
89
-
90
- - **form-field error messages use `${prefix}` format** — Error messages from the `form-field` case
91
- now follow the `content[N] (form-field): ...` format used by all other element types, instead of
92
- the old `[N] form-field.` prefix.
93
-
94
- - **`assertUnknownProps` hint punctuation fixed** The "unknown property" message previously
95
- produced `unknown property. did you mean "color"` (period before hint). Fixed to
96
- `unknown property; did you mean "color"` no period, semicolon separator.
97
-
98
- - **British "colour" "color" in JSDoc** Two `QrCodeElement` field comments
99
- (`foreground`, `background`) and the `ValidationError.path` JSDoc example corrected.
100
-
101
- - **`TocEntryElement`, `RichLine`, `RichFragment` removed from public exports** — These types are
102
- marked `@internal` in `types-public.ts` and should not be part of the npm API surface. Removed
103
- from `src/index.ts`.
104
-
105
- - **Signature error includes original cause** — `SIGNATURE_FAILED` now preserves the underlying
106
- error message: `PDF signing failed: <original message>` instead of a static string.
107
-
108
- - **Header-only table now valid** — `validate()` previously rejected tables where all rows are
109
- headers (`headerRowCount === rows.length`). Changed `>=` to `>`: tables where every row is a
110
- header are valid (useful for column-label-only tables).
111
-
112
- - **Dead sub-condition removed in `float-group` floatWidth guard** — `fg.floatWidth <= 0` was a
113
- dead branch (any value `<= 0` is already `< 30`). Removed to clarify intent.
114
-
115
- - **`warningCount` JSDoc updated** — Documents that the validator currently only emits errors, so
116
- `warningCount` is always 0 (reserved for future use).
117
-
118
- - **`validateDocument` no longer re-throws unexpected errors** Non-`PretextPdfError` exceptions
119
- (e.g. circular JSON, unexpected runtime errors) are now caught and returned as a structured
120
- `ValidationResult` instead of propagating. `validateDocument` now always returns, never throws.
121
-
122
- ### Changed (Schema additions — `pretext-pdf/schema`)
123
-
124
- - `qrCodeSchema`: added `margin` field.
125
- - `imageSchema`: added `floatFontSize`, `floatFontFamily`, `floatColor` fields.
126
- - `codeSchema`: added `dir` and `highlightTheme` fields.
127
- - `tableSchema`: added `dir`, `headerRows`, and cell-level `dir`, `fontFamily`, `fontSize`,
128
- `tabularNumbers` fields.
129
-
130
- ### Docs
131
-
132
- - README: `highlight.js` added to optional peer dependencies table.
133
- - README: `validate_document` added to MCP server tool list.
134
-
135
- ---
136
-
137
- ## [1.0.5] 2026-05-04
138
-
139
- Schema coverage completion, `ValidationResult.warningCount`, and README API docs.
140
-
141
- ### Added
142
-
143
- - **`ValidationResult.warningCount`** — `validateDocument()` now returns `warningCount` alongside
144
- `errorCount`. Computed by filtering `errors[]` by `severity === 'warning'`. MCP consumers no
145
- longer need to derive it client-side.
146
-
147
- - **JSON Schema: remaining field coverage** `src/schema.ts` now covers all previously missing
148
- fields across 9 element types:
149
- - `inlineSpanSchema`: `dir`
150
- - `paragraphSchema`: `columns`, `columnGap`, `tabularNumbers`, `hyphenate`
151
- - `headingSchema`: `tabularNumbers`, `hyphenate`
152
- - `blockquoteSchema`: `lineHeight`, `padding`, `paddingH`, `paddingV`, `underline`, `strikethrough`
153
- - `calloutSchema`: `titleColor`, `fontWeight`, `lineHeight`, `padding`, `paddingH`, `paddingV`
154
- - `listSchema`: `lineHeight`, `markerWidth`, `itemSpaceAfter`, `nestedNumberingStyle`; nested
155
- items now carry `dir` and have a typed inner schema
156
- - `tocSchema`: `titleFontSize`, `levelIndent`, `leader`, `entrySpacing`
157
- - `formFieldSchema`: `borderColor`, `backgroundColor`, `keepTogether`, `defaultSelected`
158
- - `richParagraphSchema`: `columns`, `columnGap`, `tabularNumbers`
159
-
160
- - **README: `validateDocument` and `pretext-pdf/schema` documented** — both entry points now have
161
- `### API reference` sections with code examples.
162
-
163
- ---
164
-
165
- ## [1.0.4] — 2026-05-04
166
-
167
- Schema export hardening: post-release audit fixes addressing coverage gaps and a
168
- malformed dialect URI.
169
-
170
- ### Fixed
171
-
172
- - **`pretext-pdf/schema`: `$schema` dialect URI corrected**was
173
- `https://json-schema.org/draft/2020-12` (not a registered URI), now
174
- `https://json-schema.org/draft/2020-12/schema`. Strict JSON Schema validators
175
- (AJV, Smithery, VS Code) will now correctly identify the dialect.
176
- - **`pretext-pdf/schema`: `hr` element spacing fields** — `spaceAbove` and
177
- `spaceBelow` (the primary documented fields, default 12) were missing.
178
- `spaceBefore` and `spaceAfter` are now correctly marked as aliases.
179
- - **`pretext-pdf/schema`: `float-group` and `chart` element types** — both
180
- first-class public element types were missing from the `content.items.anyOf`
181
- list. Schema-driven tooling will now know they exist.
182
-
183
- ### Added (schema coverage)
184
-
185
- - `pdfDocumentSchema.sections` page-range header/footer overrides
186
- - `headingSchema.annotation` annotation field (was already on paragraph)
187
- - `tableSchema.cellPaddingH` / `cellPaddingV` — primary table density controls
188
- - `imageSchema.floatWidth` / `floatGap` / `floatSpans` column-layout controls
189
- for floated images
190
-
191
- ---
192
-
193
- ## [1.0.3] — 2026-05-03
194
-
195
- Enhancements: JSON Schema export, simplified marked peer dep range, and internal API polish.
196
-
197
- ### Added
198
-
199
- - **`pretext-pdf/schema` entry point** — exports `pdfDocumentSchema`, a machine-readable JSON Schema
200
- object describing the full `PdfDocument` type. Covers all 22 element types and 18 top-level
201
- document properties. Intended for editor tooling, MCP clients, and Smithery UI form generation.
202
-
203
- ```typescript
204
- import { pdfDocumentSchema } from 'pretext-pdf/schema'
205
- ```
206
-
207
- ### Changed
208
-
209
- - **`marked` peer dependency simplified** `^9.0.0 || ^10.0.0 || ... || ^18.0.0` condensed to
210
- `>=9.0.0`. Semantically identical, cleaner npm output.
211
-
212
- - **`validateDocument` logger option** — `options.logger` now passed to the underlying `validate()`
213
- call via conditional spread, respecting `exactOptionalPropertyTypes: true` constraints.
214
-
215
- ### Fixed
216
-
217
- - **`fonts.ts` unsafe cast removed** — `(spec as { style?: string }).style` replaced with direct
218
- property access on the widened parameter type.
219
-
220
- ---
221
-
222
- ## [1.0.2] — 2026-05-03
223
-
224
- ### Added
225
-
226
- - `validateDocument(doc, options?)` — non-throwing validation API that returns a structured `ValidationResult` with typed `ValidationError[]` instead of throwing. Each error includes `path`, `message`, `code`, `severity`, and `suggestion` fields.
227
- - `ValidationError` and `ValidationResult` exported from the public API surface.
228
- - `Logger` interface and `logger?: Logger` in `RenderOptions` — route diagnostic warnings through a custom logger instead of `console.warn`.
229
- - Inter italic font support (Inter-400-italic, Inter-700-italic) via bundled `@fontsource/inter` — italic markdown and `fontStyle: 'italic'` now work without manual font setup.
230
-
231
- ---
232
-
233
- ## [1.0.1] 2026-05-02
234
-
235
- Patch: strict mode correctness fixes. No API changes.
236
-
237
- ### Fixed
238
-
239
- - **`levenshteinDist` early-exit bug** — per-cell `if (curr[j]! > 2) return 999` inside
240
- the inner DP loop fired on intermediate cells, causing d=1 pairs like `hrefs→href` and
241
- `spaceafter→spaceAfter` to incorrectly return 999 instead of 1. Fix: removed the per-cell
242
- guard; final check only (`prev[n]! > 2 ? 999 : prev[n]!`).
243
- - **Seven path-prefix annotations** strict-mode error paths had `(type)` suffixes
244
- (e.g. `doc(table).rows[0]`) that no other validator used and that tests didn't expect.
245
- All seven removed so paths are plain dot-notation.
246
- - **`encryption` block not strict-checked** — unknown props inside `doc.encryption`
247
- were silently accepted in strict mode. Now validated against `ALLOWED_PROPS_SUB['encryption']`.
248
- - **Root path was `'document'` not `'doc'`** top-level `assertUnknownProps` was called
249
- with `'document'` as the path prefix, producing paths like `document.content[0]` instead
250
- of `doc.content[0]`. Corrected to `'doc'`.
251
- - **Suggestion format mismatched** `Did you mean 'x'?` → `did you mean "x"` (lowercase,
252
- double-quotes) to match the format tests asserted.
253
- - **`formatErrors` missing header** multi-error output now begins with
254
- `Strict validation failed (N issues):\n` so callers can detect strict vs. regular errors.
255
-
256
- ### Tests
257
-
258
- - Added `test/validate-strict.test.ts` (35 tests) to `test:unit` script — these tests were
259
- written but not wired into CI in v1.0.0.
260
-
261
- ---
262
-
263
- ## [1.0.0]2026-05-02
264
-
265
- First stable release. Completes the plugin extension API, closes all v1.0 gate requirements,
266
- and ships a fully verified public surface with zero breaking changes from 0.9.x.
267
-
268
- ### Added
269
-
270
- - **Plugin extension API** — Register custom element types via `RenderOptions.plugins`.
271
- Each `PluginDefinition` participates in all four pipeline stages: `validate`, `loadAsset`,
272
- `measure`, and `render`. Plugins are fully typed and tree-shaken from documents
273
- that don't use them. See README § Custom element types (plugins) and
274
- `examples/plugin-custom-element.ts` for a runnable example.
275
- - **`PluginDefinition`, `PluginMeasureContext`, `PluginMeasureResult`, `PluginRenderContext`**
276
- exported from `pretext-pdf` public surface (previously internal).
277
- - **`PdfBuilder` and `PdfBuilderOptions`** exported from `pretext-pdf` (enables type-safe
278
- builder construction in downstream code without re-declaring the interface).
279
- - **`TocEntryElement`** exported from `pretext-pdf` public surface (was in the `ContentElement`
280
- union but not individually importable).
281
- - **`plugins` option on `createPdf()`** — `PdfBuilderOptions.plugins` threads plugins through
282
- the builder's `build()` call automatically.
283
- - **`Intl.Segmenter` pre-flight guard** in `render()` — throws `RENDER_FAILED` with a clear
284
- message on Node.js < 16 or runtimes without full-ICU data, instead of silently producing
285
- incorrect line breaks.
286
- - **`PluginRenderContext.pageWidth/pageHeight/margins`** render hooks now receive full page
287
- geometry for layout calculations (page-relative positioning, bleed boxes, etc.).
288
- - **`render` context Y-coordinate docs** — expanded JSDoc with multi-line text example showing
289
- how to position text baselines relative to `context.y`.
290
- - **Benchmark corpora manifest** and **smoke staging** tests wired into `npm test`
291
- (previously orphaned).
292
- - **`test/table-determinism.test.ts`** — asserts that table pagination produces identical
293
- layout traces across repeated invocations of `prepareLayoutState`.
294
- - **`test/validate-strict.test.ts`** (35 tests) comprehensive contract for `strict: true`
295
- validation covering all element types, nested structures, Levenshtein suggestions, error
296
- message format, doc-level and sub-structure prop checks. Total test count: 676.
297
- - `examples/plugin-custom-element.ts` — runnable plugin example (`npm run example:plugin`).
298
-
299
- ### Fixed
300
-
301
- - **`SIGNATURE_CERT_AND_ENCRYPTION` error code** — was declared in the `ErrorCode` union
302
- but never thrown; validate.ts now uses it correctly when a document specifies both
303
- signatures and encryption (previously threw a generic `VALIDATION_ERROR`).
304
- - **Build break under `exactOptionalPropertyTypes: true`** `PdfBuilder.build()` no longer
305
- passes `{ plugins: undefined }` to `runPipeline` when no plugins are configured.
306
- - **Plugin `validate` hook empty-string normalization** — `plugin.validate()` returning `''`
307
- now correctly accepts the element (was previously treated as a rejection message).
308
- - **`toc` element reaching render default arm** — `render.ts` now has an explicit
309
- `case 'toc': return` guard before the default arm; TOC elements are pre-processed
310
- during pagination and should never reach the renderer.
311
- - **`RichLine` and `RichFragment`** demoted from `@public` to `@internal`; these are
312
- implementation details of the rich-text pipeline, not intended for external use.
313
- - **Sentinel value documentation** — `MeasuredBlock` comment now explicitly states that
314
- `lines: []`, `fontSize: 0`, `lineHeight: 0`, `fontKey: ''` applies to spacers, tables,
315
- images, hr, *and plugin blocks* not a bug but a documented convention.
316
-
317
- ### Internal
318
-
319
- - `src/plugin-registry.ts` (new): Pure orchestration helpers for the four plugin injection
320
- points (`findPlugin`, `runPluginValidate`, `runPluginLoadAsset`, `runPluginMeasure`,
321
- `runPluginRender`).
322
- - `src/plugin-types.ts` (new): `PluginDefinition` interface and context/result types.
323
- - `src/layout-state.ts`: `prepareLayoutState` now accepts `options?: RenderOptions` and
324
- threads plugins to `stageValidate`, `stageLoadAssets`, and `stageMeasure`.
325
- - `docs/V1.0-RUNBOOK.md`: Full release runbook with first-principles audit, anti-hallucination
326
- protocol, verified-facts table, and phase-by-phase plan.
327
-
328
- ---
329
-
330
- ## [0.9.4] 2026-05-02
331
-
332
- > **Note:** This release was never published to npm as a standalone tag. All changes listed
333
- > here shipped as part of [1.0.0] on the same date.
334
-
335
- Architecture hardening + API surface snapshot. No public API changes; internal
336
- restructuring to eliminate circular dependencies and add drift guards before v1.0 freeze.
337
-
338
- ### Added
339
-
340
- - **API surface snapshot** (`etc/pretext-pdf.api.md`) checked into source control as
341
- the v1.0 baseline. The `api:check` CI step will fail on unintentional public-API drift.
342
- - **`src/layout-state.ts`** `prepareLayoutState()` and `summarizeLayoutState()` extracted
343
- from the pipeline for testability; `layout-contract` and `hard-text-contract` tests
344
- wired into `test:unit`.
345
- - **`src/benchmarks/corpora.ts`** — benchmark corpus manifest (`getBenchmarkCorpora()`)
346
- restored from git history; `benchmark-baseline.test.ts` wired into `test:contract`.
347
- - **Drift guards** (`test/drift-guards.test.ts`) asserts that `ELEMENT_TYPES`,
348
- `ALLOWED_PROPS`, `validate.ts` cases, and `render.ts` cases all agree at test time.
349
- Catches any future element-type addition that isn't plumbed through all four places.
350
- - **`render.ts` default arm** unknown element types now throw immediately instead of
351
- silently producing a blank block.
352
-
353
- ### Refactored
354
-
355
- - **Circular dependency broken**: `src/post-process.ts` extracted so `builder.ts` and
356
- `index.ts` no longer form a cycle through each other.
357
- - **`ELEMENT_TYPES` extracted** to `src/element-types.ts` as single source of truth;
358
- re-exported from `index.ts`, imported by `validate.ts` — eliminates the previous
359
- per-file string-literal duplication.
360
-
361
- ### Fixed
362
-
363
- - `post-process.ts`: drop raw signing library error message from `SIGNATURE_FAILED`
364
- to avoid leaking certificate or passphrase details in error output.
365
- - `layout-state.ts`: polyfill install wrapped in try/catch; throws `CANVAS_UNAVAILABLE`
366
- on failure instead of an untyped exception.
367
-
368
- ---
369
-
370
- ## [0.9.3]2026-04-23
371
-
372
- Strict validation release. Opt-in property validation to catch unknown properties on elements and sub-structures via typo detection and precise JSONPath error reporting.
373
-
374
- ### Added
375
-
376
- - **Strict validation mode**: Pass `{ strict: true }` to `render(doc, options)` to reject unknown properties. Non-strict mode (default) remains permissive for backwards compatibility.
377
- - **`render()` options parameter**: Updated signature to `render(doc: PdfDocument, options?: RenderOptions)` where `RenderOptions = { strict?: boolean }`.
378
- - **`validate()` public export**: `validate()` is now exported from `pretext-pdf` for standalone validation and testing.
379
- - **Validation error details**:
380
- - Unknown properties reported with Levenshtein edit-distance suggestions (distance ≤2) for typo correction.
381
- - Errors include JSONPath-like paths (`content[3].table.rows[0].cells[1].align`) for precise location reporting.
382
- - Error accumulation: all violations collected before throwing a single VALIDATION_ERROR with formatted multi-line message.
383
- - First 20 errors shown; overflow indicator present.
384
- - **Compile-time drift guards**: `src/allowed-props.ts` uses `Exact<T, Keys>` TypeScript type assertions to catch property definition drift at type-check time. If element types change, `tsc --noEmit` will error if allowed-props lists don't match.
385
- - **Property allowlists**:
386
- - `ALLOWED_PROPS`: 22 element types (paragraph, heading, table, image, code, list, etc.)
387
- - `ALLOWED_PROPS_SUB`: 8 sub-structures (document, metadata, table-row, table-cell, list-item, inline-span, column-def, annotation)
388
-
389
- ### Internal
390
-
391
- - `src/allowed-props.ts` (new): Central configuration for allowed properties with compile-time assertions.
392
- - `src/validate.ts` (enhanced): Added `levenshteinDist()`, `closestMatch()`, `assertUnknownProps()`, and `formatErrors()` helpers; threading strict flag through `validateElement()` for nested structure validation (tables, lists, rich-paragraphs, float-groups, annotations).
393
-
394
- ---
395
-
396
- ## [0.9.2] 2026-04-22
397
-
398
- Maintenance release. Engine refresh + repo-hygiene automation. No runtime behavior changes beyond the `@chenglou/pretext` bump.
399
-
400
- ### Changed
401
-
402
- - **Bumped `@chenglou/pretext` to 0.0.6** (from 0.0.5). Brings two upstream improvements: (a) CJK text followed by opening-bracket annotations now wraps like browsers instead of leaving the opening bracket on the previous line (upstream PR #148), (b) native numeric `letterSpacing` support on `prepare()` and `prepareWithSegments()` (upstream PRs #108/#156). Our manual letterSpacing compensation in `src/measure-blocks.ts` and `src/rich-text.ts` continues to work unchanged — delegating to pretext's native path is tracked as Tier 1 follow-up in `docs/ROADMAP.md`. All 624 tests green, all 5 visual regression baselines green.
403
-
404
- ### Fixed
405
-
406
- - **README badges matched to reality**: `runtime-deps-7` → `runtime-deps-8` (there are 8 direct `dependencies`, not 7), `tests-600+` → `tests-624` (the full `npm test` chain runs 624 tests across 5 subsuites). Drift guarded by a new CI step; see below.
407
-
408
- ### Added
409
-
410
- - `scripts/verify-badges.js` + CI step — compares README shields.io badge values against `package.json` dep count and `npm test` total. Fails CI on drift. Fast path via `SKIP_TEST_RUN=1` for pre-commit use.
411
- - `release` job in `ci.yml` — on `v*` tag push, auto-extracts the matching `## [X.Y.Z]` section from this file and creates the GitHub release (requires publish to succeed first). Closes the "tag exists but no release page" gap that affected v0.9.1. (Note: originally shipped as `.github/workflows/release-on-tag.yml`; merged into `ci.yml` for dependency ordering in Tier 0.5.)
412
- - `renovate.json` watches dependencies, auto-merges devDependency bumps that pass CI, opens PRs (without auto-merge) for runtime, peer, and `@chenglou/pretext` engine bumps. Closes the gap that left us one release behind upstream.
413
-
414
- ### Removed
415
-
416
- - `test/smoke-staging.test.ts` — exercised a non-existent `{ type: 'paragraph', footnote: {...} }` shape that the permissive validator silently accepted. False coverage. A strict validator rollout (rejecting unknown element properties) is the root fix and is tracked as a Tier 1 item in the rewritten `docs/ROADMAP.md`.
417
- - `src/brain/` inert auto-logger artifact (34 blank-body entries, no active writer). Never published to npm.
418
-
419
- ### Docs
420
-
421
- - `docs/ROADMAP.md`complete rewrite as a living document (Now / Next / Under consideration / Shipped / History + Update discipline). The previous "master remediation plan" with phase-numbered sections was dropped: phases 0–5 all shipped by v0.9.1, and the document had rotted to the point of contradicting `package.json` on dependency pinning and `CHANGELOG.md` on what was live. History section preserves the prior plan's origin date and scope for reference.
422
-
423
- ---
424
-
425
- ## [0.9.1] 2026-04-21
426
-
427
- Bug-fix + hardening release. Ships the callout + rich-text rendering fixes from PR #2 together with PR #3's producer-validator contract around measured blocks.
428
-
429
- ### Fixed
430
-
431
- - **Rich-paragraph: leading-space tokens stripped after hard break** ([src/rich-text.ts](src/rich-text.ts)). A pre-overflow guard (`isLeadingSpace: currentX === 0 && token.text.trim() === ''`) fired whenever `currentX` was zero — both at block start *and* after a `\n` hard break reset the cursor. Continuation spans beginning with whitespace (e.g. `' · text'`) had their first token silently dropped, causing separator glyphs and indented text to appear mis-positioned. Guard removed; the overflow-wrap skip path that correctly skips trailing spaces after soft wraps is unaffected.
432
- - **Callout: `spaceAfter` double-applied by paginator** ([src/measure-blocks.ts](src/measure-blocks.ts)). `callout` block measurement included `el.spaceAfter ?? 12` inside `totalHeight` *and* returned the same value as `block.spaceAfter`. `paginate.ts` added `block.spaceAfter` on top of `block.height`, counting it twice and pushing callout content ~12 pt below its intended position. Fixed by removing `spaceAfter` from the `totalHeight` formula; the value is still returned in `block.spaceAfter` for the paginator.
433
- - **Callout with title: background rect clips title row when split across pages** ([src/paginate.ts](src/paginate.ts)). `splitBlock` did not subtract `calloutData.titleHeight` from `availableForLines` for the first chunk, allowing `floor((titleH + lh) / lh)` extra lines to be placed, leaving no room for the title row. `getCurrentY` also omitted `titleHeight` from `blockBottom`, producing incorrect Y tracking after a split callout. Both fixed: `titleH` is now subtracted from available space on the first chunk only, and added to `blockBottom` when computing the cursor position after the first chunk renders.
434
-
435
- ### Added / hardened
436
-
437
- - **Producer-validator contract for measured blocks** ([src/paginate.ts](src/paginate.ts)). `validateMeasuredBlocks()` runs at `paginate()` entry in O(n) and throws `PretextPdfError('PAGINATION_FAILED')` if a callout `MeasuredBlock` is missing `calloutData` or any of `titleHeight` / `paddingV` / `paddingH` is non-finite — same for blockquote padding/border fields. Surfaces producer bugs directly instead of as downstream NaN arithmetic or `PAGE_LIMIT_EXCEEDED`.
438
- - **Narrowed internal types** `MeasuredCalloutBlock` / `MeasuredBlockquoteBlock` (intersection types in [src/types.ts](src/types.ts)) consumed by `calloutTitleHeight` + `verticalPadding` helpers in `paginate.ts`. No defensive runtime checks downstream.
439
- - **Extracted `CalloutData` interface** from the previously-inline shape on `MeasuredBlock.calloutData`. Measurer constructs it as a typed literal, so TypeScript enforces the full contract at the producer site.
440
- - **Zero-width non-whitespace tokens preserved**: the rich-text post-soft-wrap guard only skips tokens where `text.trim() === ''`. ZWJ (U+200D), combining marks, and other zero-width non-whitespace characters pass through so emoji / CJK shaping stays intact — pinned by a regression test.
441
- - **Extracted `LINK_COLOR_DEFAULT`** constant in `src/rich-text.ts`.
442
-
443
- ### Tests
444
-
445
- - `test/rich-text.test.ts` 20 → 23 (+3): block-start leading whitespace preserved; leading whitespace after hard break preserved; ZWJ preservation.
446
- - `test/phase-8d-callout.test.ts` 12 → 19 (+7): callout `spaceAfter` double-count regression, titled split line count, untitled split, continuation chunk `yFromTop === 0`, mid-page split entry, validator rejection on missing `calloutData`, validator rejection on partial `calloutData` (non-finite fields), validator rejection on partial blockquote padding, non-callout-document early-return.
447
- - Full suite: 624 tests, 100% pass.
448
-
449
- ### Chore / docs
450
-
451
- - Removed `brain/learnings/*.md`, `docs/PLAN-v0.6-v1.0.md`, `test/paginate.test.ts.archive` — internal dev artifacts not for the public repo.
452
- - Stripped `Phase N:` nomenclature from `src/` comments (pure rename no logic delta).
453
- - Added `demo/stackblitz/.stackblitzrc`, `docs/articles/pretext-pdf-vs-pdfmake-2026.md` (draft).
454
- - Added `examples/visual-pr2-bug1-separator.ts` + `examples/visual-pr2-bug3-callout-split.ts` plus 4 reference PNGs under `docs/visuals/pr2/` for bug-reproduction demonstrations.
455
- - README test badge corrected `650+ → 600+` (verified: 624 tests total).
456
-
457
- ---
458
-
459
- ## [0.9.0] 2026-04-20
460
-
461
- Three additive enhancements that broaden the package's surface without growing its mandatory dependency footprint.
462
-
463
- ### Added
464
-
465
- - **CLI binary** — `pretext-pdf` is now a `bin` entry. `pretext-pdf doc.json out.pdf`, `cat doc.json | pretext-pdf > out.pdf`, `echo '{...}' | pretext-pdf -o out.pdf`. Supports stdin/stdout and file arguments. `--markdown` flag converts Markdown input to PDF in one step (requires the `marked` peer dep). See [src/cli.ts](src/cli.ts).
466
- - **`pretext-pdf/compat` entry point** — `fromPdfmake(pdfmakeDoc)` translates pdfmake document descriptors into `PdfDocument` so existing pdfmake codebases can switch with a one-line change at the entry point. Covers strings, `text` nodes (with `style`/`bold`/`italics`/`color`/`fontSize`/`alignment`/`font`), `ul`/`ol`, `table` (with `widths` + `headerRows`), `image`, `qr`, `pageBreak` (`before`/`after`), `stack`, `pageSize`/`pageOrientation`/`pageMargins`, `defaultStyle`/`styles`, `info` → metadata, and string-form `header`/`footer`. Default style-name → heading mapping is configurable via `headingMap` option.
467
- - **Markdown: GFM tables** ([src/markdown.ts](src/markdown.ts)) — `markdownToContent()` now recognises GFM tables and translates them to `TableElement`, including column alignment from `:---:` / `---:` markers. Ragged rows are padded with empty cells.
468
- - **Markdown: GFM task lists** — `- [x] done` and `- [ ] todo` render with / Unicode markers prepended to the item text.
469
-
470
- ### Tests
471
-
472
- - New `test/v0.9.0-features.test.ts` (21 tests): markdown table + task list, full CLI exec coverage (stdin, file, `--markdown`, error paths), and pdfmake compat (strings, headings, rich-paragraphs, lists, tables, images, QR, `pageBreak`, `stack`, `pageSize`/`pageMargins`, end-to-end render of a translated document).
473
-
474
- ### Notes
475
-
476
- - Zero new mandatory dependencies. The CLI uses only Node built-ins. The compat shim is pure TypeScript. Markdown additions ride on the existing optional `marked` peer.
477
- - `dist/cli.js` is wired through `package.json#bin.pretext-pdf` — `npm install -g pretext-pdf` makes the CLI globally available; `npx pretext-pdf` works without install.
478
-
479
- ---
480
-
481
- ## [0.8.3] — 2026-04-20
482
-
483
- ### Security
484
-
485
- - **SSRF — IPv4-mapped IPv6 bypass** ([src/assets.ts](src/assets.ts) `assertSafeUrl`). Pre-0.8.3 the private-IP guard checked the parsed hostname against dotted-decimal regexes only. WHATWG `URL` normalizes `[::ffff:127.0.0.1]` to `[::ffff:7f00:1]` (hex IPv4-in-IPv6), so attacker-supplied URLs of the form `https://[::ffff:127.0.0.1]/admin` slipped past every `^127\.`/`^10\.`/etc. check and reached localhost or RFC 1918 ranges. Patched by detecting both the dotted (`::ffff:127.0.0.1`) and hex-compressed (`::ffff:7f00:1`) IPv4-mapped forms and decoding the embedded IPv4 before regex matching. Also explicitly blocks the IPv6 unspecified address `::`.
486
- - **SSRF — redirect-following bypass** ([src/assets.ts](src/assets.ts) `fetchWithTimeout`). The previous implementation used the default `redirect: 'follow'`, so a public URL could `302` to `http://127.0.0.1:8080/internal` and the library would happily fetch the private target despite the upfront `assertSafeUrl` check on the *initial* URL. Patched to use `redirect: 'manual'` and re-validate every `Location` hop with `assertSafeUrl`, capped at 3 redirects. Browser opaqueredirect responses are rejected with a clear error.
487
-
488
- ### Fixed
489
-
490
- - **`createGstInvoice` amount-in-words double space for sub-rupee totals** ([src/templates.ts](src/templates.ts)). An invoice whose total was less than ₹1 (e.g. ₹0.50) produced `"Rupees and Fifty Paise Only"` (two spaces after "Rupees") because the rupee-words branch resolved to an empty string. Now uses an explicit `"Zero"` when there are no rupees: `"Rupees Zero and Fifty Paise Only"`.
491
- - **Markdown deeper-than-2-level lists silently dropped** ([src/markdown.ts](src/markdown.ts) `convertListItem`). Pre-0.8.3 the converter only created text-only leaves for nested lists, so `- A\n - B\n - C` lost C entirely. Now recursive — preserves arbitrary nesting depth in the resulting `ListItem` tree.
492
- - **Markdown list items with paragraph-typed content** ([src/markdown.ts](src/markdown.ts)). When list items were separated by blank lines, marked emits `paragraph` tokens (not `text` tokens) for the item content. The converter only handled `text`, silently dropping the item text. Now also handles `paragraph` tokens.
493
-
494
- ### Tests
495
-
496
- - New `test/v0.8.3-ssrf.test.ts` covers 11 IPv4-mapped IPv6 bypass cases, IPv6 unspecified/loopback regressions, and HTTP rejection.
497
- - Extended `test/phase-10c-markdown.test.ts` with regressions for 3-level nesting and paragraph-typed list items.
498
- - Extended `test/phase-10d-templates.test.ts` with the sub-rupee amount-in-words case.
499
-
500
- ---
501
-
502
- ## [0.8.2] — 2026-04-20
503
-
504
- ### Fixed
505
-
506
- - **Rich-paragraph whitespace collapse** — multi-span `rich-paragraph` content rendered with adjacent words overlapping (e.g. `"Founder & CEO" + " — Antigravity Systems"` displayed as `"Founder& CEO—AntigravitySystems"`). Root cause: pretext's `layoutWithLines` follows CSS-like behavior and excludes trailing whitespace from line widths, so tokens like `"Hello "` or `" "` measured to width 0 and downstream fragments overlapped the previous one. `measureTokenWidth` in [src/rich-text.ts](src/rich-text.ts) now uses a sentinel-character technique (append non-whitespace `\u2588`, measure combined string, subtract sentinel width) to recover the true rendered width whenever a token has trailing whitespace. Sentinel width is cached per font config.
507
- - The fast path (no trailing whitespace) is unchangedsingle pretext call. Slow path adds two pretext calls per affected token, with one cached.
508
-
509
- ### Tests
510
-
511
- - Added 3 regression tests in `test/rich-text.test.ts` under `whitespace preservation (v0.8.2 fix)` covering trailing whitespace inside spans, whitespace-only separator spans, and the exact `"Founder & CEO" → "Antigravity Systems"` resume-preset scenario.
512
-
513
- ---
514
-
515
- ## [0.8.1] 2026-04-20
516
-
517
- ### Fixed
518
-
519
- - **Browser support** — `pretext-pdf` now imports cleanly in browsers. Module-init in `src/fonts.ts` previously called `fileURLToPath(import.meta.url)` and `createRequire(import.meta.url)` eagerly, which threw `"The URL must be of scheme file"` whenever the module was loaded from a non-`file://` URL (esm.sh, jsdelivr, Vite dev server). Both calls are now gated on a runtime `IS_NODE` check, and the bundled-Inter `BUNDLED_INTER_PATHS` arrays are constructed only in Node.
520
- - **Browser font-loading errors** — `loadFontBytes` now throws clear `FONT_LOAD_FAILED` messages when bundled Inter or string font paths are requested in a browser, pointing the consumer at the correct workaround (supply `Uint8Array` bytes via `doc.fonts`).
521
-
522
- ### Notes for browser users
523
-
524
- - Always supply Inter (or your default font) explicitly via `doc.fonts: [{ family: 'Inter', weight: 400, src: <Uint8Array> }, { family: 'Inter', weight: 700, src: <Uint8Array> }]`. The library cannot read local font files in the browser.
525
- - SVG / chart / qr-code / barcode elements still depend on `@napi-rs/canvas` at runtime; in the browser, the native `OffscreenCanvas` is used instead and the polyfill is skipped automatically.
526
-
527
- ---
528
-
529
- ## [0.8.0] 2026-04-19
530
-
531
- ### Added
532
-
533
- - **`qr-code` element** — generate QR codes as inline PDF content using the `qrcode` optional peer dependency. Supports `data`, `size`, `errorCorrectionLevel` (L/M/Q/H), `foreground`/`background` hex colours, `margin`, `align`, `spaceBefore`/`spaceAfter`. Fully serverless — pure JS, no canvas required.
534
- - **`barcode` element** — generate 100+ barcode symbologies (EAN-13, Code128, PDF417, QR, DataMatrix, etc.) via the `bwip-js` optional peer dependency. Supports `symbology`, `data`, `width`, `height`, `includeText`, `align`, `spaceBefore`/`spaceAfter`. Pure JS, Lambda/Edge safe.
535
- - **`chart` element** embed Vega-Lite charts as vector SVG using `vega` + `vega-lite` optional peer deps. Accepts any Vega-Lite `spec`, `width`, `height`, `caption`, `align`. Rendered with `renderer: 'none'` — zero canvas/puppeteer dependency.
536
- - **`pretext-pdf/markdown` entry point** — `markdownToContent(md, options?)` converts a Markdown string to `ContentElement[]`. Requires optional `marked` peer dep. Supports headings, bold/italic/links (→ rich-paragraph), lists (2 levels), blockquotes, code blocks, and HR.
537
- - **`pretext-pdf/templates` entry point** three typed template functions with zero extra dependencies: `createInvoice(data)` (generic invoice with currency, tax, discount, QR payment), `createGstInvoice(data)` (GST-compliant Indian tax invoice with IGST/CGST+SGST, UPI QR, bank details, amount in words), `createReport(data)` (structured business report with optional TOC).
538
- - **New error codes** — `QR_DEP_MISSING`, `QR_GENERATE_FAILED`, `BARCODE_DEP_MISSING`, `BARCODE_GENERATE_FAILED`, `BARCODE_SYMBOLOGY_INVALID`, `CHART_DEP_MISSING`, `CHART_SPEC_INVALID`, `CHART_RENDER_FAILED`, `MARKDOWN_DEP_MISSING`.
539
-
540
- ---
541
-
542
- ## [0.7.2]2026-04-20
543
-
544
- Phase 11 cross-cutting enhancements. Retroactively attributed to 0.7.2; these features were
545
- originally left as `[Unreleased]` and published out of chronological order after 0.7.1.
546
-
547
- ### Added
548
-
549
- - **`floatSpans` on image elements** — rich-text alternative to plain `floatText`. Accepts `InlineSpan[]` for mixed bold/italic/color/link captions beside float images. Mutually exclusive with `floatText` (validated).
550
- - **2-level list nesting** — `ListItem.items` now supports one further level of nesting (depth 0 → 1 → 2). Unordered marker: `▪`. Ordered: inherits parent counter or restarts via `nestedNumberingStyle: 'restart'`.
551
- - **Table `rowspan`** — `TableCell.rowspan` spans a cell across multiple rows. Works alongside `colspan`. Origin cell draws background over full span height; continuation rows automatically receive placeholder cells.
552
- - **`onFormFieldError` callback** `doc.onFormFieldError: (name, err) => 'skip' | 'throw'` mirrors `onImageLoadError`. Controls render behaviour when a form field fails.
553
- - **`createFootnoteSet(defs)`** helper exported from `pretext-pdf` that generates footnote definition/reference pairs with globally unique IDs. Returns `Array<{ id, def }>`.
554
- - **`renderDate` field** — `doc.renderDate: Date | string` overrides the PDF creation date. Useful for reproducible builds and testing.
555
- - **`{{date}}` and `{{author}}` tokens** in header/footer text — join existing `{{pageNumber}}` / `{{totalPages}}`. `{{date}}` resolves from `renderDate`; `{{author}}` resolves from `doc.metadata.author`.
556
- - **`tabularNumbers`** on `rich-paragraph` — digits rendered at uniform slot width (widest digit in font), so columns of numbers align without OpenType TNUM feature.
557
- - **`smallCaps` + `letterSpacing` per span** — `InlineSpan.smallCaps` and `InlineSpan.letterSpacing` now respected in `rich-paragraph` rendering.
558
- - **Per-span `fontSize`** — `InlineSpan.fontSize` overrides the element-level font size for that span. Enables mixed-size text in a single paragraph.
559
-
560
- ### Fixed
561
-
562
- - `resolveTokens()` used `.replace()` (replaces first occurrence only) changed to `.replaceAll()` for all four tokens.
563
- - Table span grid: continuation-row cursor was advancing by 1 instead of `colspan` when skipping a spanned column — now advances by full span width.
564
- - Font family names now validated for safe characters (`/^[a-zA-Z0-9 _-]+$/`) in `requireFamily()` — rejects null bytes and control characters.
565
- - Annotation `color` and `author` fields now validated in `validateElement()` for both `paragraph` and `heading` annotations.
566
- - `buildOutlineTree` memoizes `parentIdxOf()` into a pre-computed array eliminates O(n²) scan for documents with large heading counts.
567
- - Table grid-line renderer pre-computes active boundary seteliminates O(rows × cols) inner loop for large tables.
568
- - `addLinkAnnotation()` re-validates URL scheme at render time (defense-in-depth; `validate.ts` is the primary gate).
569
-
570
- ---
571
-
572
- ## [0.7.1] 2026-04-19
573
-
574
- ### Changed
575
-
576
- - **Upstream pretext pinned to `f2014338487a`** — picks up unreleased CJK opening-bracket annotation fix, Hangul jamo line-walker alignment fix, and two internal line-object churn reductions. No public API changes.
577
-
578
- ### Fixed
579
-
580
- - **List nesting depth enforced at validation** — `ListItem.items` (2nd-level items) now correctly rejects any further `.items` property, matching the documented 2-level maximum. Previously the validation silently passed 3-level data which could cause undefined render behaviour.
581
- - **3 phase-11 list tests corrected** — test data incorrectly contained 3-level nesting while named "2-level"; data trimmed to match documented contract.
582
-
583
- ---
584
-
585
- ## [0.7.0] — 2026-04-17
586
-
587
- ### Added
588
-
589
- - **6 production templates** (`templates/`) — GST invoice, international invoice, resume, multi-section report, NDA, and meeting minutes. Each is a self-contained `.ts` file outputting a valid PDF. Smoke-tested in Phase 2F Block D.
590
- - **StackBlitz live demo** (`demo/stackblitz/`) — 4-tab UI (Invoice, Report, Resume, Custom) backed by a Node.js render server. Edit JSON and generate PDFs instantly, no install required. Accessible at the StackBlitz link in the README.
591
- - **`## Performance` section in README** measured render times and PDF sizes for 1-page, 10-page, and mixed-element documents. Font subsetting behaviour documented.
592
- - **Stress tests and benchmarks** (`test/phase-2f-stress.test.ts`) — 32 tests across 4 blocks: large document stress (400-element, 200-row table), edge case stress (CJK, RTL, empty arrays, extreme sizes), timing benchmarks (1-page < 500 ms, 10-page < 5,000 ms), and template smoke tests.
593
- - **Error code coverage** — new tests for `COLUMN_WIDTH_TOO_NARROW`, `IMAGE_LOAD_FAILED`, `SVG_LOAD_FAILED`, and `ASSEMBLY_FAILED`. 16 of 19 error codes now have direct test coverage.
594
-
595
- ### Changed
596
-
597
- - **`as any` audit** — eliminated 10 casts in `validate.ts` by introducing a typed `FormFieldElement` local binding. The remaining 8 instances (pdf-lib interop, dynamic import, internal back-references) are now documented with one-line comments explaining the constraint.
598
- - **Comparison article** (`docs/articles/pretext-pdf-vs-pdfmake-2026.md`) — 2,200-word draft covering feature matrix, typography quality, API design, performance, and migration quick-start. Marked `published: false` pending live demo.
599
- - **Migration guide** (`docs/MIGRATION_FROM_PDFMAKE.md`) — 30+ pdfmake → pretext-pdf mappings, complete before/after invoice example, and a quick-start checklist. Linked from README.
600
-
601
- ### Fixed
602
-
603
- - **Phase 2F test types** — `fontWeight: 700 as 700` cast in pre-constructed rows array; removed non-existent `creationDate` from `DocumentMetadata`; replaced `allowCopying: false` with correct `encryption: { permissions: { copying: false } }`.
604
- - **StackBlitz integration** — added `.stackblitzrc` so WebContainer auto-runs `npm start` and opens the browser preview on port 3000.
605
-
606
- ---
607
-
608
- ## [0.5.3] — 2026-04-16
609
-
610
- ### Changed
611
-
612
- - **Upgraded `@chenglou/pretext` from 0.0.3 to 0.0.5** — picks up improved text analysis accuracy (~35% larger analysis module), better measurement precision, extracted bidi-data module for cleaner tree-shaking, and new `rich-inline` export (not yet used by pretext-pdf). No breaking changes — `prepareWithSegments()` and `layoutWithLines()` APIs are unchanged. All 223 tests pass, 3 example PDFs visually verified (RTL, TOC, hyperlinks).
613
-
614
- ---
615
-
616
- ## [0.5.2] — 2026-04-13
617
-
618
- ### Added
619
-
620
- - **`onImageLoadError` callback on `PdfDocument`** — gives callers control over image load failures. Return `'skip'` to silently omit the image (preserves existing default behavior). Return `'throw'` to abort rendering with the original error. Previously, all image failures were silently downgraded to `console.warn` with no way to detect them programmatically.
621
-
622
- ```typescript
623
- await render({
624
- content: [...],
625
- onImageLoadError: (src, error) => {
626
- myLogger.warn('Image skipped', { src, error })
627
- return 'skip' // or 'throw' to abort
628
- }
629
- })
630
- ```
631
-
632
- ---
633
-
634
- ## [0.4.0] 2026-04-08
635
-
636
- ### Breaking Changes
637
-
638
- - **Migrated from `pdf-lib` to `@cantoo/pdf-lib`** — `@cantoo/pdf-lib` is now a direct `dependency` (always installed). Previously it was an optional peer dependency required only for encryption. This removes the `ENCRYPTION_NOT_AVAILABLE` error code and the separate `npm install @cantoo/pdf-lib` installation step. Encryption now works out of the box.
639
- - **`ENCRYPTION_NOT_AVAILABLE` error code removed** encryption is now always available. Update any `switch` statements that handled this code.
640
-
641
- ### Why this change
642
-
643
- `pdf-lib` (the original) has not received a meaningful commit since November 2021. `@cantoo/pdf-lib` is the actively maintained fork (v2.6.5, 107+ releases, MIT license). pretext-pdf was already using `@cantoo/pdf-lib` for encryption — this commit makes it the single source of truth for all PDF operations.
644
-
645
- ### Added
646
-
647
- - `test/pretext-api-contract.test.ts` — canary test that asserts `@chenglou/pretext` exports the exact functions pretext-pdf depends on. Breaks loudly if pretext changes its API.
648
- - `docs/ROADMAP.md`public multi-phase development plan
649
-
650
- ### Changed
651
-
652
- - `@chenglou/pretext` version pinned to exact `0.0.3` (no caret) prevents surprise breaking changes from upstream auto-updates
653
- - `test:contract` script added — runs the pretext API contract test before the full test suite
654
- - All internal comments updated from `pdf-lib` to `@cantoo/pdf-lib`
655
-
656
- ---
657
-
658
- ## [0.3.1] — 2026-04-08
659
-
660
- ### Fixed
661
-
662
- - **Critical: Font resolution when installed as npm package** — `@fontsource/inter` is now resolved via `createRequire(import.meta.url)` instead of a hardcoded relative path. Previously, `path.join(__dirname, '..', 'node_modules', '@fontsource', 'inter', ...)` failed when npm hoisted the dependency to the consumer's top-level `node_modules`, causing `FONT_LOAD_FAILED` on every install. Now resolves correctly regardless of npm hoisting behavior.
663
-
664
- ---
665
-
666
- ## [0.3.0] 2026-04-08
667
-
668
- ### Added (Phase 8B Interactive Forms)
669
-
670
- - New `form-field` element type — creates interactive AcroForm fields in PDFs
671
- - `fieldType: 'text' | 'checkbox' | 'radio' | 'dropdown' | 'button'`
672
- - `label` renders above the field as static text
673
- - Text fields: `defaultValue`, `multiline`, `placeholder`, `maxLength`
674
- - Checkboxes: `checked` initial state
675
- - Radio groups and dropdowns: `options` array, `defaultSelected`
676
- - `doc.flattenForms: true` — bakes all fields into static content
677
- - Custom `borderColor`, `backgroundColor`, `width`, `height`, `fontSize` per field
678
- - New error codes: `FORM_FIELD_NAME_DUPLICATE` (duplicate `name` across fields), `FORM_FLATTEN_FAILED`
679
- - Post-render `form.updateFieldAppearances()` ensures proper display in all PDF readers
680
- - 10 comprehensive tests covering all form field types
681
-
682
- ### Added (Phase 8E — Signature Placeholder)
683
-
684
- - `doc.signature`visual signature box drawn on a specified page
685
- - Fields: `signerName`, `reason`, `location`, `x`, `y`, `width`, `height`, `page`, `borderColor`, `fontSize`
686
- - Draws signature line, date line, and optional text inside a bordered rectangle
687
- - `page` is 0-indexed, defaults to last page, clamps gracefully if out of range
688
- - 6 comprehensive tests
689
-
690
- ### Added (Phase 8D — Callout Boxes)
691
-
692
- - New `callout` element type styled highlight box with optional title
693
- - Preset styles: `style: 'info'` (blue), `'warning'` (amber), `'tip'` (green), `'note'` (gray)
694
- - Optional `title` rendered bold above content with left border accent
695
- - Fully customizable: `backgroundColor`, `borderColor`, `color`, `titleColor`, `padding`
696
- - Paginates correctly across pages (reuses blockquote pagination logic)
697
- - 8 comprehensive tests
698
-
699
- ### Added (Phase 8F — Document Metadata Extensions)
700
-
701
- - `doc.metadata.language` — sets PDF `/Lang` catalog entry (BCP47 tag e.g. `'en-US'`, `'hi'`)
702
- - `doc.metadata.producer` sets PDF producer field (e.g. `'MyApp v2.1'`)
703
- - Both fields validate as non-empty strings
704
- - 5 comprehensive tests
705
-
706
- ---
707
-
708
- ## [0.2.0] — 2026-04-08
709
-
710
- ### Added (Phase 8H Inline Formatting)
711
-
712
- - `verticalAlign: 'superscript' | 'subscript'` on `InlineSpan` in rich-paragraphs
713
- - Superscript renders at 65% font size, baseline shifted up by 40% of font size
714
- - Subscript renders at 65% font size, baseline shifted down by 20% of font size
715
- - `letterSpacing?: number` on `ParagraphElement`, `HeadingElement`, `RichParagraphElement` extra pt between characters
716
- - `smallCaps?: boolean` on those same three element types — simulated via uppercase + 80% fontSize
717
- - Character-by-character rendering for letterSpacing (pdf-lib has no native spacing param)
718
- - 8 comprehensive tests covering all inline formatting functionality
719
-
720
- ### Added (Phase 8A — Annotations/Comments)
721
-
722
- - New `comment` element type — sticky note annotation at position in document
723
- - `annotation?: AnnotationSpec` on `ParagraphElement` and `HeadingElement` attach note to element
724
- - Supports: `contents`, `author`, `color` (hex), `open` (popup default state)
725
- - Uses PDF `Subtype: 'Text'` annotation (sticky note icon in PDF viewers)
726
- - 8 comprehensive tests covering all annotation functionality
727
-
728
- ### Added (Phase 8CDocument Assembly)
729
-
730
- - New `merge(pdfs: Uint8Array[])` exported function combine pre-rendered PDFs
731
- - New `assemble(parts: AssemblyPart[])` exported function — mix rendered docs + existing PDFs
732
- - `AssemblyPart` interface: `{ doc?: PdfDocument, pdf?: Uint8Array }`
733
- - New error codes: `ASSEMBLY_EMPTY`, `ASSEMBLY_FAILED`
734
- - 8 comprehensive tests covering all assembly functionality
735
-
736
- ### Fixed
737
-
738
- - **CI case-sensitivity bug**: `test/phase-7-integration.test.ts` used `'en-US'` (uppercase) for hyphenation language. On Linux CI (case-sensitive filesystem) this failed with `UNSUPPORTED_LANGUAGE`. Changed to `'en-us'` to match package name `hyphenation.en-us`.
739
-
740
- ---
741
-
742
- ## [0.1.1] — 2026-04-08
743
-
744
- ### Added
745
-
746
- - **Phase 8G: Hyperlinks**Complete link annotation support:
747
- - `paragraph.url` for external URI links on paragraphs
748
- - `heading.url` for external URI links on headings
749
- - `heading.anchor` for named PDF destinations (internal cross-references)
750
- - `InlineSpan.href` for external and internal `#anchorId` links in rich-paragraphs
751
- - `mailto:` scheme support for email links
752
- - GoTo annotations for internal anchor references
753
- - 9 comprehensive tests covering all hyperlink functionality
754
-
755
- ### Fixed
756
-
757
- - **Memory leak in test suite**: Removed module-level `_hypherCache` in `src/measure.ts` that accumulated ~188KB per language across 255+ test runs. Changed from cached Hypher instances to fresh instances per call (negligible performance impact, massive memory savings).
758
- - **Node.js version compatibility**: Replaced `--experimental-strip-types` with `tsx` runner to support Node.js 18.x, 20.x, and 22.x in CI
759
- - **Broken CI examples**: Removed references to non-existent Phase 8 example scripts from GitHub Actions workflow
760
- - **README examples mismatch**: Updated Examples section to only list 5 existing Phase 7 examples (watermark, bookmarks, toc, rtl, encryption)
761
- - **Test suite OOM issues**: Split large test files (paginate.test.ts) into paginate-basic.test.ts to work around Node.js `--experimental-strip-types` heap exhaustion bug on files >17KB
762
-
763
- ### Changed
764
-
765
- - `test:unit` now runs only `test/paginate-basic.test.ts` (fast, no canvas overhead)
766
- - Reorganized test scripts: `test:unit`, `test:validate`, `test:e2e`, `test:phases` for better memory management
767
- - Moved internal planning documentation to archive (preserved, not published)
768
- - `devDependencies`: Added `@napi-rs/canvas` explicitly (was missing, causing CI failures)
769
-
770
- ### Added
771
-
772
- - `CONTRIBUTING.md`: Development setup, TDD workflow, PR process guide
773
- - `CHENG_LOU_EMAIL_DRAFT.md`: Template for requesting endorsement from pretext creator
774
- - `examples/comparison-pdfmake.ts`: pdfmake version of invoice for typography comparison
775
-
776
- ---
777
-
778
- ## [0.1.0]2026-04-07
779
-
780
- ### Added (Phase 7G — Encryption)
781
-
782
- - `doc.encryption` configuration for password-protecting PDFs
783
- - User password and owner password support
784
- - Granular permission restrictions: printing, copying, modifying, annotating
785
- - Lazy-loads `@cantoo/pdf-lib` (optional peer dependency) — zero cost when not used
786
- - Error code: `ENCRYPTION_NOT_AVAILABLE` when encryption is requested but dependency not installed
787
-
788
- ### Added (Phase 7F RTL Text Support)
789
-
790
- - Right-to-left text support for Arabic, Hebrew, and other RTL languages
791
- - Unicode bidirectional text algorithm via `bidi-js`
792
- - `dir` attribute on text elements: `'ltr'` | `'rtl'` | `'auto'` for per-element control
793
- - RTL text works with headings, paragraphs, lists, tables, and all text elements
794
- - Automatic detection of mixed LTR/RTL content
795
-
796
- ### Added (Phase 7ESVG Support)
797
-
798
- - `{ type: 'svg', svg: '<...' }` element for embedding SVG graphics
799
- - SVG rasterization via `@napi-rs/canvas`
800
- - ViewBox auto-sizing: automatic height calculation from viewBox aspect ratio
801
- - Explicit sizing: `width` and `height` parameters for precise control
802
- - Alignment options: `align: 'left' | 'center' | 'right'`
803
- - Multi-page support: SVGs paginate correctly across page breaks
804
- - Error code: `SVG_RENDER_FAILED` for SVG rasterization errors
805
-
806
- ### Added (Phase 7DTable of Contents)
807
-
808
- - `{ type: 'toc' }` element for automatic TOC generation
809
- - Two-pass rendering pipeline ensures accurate page numbers
810
- - Configurable: `title`, `showTitle`, `minLevel`/`maxLevel`, dot leaders, level indentation
811
- - Auto-indexed from heading structure (H1, H2, H3, etc.)
812
- - Supports custom formatting via `fontSize`, `color`, `spaceAfter` parameters
813
-
814
- ### Added (Phase 7C Hyphenation)
815
-
816
- - Automatic word hyphenation for better justified text layout
817
- - `doc.hyphenation: { language: 'en-US' }` for document-level config
818
- - Liang's algorithm via `hypher` package for accurate break points
819
- - Configurable: `minWordLength`, `leftMin`, `rightMin`, per-element `hyphenate: false` opt-out
820
- - Language support: includes `hyphenation.en-us` (additional languages via npm packages)
821
- - Error code: `UNSUPPORTED_LANGUAGE` when language not available
822
-
823
- ### Added (Phase 7B Watermarks)
824
-
825
- - `doc.watermark` for text or image watermarks on every page
826
- - Text watermarks: `text`, `fontSize`, `fontWeight`, `color`, `opacity`, `rotation`
827
- - Image watermarks: `image` (Uint8Array), `opacity`, `rotation`, `color` (tint)
828
- - Watermarks render behind content (lower z-index)
829
- - Rotation bounds: -360 rotation 360 degrees
830
- - Validation: must provide either text or image, never both required
831
-
832
- ### Added (Phase 7A — Bookmarks / PDF Outline)
833
-
834
- - PDF sidebar bookmarks auto-generated from heading structure
835
- - Enabled by default: `bookmarks: true` or `bookmarks: { minLevel: 1, maxLevel: 3 }`
836
- - Level filtering: include/exclude heading levels from outline
837
- - Per-heading opt-out: `bookmark: false` on heading elements
838
- - Keyboard navigation: Cmd/Ctrl+Opt/Alt+O in PDF readers to toggle bookmark sidebar
839
-
840
- ### Added (Phase 6 — Advanced Features)
841
-
842
- - Header and footer support with {{pageNumber}} and {{totalPages}} tokens
843
- - Text decoration: strikethrough, underline
844
- - Text alignment: left, center, right, justify
845
- - Line height control: custom line-height multipliers
846
- - Column layout with multi-column content flow
847
- - Tables with colspan/rowspan support
848
-
849
- ### Added (Phase 5 Rich Text / Builder API)
850
-
851
- - Fluent builder API for programmatic document construction
852
- - Rich text element with nested formatting (bold, italic, links)
853
- - Inline code and code blocks with syntax highlighting
854
- - Block quotes with custom styling
855
- - Horizontal rules (hr element)
856
- - Numbered and bulleted lists with nesting
857
-
858
- ### Added (Phases 1–4 Core Engine)
859
-
860
- - Core PDF generation via `pdf-lib`
861
- - Element types: paragraph, heading, table, image, list, code, blockquote
862
- - Font support: Inter bundled, custom TTF embedding
863
- - Document metadata: title, author, subject, keywords, created date
864
- - Page sizing: A4, A3, A5, Letter, Legal, or custom dimensions
865
- - Margins: top, bottom, left, right per page
866
- - Multi-page pagination with orphan/widow control
867
- - Image formats: PNG, JPG, WebP
868
- - Table features: custom column widths, cell padding, borders, header styling
869
- - Colors: hex color codes throughout (text, backgrounds, borders)
1
+ # Changelog
2
+
3
+ <!-- markdownlint-disable MD024 -->
4
+
5
+ All notable changes to pretext-pdf are documented here.
6
+ Format: [Keep a Changelog 1.1.0](https://keepachangelog.com/en/1.1.0/)
7
+
8
+ ---
9
+
10
+ ## [1.1.0] — 2026-05-07
11
+
12
+ Vendor `@chenglou/pretext` source directly into the package, eliminating the
13
+ GitHub URL dependency and all associated install risks (mutable tags, npm audit
14
+ gaps, network-only install, no SRI).
15
+
16
+ ### Changed
17
+
18
+ - **`@chenglou/pretext` is now vendored** The upstream text-layout engine
19
+ (`src/vendor/pretext/`) is compiled as part of pretext-pdf itself. Consumers
20
+ no longer need to install `@chenglou/pretext`; the GitHub URL dependency has
21
+ been removed from `package.json`. The vendored snapshot is pinned to
22
+ `v0.0.6-patched.2` (commit `658edfec`) with 9 upstream PRs cherry-picked on
23
+ top of the `v0.0.6` release. See `UPSTREAM.md` for the full patch inventory
24
+ and upgrade procedure.
25
+
26
+ ### Added
27
+
28
+ - **`UPSTREAM.md`** — Authoritative attribution and upgrade guide for the
29
+ vendored `@chenglou/pretext` source. Documents provenance, the 9 cherry-picked
30
+ upstream PRs (#3, #29, #105, #119, #132, #138, #140, #161, #165), which
31
+ commits are excluded from vendoring (fork infra), and the procedure for
32
+ updating when upstream publishes a new release.
33
+
34
+ ### Removed
35
+
36
+ - **`@chenglou/pretext` dependency** Removed from `dependencies`. The library
37
+ source is now bundled inside the package at `dist/vendor/pretext/`. No runtime
38
+ behavior change; the same patched code is used.
39
+
40
+ ---
41
+
42
+ ## [1.0.9] 2026-05-06
43
+
44
+ Test coverage Phase 2: filling blind spots in the CLI, the pdfmake compat shim, and
45
+ the performance regression guard. Adds c8 coverage tooling for measurability.
46
+
47
+ ### Added
48
+
49
+ - **`test/cli.test.ts`** (+13 tests) — End-to-end coverage for the `pretext-pdf` CLI binary,
50
+ spawning `dist/cli.js` as a subprocess. Covers argument parsing (`--version`, `--help`,
51
+ `-i/-o/--markdown/--code-font`, positional fallback, unknown flags), JSON and Markdown
52
+ input modes, stdin/stdout piping, and exit codes 0/1/2.
53
+
54
+ - **`test/compat.test.ts`** (+34 tests) Coverage for the pdfmake pretext-pdf
55
+ translation shim (`fromPdfmake`). Covers page setup (pageSize string and object,
56
+ pageMargins scalar/2-tuple/4-tuple, orientation), styles (defaultStyle, named styles,
57
+ headingMap override), all content node types (string, `text`, `ul`/`ol` with nesting,
58
+ `table` with header rows, `image`, `qr`, `pageBreak`, `stack`), header/footer string
59
+ forms, integration render, and unsupported nodes (`columns`, `canvas`).
60
+
61
+ - **c8 coverage tooling** — `npm run coverage` (text + lcov reporters) and
62
+ `npm run coverage:check` (75/65/75 thresholds, non-blocking in CI initially).
63
+ Configuration in `.c8rc.json` excludes type-only files and CLI from instrumentation.
64
+ Coverage step added to CI as `continue-on-error: true` while baseline thresholds
65
+ are calibrated.
66
+
67
+ ### Fixed
68
+
69
+ - **`test/benchmark-baseline.test.ts`: regression guard now actually guards** —
70
+ Replaced the prior "TODO: enable when baseline is calibrated" stub (which collected
71
+ timings but asserted nothing) with a real 3x-baseline-with-500ms-floor budget per
72
+ corpus. Missing corpora in the baseline JSON now `assert.fail()` instead of silently
73
+ defaulting to a zero budget that would mask any regression.
74
+
75
+ - **CONTRIBUTING.md: removed stale "(676 tests)" annotation** Test count drift bait;
76
+ the README badge already auto-verifies via `verify:badges`.
77
+
78
+ ### Changed
79
+
80
+ - **Test runner now builds first** — Added `pretest:unit: npm run build` so contributors
81
+ running `npm run test:unit` always get a fresh dist; the new CLI tests spawn the
82
+ compiled binary and would otherwise fail with a confusing module-not-found error.
83
+
84
+ ---
85
+
86
+ ## [1.0.8] 2026-05-06
87
+
88
+ Public API contract integrity: the `RenderOptions.logger` option now actually does what
89
+ its JSDoc has always promised, and `@napi-rs/canvas` no longer auto-installs.
90
+
91
+ ### Fixed
92
+
93
+ - **`RenderOptions.logger` now routes warnings from asset loading and rendering** —
94
+ Previously only validation warnings respected the `logger` option. Now all advisory
95
+ warnings from `loadImages` (image load, image embed, QR/barcode/chart skipped, plugin
96
+ loadAsset failed, watermark image skipped7 call sites) and `renderDocument` (form
97
+ field render failure) flow through `logger.warn` when one is provided. Bidi-js fallback
98
+ warnings from RTL reordering remain on `console.warn`; the JSDoc on `RenderOptions.logger`
99
+ has been updated to document the actual scope honestly.
100
+
101
+ - **Missing `[pretext-pdf]` log prefix on bidi-js error path** — One `console.warn` in
102
+ `measure-text.ts` was logging without the canonical `[pretext-pdf]` prefix, making it
103
+ hard to identify the library as the source in consumer logs. Now consistent.
104
+
105
+ ### Changed
106
+
107
+ - **`@napi-rs/canvas` removed from `optionalDependencies`** — Was double-listed in both
108
+ `peerDependencies` (with `optional: true`) and `optionalDependencies`. The latter caused
109
+ npm to attempt installing the native canvas binary on every install, including in
110
+ edge/serverless environments where the platform may not be supported and the dep is
111
+ not needed. Now only listed under `peerDependencies` — install it explicitly when you
112
+ need SVG/QR/barcode/chart rasterization in Node.
113
+
114
+ ### Documentation
115
+
116
+ - **README security callout for `allowedFileDirs`** — Added a prominent callout in the
117
+ Quick Start section. The default behavior allows `image.src` and `svg.src` to read any
118
+ absolute file path, which is a path-traversal vector when document JSON originates from
119
+ user input or an LLM. The callout now appears immediately after the first `render()`
120
+ example.
121
+
122
+ ---
123
+
124
+ ## [1.0.7] 2026-05-05
125
+
126
+ Picks up pretext fork v0.0.6-patched.2: 8 additional upstream PRs (11 total).
127
+
128
+ ### Fixed
129
+
130
+ - **German low opening quote `„` no longer breaks at line-start on hyphenation path** —
131
+ `KINSOKU_START_FORBIDDEN` in `src/measure-text.ts` now includes U+201E (`„`), matching
132
+ pretext PR #165 which fixed the non-hyphenation path. Previously `„` could appear
133
+ at the start of a wrapped line when hyphenation was active.
134
+
135
+ - **Currency symbols stay glued to adjacent numbers** — Upstream PR #105 (cherry-picked in
136
+ `v0.0.6-patched.2`) prevents `$`, `€`, `£`, `₹` etc. from line-breaking away from
137
+ the number they annotate.
138
+
139
+ - **Trailing collapsible-space reconstruction fixed** Upstream PR #29 fix (extended in
140
+ v0.0.6-patched.2): a word followed by a space that exactly fills `maxWidth` no longer
141
+ drops the space from line boundary cursors, preventing Arabic/mixed-script text from
142
+ losing inter-word spaces during reconstruction.
143
+
144
+ ### Changed
145
+
146
+ - **`@chenglou/pretext` dependency** — Bumped from `v0.0.6-patched` to `v0.0.6-patched.2`
147
+ (GitHub fork, 11 upstream PRs total). Adds: CJK overflow prevention (PR #132),
148
+ fit-advance cache fix (PR #161), rich inline stats unification (PR #138),
149
+ chunk layout side table O(1) lookup (PR #140), bidi surrogate handling (PR #3),
150
+ skip no-op merge passes (PR #119), currency stickiness (PR #105),
151
+ German quote fix (PR #165), and trailing-space reconstruction (PR #29).
152
+
153
+ ---
154
+
155
+ ## [1.0.6] 2026-05-04
156
+
157
+ Audit bug fixes: validator correctness, internal export hygiene, schema gaps, README accuracy.
158
+
159
+ ### Fixed
160
+
161
+ - **lineHeight upper-bound cap removed** — `validate()` no longer rejects `lineHeight > 20`. The
162
+ field is in points (pt), not a multiplier; 36pt is valid for a large heading. The `> 20` cap in
163
+ `paragraph`, `heading`, and `defaultParagraphStyle` validators has been removed. The lower-bound
164
+ check (lineHeight >= fontSize) is preserved.
165
+
166
+ - **form-field error messages use `${prefix}` format** — Error messages from the `form-field` case
167
+ now follow the `content[N] (form-field): ...` format used by all other element types, instead of
168
+ the old `[N] form-field.` prefix.
169
+
170
+ - **`assertUnknownProps` hint punctuation fixed** — The "unknown property" message previously
171
+ produced `unknown property. did you mean "color"` (period before hint). Fixed to
172
+ `unknown property; did you mean "color"`no period, semicolon separator.
173
+
174
+ - **British "colour" "color" in JSDoc** — Two `QrCodeElement` field comments
175
+ (`foreground`, `background`) and the `ValidationError.path` JSDoc example corrected.
176
+
177
+ - **`TocEntryElement`, `RichLine`, `RichFragment` removed from public exports** These types are
178
+ marked `@internal` in `types-public.ts` and should not be part of the npm API surface. Removed
179
+ from `src/index.ts`.
180
+
181
+ - **Signature error includes original cause** — `SIGNATURE_FAILED` now preserves the underlying
182
+ error message: `PDF signing failed: <original message>` instead of a static string.
183
+
184
+ - **Header-only table now valid** — `validate()` previously rejected tables where all rows are
185
+ headers (`headerRowCount === rows.length`). Changed `>=` to `>`: tables where every row is a
186
+ header are valid (useful for column-label-only tables).
187
+
188
+ - **Dead sub-condition removed in `float-group` floatWidth guard** — `fg.floatWidth <= 0` was a
189
+ dead branch (any value `<= 0` is already `< 30`). Removed to clarify intent.
190
+
191
+ - **`warningCount` JSDoc updated** — Documents that the validator currently only emits errors, so
192
+ `warningCount` is always 0 (reserved for future use).
193
+
194
+ - **`validateDocument` no longer re-throws unexpected errors** — Non-`PretextPdfError` exceptions
195
+ (e.g. circular JSON, unexpected runtime errors) are now caught and returned as a structured
196
+ `ValidationResult` instead of propagating. `validateDocument` now always returns, never throws.
197
+
198
+ ### Changed (Schema additions — `pretext-pdf/schema`)
199
+
200
+ - `qrCodeSchema`: added `margin` field.
201
+ - `imageSchema`: added `floatFontSize`, `floatFontFamily`, `floatColor` fields.
202
+ - `codeSchema`: added `dir` and `highlightTheme` fields.
203
+ - `tableSchema`: added `dir`, `headerRows`, and cell-level `dir`, `fontFamily`, `fontSize`,
204
+ `tabularNumbers` fields.
205
+
206
+ ### Docs
207
+
208
+ - README: `highlight.js` added to optional peer dependencies table.
209
+ - README: `validate_document` added to MCP server tool list.
210
+
211
+ ---
212
+
213
+ ## [1.0.5] 2026-05-04
214
+
215
+ Schema coverage completion, `ValidationResult.warningCount`, and README API docs.
216
+
217
+ ### Added
218
+
219
+ - **`ValidationResult.warningCount`** — `validateDocument()` now returns `warningCount` alongside
220
+ `errorCount`. Computed by filtering `errors[]` by `severity === 'warning'`. MCP consumers no
221
+ longer need to derive it client-side.
222
+
223
+ - **JSON Schema: remaining field coverage** — `src/schema.ts` now covers all previously missing
224
+ fields across 9 element types:
225
+ - `inlineSpanSchema`: `dir`
226
+ - `paragraphSchema`: `columns`, `columnGap`, `tabularNumbers`, `hyphenate`
227
+ - `headingSchema`: `tabularNumbers`, `hyphenate`
228
+ - `blockquoteSchema`: `lineHeight`, `padding`, `paddingH`, `paddingV`, `underline`, `strikethrough`
229
+ - `calloutSchema`: `titleColor`, `fontWeight`, `lineHeight`, `padding`, `paddingH`, `paddingV`
230
+ - `listSchema`: `lineHeight`, `markerWidth`, `itemSpaceAfter`, `nestedNumberingStyle`; nested
231
+ items now carry `dir` and have a typed inner schema
232
+ - `tocSchema`: `titleFontSize`, `levelIndent`, `leader`, `entrySpacing`
233
+ - `formFieldSchema`: `borderColor`, `backgroundColor`, `keepTogether`, `defaultSelected`
234
+ - `richParagraphSchema`: `columns`, `columnGap`, `tabularNumbers`
235
+
236
+ - **README: `validateDocument` and `pretext-pdf/schema` documented** — both entry points now have
237
+ `### API reference` sections with code examples.
238
+
239
+ ---
240
+
241
+ ## [1.0.4] 2026-05-04
242
+
243
+ Schema export hardening: post-release audit fixes addressing coverage gaps and a
244
+ malformed dialect URI.
245
+
246
+ ### Fixed
247
+
248
+ - **`pretext-pdf/schema`: `$schema` dialect URI corrected** — was
249
+ `https://json-schema.org/draft/2020-12` (not a registered URI), now
250
+ `https://json-schema.org/draft/2020-12/schema`. Strict JSON Schema validators
251
+ (AJV, Smithery, VS Code) will now correctly identify the dialect.
252
+ - **`pretext-pdf/schema`: `hr` element spacing fields** — `spaceAbove` and
253
+ `spaceBelow` (the primary documented fields, default 12) were missing.
254
+ `spaceBefore` and `spaceAfter` are now correctly marked as aliases.
255
+ - **`pretext-pdf/schema`: `float-group` and `chart` element types** — both
256
+ first-class public element types were missing from the `content.items.anyOf`
257
+ list. Schema-driven tooling will now know they exist.
258
+
259
+ ### Added (schema coverage)
260
+
261
+ - `pdfDocumentSchema.sections` — page-range header/footer overrides
262
+ - `headingSchema.annotation` — annotation field (was already on paragraph)
263
+ - `tableSchema.cellPaddingH` / `cellPaddingV` primary table density controls
264
+ - `imageSchema.floatWidth` / `floatGap` / `floatSpans` — column-layout controls
265
+ for floated images
266
+
267
+ ---
268
+
269
+ ## [1.0.3] — 2026-05-03
270
+
271
+ Enhancements: JSON Schema export, simplified marked peer dep range, and internal API polish.
272
+
273
+ ### Added
274
+
275
+ - **`pretext-pdf/schema` entry point** — exports `pdfDocumentSchema`, a machine-readable JSON Schema
276
+ object describing the full `PdfDocument` type. Covers all 22 element types and 18 top-level
277
+ document properties. Intended for editor tooling, MCP clients, and Smithery UI form generation.
278
+
279
+ ```typescript
280
+ import { pdfDocumentSchema } from 'pretext-pdf/schema'
281
+ ```
282
+
283
+ ### Changed
284
+
285
+ - **`marked` peer dependency simplified** — `^9.0.0 || ^10.0.0 || ... || ^18.0.0` condensed to
286
+ `>=9.0.0`. Semantically identical, cleaner npm output.
287
+
288
+ - **`validateDocument` logger option** — `options.logger` now passed to the underlying `validate()`
289
+ call via conditional spread, respecting `exactOptionalPropertyTypes: true` constraints.
290
+
291
+ ### Fixed
292
+
293
+ - **`fonts.ts` unsafe cast removed** `(spec as { style?: string }).style` replaced with direct
294
+ property access on the widened parameter type.
295
+
296
+ ---
297
+
298
+ ## [1.0.2] — 2026-05-03
299
+
300
+ ### Added
301
+
302
+ - `validateDocument(doc, options?)` non-throwing validation API that returns a structured `ValidationResult` with typed `ValidationError[]` instead of throwing. Each error includes `path`, `message`, `code`, `severity`, and `suggestion` fields.
303
+ - `ValidationError` and `ValidationResult` exported from the public API surface.
304
+ - `Logger` interface and `logger?: Logger` in `RenderOptions` route diagnostic warnings through a custom logger instead of `console.warn`.
305
+ - Inter italic font support (Inter-400-italic, Inter-700-italic) via bundled `@fontsource/inter` italic markdown and `fontStyle: 'italic'` now work without manual font setup.
306
+
307
+ ---
308
+
309
+ ## [1.0.1] 2026-05-02
310
+
311
+ Patch: strict mode correctness fixes. No API changes.
312
+
313
+ ### Fixed
314
+
315
+ - **`levenshteinDist` early-exit bug**per-cell `if (curr[j]! > 2) return 999` inside
316
+ the inner DP loop fired on intermediate cells, causing d=1 pairs like `hrefs→href` and
317
+ `spaceafter→spaceAfter` to incorrectly return 999 instead of 1. Fix: removed the per-cell
318
+ guard; final check only (`prev[n]! > 2 ? 999 : prev[n]!`).
319
+ - **Seven path-prefix annotations** strict-mode error paths had `(type)` suffixes
320
+ (e.g. `doc(table).rows[0]`) that no other validator used and that tests didn't expect.
321
+ All seven removed so paths are plain dot-notation.
322
+ - **`encryption` block not strict-checked** unknown props inside `doc.encryption`
323
+ were silently accepted in strict mode. Now validated against `ALLOWED_PROPS_SUB['encryption']`.
324
+ - **Root path was `'document'` not `'doc'`** top-level `assertUnknownProps` was called
325
+ with `'document'` as the path prefix, producing paths like `document.content[0]` instead
326
+ of `doc.content[0]`. Corrected to `'doc'`.
327
+ - **Suggestion format mismatched** — `Did you mean 'x'?` → `did you mean "x"` (lowercase,
328
+ double-quotes) to match the format tests asserted.
329
+ - **`formatErrors` missing header** — multi-error output now begins with
330
+ `Strict validation failed (N issues):\n` so callers can detect strict vs. regular errors.
331
+
332
+ ### Tests
333
+
334
+ - Added `test/validate-strict.test.ts` (35 tests) to `test:unit` script — these tests were
335
+ written but not wired into CI in v1.0.0.
336
+
337
+ ---
338
+
339
+ ## [1.0.0] — 2026-05-02
340
+
341
+ First stable release. Completes the plugin extension API, closes all v1.0 gate requirements,
342
+ and ships a fully verified public surface with zero breaking changes from 0.9.x.
343
+
344
+ ### Added
345
+
346
+ - **Plugin extension API** Register custom element types via `RenderOptions.plugins`.
347
+ Each `PluginDefinition` participates in all four pipeline stages: `validate`, `loadAsset`,
348
+ `measure`, and `render`. Plugins are fully typed and tree-shaken from documents
349
+ that don't use them. See README § Custom element types (plugins) and
350
+ `examples/plugin-custom-element.ts` for a runnable example.
351
+ - **`PluginDefinition`, `PluginMeasureContext`, `PluginMeasureResult`, `PluginRenderContext`**
352
+ exported from `pretext-pdf` public surface (previously internal).
353
+ - **`PdfBuilder` and `PdfBuilderOptions`** exported from `pretext-pdf` (enables type-safe
354
+ builder construction in downstream code without re-declaring the interface).
355
+ - **`TocEntryElement`** exported from `pretext-pdf` public surface (was in the `ContentElement`
356
+ union but not individually importable).
357
+ - **`plugins` option on `createPdf()`** — `PdfBuilderOptions.plugins` threads plugins through
358
+ the builder's `build()` call automatically.
359
+ - **`Intl.Segmenter` pre-flight guard** in `render()` — throws `RENDER_FAILED` with a clear
360
+ message on Node.js < 16 or runtimes without full-ICU data, instead of silently producing
361
+ incorrect line breaks.
362
+ - **`PluginRenderContext.pageWidth/pageHeight/margins`** — render hooks now receive full page
363
+ geometry for layout calculations (page-relative positioning, bleed boxes, etc.).
364
+ - **`render` context Y-coordinate docs** expanded JSDoc with multi-line text example showing
365
+ how to position text baselines relative to `context.y`.
366
+ - **Benchmark corpora manifest** and **smoke staging** tests wired into `npm test`
367
+ (previously orphaned).
368
+ - **`test/table-determinism.test.ts`** — asserts that table pagination produces identical
369
+ layout traces across repeated invocations of `prepareLayoutState`.
370
+ - **`test/validate-strict.test.ts`** (35 tests) comprehensive contract for `strict: true`
371
+ validation covering all element types, nested structures, Levenshtein suggestions, error
372
+ message format, doc-level and sub-structure prop checks. Total test count: 676.
373
+ - `examples/plugin-custom-element.ts` — runnable plugin example (`npm run example:plugin`).
374
+
375
+ ### Fixed
376
+
377
+ - **`SIGNATURE_CERT_AND_ENCRYPTION` error code** was declared in the `ErrorCode` union
378
+ but never thrown; validate.ts now uses it correctly when a document specifies both
379
+ signatures and encryption (previously threw a generic `VALIDATION_ERROR`).
380
+ - **Build break under `exactOptionalPropertyTypes: true`** `PdfBuilder.build()` no longer
381
+ passes `{ plugins: undefined }` to `runPipeline` when no plugins are configured.
382
+ - **Plugin `validate` hook empty-string normalization** `plugin.validate()` returning `''`
383
+ now correctly accepts the element (was previously treated as a rejection message).
384
+ - **`toc` element reaching render default arm** `render.ts` now has an explicit
385
+ `case 'toc': return` guard before the default arm; TOC elements are pre-processed
386
+ during pagination and should never reach the renderer.
387
+ - **`RichLine` and `RichFragment`** demoted from `@public` to `@internal`; these are
388
+ implementation details of the rich-text pipeline, not intended for external use.
389
+ - **Sentinel value documentation** — `MeasuredBlock` comment now explicitly states that
390
+ `lines: []`, `fontSize: 0`, `lineHeight: 0`, `fontKey: ''` applies to spacers, tables,
391
+ images, hr, *and plugin blocks* not a bug but a documented convention.
392
+
393
+ ### Internal
394
+
395
+ - `src/plugin-registry.ts` (new): Pure orchestration helpers for the four plugin injection
396
+ points (`findPlugin`, `runPluginValidate`, `runPluginLoadAsset`, `runPluginMeasure`,
397
+ `runPluginRender`).
398
+ - `src/plugin-types.ts` (new): `PluginDefinition` interface and context/result types.
399
+ - `src/layout-state.ts`: `prepareLayoutState` now accepts `options?: RenderOptions` and
400
+ threads plugins to `stageValidate`, `stageLoadAssets`, and `stageMeasure`.
401
+ - `docs/V1.0-RUNBOOK.md`: Full release runbook with first-principles audit, anti-hallucination
402
+ protocol, verified-facts table, and phase-by-phase plan.
403
+
404
+ ---
405
+
406
+ ## [0.9.4] 2026-05-02
407
+
408
+ > **Note:** This release was never published to npm as a standalone tag. All changes listed
409
+ > here shipped as part of [1.0.0] on the same date.
410
+
411
+ Architecture hardening + API surface snapshot. No public API changes; internal
412
+ restructuring to eliminate circular dependencies and add drift guards before v1.0 freeze.
413
+
414
+ ### Added
415
+
416
+ - **API surface snapshot** (`etc/pretext-pdf.api.md`) checked into source control as
417
+ the v1.0 baseline. The `api:check` CI step will fail on unintentional public-API drift.
418
+ - **`src/layout-state.ts`** — `prepareLayoutState()` and `summarizeLayoutState()` extracted
419
+ from the pipeline for testability; `layout-contract` and `hard-text-contract` tests
420
+ wired into `test:unit`.
421
+ - **`src/benchmarks/corpora.ts`**benchmark corpus manifest (`getBenchmarkCorpora()`)
422
+ restored from git history; `benchmark-baseline.test.ts` wired into `test:contract`.
423
+ - **Drift guards** (`test/drift-guards.test.ts`) — asserts that `ELEMENT_TYPES`,
424
+ `ALLOWED_PROPS`, `validate.ts` cases, and `render.ts` cases all agree at test time.
425
+ Catches any future element-type addition that isn't plumbed through all four places.
426
+ - **`render.ts` default arm** — unknown element types now throw immediately instead of
427
+ silently producing a blank block.
428
+
429
+ ### Refactored
430
+
431
+ - **Circular dependency broken**: `src/post-process.ts` extracted so `builder.ts` and
432
+ `index.ts` no longer form a cycle through each other.
433
+ - **`ELEMENT_TYPES` extracted** to `src/element-types.ts` as single source of truth;
434
+ re-exported from `index.ts`, imported by `validate.ts` — eliminates the previous
435
+ per-file string-literal duplication.
436
+
437
+ ### Fixed
438
+
439
+ - `post-process.ts`: drop raw signing library error message from `SIGNATURE_FAILED`
440
+ to avoid leaking certificate or passphrase details in error output.
441
+ - `layout-state.ts`: polyfill install wrapped in try/catch; throws `CANVAS_UNAVAILABLE`
442
+ on failure instead of an untyped exception.
443
+
444
+ ---
445
+
446
+ ## [0.9.3] 2026-04-23
447
+
448
+ Strict validation release. Opt-in property validation to catch unknown properties on elements and sub-structures via typo detection and precise JSONPath error reporting.
449
+
450
+ ### Added
451
+
452
+ - **Strict validation mode**: Pass `{ strict: true }` to `render(doc, options)` to reject unknown properties. Non-strict mode (default) remains permissive for backwards compatibility.
453
+ - **`render()` options parameter**: Updated signature to `render(doc: PdfDocument, options?: RenderOptions)` where `RenderOptions = { strict?: boolean }`.
454
+ - **`validate()` public export**: `validate()` is now exported from `pretext-pdf` for standalone validation and testing.
455
+ - **Validation error details**:
456
+ - Unknown properties reported with Levenshtein edit-distance suggestions (distance ≤2) for typo correction.
457
+ - Errors include JSONPath-like paths (`content[3].table.rows[0].cells[1].align`) for precise location reporting.
458
+ - Error accumulation: all violations collected before throwing a single VALIDATION_ERROR with formatted multi-line message.
459
+ - First 20 errors shown; overflow indicator present.
460
+ - **Compile-time drift guards**: `src/allowed-props.ts` uses `Exact<T, Keys>` TypeScript type assertions to catch property definition drift at type-check time. If element types change, `tsc --noEmit` will error if allowed-props lists don't match.
461
+ - **Property allowlists**:
462
+ - `ALLOWED_PROPS`: 22 element types (paragraph, heading, table, image, code, list, etc.)
463
+ - `ALLOWED_PROPS_SUB`: 8 sub-structures (document, metadata, table-row, table-cell, list-item, inline-span, column-def, annotation)
464
+
465
+ ### Internal
466
+
467
+ - `src/allowed-props.ts` (new): Central configuration for allowed properties with compile-time assertions.
468
+ - `src/validate.ts` (enhanced): Added `levenshteinDist()`, `closestMatch()`, `assertUnknownProps()`, and `formatErrors()` helpers; threading strict flag through `validateElement()` for nested structure validation (tables, lists, rich-paragraphs, float-groups, annotations).
469
+
470
+ ---
471
+
472
+ ## [0.9.2] 2026-04-22
473
+
474
+ Maintenance release. Engine refresh + repo-hygiene automation. No runtime behavior changes beyond the `@chenglou/pretext` bump.
475
+
476
+ ### Changed
477
+
478
+ - **Bumped `@chenglou/pretext` to 0.0.6** (from 0.0.5). Brings two upstream improvements: (a) CJK text followed by opening-bracket annotations now wraps like browsers instead of leaving the opening bracket on the previous line (upstream PR #148), (b) native numeric `letterSpacing` support on `prepare()` and `prepareWithSegments()` (upstream PRs #108/#156). Our manual letterSpacing compensation in `src/measure-blocks.ts` and `src/rich-text.ts` continues to work unchanged — delegating to pretext's native path is tracked as Tier 1 follow-up in `docs/ROADMAP.md`. All 624 tests green, all 5 visual regression baselines green.
479
+
480
+ ### Fixed
481
+
482
+ - **README badges matched to reality**: `runtime-deps-7` → `runtime-deps-8` (there are 8 direct `dependencies`, not 7), `tests-600+` → `tests-624` (the full `npm test` chain runs 624 tests across 5 subsuites). Drift guarded by a new CI step; see below.
483
+
484
+ ### Added
485
+
486
+ - `scripts/verify-badges.js` + CI step compares README shields.io badge values against `package.json` dep count and `npm test` total. Fails CI on drift. Fast path via `SKIP_TEST_RUN=1` for pre-commit use.
487
+ - `release` job in `ci.yml` — on `v*` tag push, auto-extracts the matching `## [X.Y.Z]` section from this file and creates the GitHub release (requires publish to succeed first). Closes the "tag exists but no release page" gap that affected v0.9.1. (Note: originally shipped as `.github/workflows/release-on-tag.yml`; merged into `ci.yml` for dependency ordering in Tier 0.5.)
488
+ - `renovate.json` — watches dependencies, auto-merges devDependency bumps that pass CI, opens PRs (without auto-merge) for runtime, peer, and `@chenglou/pretext` engine bumps. Closes the gap that left us one release behind upstream.
489
+
490
+ ### Removed
491
+
492
+ - `test/smoke-staging.test.ts` exercised a non-existent `{ type: 'paragraph', footnote: {...} }` shape that the permissive validator silently accepted. False coverage. A strict validator rollout (rejecting unknown element properties) is the root fix and is tracked as a Tier 1 item in the rewritten `docs/ROADMAP.md`.
493
+ - `src/brain/` — inert auto-logger artifact (34 blank-body entries, no active writer). Never published to npm.
494
+
495
+ ### Docs
496
+
497
+ - `docs/ROADMAP.md` — complete rewrite as a living document (Now / Next / Under consideration / Shipped / History + Update discipline). The previous "master remediation plan" with phase-numbered sections was dropped: phases 0–5 all shipped by v0.9.1, and the document had rotted to the point of contradicting `package.json` on dependency pinning and `CHANGELOG.md` on what was live. History section preserves the prior plan's origin date and scope for reference.
498
+
499
+ ---
500
+
501
+ ## [0.9.1] — 2026-04-21
502
+
503
+ Bug-fix + hardening release. Ships the callout + rich-text rendering fixes from PR #2 together with PR #3's producer-validator contract around measured blocks.
504
+
505
+ ### Fixed
506
+
507
+ - **Rich-paragraph: leading-space tokens stripped after hard break** ([src/rich-text.ts](src/rich-text.ts)). A pre-overflow guard (`isLeadingSpace: currentX === 0 && token.text.trim() === ''`) fired whenever `currentX` was zero both at block start *and* after a `\n` hard break reset the cursor. Continuation spans beginning with whitespace (e.g. `' · text'`) had their first token silently dropped, causing separator glyphs and indented text to appear mis-positioned. Guard removed; the overflow-wrap skip path that correctly skips trailing spaces after soft wraps is unaffected.
508
+ - **Callout: `spaceAfter` double-applied by paginator** ([src/measure-blocks.ts](src/measure-blocks.ts)). `callout` block measurement included `el.spaceAfter ?? 12` inside `totalHeight` *and* returned the same value as `block.spaceAfter`. `paginate.ts` added `block.spaceAfter` on top of `block.height`, counting it twice and pushing callout content ~12 pt below its intended position. Fixed by removing `spaceAfter` from the `totalHeight` formula; the value is still returned in `block.spaceAfter` for the paginator.
509
+ - **Callout with title: background rect clips title row when split across pages** ([src/paginate.ts](src/paginate.ts)). `splitBlock` did not subtract `calloutData.titleHeight` from `availableForLines` for the first chunk, allowing `floor((titleH + lh) / lh)` extra lines to be placed, leaving no room for the title row. `getCurrentY` also omitted `titleHeight` from `blockBottom`, producing incorrect Y tracking after a split callout. Both fixed: `titleH` is now subtracted from available space on the first chunk only, and added to `blockBottom` when computing the cursor position after the first chunk renders.
510
+
511
+ ### Added / hardened
512
+
513
+ - **Producer-validator contract for measured blocks** ([src/paginate.ts](src/paginate.ts)). `validateMeasuredBlocks()` runs at `paginate()` entry in O(n) and throws `PretextPdfError('PAGINATION_FAILED')` if a callout `MeasuredBlock` is missing `calloutData` or any of `titleHeight` / `paddingV` / `paddingH` is non-finite — same for blockquote padding/border fields. Surfaces producer bugs directly instead of as downstream NaN arithmetic or `PAGE_LIMIT_EXCEEDED`.
514
+ - **Narrowed internal types** `MeasuredCalloutBlock` / `MeasuredBlockquoteBlock` (intersection types in [src/types.ts](src/types.ts)) consumed by `calloutTitleHeight` + `verticalPadding` helpers in `paginate.ts`. No defensive runtime checks downstream.
515
+ - **Extracted `CalloutData` interface** from the previously-inline shape on `MeasuredBlock.calloutData`. Measurer constructs it as a typed literal, so TypeScript enforces the full contract at the producer site.
516
+ - **Zero-width non-whitespace tokens preserved**: the rich-text post-soft-wrap guard only skips tokens where `text.trim() === ''`. ZWJ (U+200D), combining marks, and other zero-width non-whitespace characters pass through so emoji / CJK shaping stays intact — pinned by a regression test.
517
+ - **Extracted `LINK_COLOR_DEFAULT`** constant in `src/rich-text.ts`.
518
+
519
+ ### Tests
520
+
521
+ - `test/rich-text.test.ts` 20 → 23 (+3): block-start leading whitespace preserved; leading whitespace after hard break preserved; ZWJ preservation.
522
+ - `test/phase-8d-callout.test.ts` 12 19 (+7): callout `spaceAfter` double-count regression, titled split line count, untitled split, continuation chunk `yFromTop === 0`, mid-page split entry, validator rejection on missing `calloutData`, validator rejection on partial `calloutData` (non-finite fields), validator rejection on partial blockquote padding, non-callout-document early-return.
523
+ - Full suite: 624 tests, 100% pass.
524
+
525
+ ### Chore / docs
526
+
527
+ - Removed `brain/learnings/*.md`, `docs/PLAN-v0.6-v1.0.md`, `test/paginate.test.ts.archive` — internal dev artifacts not for the public repo.
528
+ - Stripped `Phase N:` nomenclature from `src/` comments (pure rename — no logic delta).
529
+ - Added `demo/stackblitz/.stackblitzrc`, `docs/articles/pretext-pdf-vs-pdfmake-2026.md` (draft).
530
+ - Added `examples/visual-pr2-bug1-separator.ts` + `examples/visual-pr2-bug3-callout-split.ts` plus 4 reference PNGs under `docs/visuals/pr2/` for bug-reproduction demonstrations.
531
+ - README test badge corrected `650+ → 600+` (verified: 624 tests total).
532
+
533
+ ---
534
+
535
+ ## [0.9.0]2026-04-20
536
+
537
+ Three additive enhancements that broaden the package's surface without growing its mandatory dependency footprint.
538
+
539
+ ### Added
540
+
541
+ - **CLI binary** — `pretext-pdf` is now a `bin` entry. `pretext-pdf doc.json out.pdf`, `cat doc.json | pretext-pdf > out.pdf`, `echo '{...}' | pretext-pdf -o out.pdf`. Supports stdin/stdout and file arguments. `--markdown` flag converts Markdown input to PDF in one step (requires the `marked` peer dep). See [src/cli.ts](src/cli.ts).
542
+ - **`pretext-pdf/compat` entry point** `fromPdfmake(pdfmakeDoc)` translates pdfmake document descriptors into `PdfDocument` so existing pdfmake codebases can switch with a one-line change at the entry point. Covers strings, `text` nodes (with `style`/`bold`/`italics`/`color`/`fontSize`/`alignment`/`font`), `ul`/`ol`, `table` (with `widths` + `headerRows`), `image`, `qr`, `pageBreak` (`before`/`after`), `stack`, `pageSize`/`pageOrientation`/`pageMargins`, `defaultStyle`/`styles`, `info` → metadata, and string-form `header`/`footer`. Default style-name → heading mapping is configurable via `headingMap` option.
543
+ - **Markdown: GFM tables** ([src/markdown.ts](src/markdown.ts)) — `markdownToContent()` now recognises GFM tables and translates them to `TableElement`, including column alignment from `:---:` / `---:` markers. Ragged rows are padded with empty cells.
544
+ - **Markdown: GFM task lists** `- [x] done` and `- [ ] todo` render with ☑ / ☐ Unicode markers prepended to the item text.
545
+
546
+ ### Tests
547
+
548
+ - New `test/v0.9.0-features.test.ts` (21 tests): markdown table + task list, full CLI exec coverage (stdin, file, `--markdown`, error paths), and pdfmake compat (strings, headings, rich-paragraphs, lists, tables, images, QR, `pageBreak`, `stack`, `pageSize`/`pageMargins`, end-to-end render of a translated document).
549
+
550
+ ### Notes
551
+
552
+ - Zero new mandatory dependencies. The CLI uses only Node built-ins. The compat shim is pure TypeScript. Markdown additions ride on the existing optional `marked` peer.
553
+ - `dist/cli.js` is wired through `package.json#bin.pretext-pdf` `npm install -g pretext-pdf` makes the CLI globally available; `npx pretext-pdf` works without install.
554
+
555
+ ---
556
+
557
+ ## [0.8.3] 2026-04-20
558
+
559
+ ### Security
560
+
561
+ - **SSRF — IPv4-mapped IPv6 bypass** ([src/assets.ts](src/assets.ts) `assertSafeUrl`). Pre-0.8.3 the private-IP guard checked the parsed hostname against dotted-decimal regexes only. WHATWG `URL` normalizes `[::ffff:127.0.0.1]` to `[::ffff:7f00:1]` (hex IPv4-in-IPv6), so attacker-supplied URLs of the form `https://[::ffff:127.0.0.1]/admin` slipped past every `^127\.`/`^10\.`/etc. check and reached localhost or RFC 1918 ranges. Patched by detecting both the dotted (`::ffff:127.0.0.1`) and hex-compressed (`::ffff:7f00:1`) IPv4-mapped forms and decoding the embedded IPv4 before regex matching. Also explicitly blocks the IPv6 unspecified address `::`.
562
+ - **SSRF — redirect-following bypass** ([src/assets.ts](src/assets.ts) `fetchWithTimeout`). The previous implementation used the default `redirect: 'follow'`, so a public URL could `302` to `http://127.0.0.1:8080/internal` and the library would happily fetch the private target despite the upfront `assertSafeUrl` check on the *initial* URL. Patched to use `redirect: 'manual'` and re-validate every `Location` hop with `assertSafeUrl`, capped at 3 redirects. Browser opaqueredirect responses are rejected with a clear error.
563
+
564
+ ### Fixed
565
+
566
+ - **`createGstInvoice` amount-in-words double space for sub-rupee totals** ([src/templates.ts](src/templates.ts)). An invoice whose total was less than ₹1 (e.g. ₹0.50) produced `"Rupees and Fifty Paise Only"` (two spaces after "Rupees") because the rupee-words branch resolved to an empty string. Now uses an explicit `"Zero"` when there are no rupees: `"Rupees Zero and Fifty Paise Only"`.
567
+ - **Markdown deeper-than-2-level lists silently dropped** ([src/markdown.ts](src/markdown.ts) `convertListItem`). Pre-0.8.3 the converter only created text-only leaves for nested lists, so `- A\n - B\n - C` lost C entirely. Now recursive preserves arbitrary nesting depth in the resulting `ListItem` tree.
568
+ - **Markdown list items with paragraph-typed content** ([src/markdown.ts](src/markdown.ts)). When list items were separated by blank lines, marked emits `paragraph` tokens (not `text` tokens) for the item content. The converter only handled `text`, silently dropping the item text. Now also handles `paragraph` tokens.
569
+
570
+ ### Tests
571
+
572
+ - New `test/v0.8.3-ssrf.test.ts` covers 11 IPv4-mapped IPv6 bypass cases, IPv6 unspecified/loopback regressions, and HTTP rejection.
573
+ - Extended `test/phase-10c-markdown.test.ts` with regressions for 3-level nesting and paragraph-typed list items.
574
+ - Extended `test/phase-10d-templates.test.ts` with the sub-rupee amount-in-words case.
575
+
576
+ ---
577
+
578
+ ## [0.8.2] — 2026-04-20
579
+
580
+ ### Fixed
581
+
582
+ - **Rich-paragraph whitespace collapse** — multi-span `rich-paragraph` content rendered with adjacent words overlapping (e.g. `"Founder & CEO" + " — Antigravity Systems"` displayed as `"Founder& CEO—AntigravitySystems"`). Root cause: pretext's `layoutWithLines` follows CSS-like behavior and excludes trailing whitespace from line widths, so tokens like `"Hello "` or `" "` measured to width 0 and downstream fragments overlapped the previous one. `measureTokenWidth` in [src/rich-text.ts](src/rich-text.ts) now uses a sentinel-character technique (append non-whitespace `\u2588`, measure combined string, subtract sentinel width) to recover the true rendered width whenever a token has trailing whitespace. Sentinel width is cached per font config.
583
+ - The fast path (no trailing whitespace) is unchanged — single pretext call. Slow path adds two pretext calls per affected token, with one cached.
584
+
585
+ ### Tests
586
+
587
+ - Added 3 regression tests in `test/rich-text.test.ts` under `whitespace preservation (v0.8.2 fix)` covering trailing whitespace inside spans, whitespace-only separator spans, and the exact `"Founder & CEO" → "Antigravity Systems"` resume-preset scenario.
588
+
589
+ ---
590
+
591
+ ## [0.8.1]2026-04-20
592
+
593
+ ### Fixed
594
+
595
+ - **Browser support** — `pretext-pdf` now imports cleanly in browsers. Module-init in `src/fonts.ts` previously called `fileURLToPath(import.meta.url)` and `createRequire(import.meta.url)` eagerly, which threw `"The URL must be of scheme file"` whenever the module was loaded from a non-`file://` URL (esm.sh, jsdelivr, Vite dev server). Both calls are now gated on a runtime `IS_NODE` check, and the bundled-Inter `BUNDLED_INTER_PATHS` arrays are constructed only in Node.
596
+ - **Browser font-loading errors** — `loadFontBytes` now throws clear `FONT_LOAD_FAILED` messages when bundled Inter or string font paths are requested in a browser, pointing the consumer at the correct workaround (supply `Uint8Array` bytes via `doc.fonts`).
597
+
598
+ ### Notes for browser users
599
+
600
+ - Always supply Inter (or your default font) explicitly via `doc.fonts: [{ family: 'Inter', weight: 400, src: <Uint8Array> }, { family: 'Inter', weight: 700, src: <Uint8Array> }]`. The library cannot read local font files in the browser.
601
+ - SVG / chart / qr-code / barcode elements still depend on `@napi-rs/canvas` at runtime; in the browser, the native `OffscreenCanvas` is used instead and the polyfill is skipped automatically.
602
+
603
+ ---
604
+
605
+ ## [0.8.0] — 2026-04-19
606
+
607
+ ### Added
608
+
609
+ - **`qr-code` element** — generate QR codes as inline PDF content using the `qrcode` optional peer dependency. Supports `data`, `size`, `errorCorrectionLevel` (L/M/Q/H), `foreground`/`background` hex colours, `margin`, `align`, `spaceBefore`/`spaceAfter`. Fully serverless — pure JS, no canvas required.
610
+ - **`barcode` element** — generate 100+ barcode symbologies (EAN-13, Code128, PDF417, QR, DataMatrix, etc.) via the `bwip-js` optional peer dependency. Supports `symbology`, `data`, `width`, `height`, `includeText`, `align`, `spaceBefore`/`spaceAfter`. Pure JS, Lambda/Edge safe.
611
+ - **`chart` element** — embed Vega-Lite charts as vector SVG using `vega` + `vega-lite` optional peer deps. Accepts any Vega-Lite `spec`, `width`, `height`, `caption`, `align`. Rendered with `renderer: 'none'` — zero canvas/puppeteer dependency.
612
+ - **`pretext-pdf/markdown` entry point** — `markdownToContent(md, options?)` converts a Markdown string to `ContentElement[]`. Requires optional `marked` peer dep. Supports headings, bold/italic/links (→ rich-paragraph), lists (2 levels), blockquotes, code blocks, and HR.
613
+ - **`pretext-pdf/templates` entry point** — three typed template functions with zero extra dependencies: `createInvoice(data)` (generic invoice with currency, tax, discount, QR payment), `createGstInvoice(data)` (GST-compliant Indian tax invoice with IGST/CGST+SGST, UPI QR, bank details, amount in words), `createReport(data)` (structured business report with optional TOC).
614
+ - **New error codes** — `QR_DEP_MISSING`, `QR_GENERATE_FAILED`, `BARCODE_DEP_MISSING`, `BARCODE_GENERATE_FAILED`, `BARCODE_SYMBOLOGY_INVALID`, `CHART_DEP_MISSING`, `CHART_SPEC_INVALID`, `CHART_RENDER_FAILED`, `MARKDOWN_DEP_MISSING`.
615
+
616
+ ---
617
+
618
+ ## [0.7.2] — 2026-04-20
619
+
620
+ Phase 11 cross-cutting enhancements. Retroactively attributed to 0.7.2; these features were
621
+ originally left as `[Unreleased]` and published out of chronological order after 0.7.1.
622
+
623
+ ### Added
624
+
625
+ - **`floatSpans` on image elements** — rich-text alternative to plain `floatText`. Accepts `InlineSpan[]` for mixed bold/italic/color/link captions beside float images. Mutually exclusive with `floatText` (validated).
626
+ - **2-level list nesting** — `ListItem.items` now supports one further level of nesting (depth 0 1 2). Unordered marker: `▪`. Ordered: inherits parent counter or restarts via `nestedNumberingStyle: 'restart'`.
627
+ - **Table `rowspan`** `TableCell.rowspan` spans a cell across multiple rows. Works alongside `colspan`. Origin cell draws background over full span height; continuation rows automatically receive placeholder cells.
628
+ - **`onFormFieldError` callback** — `doc.onFormFieldError: (name, err) => 'skip' | 'throw'` mirrors `onImageLoadError`. Controls render behaviour when a form field fails.
629
+ - **`createFootnoteSet(defs)`** — helper exported from `pretext-pdf` that generates footnote definition/reference pairs with globally unique IDs. Returns `Array<{ id, def }>`.
630
+ - **`renderDate` field** — `doc.renderDate: Date | string` overrides the PDF creation date. Useful for reproducible builds and testing.
631
+ - **`{{date}}` and `{{author}}` tokens** in header/footer text — join existing `{{pageNumber}}` / `{{totalPages}}`. `{{date}}` resolves from `renderDate`; `{{author}}` resolves from `doc.metadata.author`.
632
+ - **`tabularNumbers`** on `rich-paragraph` — digits rendered at uniform slot width (widest digit in font), so columns of numbers align without OpenType TNUM feature.
633
+ - **`smallCaps` + `letterSpacing` per span** — `InlineSpan.smallCaps` and `InlineSpan.letterSpacing` now respected in `rich-paragraph` rendering.
634
+ - **Per-span `fontSize`** — `InlineSpan.fontSize` overrides the element-level font size for that span. Enables mixed-size text in a single paragraph.
635
+
636
+ ### Fixed
637
+
638
+ - `resolveTokens()` used `.replace()` (replaces first occurrence only) changed to `.replaceAll()` for all four tokens.
639
+ - Table span grid: continuation-row cursor was advancing by 1 instead of `colspan` when skipping a spanned column — now advances by full span width.
640
+ - Font family names now validated for safe characters (`/^[a-zA-Z0-9 _-]+$/`) in `requireFamily()` — rejects null bytes and control characters.
641
+ - Annotation `color` and `author` fields now validated in `validateElement()` for both `paragraph` and `heading` annotations.
642
+ - `buildOutlineTree` memoizes `parentIdxOf()` into a pre-computed array — eliminates O(n²) scan for documents with large heading counts.
643
+ - Table grid-line renderer pre-computes active boundary set eliminates O(rows × cols) inner loop for large tables.
644
+ - `addLinkAnnotation()` re-validates URL scheme at render time (defense-in-depth; `validate.ts` is the primary gate).
645
+
646
+ ---
647
+
648
+ ## [0.7.1]2026-04-19
649
+
650
+ ### Changed
651
+
652
+ - **Upstream pretext pinned to `f2014338487a`** picks up unreleased CJK opening-bracket annotation fix, Hangul jamo line-walker alignment fix, and two internal line-object churn reductions. No public API changes.
653
+
654
+ ### Fixed
655
+
656
+ - **List nesting depth enforced at validation** — `ListItem.items` (2nd-level items) now correctly rejects any further `.items` property, matching the documented 2-level maximum. Previously the validation silently passed 3-level data which could cause undefined render behaviour.
657
+ - **3 phase-11 list tests corrected** — test data incorrectly contained 3-level nesting while named "2-level"; data trimmed to match documented contract.
658
+
659
+ ---
660
+
661
+ ## [0.7.0] — 2026-04-17
662
+
663
+ ### Added
664
+
665
+ - **6 production templates** (`templates/`) — GST invoice, international invoice, resume, multi-section report, NDA, and meeting minutes. Each is a self-contained `.ts` file outputting a valid PDF. Smoke-tested in Phase 2F Block D.
666
+ - **StackBlitz live demo** (`demo/stackblitz/`) — 4-tab UI (Invoice, Report, Resume, Custom) backed by a Node.js render server. Edit JSON and generate PDFs instantly, no install required. Accessible at the StackBlitz link in the README.
667
+ - **`## Performance` section in README** — measured render times and PDF sizes for 1-page, 10-page, and mixed-element documents. Font subsetting behaviour documented.
668
+ - **Stress tests and benchmarks** (`test/phase-2f-stress.test.ts`)32 tests across 4 blocks: large document stress (400-element, 200-row table), edge case stress (CJK, RTL, empty arrays, extreme sizes), timing benchmarks (1-page < 500 ms, 10-page < 5,000 ms), and template smoke tests.
669
+ - **Error code coverage** — new tests for `COLUMN_WIDTH_TOO_NARROW`, `IMAGE_LOAD_FAILED`, `SVG_LOAD_FAILED`, and `ASSEMBLY_FAILED`. 16 of 19 error codes now have direct test coverage.
670
+
671
+ ### Changed
672
+
673
+ - **`as any` audit** — eliminated 10 casts in `validate.ts` by introducing a typed `FormFieldElement` local binding. The remaining 8 instances (pdf-lib interop, dynamic import, internal back-references) are now documented with one-line comments explaining the constraint.
674
+ - **Comparison article** (`docs/articles/pretext-pdf-vs-pdfmake-2026.md`) 2,200-word draft covering feature matrix, typography quality, API design, performance, and migration quick-start. Marked `published: false` pending live demo.
675
+ - **Migration guide** (`docs/MIGRATION_FROM_PDFMAKE.md`) — 30+ pdfmake → pretext-pdf mappings, complete before/after invoice example, and a quick-start checklist. Linked from README.
676
+
677
+ ### Fixed
678
+
679
+ - **Phase 2F test types** — `fontWeight: 700 as 700` cast in pre-constructed rows array; removed non-existent `creationDate` from `DocumentMetadata`; replaced `allowCopying: false` with correct `encryption: { permissions: { copying: false } }`.
680
+ - **StackBlitz integration** added `.stackblitzrc` so WebContainer auto-runs `npm start` and opens the browser preview on port 3000.
681
+
682
+ ---
683
+
684
+ ## [0.5.3]2026-04-16
685
+
686
+ ### Changed
687
+
688
+ - **Upgraded `@chenglou/pretext` from 0.0.3 to 0.0.5** — picks up improved text analysis accuracy (~35% larger analysis module), better measurement precision, extracted bidi-data module for cleaner tree-shaking, and new `rich-inline` export (not yet used by pretext-pdf). No breaking changes — `prepareWithSegments()` and `layoutWithLines()` APIs are unchanged. All 223 tests pass, 3 example PDFs visually verified (RTL, TOC, hyperlinks).
689
+
690
+ ---
691
+
692
+ ## [0.5.2]2026-04-13
693
+
694
+ ### Added
695
+
696
+ - **`onImageLoadError` callback on `PdfDocument`** — gives callers control over image load failures. Return `'skip'` to silently omit the image (preserves existing default behavior). Return `'throw'` to abort rendering with the original error. Previously, all image failures were silently downgraded to `console.warn` with no way to detect them programmatically.
697
+
698
+ ```typescript
699
+ await render({
700
+ content: [...],
701
+ onImageLoadError: (src, error) => {
702
+ myLogger.warn('Image skipped', { src, error })
703
+ return 'skip' // or 'throw' to abort
704
+ }
705
+ })
706
+ ```
707
+
708
+ ---
709
+
710
+ ## [0.4.0]2026-04-08
711
+
712
+ ### Breaking Changes
713
+
714
+ - **Migrated from `pdf-lib` to `@cantoo/pdf-lib`** `@cantoo/pdf-lib` is now a direct `dependency` (always installed). Previously it was an optional peer dependency required only for encryption. This removes the `ENCRYPTION_NOT_AVAILABLE` error code and the separate `npm install @cantoo/pdf-lib` installation step. Encryption now works out of the box.
715
+ - **`ENCRYPTION_NOT_AVAILABLE` error code removed** encryption is now always available. Update any `switch` statements that handled this code.
716
+
717
+ ### Why this change
718
+
719
+ `pdf-lib` (the original) has not received a meaningful commit since November 2021. `@cantoo/pdf-lib` is the actively maintained fork (v2.6.5, 107+ releases, MIT license). pretext-pdf was already using `@cantoo/pdf-lib` for encryption — this commit makes it the single source of truth for all PDF operations.
720
+
721
+ ### Added
722
+
723
+ - `test/pretext-api-contract.test.ts` — canary test that asserts `@chenglou/pretext` exports the exact functions pretext-pdf depends on. Breaks loudly if pretext changes its API.
724
+ - `docs/ROADMAP.md` public multi-phase development plan
725
+
726
+ ### Changed
727
+
728
+ - `@chenglou/pretext` version pinned to exact `0.0.3` (no caret)prevents surprise breaking changes from upstream auto-updates
729
+ - `test:contract` script added — runs the pretext API contract test before the full test suite
730
+ - All internal comments updated from `pdf-lib` to `@cantoo/pdf-lib`
731
+
732
+ ---
733
+
734
+ ## [0.3.1] 2026-04-08
735
+
736
+ ### Fixed
737
+
738
+ - **Critical: Font resolution when installed as npm package** — `@fontsource/inter` is now resolved via `createRequire(import.meta.url)` instead of a hardcoded relative path. Previously, `path.join(__dirname, '..', 'node_modules', '@fontsource', 'inter', ...)` failed when npm hoisted the dependency to the consumer's top-level `node_modules`, causing `FONT_LOAD_FAILED` on every install. Now resolves correctly regardless of npm hoisting behavior.
739
+
740
+ ---
741
+
742
+ ## [0.3.0] — 2026-04-08
743
+
744
+ ### Added (Phase 8B — Interactive Forms)
745
+
746
+ - New `form-field` element type creates interactive AcroForm fields in PDFs
747
+ - `fieldType: 'text' | 'checkbox' | 'radio' | 'dropdown' | 'button'`
748
+ - `label` renders above the field as static text
749
+ - Text fields: `defaultValue`, `multiline`, `placeholder`, `maxLength`
750
+ - Checkboxes: `checked` initial state
751
+ - Radio groups and dropdowns: `options` array, `defaultSelected`
752
+ - `doc.flattenForms: true` bakes all fields into static content
753
+ - Custom `borderColor`, `backgroundColor`, `width`, `height`, `fontSize` per field
754
+ - New error codes: `FORM_FIELD_NAME_DUPLICATE` (duplicate `name` across fields), `FORM_FLATTEN_FAILED`
755
+ - Post-render `form.updateFieldAppearances()` ensures proper display in all PDF readers
756
+ - 10 comprehensive tests covering all form field types
757
+
758
+ ### Added (Phase 8E Signature Placeholder)
759
+
760
+ - `doc.signature` visual signature box drawn on a specified page
761
+ - Fields: `signerName`, `reason`, `location`, `x`, `y`, `width`, `height`, `page`, `borderColor`, `fontSize`
762
+ - Draws signature line, date line, and optional text inside a bordered rectangle
763
+ - `page` is 0-indexed, defaults to last page, clamps gracefully if out of range
764
+ - 6 comprehensive tests
765
+
766
+ ### Added (Phase 8D Callout Boxes)
767
+
768
+ - New `callout` element type styled highlight box with optional title
769
+ - Preset styles: `style: 'info'` (blue), `'warning'` (amber), `'tip'` (green), `'note'` (gray)
770
+ - Optional `title` rendered bold above content with left border accent
771
+ - Fully customizable: `backgroundColor`, `borderColor`, `color`, `titleColor`, `padding`
772
+ - Paginates correctly across pages (reuses blockquote pagination logic)
773
+ - 8 comprehensive tests
774
+
775
+ ### Added (Phase 8F — Document Metadata Extensions)
776
+
777
+ - `doc.metadata.language` — sets PDF `/Lang` catalog entry (BCP47 tag e.g. `'en-US'`, `'hi'`)
778
+ - `doc.metadata.producer`sets PDF producer field (e.g. `'MyApp v2.1'`)
779
+ - Both fields validate as non-empty strings
780
+ - 5 comprehensive tests
781
+
782
+ ---
783
+
784
+ ## [0.2.0] 2026-04-08
785
+
786
+ ### Added (Phase 8H Inline Formatting)
787
+
788
+ - `verticalAlign: 'superscript' | 'subscript'` on `InlineSpan` in rich-paragraphs
789
+ - Superscript renders at 65% font size, baseline shifted up by 40% of font size
790
+ - Subscript renders at 65% font size, baseline shifted down by 20% of font size
791
+ - `letterSpacing?: number` on `ParagraphElement`, `HeadingElement`, `RichParagraphElement` — extra pt between characters
792
+ - `smallCaps?: boolean` on those same three element types simulated via uppercase + 80% fontSize
793
+ - Character-by-character rendering for letterSpacing (pdf-lib has no native spacing param)
794
+ - 8 comprehensive tests covering all inline formatting functionality
795
+
796
+ ### Added (Phase 8AAnnotations/Comments)
797
+
798
+ - New `comment` element type sticky note annotation at position in document
799
+ - `annotation?: AnnotationSpec` on `ParagraphElement` and `HeadingElement` — attach note to element
800
+ - Supports: `contents`, `author`, `color` (hex), `open` (popup default state)
801
+ - Uses PDF `Subtype: 'Text'` annotation (sticky note icon in PDF viewers)
802
+ - 8 comprehensive tests covering all annotation functionality
803
+
804
+ ### Added (Phase 8C Document Assembly)
805
+
806
+ - New `merge(pdfs: Uint8Array[])` exported function combine pre-rendered PDFs
807
+ - New `assemble(parts: AssemblyPart[])` exported function — mix rendered docs + existing PDFs
808
+ - `AssemblyPart` interface: `{ doc?: PdfDocument, pdf?: Uint8Array }`
809
+ - New error codes: `ASSEMBLY_EMPTY`, `ASSEMBLY_FAILED`
810
+ - 8 comprehensive tests covering all assembly functionality
811
+
812
+ ### Fixed
813
+
814
+ - **CI case-sensitivity bug**: `test/phase-7-integration.test.ts` used `'en-US'` (uppercase) for hyphenation language. On Linux CI (case-sensitive filesystem) this failed with `UNSUPPORTED_LANGUAGE`. Changed to `'en-us'` to match package name `hyphenation.en-us`.
815
+
816
+ ---
817
+
818
+ ## [0.1.1] 2026-04-08
819
+
820
+ ### Added
821
+
822
+ - **Phase 8G: Hyperlinks** — Complete link annotation support:
823
+ - `paragraph.url` for external URI links on paragraphs
824
+ - `heading.url` for external URI links on headings
825
+ - `heading.anchor` for named PDF destinations (internal cross-references)
826
+ - `InlineSpan.href` for external and internal `#anchorId` links in rich-paragraphs
827
+ - `mailto:` scheme support for email links
828
+ - GoTo annotations for internal anchor references
829
+ - 9 comprehensive tests covering all hyperlink functionality
830
+
831
+ ### Fixed
832
+
833
+ - **Memory leak in test suite**: Removed module-level `_hypherCache` in `src/measure.ts` that accumulated ~188KB per language across 255+ test runs. Changed from cached Hypher instances to fresh instances per call (negligible performance impact, massive memory savings).
834
+ - **Node.js version compatibility**: Replaced `--experimental-strip-types` with `tsx` runner to support Node.js 18.x, 20.x, and 22.x in CI
835
+ - **Broken CI examples**: Removed references to non-existent Phase 8 example scripts from GitHub Actions workflow
836
+ - **README examples mismatch**: Updated Examples section to only list 5 existing Phase 7 examples (watermark, bookmarks, toc, rtl, encryption)
837
+ - **Test suite OOM issues**: Split large test files (paginate.test.ts) into paginate-basic.test.ts to work around Node.js `--experimental-strip-types` heap exhaustion bug on files >17KB
838
+
839
+ ### Changed
840
+
841
+ - `test:unit` now runs only `test/paginate-basic.test.ts` (fast, no canvas overhead)
842
+ - Reorganized test scripts: `test:unit`, `test:validate`, `test:e2e`, `test:phases` for better memory management
843
+ - Moved internal planning documentation to archive (preserved, not published)
844
+ - `devDependencies`: Added `@napi-rs/canvas` explicitly (was missing, causing CI failures)
845
+
846
+ ### Added
847
+
848
+ - `CONTRIBUTING.md`: Development setup, TDD workflow, PR process guide
849
+ - `CHENG_LOU_EMAIL_DRAFT.md`: Template for requesting endorsement from pretext creator
850
+ - `examples/comparison-pdfmake.ts`: pdfmake version of invoice for typography comparison
851
+
852
+ ---
853
+
854
+ ## [0.1.0] 2026-04-07
855
+
856
+ ### Added (Phase 7G Encryption)
857
+
858
+ - `doc.encryption` configuration for password-protecting PDFs
859
+ - User password and owner password support
860
+ - Granular permission restrictions: printing, copying, modifying, annotating
861
+ - Lazy-loads `@cantoo/pdf-lib` (optional peer dependency) zero cost when not used
862
+ - Error code: `ENCRYPTION_NOT_AVAILABLE` when encryption is requested but dependency not installed
863
+
864
+ ### Added (Phase 7F RTL Text Support)
865
+
866
+ - Right-to-left text support for Arabic, Hebrew, and other RTL languages
867
+ - Unicode bidirectional text algorithm via `bidi-js`
868
+ - `dir` attribute on text elements: `'ltr'` | `'rtl'` | `'auto'` for per-element control
869
+ - RTL text works with headings, paragraphs, lists, tables, and all text elements
870
+ - Automatic detection of mixed LTR/RTL content
871
+
872
+ ### Added (Phase 7E — SVG Support)
873
+
874
+ - `{ type: 'svg', svg: '<...' }` element for embedding SVG graphics
875
+ - SVG rasterization via `@napi-rs/canvas`
876
+ - ViewBox auto-sizing: automatic height calculation from viewBox aspect ratio
877
+ - Explicit sizing: `width` and `height` parameters for precise control
878
+ - Alignment options: `align: 'left' | 'center' | 'right'`
879
+ - Multi-page support: SVGs paginate correctly across page breaks
880
+ - Error code: `SVG_RENDER_FAILED` for SVG rasterization errors
881
+
882
+ ### Added (Phase 7D — Table of Contents)
883
+
884
+ - `{ type: 'toc' }` element for automatic TOC generation
885
+ - Two-pass rendering pipeline ensures accurate page numbers
886
+ - Configurable: `title`, `showTitle`, `minLevel`/`maxLevel`, dot leaders, level indentation
887
+ - Auto-indexed from heading structure (H1, H2, H3, etc.)
888
+ - Supports custom formatting via `fontSize`, `color`, `spaceAfter` parameters
889
+
890
+ ### Added (Phase 7C — Hyphenation)
891
+
892
+ - Automatic word hyphenation for better justified text layout
893
+ - `doc.hyphenation: { language: 'en-US' }` for document-level config
894
+ - Liang's algorithm via `hypher` package for accurate break points
895
+ - Configurable: `minWordLength`, `leftMin`, `rightMin`, per-element `hyphenate: false` opt-out
896
+ - Language support: includes `hyphenation.en-us` (additional languages via npm packages)
897
+ - Error code: `UNSUPPORTED_LANGUAGE` when language not available
898
+
899
+ ### Added (Phase 7B — Watermarks)
900
+
901
+ - `doc.watermark` for text or image watermarks on every page
902
+ - Text watermarks: `text`, `fontSize`, `fontWeight`, `color`, `opacity`, `rotation`
903
+ - Image watermarks: `image` (Uint8Array), `opacity`, `rotation`, `color` (tint)
904
+ - Watermarks render behind content (lower z-index)
905
+ - Rotation bounds: -360 ≤ rotation ≤ 360 degrees
906
+ - Validation: must provide either text or image, never both required
907
+
908
+ ### Added (Phase 7A — Bookmarks / PDF Outline)
909
+
910
+ - PDF sidebar bookmarks auto-generated from heading structure
911
+ - Enabled by default: `bookmarks: true` or `bookmarks: { minLevel: 1, maxLevel: 3 }`
912
+ - Level filtering: include/exclude heading levels from outline
913
+ - Per-heading opt-out: `bookmark: false` on heading elements
914
+ - Keyboard navigation: Cmd/Ctrl+Opt/Alt+O in PDF readers to toggle bookmark sidebar
915
+
916
+ ### Added (Phase 6 — Advanced Features)
917
+
918
+ - Header and footer support with {{pageNumber}} and {{totalPages}} tokens
919
+ - Text decoration: strikethrough, underline
920
+ - Text alignment: left, center, right, justify
921
+ - Line height control: custom line-height multipliers
922
+ - Column layout with multi-column content flow
923
+ - Tables with colspan/rowspan support
924
+
925
+ ### Added (Phase 5 — Rich Text / Builder API)
926
+
927
+ - Fluent builder API for programmatic document construction
928
+ - Rich text element with nested formatting (bold, italic, links)
929
+ - Inline code and code blocks with syntax highlighting
930
+ - Block quotes with custom styling
931
+ - Horizontal rules (hr element)
932
+ - Numbered and bulleted lists with nesting
933
+
934
+ ### Added (Phases 1–4 — Core Engine)
935
+
936
+ - Core PDF generation via `pdf-lib`
937
+ - Element types: paragraph, heading, table, image, list, code, blockquote
938
+ - Font support: Inter bundled, custom TTF embedding
939
+ - Document metadata: title, author, subject, keywords, created date
940
+ - Page sizing: A4, A3, A5, Letter, Legal, or custom dimensions
941
+ - Margins: top, bottom, left, right per page
942
+ - Multi-page pagination with orphan/widow control
943
+ - Image formats: PNG, JPG, WebP
944
+ - Table features: custom column widths, cell padding, borders, header styling
945
+ - Colors: hex color codes throughout (text, backgrounds, borders)