Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/shaggy-dogs-attack.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@react-pdf/pdfkit': patch
---

Switch the browser build's Node polyfills from `rollup-plugin-polyfill-node` to `node-stdlib-browser`
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
"@rollup/plugin-alias": "^5.1.0",
"@rollup/plugin-babel": "^6.0.0",
"@rollup/plugin-commonjs": "^25.0.0",
"@rollup/plugin-inject": "^5.0.4",
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-node-resolve": "^15.2.0",
"@rollup/plugin-replace": "^5.0.0",
Expand Down
3 changes: 3 additions & 0 deletions packages/pdfkit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,8 @@
"pako": "^1.0.11",
"png-js": "^2.0.0",
"vite-compatible-readable-stream": "^3.6.1"
},
"devDependencies": {
"node-stdlib-browser": "^1.3.1"
}
}
45 changes: 29 additions & 16 deletions packages/pdfkit/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,15 @@ import replace from '@rollup/plugin-replace';
import nodeResolve from '@rollup/plugin-node-resolve';
import ignore from 'rollup-plugin-ignore';
import alias from '@rollup/plugin-alias';
import nodePolyfills from 'rollup-plugin-polyfill-node';
import inject from '@rollup/plugin-inject';
import commonjs from '@rollup/plugin-commonjs';
import { createRequire } from 'module';

import pkg from './package.json' with { type: 'json' };

const require = createRequire(import.meta.url);
const stdLibBrowser = require('node-stdlib-browser');

const STANDARD_FONTS = [
'Courier',
'CourierBold',
Expand Down Expand Up @@ -45,29 +49,38 @@ const getExternal = ({ browser }) => [
...(browser ? [] : ['fs'])
];

// node-stdlib-browser entries are absolute paths (they point at installed
// packages); these get bundled inline so the absolute paths are fine. Aliases
// for externalized modules (pako/*) MUST stay as bare specifiers so the
// consumer's bundler can resolve them.
const browserAliasEntries = {
...stdLibBrowser,
// Override stdLibBrowser's stream-browserify with the vite-compatible variant
// (bundled inline; nodeResolve will pick it up).
stream: 'vite-compatible-readable-stream',
// pako sub-paths fail to resolve without explicit .js suffix; see
// https://github.com/browserify/browserify-zlib/pull/45
'pako/lib/zlib/zstream': 'pako/lib/zlib/zstream.js',
'pako/lib/zlib/constants': 'pako/lib/zlib/constants.js',
};

const getPlugins = ({ browser }) => [
...(browser
? [
ignore(['fs']),
alias({
entries: [
// See https://github.com/browserify/browserify-zlib/pull/45
{
find: 'pako/lib/zlib/zstream',
replacement: 'pako/lib/zlib/zstream.js'
},
{
find: 'pako/lib/zlib/constants',
replacement: 'pako/lib/zlib/constants.js'
},
{ find: 'stream', replacement: 'vite-compatible-readable-stream' },
{ find: 'zlib', replacement: 'browserify-zlib' }
]
entries: Object.entries(browserAliasEntries).map(
([find, replacement]) => ({
find,
replacement
})
)
}),
commonjs(),
nodeResolve({ browser, preferBuiltins: !browser }),
nodePolyfills({
include: [/node_modules\/.+\.js/, /pdfkit\/src\/.*\.js/]
inject({
Buffer: [stdLibBrowser.buffer, 'Buffer'],
process: stdLibBrowser.process
})
]
: [nodeResolve({ browser, preferBuiltins: !browser })]),
Expand Down
71 changes: 71 additions & 0 deletions packages/pdfkit/tests/browser-bundle.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import fs from 'fs';
import { describe, expect, it } from 'vitest';

// The browser build inlines its own Buffer polyfill, so this has to exercise the
// built artifact instead of src. The previous polyfill shipped a Buffer whose
// concat() rejected plain Uint8Array chunks, which broke font embedding in the
// browser because fontkit v2's subset.encode() returns a Uint8Array.
const bundleUrl = new URL('../lib/pdfkit.browser.js', import.meta.url);

if (!fs.existsSync(bundleUrl)) {
throw new Error(
'lib/pdfkit.browser.js is missing. Build the package before running this test.',
);
}

const { default: PDFDocument, registerStdFonts } = await import(bundleUrl.href);
const { default: Helvetica } = await import(
new URL('../lib/standard-fonts/Helvetica.js', import.meta.url).href,
);

registerStdFonts(Helvetica);

const render = async (options, fill: (doc) => void) => {
const doc = new PDFDocument(options);
const chunks: Uint8Array[] = [];

doc.on('data', (chunk: Uint8Array) => chunks.push(chunk));
const done = new Promise((resolve, reject) => {
doc.on('end', resolve);
doc.on('error', reject);
});

fill(doc);
doc.end();
await done;

const size = chunks.reduce((total, chunk) => total + chunk.length, 0);
const output = new Uint8Array(size);
let offset = 0;
for (const chunk of chunks) {
output.set(chunk, offset);
offset += chunk.length;
}
return output;
};

describe('browser bundle', () => {
it('writes Uint8Array chunks to a stream reference', async () => {
let ref;

const output = await render({ compress: false }, (doc) => {
ref = doc.ref();
ref.end(new Uint8Array([1, 2, 3, 4]));
});

expect(ref.data.Length).toBe(4);
expect(Array.from(output).join(',')).toContain('1,2,3,4');
});

it('deflates Uint8Array chunks when compression is on', async () => {
let ref;

await render({ compress: true }, (doc) => {
ref = doc.ref();
ref.end(new Uint8Array(1024));
});

expect(ref.data.Filter).toBe('FlateDecode');
expect(ref.data.Length).toBeLessThan(1024);
});
});
Loading
Loading