Repository navigation
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub. |
|
Important Review skippedAuto reviews are limited based on label configuration. 🏷️ Required labels (at least one) (1)
Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Repository UI Review profile: ASSERTIVE Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
Hey there, it looks like you haven't accepted our contributor license agreement yet. In order for us to accept your pull request we ask that you please fill out the CLA: https://documen.so/cla |
There was a problem hiding this comment.
Pull request overview
Adds Unicode-aware font selection for typed signatures so non‑Latin text renders correctly in sealed PDFs/certificates by falling back from Caveat to appropriate Noto Sans variants.
Changes:
- Introduces script detection + font fetching helpers for typed signature rendering (pdf-lib path).
- Updates PDF insertion (v1 + legacy) to embed the selected Unicode font for typed signatures when needed.
- Updates Konva/skia-canvas rendering (signature field + certificate) to use a font-family fallback chain via a shared constant, plus adds unit tests.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 5 comments.
Show a summary per file
| File | Description |
|---|---|
| packages/lib/universal/field-renderer/render-signature-field.ts | Switches typed signature Konva text rendering to use the shared fallback font-family chain. |
| packages/lib/server-only/pdf/render-certificate.ts | Uses the shared fallback font-family chain when rendering typed signatures on the signing certificate. |
| packages/lib/server-only/pdf/legacy-insert-field-in-pdf.ts | Selects and embeds a script-appropriate font for typed signatures in the legacy pdf-lib insertion path. |
| packages/lib/server-only/pdf/insert-field-in-pdf-v1.ts | Selects and embeds a script-appropriate font for typed signatures in the v1 pdf-lib insertion path. |
| packages/lib/server-only/pdf/font-selection.ts | New helper module for script detection and font fetching for typed signatures. |
| packages/lib/server-only/pdf/font-selection.test.ts | Adds unit tests covering script detection for multiple writing systems and mixed inputs. |
| packages/lib/constants/pdf.ts | Adds SIGNATURE_FONT_FAMILY fallback chain constant for Konva/skia-canvas rendering. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Address PR documenso#2728 review feedback from Copilot: - Add a process-level cache in font-selection.ts so repeated field insertions (one insertFieldInPDFV1/legacy call per field) don't re-download Caveat/Noto Sans on every invocation. Storing the in-flight Promise also dedupes concurrent fetches. Failed fetches are evicted so later calls can retry. - Route Caveat and Noto Sans fetches through fetchSignatureFont to benefit from the same cache; drop the now-unused NEXT_PRIVATE_INTERNAL_WEBAPP_URL import. - Throw a clear error (fontKey, status, url) when the font URL responds non-2xx, instead of letting an HTML error body surface later as a confusing font parse failure. - Remove the redundant second pdf.embedFont call for signature fields. The first embedFont already embeds the font and returns the reference we use; the second call bloated the PDF with a duplicate font stream. Refs documenso#1646 documenso#1668
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Address PR documenso#2728 review feedback from Copilot. Noto Sans Japanese includes Han ideographs (for kanji), so with the old ordering Caveat → Noto Sans → Noto Sans Japanese → Noto Sans Chinese the Konva/skia-canvas path (V2 and certificate rendering) would resolve pure Chinese text to the Japanese variant and render with JP-specific glyph shapes, diverging from getSignatureFontKey which maps Han ideographs to 'noto-sans-chinese' in the pdf-lib path. Swap the order so Chinese precedes Japanese. Kana and Hangul are absent from the Chinese font, so Japanese and Korean text still fall through to the correct variants. This aligns V2 output with V1 output and gives Chinese signers the expected glyph forms. Refs documenso#1646 documenso#1668
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Address PR documenso#2728 review feedback from Copilot. Previously, pdf.embedFont(bytes) was called once per field on the same PDFDocument. Even with the ArrayBuffer cache added earlier, each call re-parsed the TTF via fontkit and wrote a duplicate font stream into the PDF. For a document with several signature fields and the Noto CJK variants (~10MB each), that meant tens of MB of redundant font streams in the sealed output. Introduce embedSignatureFont in font-selection.ts: a helper that embeds a font into the given PDFDocument and caches the resulting PDFFont in a WeakMap<PDFDocument, Map<cacheKey, Promise<PDFFont>>>. The WeakMap lets GC reclaim the cache alongside the document. The cache key includes a suffix for `features.calt = false` so embeds with different options (only Caveat uses calt: false today) don't alias. Refactor V1 and legacy field insertion to use embedSignatureFont and pick exactly one font per field (previously both Caveat and Noto Sans were fetched eagerly even when only one was used). Failures evict the cache entry so a later call can retry. Refs documenso#1646 documenso#1668
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated no new comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated no new comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Address PR documenso#2728 review feedback. Per CODE_STYLE.md, application errors should use the AppError class so they integrate with the project's error model (logging, AppError.parseError on the frontend, AppError.toRestAPIError in tRPC handlers). A plain Error slipped through and is now replaced with AppError(AppErrorCode.UNKNOWN_ERROR, { message }), which maps to HTTP 500 / INTERNAL_SERVER_ERROR - appropriate for an internal font fetch failure that signals a server/infra problem rather than user input. Refs documenso#1646 documenso#1668
…ping Address the nice-to-haves from PR documenso#2728 review. - Add 8 new unit tests covering the two-level cache helpers: * fetchSignatureFont: caches subsequent calls, dedupes concurrent in-flight fetches, throws AppError on non-ok responses with the expected message format, evicts on failure for retry * embedSignatureFont: embeds once per (document, fontKey), keys the cache separately for distinct options (calt-off vs default), uses separate caches per PDFDocument, evicts on embed failure Tests use vi.resetModules() + dynamic import so each test starts with a fresh module-level cache, and a tiny mock PDFDocument that returns a unique Symbol per embedFont invocation so reference equality cleanly distinguishes cache hits from misses. - Document the pure-kanji limitation in getSignatureFontKey JSDoc: Han ideographs alone (no kana) are ambiguous between Chinese and Japanese, so we map them to the Chinese variant by convention. Note this matches the SIGNATURE_FONT_FAMILY fallback order in the Konva paths. - Reword the CJK_REGEX comment to make explicit that we are choosing to map Han to Chinese (rather than Han being "primarily Chinese"). Refs documenso#1646 documenso#1668
…roject logger Address three PR documenso#2728 review comments from Copilot. 1. Add AbortController-based timeout (FONT_FETCH_TIMEOUT_MS = 10s) to fetchFontBytes. Without it a hung fetch would pin a never-resolving Promise in fontCache and block every subsequent caller indefinitely. On abort the signal fires, fetch throws, the existing catch block wraps it in AppError, and the outer wrapper in fetchPdfFontBytes evicts the cache entry so the next call retries. A new test verifies the SUT passes an AbortSignal on every fetch. 2. Drop the explicit `Response` type annotation. Inlining the response handling inside the try block lets TypeScript infer the type from fetch's return, which keeps the file portable across TS configs that don't include DOM libs. The AppError thrown for non-OK responses passes through the surrounding catch via `if (err instanceof AppError) throw err` so the specific status message is preserved. 3. Replace console.error with the project's pino-based logger from packages/lib/utils/logger. Integrates with the codebase's existing logging/telemetry pipeline (levels, structured fields, optional file transport). Test updates the spy from console.error to the logger. Refs documenso#1646 documenso#1668
- CAVEAT_INCOMPATIBLE_REGEX: use Script=Common/Inherited instead of Script_Extensions=. Script_Extensions broadens the match for shared punctuation, but every code point we care about is already covered by the plain Script= properties and the simpler form is easier to reason about across Unicode versions. - AbortSignal test: replace `instanceof AbortSignal` with a shape check on `signal.aborted`. The contract that matters is "fetch can read an aborted flag" - the global identity check would flake on runtimes where AbortSignal is polyfilled or absent.
…e-typed-signatures
The old comment said "update all three places" but actually referenced four locations and omitted FONT_FILE_MAP itself. Replace the prose with a numbered list of all five places (public asset, @font-face, FontLibrary.use, SIGNATURE_FONT_FAMILY, FONT_FILE_MAP) so a future add/rename can't silently miss one.
- Make FONT_FILE_MAP the single source of truth (`as const`) and derive `PdfFontKey` via `keyof typeof FONT_FILE_MAP`. Adding or renaming a font is now a one-line edit; the union and the file lookup can't drift. Moves the 5-location sync comment onto the map's JSDoc so it sits at the source of truth. - Add a concurrency test asserting embedPdfTextFont dedupes parallel callers onto a single embedFont invocation. The cache stores the in-flight Promise, so this guards against a future refactor that stores the resolved PDFFont and races on first call.
- FONT_FILE_MAP docblock no longer contradicts itself: scope the "single source of truth" claim to within this module (where PdfFontKey is derived from it), then separately note that the same identifiers are still restated in several shapes outside the module and require manual coordination. - CAVEAT_INCOMPATIBLE_REGEX comment now describes itself as a heuristic rather than an exact coverage test, and calls out the Script=Common long tail (symbols/pictographs/emoji) that Caveat doesn't cover - with a note that emoji support is intentionally out of scope until we ship a Noto Emoji font.
- font-selection: construct the font URL with `new URL(path, base)` rather than string interpolation so a trailing slash on NEXT_PRIVATE_INTERNAL_WEBAPP_URL doesn't produce `//fonts/...` and any reserved characters in the (statically-known) file name are encoded correctly. - insert-field-in-pdf-v1: reword the embedDefaultTextFont comment from "lazy / hoisting" (ambiguous - the helper IS hoisted, what's lazy is the await) to "deferred await". The intent is that no work happens until a non-signature branch actually needs the font, avoiding a wasted embed for image-signature-only documents.
|
I appreciate all the effort that went into this but wouldn't this be bettered rendered as a simple
Where noto would just use the fontstack to match per character since it uses the same stroking and glyphs across it cjk languages anyways. I understand not wanting to mishmash caveat with noto obviously thus we can just toss it into code rather than running all the heuristics |
…lper V2-only simplification per maintainer feedback. The fontstack already does per-character fallback in skia-canvas, so the script-priority logic in `getSignatureFontKey` was doing work the fontstack does for free. Collapses to a single binary: every char Caveat-coverable -> Caveat, otherwise the Noto fallback chain (no mishmash within one signature). - packages/lib/constants/pdf.ts: replace `SIGNATURE_FONT_FAMILY` (a single string with Caveat at the front of the chain) with `getSignatureFontFamily` which returns either 'Caveat' or the Noto chain depending on text content. - packages/lib/constants/pdf.test.ts: minimal unit test for the helper. - V2 call sites (`render-signature-field.ts`, `render-certificate.ts`) now call the helper with the typed signature text. - Delete `packages/lib/server-only/pdf/font-selection.ts` and its tests (329 + 415 LOC) - the script-detection enum, font byte fetcher, embed cache, AbortController + AppError wrapping, and per-document WeakMap are all unnecessary under the simpler design. - Revert `packages/lib/server-only/pdf/insert-field-in-pdf-v1.ts` to upstream/main. V1 is out of scope for this PR; the V2 path is the default for new envelopes and is what the helper covers.
Drop comment lines that restate names, types, or what the code does on its face. Keep only the ones a future maintainer needs to avoid silently breaking something: - Chinese-before-Japanese ordering (reordering breaks pure-Chinese text) - Family names match @font-face, not TTF internal name tables (fixing the names to "Noto Sans JP/KR/SC" would silently break rendering) - Emoji caveat on CAVEAT_INCOMPATIBLE_REGEX (adding Extended_Pictographic wouldn't help and would route Latin-with-emoji to Noto) - All-or-nothing design intent (explains why we don't use one combined chain)
Replaces the Script=Latin/Cyrillic/Common/Inherited heuristic with a
pure-ASCII check via the \p{ASCII} Unicode property escape. Pure-ASCII
text keeps Caveat handwriting; anything else routes to the existing
Noto chain, which already fallback-walks per-character.
Trade-off: Latin-Extended names (Müller, François, Søren) and Cyrillic
now render in Noto Sans instead of Caveat. Per maintainer feedback on
the PR — preferable to running a Unicode-property heuristic per render.
HI @Mythie , thank you for the input. Done. Please check |
| text: recipient.signatureField?.signature?.typedSignature, | ||
| padding: 4, | ||
| fontFamily: 'Caveat', | ||
| fontFamily: getSignatureFontFamily(recipient.signatureField.signature.typedSignature), |
| const expectCaveat = (family: string) => expect(family).toBe('Caveat'); | ||
| // toContain (not toBe) so the chain can grow without rewriting tests. | ||
| const expectNotoChain = (family: string) => { | ||
| expect(family).toContain('Noto Sans'); |
|
Awesome stuff! |
Summary
Typed signatures using non-ASCII characters (Latin-Extended accents, Cyrillic, Greek, Arabic, CJK, Japanese, Korean, etc.) render as empty boxes/tofu in the sealed PDF because the Caveat handwriting font doesn't cover those code points.
This PR fixes the default V2 rendering pipeline (Konva / skia-canvas) and the signing certificate (which is attached to every sealed PDF) by extending the typed-signature
fontFamilyfrom'Caveat, sans-serif'to a chain that includes Noto Sans + Noto Sans CJK variants. All four Noto Sans variants already ship inapps/remix/public/fonts/and are already registered with skia-canvas viaFontLibrary.use(...)— no new assets, no new dependencies.A tiny helper picks one font family for the whole signature: Caveat handwriting if the text is pure ASCII, otherwise the Noto fallback chain. Deliberately all-or-nothing, so a single signature is never split between handwriting and sans-serif.
Behavior
John Doe, punctuation/digits)"Noto Sans", "Noto Sans Chinese", "Noto Sans Japanese", "Noto Sans Korean", sans-serifExamples:
John Doe→ Caveat (handwriting)François,Müller,Søren,Иванов,Ελληνικά,عربي,עברית,한글,中文,こんにちは→ Noto chainHello 안녕,Ivan Ωmega(mixed) → Noto chain (whole string; no mishmash)The dispatch is a single
\p{ASCII}Unicode-property test. The Konva/skia-canvas chain walks the four Noto Sans variants per-character, so one string handles every script we ship a font for. Chinese precedes Japanese in the chain so pure Han text gets CN glyph shapes (the Japanese font also contains Han ideographs for kanji with JP-specific shapes).Implementation
Two private constants and one exported helper in
packages/lib/constants/pdf.ts:Call sites:
packages/lib/universal/field-renderer/render-signature-field.ts— V2 field rendering, three places that build a Konva text node for a typed signature.packages/lib/server-only/pdf/render-certificate.ts— the typed signature on the signing certificate page.Each call site passes the actual typed signature text to the helper so the family is picked per-signature.
The ASCII check is a trade-off, not a precise per-glyph test. Latin-Extended names (
Müller,François) lose Caveat's handwriting style and render in Noto Sans. That's accepted: keeps the helper trivial, no heuristics, and Noto Sans renders those names cleanly. Emoji and pictographs are non-ASCII too and route to Noto — we don't ship an emoji font, so they fall through to the chain's trailingsans-serifand render as the platform default (still better than Caveat's.notdef).Scope
drawText), so fixing V1 properly would require per-script TTF embedding — a much larger change with its own trade-offs. V1-rendered signatures with non-ASCII text still tofu after this PR.legacy_insertFieldInPDFpath — also out of scope (same reason).Performance / footprint
getSignatureFontFamily(text)is a single regex test on a typically-short string. No allocation beyond the test result.FontLibraryregistrations forNoto Sansand the three CJK variants are already present inensureFontLibraryonmain; this PR just adds the family names to the consumed fontFamily string.Test plan
npm run test -w @documenso/lib— passing, including the 4 tests inpackages/lib/constants/pdf.test.ts:John Doe, empty string) → CaveatHello 안녕,Ivan Ωmega) → Noto chain (whole string)sans-serifnpm run build— all packages build successfullye2e/envelopes/envelope-v2-field-insertion.spec.ts— passinge2e/features/include-document-certificate.spec.ts— passinge2e/envelopes/envelope-alignment.spec.ts— passingManual verification (anyone can repeat)
Ελληνικά(issue Typed Signatures Unicode Problem with Greek Characters #1646)도큐멘소(issue Unicode Tofus #1668)中文签名(issue Chines characters displays incorrectly in "Signature" field #2822)こんにちはИвановFrançoisJohn Doe(regression check — must stay in Caveat handwriting)□□□), both on the signed page and on the attached signing certificate.Closes #1646
Closes #1668
Closes #2822