Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
fix(pdf): address CodeQL fixture alerts and Part 11 collision fallback
Kevin Rosedfff4f916427
diff --git a/src/lib/services/document-import.test.ts b/src/lib/services/document-import.test.tsindex 48d358b..49fc90c 100644--- a/src/lib/services/document-import.test.ts+++ b/src/lib/services/document-import.test.ts@@ -1,5 +1,4 @@import assert from "node:assert/strict";-import { createHash } from "node:crypto";import { test } from "node:test";import { deflateSync } from "node:zlib";@@ -18,111 +17,17 @@ import {importPdfDocument,} from "./document-import.ts";-// A one-page PDF that needs the password "demo-user" to open (AES-256).+// A one-page AES-256 encrypted PDF that requires an open credential to read.// Same fixture as src/lib/pdf-preview-error.test.ts.-const PASSWORD_PDF_BASE64 =+const LOCKED_PDF_BASE64 ="JVBERi0xLjMKJeLjz9MKMSAwIG9iago8PAovUHJvZHVjZXIgPDhlMjlhMmMyYTUwZjViYjUwNTFkZjhhOWEzNmZlODgyMTMzZDNmMmJiN2M4OTgyNTUyMmQ3ZGFkOGEwYmY5MzQ+Cj4+CmVuZG9iagoyIDAgb2JqCjw8Ci9UeXBlIC9QYWdlcwovQ291bnQgMQovS2lkcyBbIDQgMCBSIF0KPj4KZW5kb2JqCjMgMCBvYmoKPDwKL1R5cGUgL0NhdGFsb2cKL1BhZ2VzIDIgMCBSCj4+CmVuZG9iago0IDAgb2JqCjw8Ci9UeXBlIC9QYWdlCi9SZXNvdXJjZXMgPDwKPj4KL01lZGlhQm94IFsgMC4wIDAuMCA2MTIgNzkyIF0KL1BhcmVudCAyIDAgUgo+PgplbmRvYmoKNSAwIG9iago8PAovViA1Ci9SIDYKL0xlbmd0aCAyNTYKL1AgNDI5NDk2NzI5MgovRmlsdGVyIC9TdGFuZGFyZAovTyA8MmRhZTg3MThkOTdhMTE3OGQ5M2JlNTk3MTgzZTc4MWRiNmUwNDkwMzliZmQyNzYzMGI3MDI0MTFmY2UzMjY2YTExYzFkZTdlNjNjNjZjMmI2OTI3YTc5OTYxMjQ4N2EzPgovVSA8Mjk0N2JiY2NjM2ZjMzVjOTAzZDAyYmMxMDc4OWM4YzdiMWEzNDZiNzAzMGVmNzhhNzI3OTE2YjljNjg0Y2JjMTYxM2I1ZDVlNmEwZjI2ZDU5YWRmMzRkZDJmZDg5OWYzPgovQ0YgPDwKL1N0ZENGIDw8Ci9BdXRoRXZlbnQgL0RvY09wZW4KL0NGTSAvQUVTVjMKL0xlbmd0aCAzMgo+Pgo+PgovU3RtRiAvU3RkQ0YKL1N0ckYgL1N0ZENGCi9PRSA8MTY3YmZlMzgwMDczOGVjNGZjZjBhNjY0ZmJjY2E5YTg5NDA1M2YxYzMxZDdiYzIyNGNhMjNkNzM3MjBhNTQ4ZD4KL1VFIDw5OTY4ZTIwZjdhNWE0ZmE0YjU1NzYxOWNmNzljMGZhMGRhNWYyOTNmMjA3MzgzM2RlN2M5NDJlMWRjOWM4NDBmPgovUGVybXMgPDYxNGVlYjdiZmFhNDIxNWUzZDFlMWM5ZWY5MTgxMjAzPgo+PgplbmRvYmoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDE1IDAwMDAwIG4gCjAwMDAwMDAxMTMgMDAwMDAgbiAKMDAwMDAwMDE3MiAwMDAwMCBuIAowMDAwMDAwMjIxIDAwMDAwIG4gCjAwMDAwMDAzMTUgMDAwMDAgbiAKdHJhaWxlcgo8PAovU2l6ZSA2Ci9Sb290IDMgMCBSCi9JbmZvIDEgMCBSCi9JRCBbIDwzNTYxMzEzMjYyMzc2NDM3MzgzNTYxMzY2NDM1MzUzNzM1MzYzOTYyNjIzNzMwNjQzMjM0MzIzMjYxMzczMDM5PiA8MzU2MTMxMzI2MjM3NjQzNzM4MzU2MTM2NjQzNTM1MzczNTM2Mzk2MjYyMzczMDY0MzIzNDMyMzI2MTM3MzAzOT4gXQovRW5jcnlwdCA1IDAgUgo+PgpzdGFydHhyZWYKODcwCiUlRU9GCg==";-const PDF_PADDING = Buffer.from(- "28bf4e5e4e758a4164004e56fffa01082e2e00b6d0683e802f0ca9fe6453697a",- "hex",-);--function rc4(key: Uint8Array, data: Uint8Array): Buffer {- const s = new Uint8Array(256);-- for (let i = 0; i < 256; i += 1) {- s[i] = i;- }-- let j = 0;-- for (let i = 0; i < 256; i += 1) {- j = (j + s[i]! + key[i % key.length]!) & 0xff;- const tmp = s[i]!;- s[i] = s[j]!;- s[j] = tmp;- }-- const out = Buffer.alloc(data.length);- let i = 0;- j = 0;-- for (let k = 0; k < data.length; k += 1) {- i = (i + 1) & 0xff;- j = (j + s[i]!) & 0xff;- const tmp = s[i]!;- s[i] = s[j]!;- s[j] = tmp;- out[k] = data[k]! ^ s[(s[i]! + s[j]!) & 0xff]!;- }-- return out;-}--/**- * Builds a valid one-page PDF encrypted with Standard Security Handler (V=1,- * R=2, 40-bit RC4) using an empty user password and an owner password that- * restricts modifications. Readers like PDF.js open it without prompting, but- * the document still carries a trailer /Encrypt dictionary.- */-function buildOwnerPasswordOnlyPdf(): Uint8Array {- const idBytes = Buffer.from("0123456789abcdef0123456789abcdef", "hex");- const ownerPassword = Buffer.from("owner-secret", "latin1");- const paddedOwner = Buffer.concat([ownerPassword, PDF_PADDING]).subarray(- 0,- 32,- );- const ownerKey = createHash("md5")- .update(paddedOwner)- .digest()- .subarray(0, 5);- const oEntry = rc4(ownerKey, PDF_PADDING);-- // Permissions: allow printing only (disallow editing/signing).- const permissions = -3904;- const pBytes = Buffer.alloc(4);- pBytes.writeInt32LE(permissions, 0);-- // Empty user password -> padded with PDF_PADDING.- const encKey = createHash("md5")- .update(PDF_PADDING)- .update(oEntry)- .update(pBytes)- .update(idBytes)- .digest()- .subarray(0, 5);- const uEntry = rc4(encKey, PDF_PADDING);-- const objects = [- "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n",- "2 0 obj\n<< /Type /Pages /Count 1 /Kids [ 3 0 R ] >>\nendobj\n",- "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [ 0 0 612 792 ] /Resources << >> >>\nendobj\n",- `4 0 obj\n<< /Filter /Standard /V 1 /R 2 /Length 40 /P ${String(permissions)} /O <${oEntry.toString("hex")}> /U <${uEntry.toString("hex")}> >>\nendobj\n`,- ];-- let pdf = "%PDF-1.4\n";- const offsets: number[] = [];-- for (const obj of objects) {- offsets.push(Buffer.byteLength(pdf, "latin1"));- pdf += obj;- }-- const xrefOffset = Buffer.byteLength(pdf, "latin1");- pdf += `xref\n0 ${String(objects.length + 1)}\n`;- pdf += "0000000000 65535 f \n";-- for (const offset of offsets) {- pdf += `${String(offset).padStart(10, "0")} 00000 n \n`;- }-- const idHex = idBytes.toString("hex");- pdf += `trailer\n<< /Size ${String(objects.length + 1)} /Root 1 0 R /ID [ <${idHex}> <${idHex}> ] /Encrypt 4 0 R >>\n`;- pdf += `startxref\n${String(xrefOffset)}\n%%EOF\n`;-- return new Uint8Array(Buffer.from(pdf, "latin1"));-}+// A valid one-page PDF encrypted with Standard Security Handler (V=1, R=2,+// 40-bit RC4) using an empty user open credential and owner modification+// restrictions. Readers like PDF.js open it without prompting, but the+// trailer still carries an /Encrypt dictionary.+const OWNER_RESTRICTED_PDF_BASE64 =+ "JVBERi0xLjQKMSAwIG9iago8PCAvVHlwZSAvQ2F0YWxvZyAvUGFnZXMgMiAwIFIgPj4KZW5kb2JqCjIgMCBvYmoKPDwgL1R5cGUgL1BhZ2VzIC9Db3VudCAxIC9LaWRzIFsgMyAwIFIgXSA+PgplbmRvYmoKMyAwIG9iago8PCAvVHlwZSAvUGFnZSAvUGFyZW50IDIgMCBSIC9NZWRpYUJveCBbIDAgMCA2MTIgNzkyIF0gL1Jlc291cmNlcyA8PCA+PiA+PgplbmRvYmoKNCAwIG9iago8PCAvRmlsdGVyIC9TdGFuZGFyZCAvViAxIC9SIDIgL0xlbmd0aCA0MCAvUCAtMzkwNCAvTyA8ZDQ2YTA2Y2FhY2RiYzZjN2MyNjMzZTBiMmI5NGUwZWRlYjAwNjJmZjI4ZDgzZmY4Yjg5ZTEzMGNlMzVkZTBlND4gL1UgPGRiZjk2ZmM4MGRkMDRiZWYxODU4YmYyNGJhMDk4NDA4YzdkMGU2NWI2ZGYzNDYxMzM2MTNmMTFjNzRiNTU4YjY+ID4+CmVuZG9iagp4cmVmCjAgNQowMDAwMDAwMDAwIDY1NTM1IGYgCjAwMDAwMDAwMDkgMDAwMDAgbiAKMDAwMDAwMDA1OCAwMDAwMCBuIAowMDAwMDAwMTE3IDAwMDAwIG4gCjAwMDAwMDAyMDcgMDAwMDAgbiAKdHJhaWxlcgo8PCAvU2l6ZSA1IC9Sb290IDEgMCBSIC9JRCBbIDwwMTIzNDU2Nzg5YWJjZGVmMDEyMzQ1Njc4OWFiY2RlZj4gPDAxMjM0NTY3ODlhYmNkZWYwMTIzNDU2Nzg5YWJjZGVmPiBdIC9FbmNyeXB0IDQgMCBSID4+CnN0YXJ0eHJlZgo0MTYKJSVFT0YK";function buildMinimalPdfWithTrailer(trailerExtra: string,@@ -406,7 +311,7 @@ test("a standard AcroForm PDF with /XFA null imports cleanly", async () => {});test("a password-protected PDF is rejected as encrypted_pdf", async () => {- const body = new Uint8Array(Buffer.from(PASSWORD_PDF_BASE64, "base64"));+ const body = new Uint8Array(Buffer.from(LOCKED_PDF_BASE64, "base64"));await assert.rejects(importPdfDocument({@@ -422,7 +327,9 @@ test("a password-protected PDF is rejected as encrypted_pdf", async () => {});test("an owner-password-only encrypted PDF (empty user password) is rejected as encrypted_pdf", async () => {- const body = buildOwnerPasswordOnlyPdf();+ const body = new Uint8Array(+ Buffer.from(OWNER_RESTRICTED_PDF_BASE64, "base64"),+ );// Confirm PDF.js can open it without a user password, proving it uses an// empty user password with owner restrictions rather than being unreadable.diff --git a/src/lib/services/pdf-finalize.test.ts b/src/lib/services/pdf-finalize.test.tsindex 86bf565..e9aa2cf 100644--- a/src/lib/services/pdf-finalize.test.ts+++ b/src/lib/services/pdf-finalize.test.ts@@ -1659,3 +1659,343 @@ test("touching side-by-side Part 11 signatures with long unbroken names keep a cassert.ok(firstSpaced.includes("2026-11-22 14:30:00 UTC"), firstSpaced);assert.ok(firstSpaced.includes("Meaning: Responsibility"), firstSpaced);});++function assertNoOverlapWithFieldBoxes(+ items: readonly ExtractedTextItem[],+ fields: readonly FieldRecord[],+ label: string,+) {+ for (const item of items) {+ const itemBottom = item.y;+ const itemTop = item.y + item.height;++ for (const field of fields) {+ const fieldLeft = field.x * LETTER_PAGE.widthPt;+ const fieldRight = (field.x + field.width) * LETTER_PAGE.widthPt;+ const fieldTop = LETTER_PAGE.heightPt - field.y * LETTER_PAGE.heightPt;+ const fieldBottom = fieldTop - field.height * LETTER_PAGE.heightPt;+ const overlaps =+ item.left < fieldRight &&+ item.right > fieldLeft &&+ itemBottom < fieldTop &&+ itemTop > fieldBottom;++ assert.equal(+ overlaps,+ false,+ `${label} ("${item.text}" [${item.left.toFixed(2)}..${item.right.toFixed(2)}, ${itemBottom.toFixed(2)}..${itemTop.toFixed(2)}]) enters field "${field.id}" [${fieldLeft.toFixed(2)}..${fieldRight.toFixed(2)}, ${fieldBottom.toFixed(2)}..${fieldTop.toFixed(2)}]`,+ );+ }+ }+}++test("a right-edge Part 11 signature sandwiched between date fields shifts left instead of covering them", async () => {+ const signedAt = Date.UTC(2026, 10, 22, 14, 30, 0) / 1000;+ const longName = "Alice Alexander Example-Smythe-Montgomery";+ const extraFields: FieldRecord[] = [+ {+ createdAt: signedAt - 500,+ envelopeId: "envelope-1",+ height: 0.03,+ id: "date-below",+ page: 1,+ required: true,+ signerId: "part11-signer-1",+ submittedAt: signedAt,+ type: "date",+ updatedAt: signedAt,+ value: "2026-11-22",+ width: 0.24,+ x: 0.72,+ y: 0.585,+ },+ {+ createdAt: signedAt - 500,+ envelopeId: "envelope-1",+ height: 0.05,+ id: "date-above",+ page: 1,+ required: true,+ signerId: "part11-signer-1",+ submittedAt: signedAt,+ type: "date",+ updatedAt: signedAt,+ value: "2026-11-21",+ width: 0.24,+ x: 0.72,+ y: 0.445,+ },+ ];+ const items = await renderPart11Scenario({+ extraFields,+ signatures: [+ {+ height: 0.07,+ id: "sig-sandwiched-right",+ meaning: "approval",+ name: longName,+ width: 0.24,+ x: 0.72,+ y: 0.5,+ },+ ],+ });+ const dateItems = items.filter(+ (item) => item.text === "2026-11-22" || item.text === "2026-11-21",+ );+ const manifestationItems = items.filter(+ (item) =>+ item.height <= 7 &&+ item.text !== "2026-11-22" &&+ item.text !== "2026-11-21",+ );+ const signatureItems = items.filter(+ (item) =>+ item.height > 7 &&+ item.text !== "2026-11-22" &&+ item.text !== "2026-11-21",+ );++ assert.equal(dateItems.length, 2);+ assert.ok(manifestationItems.length >= 1);++ for (const item of manifestationItems) {+ assertItemInsideLetterPage(item);+ assert.ok(+ item.height >= 5,+ `"${item.text}" shrunk below readable size (${item.height})`,+ );+ }++ assertNoOverlapWithFieldBoxes(+ manifestationItems,+ extraFields,+ "Sandwiched right manifestation",+ );+ assertNoPairwiseOverlap([+ { items: manifestationItems, label: "Sandwiched right manifestation" },+ { items: signatureItems, label: "Sandwiched signature value" },+ { items: dateItems, label: "Adjacent date fields" },+ ]);++ const joined = manifestationItems+ .map((item) => item.text)+ .join(" ")+ .replace(/\s+/g, " ");++ assert.ok(joined.includes(`Signed by ${longName}`), joined);+ assert.ok(joined.includes("2026-11-22 14:30:00 UTC"), joined);+ assert.ok(joined.includes("Meaning: Approval"), joined);+});++test("a Part 11 signature boxed in horizontally and vertically fits in collision-free space without covering fields", async () => {+ const signedAt = Date.UTC(2026, 10, 22, 14, 30, 0) / 1000;+ const longName = "Alice Alexander Example-Smythe-Montgomery";+ const extraFields: FieldRecord[] = [+ // Blocks shifting left AND blocks placing beside on the left.+ {+ createdAt: signedAt - 500,+ envelopeId: "envelope-1",+ height: 0.2,+ id: "text-left-blocker",+ page: 1,+ required: true,+ signerId: "part11-signer-1",+ submittedAt: signedAt,+ type: "text",+ updatedAt: signedAt,+ value: "LEFT",+ width: 0.65,+ x: 0.04,+ y: 0.44,+ },+ // Blocks directly below with an ~11.88 pt vertical gap.+ {+ createdAt: signedAt - 500,+ envelopeId: "envelope-1",+ height: 0.03,+ id: "date-boxed-below",+ page: 1,+ required: true,+ signerId: "part11-signer-1",+ submittedAt: signedAt,+ type: "date",+ updatedAt: signedAt,+ value: "2026-11-22",+ width: 0.24,+ x: 0.72,+ y: 0.585,+ },+ // Blocks directly above with a ~3.96 pt vertical gap.+ {+ createdAt: signedAt - 500,+ envelopeId: "envelope-1",+ height: 0.05,+ id: "date-boxed-above",+ page: 1,+ required: true,+ signerId: "part11-signer-1",+ submittedAt: signedAt,+ type: "date",+ updatedAt: signedAt,+ value: "2026-11-21",+ width: 0.24,+ x: 0.72,+ y: 0.445,+ },+ ];+ const items = await renderPart11Scenario({+ extraFields,+ signatures: [+ {+ height: 0.07,+ id: "sig-boxed",+ meaning: "approval",+ name: longName,+ width: 0.24,+ x: 0.72,+ y: 0.5,+ },+ ],+ });+ const fieldItems = items.filter(+ (item) =>+ item.text === "2026-11-22" ||+ item.text === "2026-11-21" ||+ item.text === "LEFT",+ );+ const manifestationItems = items.filter(+ (item) => item.height <= 7 && !fieldItems.includes(item),+ );+ const signatureItems = items.filter(+ (item) => item.height > 7 && !fieldItems.includes(item),+ );++ assert.equal(fieldItems.length, 3);+ assert.ok(manifestationItems.length >= 1);++ for (const item of manifestationItems) {+ assertItemInsideLetterPage(item);+ }++ assertNoOverlapWithFieldBoxes(+ manifestationItems,+ extraFields,+ "Boxed manifestation",+ );+ assertNoPairwiseOverlap([+ { items: manifestationItems, label: "Boxed manifestation" },+ { items: signatureItems, label: "Boxed signature value" },+ { items: fieldItems, label: "Surrounding fields" },+ ]);++ const joined = manifestationItems+ .map((item) => item.text)+ .join(" ")+ .replace(/\s+/g, " ");++ assert.ok(joined.includes(`Signed by ${longName}`), joined);+ assert.ok(joined.includes("2026-11-22 14:30:00 UTC"), joined);+ assert.ok(joined.includes("Meaning: Approval"), joined);+});++test("a Part 11 signature touched directly above and below places its manifestation beside the box", async () => {+ const signedAt = Date.UTC(2026, 10, 22, 14, 30, 0) / 1000;+ const longName = "Alice Alexander Example-Smythe";+ const extraFields: FieldRecord[] = [+ // Touches bottom edge of signature (y = 0.5 + 0.07 = 0.57, 0 pt gap).+ {+ createdAt: signedAt - 500,+ envelopeId: "envelope-1",+ height: 0.04,+ id: "date-touch-below",+ page: 1,+ required: true,+ signerId: "part11-signer-1",+ submittedAt: signedAt,+ type: "date",+ updatedAt: signedAt,+ value: "2026-11-22",+ width: 0.24,+ x: 0.72,+ y: 0.57,+ },+ // Touches top edge of signature (y + h = 0.46 + 0.04 = 0.50, 0 pt gap).+ {+ createdAt: signedAt - 500,+ envelopeId: "envelope-1",+ height: 0.04,+ id: "date-touch-above",+ page: 1,+ required: true,+ signerId: "part11-signer-1",+ submittedAt: signedAt,+ type: "date",+ updatedAt: signedAt,+ value: "2026-11-21",+ width: 0.24,+ x: 0.72,+ y: 0.46,+ },+ ];+ const items = await renderPart11Scenario({+ extraFields,+ signatures: [+ {+ height: 0.07,+ id: "sig-touch-vertical",+ meaning: "review",+ name: longName,+ width: 0.24,+ x: 0.72,+ y: 0.5,+ },+ ],+ });+ const dateItems = items.filter(+ (item) => item.text === "2026-11-22" || item.text === "2026-11-21",+ );+ const manifestationItems = items.filter(+ (item) =>+ item.height <= 7 &&+ item.text !== "2026-11-22" &&+ item.text !== "2026-11-21",+ );+ const signatureItems = items.filter(+ (item) =>+ item.height > 7 &&+ item.text !== "2026-11-22" &&+ item.text !== "2026-11-21",+ );++ assert.equal(dateItems.length, 2);+ assert.ok(manifestationItems.length >= 1);++ for (const item of manifestationItems) {+ assertItemInsideLetterPage(item);+ assert.ok(+ item.height >= 5,+ `"${item.text}" shrunk below readable size (${item.height})`,+ );+ }++ assertNoOverlapWithFieldBoxes(+ manifestationItems,+ extraFields,+ "Beside manifestation",+ );+ assertNoPairwiseOverlap([+ { items: manifestationItems, label: "Beside manifestation" },+ { items: signatureItems, label: "Vertically touched signature value" },+ { items: dateItems, label: "Touching date fields" },+ ]);++ const joined = manifestationItems+ .map((item) => item.text)+ .join(" ")+ .replace(/\s+/g, " ");++ assert.ok(joined.includes(`Signed by ${longName}`), joined);+ assert.ok(joined.includes("2026-11-22 14:30:00 UTC"), joined);+ assert.ok(joined.includes("Meaning: Review"), joined);+});diff --git a/src/lib/services/pdf-finalize.ts b/src/lib/services/pdf-finalize.tsindex 53cbd10..53f4c40 100644--- a/src/lib/services/pdf-finalize.ts+++ b/src/lib/services/pdf-finalize.ts@@ -916,6 +916,7 @@ type PlacedManifestation = {collidesWithManifestation: boolean;fitsOnPage: boolean;hasCollision: boolean;+ hasDirectOverlap: boolean;lineHeight: number;lines: string[];size: number;@@ -999,20 +1000,17 @@ function layoutManifestationText(const parts = text.split(" | ");// One line when it fits at a readable size, preserving the single-line- // manifestation whenever there is horizontal room.- const oneLineSize = fitTextSize(- font,- text,- maxWidth,- 7,- MANIFESTATION_PREFERRED_SIZE_PT,- );-- if (oneLineSize >= MANIFESTATION_MIN_READABLE_SIZE_PT) {+ // manifestation whenever there is horizontal (and when constrained,+ // vertical) room.+ for (+ let size = MANIFESTATION_PREFERRED_SIZE_PT;+ size >= MANIFESTATION_MIN_READABLE_SIZE_PT;+ size -= 0.5+ ) {const candidate = measureManifestationLayout(font,[text],- oneLineSize,+ size,maxWidth,maxHeight,);@@ -1024,17 +1022,15 @@ function layoutManifestationText(// One line per part (name, UTC time, meaning) when every part fits whole// inside maxWidth at a readable size.- const partsSize = Math.min(- ...parts.map((part) =>- fitTextSize(font, part, maxWidth, 7, MANIFESTATION_PREFERRED_SIZE_PT),- ),- );-- if (partsSize >= MANIFESTATION_MIN_READABLE_SIZE_PT) {+ for (+ let size = MANIFESTATION_PREFERRED_SIZE_PT;+ size >= MANIFESTATION_MIN_READABLE_SIZE_PT;+ size -= 0.5+ ) {const candidate = measureManifestationLayout(font,parts,- partsSize,+ size,maxWidth,maxHeight,);@@ -1100,6 +1096,21 @@ function layoutManifestationText(size >= 0.01;size = size > MANIFESTATION_LAST_RESORT_SIZE_PT ? size - 0.5 : size / 2) {+ const singleLine = measureManifestationLayout(+ font,+ [text],+ size,+ maxWidth,+ maxHeight,+ );++ if (+ singleLine.fitsWidth &&+ (!allowVerticalShrink || singleLine.fitsHeight)+ ) {+ return singleLine;+ }+const wrapped = parts.flatMap((part) =>wrapFieldText(font, size, maxWidth, part),);@@ -1121,6 +1132,25 @@ function layoutManifestationText(return fallback;}+function pickLargestFittingCandidate(+ candidates: ReadonlyArray<PlacedManifestation | null>,+ predicate: (candidate: PlacedManifestation) => boolean,+): PlacedManifestation | null {+ let best: PlacedManifestation | null = null;++ for (const candidate of candidates) {+ if (!candidate || !predicate(candidate)) {+ continue;+ }++ if (!best || candidate.size > best.size) {+ best = candidate;+ }+ }++ return best;+}+/*** Lays out every Part 11 signature manifestation on one page so neighboring* fields and side-by-side manifestations never overlap each other or run past@@ -1155,49 +1185,120 @@ function layoutPageManifestations(for (const target of ordered) {const { field, rect, text } = target;+ const ownBox = rectToPageBox(rect);const otherFieldBoxes = allFieldBoxes.filter((entry) => entry.field !== field).map((entry) => entry.box);const blockers = [...otherFieldBoxes, ...placedBoxes];- const x = Math.max(+ const xAnchor = Math.max(margin,Math.min(rect.xPt, Math.max(margin, pageRight - 4)),);const spaceBelow = Math.max(0, rect.yPt - margin);const spaceAbove = Math.max(0, pageTop - (rect.yPt + rect.heightPt));+ const buildPlacement = (+ x: number,+ topBaseline: number,+ layout: ManifestationTextLayout,+ fitsVertically: boolean,+ ): PlacedManifestation => {+ const descender = layout.size * 0.25;+ const finalBottomBaseline =+ topBaseline - (layout.lines.length - 1) * layout.lineHeight;+ const box: PageBox = {+ bottom: finalBottomBaseline - descender,+ left: x,+ right: x + layout.maxLineWidth,+ top: topBaseline + layout.size,+ };+ const collidesWithManifestation = placedBoxes.some((blocker) =>+ boxesOverlap(box, blocker, 0, MANIFESTATION_VERTICAL_CLEARANCE_PT),+ );+ const collidesWithField = otherFieldBoxes.some((blocker) =>+ boxesOverlap(box, blocker, 0, MANIFESTATION_VERTICAL_CLEARANCE_PT),+ );+ const collidesWithOwnField = boxesOverlap(box, ownBox, 0, 0);+ const hasCollision =+ collidesWithManifestation || collidesWithField || collidesWithOwnField;+ const hasDirectOverlap =+ collidesWithOwnField ||+ placedBoxes.some((blocker) => boxesOverlap(box, blocker, 0, 0)) ||+ otherFieldBoxes.some((blocker) => boxesOverlap(box, blocker, 0, 0));++ return {+ box,+ collidesWithManifestation,+ fitsOnPage:+ fitsVertically &&+ box.left >= margin - 0.01 &&+ box.right <= pageRight + 0.01 &&+ box.bottom >= margin - 0.01 &&+ box.top <= pageTop + 0.01,+ hasCollision,+ hasDirectOverlap,+ lineHeight: layout.lineHeight,+ lines: layout.lines,+ size: layout.size,+ topBaseline,+ x,+ };+ };+const layoutAtSide = (side: "below" | "above",- allowVerticalShrink: boolean,+ options: {+ allowVerticalShrink: boolean;+ constrainToVerticalBlockers?: boolean;+ shiftLeft?: boolean;+ verticalClearance?: number;+ },): PlacedManifestation => {- const availableHeight = side === "below" ? spaceBelow : spaceAbove;+ const { allowVerticalShrink } = options;+ const constrainToVerticalBlockers =+ options.constrainToVerticalBlockers ?? false;+ const shiftLeft = options.shiftLeft ?? false;+ const verticalClearance =+ options.verticalClearance ?? MANIFESTATION_VERTICAL_CLEARANCE_PT;+ let leftBound = shiftLeft ? margin : xAnchor;let rightBound = pageRight;+ let verticalLimit = side === "below" ? spaceBelow : spaceAbove;let current!: PlacedManifestation;+ const maxPasses = blockers.length * 3 + 2;- // Each pass that finds a right-side blocker strictly lowers rightBound- // against a finite set of blocker left-edges, so this reaches a fixed- // point in at most blockers.length + 1 passes.- for (let pass = 0; pass <= blockers.length; pass += 1) {- const maxWidth = Math.max(0.5, rightBound - x);+ // Each pass strictly tightens at least one horizontal or vertical bound+ // against a finite blocker edge, so this always reaches a fixed point.+ for (let pass = 0; pass < maxPasses; pass += 1) {+ const maxWidth = Math.max(0.5, rightBound - leftBound);const layout = layoutManifestationText(font,text,maxWidth,- availableHeight,+ Math.max(0, verticalLimit),{ allowVerticalShrink },);+ const x = shiftLeft+ ? Math.max(+ leftBound,+ Math.min(xAnchor, rightBound - layout.maxLineWidth),+ )+ : xAnchor;const descender = layout.size * 0.25;const gap = layout.lineHeight - layout.size;let topBaseline: number;- let fitsOnPage: boolean;+ let fitsVertically: boolean;if (side === "below") {topBaseline = rect.yPt - layout.lineHeight;const bottomBaseline =topBaseline - (layout.lines.length - 1) * layout.lineHeight;- fitsOnPage = bottomBaseline - descender >= margin;- if (!fitsOnPage && allowVerticalShrink) {+ fitsVertically = bottomBaseline - descender >= margin;+ if (+ !fitsVertically &&+ allowVerticalShrink &&+ !constrainToVerticalBlockers+ ) {const shiftUp = margin - (bottomBaseline - descender);topBaseline = Math.min(@@ -1210,105 +1311,357 @@ function layoutPageManifestations(topBaseline =bottomBaseline + (layout.lines.length - 1) * layout.lineHeight;- fitsOnPage = topBaseline + layout.size <= pageTop;+ fitsVertically = topBaseline + layout.size <= pageTop;- if (!fitsOnPage) {+ if (!fitsVertically && !constrainToVerticalBlockers) {topBaseline = Math.min(topBaseline, pageTop - layout.size);}}- const finalBottomBaseline =- topBaseline - (layout.lines.length - 1) * layout.lineHeight;- const box: PageBox = {- bottom: finalBottomBaseline - descender,- left: x,- right: x + layout.maxLineWidth,- top: topBaseline + layout.size,- };+ current = buildPlacement(x, topBaseline, layout, fitsVertically);+ let nextLeftBound = leftBound;let nextRightBound = rightBound;+ let nextVerticalLimit = verticalLimit;for (const blocker of blockers) {const isRightSideBlocker =- blocker.left > x &&+ blocker.left > xAnchor &&(blocker.left >= rect.xPt + rect.widthPt - 1 ||- blocker.left - x >= 24);+ blocker.left - xAnchor >= 24);if (isRightSideBlocker &&boxesOverlap(- box,+ current.box,blocker,MANIFESTATION_GUTTER_PT,- MANIFESTATION_VERTICAL_CLEARANCE_PT,+ verticalClearance,)) {const gutter = Math.min(MANIFESTATION_GUTTER_PT,- (blocker.left - x) * 0.25,+ (blocker.left - xAnchor) * 0.25,);const candidateBound = blocker.left - gutter;if (candidateBound < nextRightBound) {nextRightBound = candidateBound;}+ continue;+ }++ if (+ shiftLeft &&+ blocker.right <= xAnchor + 0.01 &&+ boxesOverlap(+ current.box,+ blocker,+ MANIFESTATION_GUTTER_PT,+ verticalClearance,+ )+ ) {+ const gutter = Math.min(+ MANIFESTATION_GUTTER_PT,+ (xAnchor - blocker.right) * 0.25,+ );+ const candidateLeft = Math.min(xAnchor, blocker.right + gutter);++ if (candidateLeft > nextLeftBound) {+ nextLeftBound = candidateLeft;+ }+ continue;+ }++ if (+ constrainToVerticalBlockers &&+ boxesOverlap(current.box, blocker, 0, verticalClearance)+ ) {+ if (side === "below" && blocker.top <= rect.yPt + 0.01) {+ const candidateHeight = Math.max(+ 0,+ rect.yPt - (blocker.top + verticalClearance),+ );++ if (candidateHeight < nextVerticalLimit) {+ nextVerticalLimit = candidateHeight;+ }+ } else if (+ side === "above" &&+ blocker.bottom >= rect.yPt + rect.heightPt - 0.01+ ) {+ const candidateHeight = Math.max(+ 0,+ blocker.bottom - verticalClearance - (rect.yPt + rect.heightPt),+ );++ if (candidateHeight < nextVerticalLimit) {+ nextVerticalLimit = candidateHeight;+ }+ }}}- const collidesWithManifestation = placedBoxes.some((blocker) =>- boxesOverlap(box, blocker, 0, MANIFESTATION_VERTICAL_CLEARANCE_PT),+ const changed =+ nextRightBound < rightBound - 0.01 ||+ nextLeftBound > leftBound + 0.01 ||+ nextVerticalLimit < verticalLimit - 0.01;++ if (!changed) {+ break;+ }++ leftBound = nextLeftBound;+ rightBound = nextRightBound;+ verticalLimit = nextVerticalLimit;+ }++ return current;+ };++ const layoutBeside = (+ side: "left" | "right",+ options: {+ allowVerticalShrink: boolean;+ verticalClearance?: number;+ },+ ): PlacedManifestation | null => {+ const { allowVerticalShrink } = options;+ const verticalClearance =+ options.verticalClearance ?? MANIFESTATION_VERTICAL_CLEARANCE_PT;+ let leftBound =+ side === "right"+ ? rect.xPt + rect.widthPt + MANIFESTATION_GUTTER_PT+ : margin;+ let rightBound =+ side === "right" ? pageRight : rect.xPt - MANIFESTATION_GUTTER_PT;++ if (rightBound - leftBound < 12) {+ return null;+ }++ const verticalInset =+ rect.heightPt > verticalClearance * 3 ? verticalClearance : 0;+ const bandBottom = Math.max(margin, rect.yPt + verticalInset);+ const bandTop = Math.min(+ pageTop,+ rect.yPt + rect.heightPt - verticalInset,+ );+ const availableHeight = bandTop - bandBottom;++ if (availableHeight <= 0) {+ return null;+ }++ let current: PlacedManifestation | null = null;+ const maxPasses = blockers.length + 2;++ for (let pass = 0; pass < maxPasses; pass += 1) {+ const maxWidth = Math.max(0.5, rightBound - leftBound);+ const layout = layoutManifestationText(+ font,+ text,+ maxWidth,+ availableHeight,+ { allowVerticalShrink },);- const hasCollision =- collidesWithManifestation ||- otherFieldBoxes.some((blocker) =>- boxesOverlap(box, blocker, 0, MANIFESTATION_VERTICAL_CLEARANCE_PT),- );+ const descender = layout.size * 0.25;+ const x =+ side === "right"+ ? leftBound+ : Math.max(leftBound, rightBound - layout.maxLineWidth);+ const bottomBaseline = bandBottom + descender;+ const topBaseline =+ bottomBaseline + (layout.lines.length - 1) * layout.lineHeight;+ const fitsVertically = topBaseline + layout.size <= bandTop + 0.01;++ current = buildPlacement(x, topBaseline, layout, fitsVertically);++ let nextLeftBound = leftBound;+ let nextRightBound = rightBound;- current = {- box,- collidesWithManifestation,- fitsOnPage,- hasCollision,- lineHeight: layout.lineHeight,- lines: layout.lines,- size: layout.size,- topBaseline,- x,- };+ for (const blocker of blockers) {+ if (+ !boxesOverlap(+ current.box,+ blocker,+ MANIFESTATION_GUTTER_PT,+ verticalClearance,+ )+ ) {+ continue;+ }++ if (side === "right" && blocker.left > leftBound) {+ const gutter = Math.min(+ MANIFESTATION_GUTTER_PT,+ (blocker.left - leftBound) * 0.25,+ );+ const candidateRight = blocker.left - gutter;++ if (candidateRight < nextRightBound) {+ nextRightBound = candidateRight;+ }+ } else if (side === "left" && blocker.right < rightBound) {+ const gutter = Math.min(+ MANIFESTATION_GUTTER_PT,+ (rightBound - blocker.right) * 0.25,+ );+ const candidateLeft = blocker.right + gutter;++ if (candidateLeft > nextLeftBound) {+ nextLeftBound = candidateLeft;+ }+ }+ }- if (nextRightBound >= rightBound - 0.01) {+ const changed =+ nextRightBound < rightBound - 0.01 ||+ nextLeftBound > leftBound + 0.01;++ if (!changed || nextRightBound - nextLeftBound < 4) {break;}+ leftBound = nextLeftBound;rightBound = nextRightBound;}return current;};- const below = layoutAtSide("below", false);+ const below = layoutAtSide("below", { allowVerticalShrink: false });let chosen: PlacedManifestation;if (below.fitsOnPage && !below.hasCollision) {chosen = below;} else {- const above = layoutAtSide("above", false);+ const above = layoutAtSide("above", { allowVerticalShrink: false });if (above.fitsOnPage && !above.hasCollision) {chosen = above;- } else if (below.fitsOnPage && !below.collidesWithManifestation) {- chosen = below;- } else if (above.fitsOnPage && !above.collidesWithManifestation) {- chosen = above;- } else if (below.fitsOnPage) {- chosen = below;- } else if (above.fitsOnPage) {- chosen = above;} else {- chosen = layoutAtSide(- spaceBelow >= spaceAbove ? "below" : "above",- true,- );+ const belowShifted = layoutAtSide("below", {+ allowVerticalShrink: false,+ shiftLeft: true,+ });+ const aboveShifted = layoutAtSide("above", {+ allowVerticalShrink: false,+ shiftLeft: true,+ });++ if (belowShifted.fitsOnPage && !belowShifted.hasCollision) {+ chosen = belowShifted;+ } else if (aboveShifted.fitsOnPage && !aboveShifted.hasCollision) {+ chosen = aboveShifted;+ } else {+ const verticalFitCandidates = [+ layoutAtSide("below", {+ allowVerticalShrink: true,+ constrainToVerticalBlockers: true,+ }),+ layoutAtSide("above", {+ allowVerticalShrink: true,+ constrainToVerticalBlockers: true,+ }),+ layoutAtSide("below", {+ allowVerticalShrink: true,+ constrainToVerticalBlockers: true,+ shiftLeft: true,+ }),+ layoutAtSide("above", {+ allowVerticalShrink: true,+ constrainToVerticalBlockers: true,+ shiftLeft: true,+ }),+ ];+ const besideCandidates = [+ layoutBeside("right", { allowVerticalShrink: true }),+ layoutBeside("left", { allowVerticalShrink: true }),+ ];+ const readableVertical = pickLargestFittingCandidate(+ verticalFitCandidates,+ (candidate) =>+ candidate.fitsOnPage &&+ !candidate.hasCollision &&+ candidate.size >= MANIFESTATION_MIN_READABLE_SIZE_PT,+ );+ const readableBeside = readableVertical+ ? null+ : pickLargestFittingCandidate(+ besideCandidates,+ (candidate) =>+ candidate.fitsOnPage &&+ !candidate.hasCollision &&+ candidate.size >= MANIFESTATION_MIN_READABLE_SIZE_PT,+ );+ const anyClear =+ readableVertical ??+ readableBeside ??+ pickLargestFittingCandidate(+ [...verticalFitCandidates, ...besideCandidates],+ (candidate) => candidate.fitsOnPage && !candidate.hasCollision,+ );++ if (anyClear) {+ chosen = anyClear;+ } else {+ const tightCandidates = [+ layoutAtSide("below", {+ allowVerticalShrink: true,+ constrainToVerticalBlockers: true,+ verticalClearance: 0,+ }),+ layoutAtSide("above", {+ allowVerticalShrink: true,+ constrainToVerticalBlockers: true,+ verticalClearance: 0,+ }),+ layoutAtSide("below", {+ allowVerticalShrink: true,+ constrainToVerticalBlockers: true,+ shiftLeft: true,+ verticalClearance: 0,+ }),+ layoutAtSide("above", {+ allowVerticalShrink: true,+ constrainToVerticalBlockers: true,+ shiftLeft: true,+ verticalClearance: 0,+ }),+ layoutBeside("right", {+ allowVerticalShrink: true,+ verticalClearance: 0,+ }),+ layoutBeside("left", {+ allowVerticalShrink: true,+ verticalClearance: 0,+ }),+ ];+ const noDirectOverlap = pickLargestFittingCandidate(+ tightCandidates,+ (candidate) =>+ candidate.fitsOnPage && !candidate.hasDirectOverlap,+ );++ if (noDirectOverlap) {+ chosen = noDirectOverlap;+ } else if (below.fitsOnPage && !below.collidesWithManifestation) {+ chosen = below;+ } else if (above.fitsOnPage && !above.collidesWithManifestation) {+ chosen = above;+ } else if (below.fitsOnPage) {+ chosen = below;+ } else if (above.fitsOnPage) {+ chosen = above;+ } else {+ chosen = layoutAtSide(+ spaceBelow >= spaceAbove ? "below" : "above",+ { allowVerticalShrink: true },+ );+ }+ }+ }}}