From 2fba44eefae205635abc206323ae1ede522319b9 Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Wed, 11 Nov 2026 12:25:45 +0100 Subject: [PATCH 1/3] feat: warn in development when a load fails without onError Without onError, a failed load left the view blank with nothing logged. In development builds PdfView now always subscribes to the native onError and, when the app passes no handler, warns once per source and code (page errors once per document). Invalid sources found in JS warn too. Release builds are unchanged: no extra subscription, no output. Closes #80 --- docs/api.md | 3 + docs/troubleshooting.md | 1 + package/src/PdfView.test.tsx | 126 ++++++++++++++++++++++++++++++++++- package/src/PdfView.tsx | 56 ++++++++++++++-- 4 files changed, 179 insertions(+), 7 deletions(-) diff --git a/docs/api.md b/docs/api.md index cc00368..70470d0 100644 --- a/docs/api.md +++ b/docs/api.md @@ -157,6 +157,9 @@ open and the other pages keep working: `error.page !== undefined` tells them apart (it narrows the type to `PdfPageError`). iOS reports load failures only (PDFKit draws the pages). +Without `onError`, development builds warn about failures with +`console.warn`, once per source and code; release builds print nothing. + ### Method errors The ref's promise methods (`getOutline`, `getPageSizes`, `renderPage`, diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 408d59e..fb63255 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -5,6 +5,7 @@ | The viewer does not appear in Expo Go | Use a development build (`npx expo run:ios` / `run:android`); Expo Go cannot load native modules. | | An error about `BetterPdfView` right after installing | Rebuild the native app: `pod install` and a new build on iOS, a new build on Android. | | Errors about the legacy architecture | Enable the New Architecture; Nitro Views need Fabric. | +| The viewer stays blank | The load failed, or is still running (there is no built-in spinner). Pass `onError` and read `error.code`; without it, a development build prints a warning such as `[react-native-better-pdf] file-not-found: …` in Metro. | | A password-protected document fails with `unsupported-pdf` on Android | The device is below Android 15 without SDK extension 13, where the platform renderer cannot open protected files. | | Search reports `isSupported: false`, long presses select nothing | Same devices as above; see the [capability matrix](../README.md#capability-matrix). | | On Android, `onError` arrives while the document is shown | It has `error.page`: one page could not be rendered after `onLoad` (`page-render-failed`, or `out-of-memory`), and the document stays open. Keep the viewer on screen; only `onError` without `page` ends the load. See [Errors](api.md#errors). | diff --git a/package/src/PdfView.test.tsx b/package/src/PdfView.test.tsx index 6be26f5..228d082 100644 --- a/package/src/PdfView.test.tsx +++ b/package/src/PdfView.test.tsx @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, mock, test } from 'bun:test'; +import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test'; import { createRef, useEffect, type ReactNode } from 'react'; import { act, create, type ReactTestRenderer } from 'react-test-renderer'; @@ -1229,3 +1229,127 @@ describe('PdfView', () => { ).rejects.toMatchObject({ code: 'invalid-argument' }); }); }); + +describe('PdfView without onError', () => { + const globals = globalThis as { __DEV__?: boolean }; + const warn = console.warn; + let warnings: string[] = []; + + beforeEach(() => { + warnings = []; + console.warn = (...args: unknown[]) => warnings.push(args.join(' ')); + }); + + afterEach(() => { + console.warn = warn; + delete globals.__DEV__; + }); + + const emitError = (error: PdfError) => + (lastHost().onError as { f: (error: PdfError) => void }).f(error); + + test('warns in development about a load failure, once per source and code', () => { + globals.__DEV__ = true; + const renderer = render(); + const missing = { + code: 'file-not-found', + message: 'No file at /a.pdf', + } as const; + emitError({ ...missing, sourceIndex: 0 }); + emitError({ ...missing, sourceIndex: 0 }); + expect(warnings).toEqual([ + '[react-native-better-pdf] file-not-found: No file at /a.pdf. Pass onError to handle load failures.', + ]); + + emitError({ code: 'invalid-pdf', message: 'Not a PDF', sourceIndex: 0 }); + act(() => renderer.update()); + emitError({ ...missing, sourceIndex: 0 }); + expect(warnings).toHaveLength(2); + expect(warnings[1]).toContain('invalid-pdf: Not a PDF.'); + + act(() => renderer.update()); + emitError({ code: 'file-not-found', message: 'No file at /b.pdf' }); + expect(warnings).toHaveLength(3); + expect(warnings[2]).toContain('file-not-found: No file at /b.pdf.'); + }); + + test('warns in development about page failures once per document, not per page', () => { + globals.__DEV__ = true; + render(); + emitError({ + code: 'page-render-failed', + message: 'Rendering page 1 failed', + page: 1, + }); + emitError({ + code: 'page-render-failed', + message: 'Rendering page 4 failed', + page: 4, + }); + expect(warnings).toEqual([ + '[react-native-better-pdf] page-render-failed: Rendering page 1 failed. Pass onError to handle page failures.', + ]); + }); + + test('warns in development about an invalid source once', () => { + globals.__DEV__ = true; + const renderer = render(); + act(() => renderer.update()); + expect(warnings).toEqual([ + '[react-native-better-pdf] invalid-source: source must be a require() result or an object with uri, filePath or base64; got {}. Pass onError to handle load failures.', + ]); + }); + + test('warns in development once the app removes its onError', () => { + globals.__DEV__ = true; + const errors: PdfError[] = []; + const renderer = render( + errors.push(error)} + />, + ); + const failure = { code: 'invalid-pdf', message: 'Not a PDF' } as const; + emitError(failure); + expect(errors).toEqual([failure]); + expect(warnings).toEqual([]); + + act(() => renderer.update()); + emitError(failure); + expect(errors).toHaveLength(1); + expect(warnings).toHaveLength(1); + }); + + test('does not warn when the app passes onError', () => { + globals.__DEV__ = true; + const errors: PdfError[] = []; + render( errors.push(e)} />); + render( + errors.push(e)} + />, + ); + emitError({ code: 'file-not-found', message: 'No file at /a.pdf' }); + expect(errors.map((error) => error.code)).toEqual([ + 'invalid-source', + 'file-not-found', + ]); + expect(warnings).toEqual([]); + }); + + test('release builds neither subscribe to onError nor warn', () => { + globals.__DEV__ = false; + render(); + expect(lastHost().onError).toBeUndefined(); + render(); + + // Subscribed for a handler the app then removed. + const renderer = render( + {}} />, + ); + act(() => renderer.update()); + emitError({ code: 'file-not-found', message: 'No file at /a.pdf' }); + expect(warnings).toEqual([]); + }); +}); diff --git a/package/src/PdfView.tsx b/package/src/PdfView.tsx index 87b0e2d..6dbf8d6 100644 --- a/package/src/PdfView.tsx +++ b/package/src/PdfView.tsx @@ -49,6 +49,7 @@ import type { NativePdfSource } from './types/NativePdfSource'; import type { PdfColorScheme } from './types/PdfColorScheme'; import type { PdfContentInset } from './types/PdfContentInset'; import type { PdfError, PdfLoadError, PdfPageError } from './types/PdfError'; +import type { PdfErrorCode } from './types/PdfErrorCode'; import type { PdfExportOptions } from './types/PdfExportOptions'; import type { PdfExportResult } from './types/PdfExportResult'; import type { PdfFitPolicy } from './types/PdfFitPolicy'; @@ -83,6 +84,33 @@ const NativeBetterPdfView = getHostComponent( type NativeRef = HybridRef; +// React Native's global, missing elsewhere (tests); the library builds without +// React Native's global types. +declare const __DEV__: boolean | undefined; + +function isDevelopment(): boolean { + return typeof __DEV__ !== 'undefined' && __DEV__ === true; +} + +const warnedErrorCodes = new WeakMap>(); + +/** + * In development, warns about an error the app has no `onError` for: once + * per `sources` and code when given. + */ +function warnUnhandledError(error: PdfError, sources?: object): void { + if (!isDevelopment()) return; + if (sources !== undefined) { + const codes = warnedErrorCodes.get(sources) ?? new Set(); + if (codes.has(error.code)) return; + warnedErrorCodes.set(sources, codes.add(error.code)); + } + const failures = error.page === undefined ? 'load' : 'page'; + console.warn( + `[react-native-better-pdf] ${error.code}: ${error.message}. Pass onError to handle ${failures} failures.`, + ); +} + /** `rgba(255, 214, 0, 0.4)` and `rgba(255, 140, 0, 0.6)` as ARGB. */ const DEFAULT_SEARCH_HIGHLIGHT_COLOR = 0x66ffd600; const DEFAULT_SEARCH_CURRENT_HIGHLIGHT_COLOR = 0x99ff8c00; @@ -429,6 +457,8 @@ export interface PdfViewProps extends ViewProps { * loaded again (e.g. a new `key`); each page is reported once. * `out-of-memory`: the viewer frees memory and tries the page again * later; reported once per document. + * + * Without it, development builds print a warning naming the code instead. */ onError?: (error: PdfLoadError | PdfPageError) => void; onPageChange?: (event: PdfPageChangeEvent) => void; @@ -653,9 +683,14 @@ export function PdfView({ handlers.current.onLoadProgress?.(event), ), // Native sets `page` only for page failures. - onError: callback((error: PdfError) => - handlers.current.onError?.(error as PdfLoadError | PdfPageError), - ), + onError: callback((error: PdfError) => { + const onError = handlers.current.onError; + if (onError === undefined) { + warnUnhandledError(error, latestSources.current); + } else { + onError(error as PdfLoadError | PdfPageError); + } + }), onPageChange: callback((event: PdfPageChangeEvent) => handlers.current.onPageChange?.(event), ), @@ -773,7 +808,10 @@ export function PdfView({ // entirely for the others. Once subscribed, an event stays subscribed (the // handler ref makes a removed handler a no-op): unsubscribing would send // `null`, which Nitro rejects. That takes reading the set during render. - const subscribed = useRef(new Set()); + // In development `onError` is always subscribed, to warn when it is missing. + const subscribed = useRef( + new Set(isDevelopment() ? ['onError'] : []), + ); const subscription = (name: K) => { if (renderedHandlers[name] !== undefined) subscribed.current.add(name); return subscribed.current.has(name) ? nativeCallbacks[name] : undefined; @@ -796,11 +834,17 @@ export function PdfView({ } if (reportedInvalidSource.current === invalidSourceKey) return; reportedInvalidSource.current = invalidSourceKey; - handlers.current.onError?.({ + const error: PdfLoadError = { code: 'invalid-source', message: invalidMessage!, sourceIndex: invalidSourceIndex, - }); + }; + const onError = handlers.current.onError; + if (onError === undefined) { + warnUnhandledError(error); + } else { + onError(error); + } }, [invalidMessage, invalidSourceIndex, invalidSourceKey]); useEffect(() => { From 371ac057254c9bfcd842eff543d8427998ee0cb0 Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Wed, 11 Nov 2026 13:02:20 +0100 Subject: [PATCH 2/3] fix: leave URL queries and fragments out of the development warning Native load-failure messages name the source URL, and a signed URL's token is in its query, so the warning could put a working link to a private document into shared logs. The warning now shows the URL up to its path. The app's onError still gets the message as it is. --- package/src/PdfView.test.tsx | 42 ++++++++++++++++++++++++++++++++++++ package/src/PdfView.tsx | 7 +++++- 2 files changed, 48 insertions(+), 1 deletion(-) diff --git a/package/src/PdfView.test.tsx b/package/src/PdfView.test.tsx index 228d082..f742d5e 100644 --- a/package/src/PdfView.test.tsx +++ b/package/src/PdfView.test.tsx @@ -1291,6 +1291,48 @@ describe('PdfView without onError', () => { ]); }); + test('warns in development without the query or fragment of URLs, where signed URLs keep their token', () => { + globals.__DEV__ = true; + const errors: PdfError[] = []; + const renderer = render(); + emitError({ + code: 'http-error', + message: + 'Downloading https://cdn.x.test/a.pdf?X-Amz-Signature=secret&X-Amz-Expires=60 failed with HTTP 500', + httpStatus: 500, + }); + emitError({ + code: 'invalid-source', + message: 'Unsupported PDF source: "ftp://x.test/a.pdf?token=secret"', + }); + emitError({ + code: 'network-error', + message: 'Downloading https://x.test/a.pdf#token=secret failed', + }); + expect(warnings).toEqual([ + '[react-native-better-pdf] http-error: Downloading https://cdn.x.test/a.pdf?… failed with HTTP 500. Pass onError to handle load failures.', + '[react-native-better-pdf] invalid-source: Unsupported PDF source: "ftp://x.test/a.pdf?…". Pass onError to handle load failures.', + '[react-native-better-pdf] network-error: Downloading https://x.test/a.pdf#… failed. Pass onError to handle load failures.', + ]); + + // The app's handler gets the message as it is. + act(() => + renderer.update( + errors.push(error)} + />, + ), + ); + emitError({ + code: 'network-error', + message: 'Downloading https://x.test/a.pdf?token=secret failed', + }); + expect(errors.map((error) => error.message)).toEqual([ + 'Downloading https://x.test/a.pdf?token=secret failed', + ]); + }); + test('warns in development about an invalid source once', () => { globals.__DEV__ = true; const renderer = render(); diff --git a/package/src/PdfView.tsx b/package/src/PdfView.tsx index 6dbf8d6..65ae27d 100644 --- a/package/src/PdfView.tsx +++ b/package/src/PdfView.tsx @@ -94,6 +94,10 @@ function isDevelopment(): boolean { const warnedErrorCodes = new WeakMap>(); +// Native messages name the source URL, and a signed URL's token is in its query. +const URL_QUERY_OR_FRAGMENT = + /(\b[a-z][a-z\d+.-]*:\/\/[^\s?#"]*)([?#])[^\s"]*/gi; + /** * In development, warns about an error the app has no `onError` for: once * per `sources` and code when given. @@ -106,8 +110,9 @@ function warnUnhandledError(error: PdfError, sources?: object): void { warnedErrorCodes.set(sources, codes.add(error.code)); } const failures = error.page === undefined ? 'load' : 'page'; + const message = error.message.replace(URL_QUERY_OR_FRAGMENT, '$1$2…'); console.warn( - `[react-native-better-pdf] ${error.code}: ${error.message}. Pass onError to handle ${failures} failures.`, + `[react-native-better-pdf] ${error.code}: ${message}. Pass onError to handle ${failures} failures.`, ); } From eb16be2ff933f52c2776c03b7c90d6f3803fc579 Mon Sep 17 00:00:00 2001 From: Jakub Kasprzyk Date: Wed, 11 Nov 2026 17:41:46 +0100 Subject: [PATCH 3/3] fix: leave user info in URLs out of the development warning MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A source URL can carry a user name and password before its host, and native messages name the URL, so the warning now shows "…@" in their place, as it already does for the query and fragment. The app's onError still gets the message as it is. --- package/src/PdfView.test.tsx | 12 +++++++++--- package/src/PdfView.tsx | 17 +++++++++++++---- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/package/src/PdfView.test.tsx b/package/src/PdfView.test.tsx index f742d5e..af41d60 100644 --- a/package/src/PdfView.test.tsx +++ b/package/src/PdfView.test.tsx @@ -1291,7 +1291,7 @@ describe('PdfView without onError', () => { ]); }); - test('warns in development without the query or fragment of URLs, where signed URLs keep their token', () => { + test('warns in development without the user info, query or fragment of URLs', () => { globals.__DEV__ = true; const errors: PdfError[] = []; const renderer = render(); @@ -1303,16 +1303,22 @@ describe('PdfView without onError', () => { }); emitError({ code: 'invalid-source', - message: 'Unsupported PDF source: "ftp://x.test/a.pdf?token=secret"', + message: + 'Unsupported PDF source: "ftp://user:p@ss@x.test/a@b.pdf?token=secret"', }); emitError({ code: 'network-error', message: 'Downloading https://x.test/a.pdf#token=secret failed', }); + emitError({ + code: 'file-not-found', + message: 'Downloading https://user:secret@x.test/a.pdf failed', + }); expect(warnings).toEqual([ '[react-native-better-pdf] http-error: Downloading https://cdn.x.test/a.pdf?… failed with HTTP 500. Pass onError to handle load failures.', - '[react-native-better-pdf] invalid-source: Unsupported PDF source: "ftp://x.test/a.pdf?…". Pass onError to handle load failures.', + '[react-native-better-pdf] invalid-source: Unsupported PDF source: "ftp://…@x.test/a@b.pdf?…". Pass onError to handle load failures.', '[react-native-better-pdf] network-error: Downloading https://x.test/a.pdf#… failed. Pass onError to handle load failures.', + '[react-native-better-pdf] file-not-found: Downloading https://…@x.test/a.pdf failed. Pass onError to handle load failures.', ]); // The app's handler gets the message as it is. diff --git a/package/src/PdfView.tsx b/package/src/PdfView.tsx index 65ae27d..3fd58a9 100644 --- a/package/src/PdfView.tsx +++ b/package/src/PdfView.tsx @@ -94,9 +94,18 @@ function isDevelopment(): boolean { const warnedErrorCodes = new WeakMap>(); -// Native messages name the source URL, and a signed URL's token is in its query. -const URL_QUERY_OR_FRAGMENT = - /(\b[a-z][a-z\d+.-]*:\/\/[^\s?#"]*)([?#])[^\s"]*/gi; +// Native messages name the source URL. Its user info can hold a password, and +// a signed URL's token is in its query. +const URL_PARTS = + /(\b[a-z][a-z\d+.-]*:\/\/)([^\s/?#"]*@)?([^\s?#"]*)([?#][^\s"]*)?/gi; + +function redactUrls(message: string): string { + return message.replace( + URL_PARTS, + (_url, scheme: string, userInfo?: string, path = '', tail?: string) => + `${scheme}${userInfo ? '…@' : ''}${path}${tail ? `${tail[0]}…` : ''}`, + ); +} /** * In development, warns about an error the app has no `onError` for: once @@ -110,7 +119,7 @@ function warnUnhandledError(error: PdfError, sources?: object): void { warnedErrorCodes.set(sources, codes.add(error.code)); } const failures = error.page === undefined ? 'load' : 'page'; - const message = error.message.replace(URL_QUERY_OR_FRAGMENT, '$1$2…'); + const message = redactUrls(error.message); console.warn( `[react-native-better-pdf] ${error.code}: ${message}. Pass onError to handle ${failures} failures.`, );