feat: Lazy-load @napi-rs/canvas to fix Jest open handle warnings#89
feat: Lazy-load @napi-rs/canvas to fix Jest open handle warnings#89JonRC wants to merge 1 commit intomehmet-kozan:mainfrom
Conversation
- Add LazyCanvasFactory that defers canvas module loading until needed - Set LazyCanvasFactory as default in Node.js environments - Add clearCanvasCache() cleanup in destroy() method - Export isCanvasLoaded() and clearCanvasCache() for explicit control - Add tests for lazy loading behavior Fixes issue where Jest reports "CustomGC" open handle when using pdf-parse for text-only operations. The canvas module is now only loaded when getImage() or getScreenshot() is called.
|
@mehmet-kozan The CI checks are failing because fork PRs don't have access to repository secrets needed for the private submodule checkout. Could you please manually re-run the failed workflows? |
|
@mehmet-kozan, also let me know if this improvement makes sense. |
|
@JonRC thanks for your contribution. I was able to reproduce the issue using the
We can add a integration test for jest --detectOpenHandles flag tod tests/integration dir. I will also add you permanently to the pro package repository, see: #77 We can rework this feature together in another branch if you’d like. This would also allow me to test the contribution workflow. |
Summary
This PR implements lazy-loading for the
@napi-rs/canvasmodule to prevent Jest from reporting "CustomGC" open handle warnings when using pdf-parse for text-only operations.Problem
When importing pdf-parse in a Jest test environment, Jest's
--detectOpenHandlesflag reports a "CustomGC" open handle. This occurs because:pdfjs-distautomatically loads@napi-rs/canvasin Node.js environmentsThis affects users who only need text extraction (
getText(),getInfo()) but still see canvas-related warnings in their test output.Solution
Introduced
LazyCanvasFactorythat defers loading of@napi-rs/canvasuntil canvas operations are actually needed:src/pdf-parse/LazyCanvasFactory.ts- Factory that lazy-loads the canvas module on first usesrc/pdf-parse/PDFParse.ts- UsesLazyCanvasFactoryas defaultCanvasFactoryin Node.jssrc/pdf-parse/index.ts- Exports new utilities for explicit controltests/unit/test-cleanup/lazy-canvas.test.ts- Verifies lazy loading behaviorKey Changes
getImage()orgetScreenshot()is calleddestroy()now callsclearCanvasCache()if canvas was loadedisCanvasLoaded()andclearCanvasCache()for explicit controlCanvasFactoryas beforeFiles Changed
src/pdf-parse/LazyCanvasFactory.tssrc/pdf-parse/PDFParse.tssrc/pdf-parse/index.tstests/unit/test-cleanup/lazy-canvas.test.tsTest Plan
getImage()works correctly with lazy-loaded canvasgetScreenshot()works correctly with lazy-loaded canvasgetText()works without loading canvas module--detectOpenHandles