unpdf 1.9.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "unpdf",
3
3
  "type": "module",
4
- "version": "1.9.1",
5
- "packageManager": "pnpm@12.11.2",
4
+ "version": "2.0.0",
5
+ "packageManager": "pnpm@12.16.1",
6
6
  "description": "PDF extraction and rendering across all JavaScript runtimes",
7
7
  "author": "Johann Schopplich <hello@johannschopplich.com>",
8
8
  "license": "MIT",
@@ -30,36 +30,19 @@
30
30
  "sideEffects": false,
31
31
  "exports": {
32
32
  ".": {
33
- "import": {
34
- "types": "./dist/index.d.mts",
35
- "default": "./dist/index.mjs"
36
- },
37
- "require": {
38
- "types": "./dist/index.d.cts",
39
- "default": "./dist/index.cjs"
40
- }
33
+ "types": "./dist/index.d.mts",
34
+ "default": "./dist/index.mjs"
41
35
  },
42
36
  "./pdfjs": {
43
37
  "types": "./dist/pdfjs.d.mts",
44
- "import": "./dist/pdfjs.mjs"
45
- }
46
- },
47
- "main": "./dist/index.cjs",
48
- "module": "./dist/index.mjs",
49
- "types": "./dist/index.d.cts",
50
- "typesVersions": {
51
- "*": {
52
- "*": [
53
- "*",
54
- "dist/*"
55
- ]
38
+ "default": "./dist/pdfjs.mjs"
56
39
  }
57
40
  },
58
41
  "files": [
59
42
  "dist"
60
43
  ],
61
44
  "engines": {
62
- "node": ">=22"
45
+ "node": ">=24"
63
46
  },
64
47
  "scripts": {
65
48
  "build": "tsdown && node scripts/post-build.mjs",
@@ -69,7 +52,7 @@
69
52
  "lint:fix": "eslint . --fix",
70
53
  "release": "bumpp",
71
54
  "test": "vitest",
72
- "test:attw": "attw --pack --ignore-rules cjs-resolves-to-esm",
55
+ "test:attw": "attw --pack --profile esm-only",
73
56
  "test:types": "tsc --noEmit",
74
57
  "test:types:dist": "tsc -p test/types/tsconfig.json"
75
58
  },
@@ -82,18 +65,18 @@
82
65
  }
83
66
  },
84
67
  "devDependencies": {
85
- "@antfu/eslint-config": "^9.5.1",
68
+ "@antfu/eslint-config": "^10.0.0",
86
69
  "@arethetypeswrong/cli": "^0.18.5",
87
- "@cloudflare/vitest-plugin": "^1.4.3",
88
- "@napi-rs/canvas": "^1.0.11",
70
+ "@cloudflare/vitest-plugin": "^1.4.9",
71
+ "@napi-rs/canvas": "^1.0.13",
89
72
  "@types/node": "^26.6.5",
90
73
  "bumpp": "^12.3.0",
91
- "eslint": "^10.12.0",
74
+ "eslint": "^10.13.0",
92
75
  "pdfjs-dist": "~6.4.299",
93
- "rolldown": "^1.2.14",
76
+ "rolldown": "^1.2.15",
94
77
  "tinyglobby": "^0.2.17",
95
- "tsdown": "^0.23.1",
78
+ "tsdown": "^0.23.2",
96
79
  "typescript": "^6.0.3",
97
- "vitest": "^4.1.11"
80
+ "vitest": "^5.0.5"
98
81
  }
99
82
  }
package/dist/index.cjs DELETED
@@ -1,449 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region src/_internal/dommatrix-polyfill.ts
3
- function polyfillDOMMatrix() {
4
- if (typeof globalThis.DOMMatrix !== "undefined") return;
5
- globalThis.DOMMatrix = class DOMMatrix {
6
- constructor(init) {
7
- if (Array.isArray(init) && init.length === 6) {
8
- this.a = init[0];
9
- this.b = init[1];
10
- this.c = init[2];
11
- this.d = init[3];
12
- this.e = init[4];
13
- this.f = init[5];
14
- } else {
15
- this.a = 1;
16
- this.b = 0;
17
- this.c = 0;
18
- this.d = 1;
19
- this.e = 0;
20
- this.f = 0;
21
- }
22
- }
23
- translateSelf(tx, ty = 0) {
24
- this.e = this.a * tx + this.c * ty + this.e;
25
- this.f = this.b * tx + this.d * ty + this.f;
26
- return this;
27
- }
28
- scaleSelf(sx, sy = sx) {
29
- this.a *= sx;
30
- this.b *= sx;
31
- this.c *= sy;
32
- this.d *= sy;
33
- return this;
34
- }
35
- };
36
- }
37
- //#endregion
38
- //#region src/_internal/env.ts
39
- /**
40
- * Stubs browser globals that PDF.js expects at the module level
41
- * in non-browser environments.
42
- *
43
- * @remarks
44
- * Must be called before importing any PDF.js module, since PDF.js
45
- * accesses these globals at parse time (top-level constants).
46
- */
47
- function stubBrowserGlobals() {
48
- polyfillDOMMatrix();
49
- }
50
- //#endregion
51
- //#region src/utils.ts
52
- let resolvedModule;
53
- const isNode = globalThis.process?.release?.name === "node";
54
- const isBrowser = typeof window !== "undefined";
55
- /**
56
- * Creates a `PDFDocumentProxy` from binary PDF data.
57
- *
58
- * Applies the following defaults:
59
- * - `useSystemFonts: true`
60
- *
61
- * In Node.js environments, additionally applies:
62
- * - `disableFontFace: true`
63
- * - `standardFontDataUrl` resolved from the local `pdfjs-dist` package
64
- * - `cMapUrl` and `cMapPacked` resolved from the local `pdfjs-dist` package
65
- */
66
- async function getDocumentProxy(data, options = {}) {
67
- const { getDocument } = await getResolvedPDFJS();
68
- let nodeDefaults = {};
69
- if (isNode) try {
70
- const base = {}.resolve("pdfjs-dist/package.json");
71
- nodeDefaults = {
72
- disableFontFace: true,
73
- standardFontDataUrl: new URL("./standard_fonts/", base).href,
74
- cMapUrl: new URL("./cmaps/", base).href,
75
- cMapPacked: true
76
- };
77
- } catch {}
78
- return await getDocument({
79
- data,
80
- useSystemFonts: true,
81
- ...nodeDefaults,
82
- ...options
83
- }).promise;
84
- }
85
- /**
86
- * Runs an operation on a `PDFDocumentProxy` resolved from either binary data
87
- * or an existing proxy. Documents created here are destroyed once the
88
- * operation settles – caller-supplied proxies keep their lifecycle with the
89
- * caller.
90
- */
91
- async function withDocument(data, operation, options) {
92
- const pdf = isPDFDocumentProxy(data) ? data : await getDocumentProxy(data, options);
93
- try {
94
- return await operation(pdf);
95
- } finally {
96
- if (pdf !== data) await pdf.loadingTask.destroy();
97
- }
98
- }
99
- async function getResolvedPDFJS() {
100
- if (!resolvedModule) await resolvePDFJSImport();
101
- return resolvedModule;
102
- }
103
- async function resolvePDFJSImport(pdfjsResolver, { reload = false } = {}) {
104
- if (resolvedModule && !reload) return;
105
- stubBrowserGlobals();
106
- if (pdfjsResolver) try {
107
- resolvedModule = await interopDefault(pdfjsResolver());
108
- return;
109
- } catch (error) {
110
- throw new Error(`PDF.js could not be resolved: ${error}`);
111
- }
112
- try {
113
- resolvedModule = await import("unpdf/pdfjs");
114
- } catch (error) {
115
- throw new Error(`Serverless PDF.js bundle could not be resolved: ${error}`);
116
- }
117
- }
118
- function isPDFDocumentProxy(data) {
119
- return typeof data === "object" && data !== null && "_pdfInfo" in data;
120
- }
121
- async function interopDefault(m) {
122
- const resolved = await m;
123
- return resolved.default || resolved;
124
- }
125
- //#endregion
126
- //#region src/_internal/canvas.ts
127
- let resolvedCanvasModule;
128
- /**
129
- * Derived from the PDF.js project by the Mozilla Foundation.
130
- * @see https://github.com/mozilla/pdf.js/blob/b8de9a372f9bbf7e33adb362eeae5ef1919dba73/src/display/canvas_factory.js#L18
131
- * @license Apache-2.0
132
- */
133
- var BaseCanvasFactory = class {
134
- #enableHWA = false;
135
- constructor({ enableHWA = false } = {}) {
136
- this.#enableHWA = enableHWA;
137
- }
138
- create(width, height) {
139
- const canvas = this._createCanvas(width, height);
140
- return {
141
- canvas,
142
- context: canvas.getContext("2d", { willReadFrequently: !this.#enableHWA })
143
- };
144
- }
145
- reset({ canvas }, width, height) {
146
- if (!canvas) throw new Error("Canvas is not specified");
147
- canvas.width = width;
148
- canvas.height = height;
149
- }
150
- destroy(context) {
151
- if (!context.canvas) throw new Error("Canvas is not specified");
152
- context.canvas.width = 0;
153
- context.canvas.height = 0;
154
- context.canvas = void 0;
155
- context.context = void 0;
156
- }
157
- _createCanvas(width, height) {
158
- throw new Error("Not implemented");
159
- }
160
- };
161
- /**
162
- * Derived from the PDF.js project by the Mozilla Foundation.
163
- * @see https://github.com/mozilla/pdf.js/blob/b8de9a372f9bbf7e33adb362eeae5ef1919dba73/src/display/canvas_factory.js#L18
164
- * @license Apache-2.0
165
- */
166
- var DOMCanvasFactory = class extends BaseCanvasFactory {
167
- constructor({ ownerDocument = globalThis.document, enableHWA = false } = {}) {
168
- super({ enableHWA });
169
- this._document = ownerDocument;
170
- }
171
- _createCanvas(width, height) {
172
- const canvas = this._document.createElement("canvas");
173
- canvas.width = width;
174
- canvas.height = height;
175
- return canvas;
176
- }
177
- };
178
- var NodeCanvasFactory = class extends BaseCanvasFactory {
179
- constructor({ enableHWA = false } = {}) {
180
- super({ enableHWA });
181
- }
182
- _createCanvas(width, height) {
183
- if (!resolvedCanvasModule) throw new Error("@napi-rs/canvas module is not resolved");
184
- return resolvedCanvasModule.createCanvas(width, height);
185
- }
186
- };
187
- async function resolveCanvasModule(canvasImport) {
188
- resolvedCanvasModule ??= await interopDefault(canvasImport());
189
- globalThis[Symbol.for("unpdf.canvasModule")] = resolvedCanvasModule;
190
- }
191
- /**
192
- * Injects `DOMMatrix`, `ImageData` and `Path2D` constructors from the
193
- * `@napi-rs/canvas` package into the global scope. This is necessary for
194
- * Node.js environments that do not support these constructors natively.
195
- *
196
- * @remarks
197
- * `DOMMatrix` is always set because {@link stubBrowserGlobals} may have
198
- * installed a minimal stub to allow PDF.js to import – the real
199
- * `@napi-rs/canvas` implementation must take precedence for rendering.
200
- */
201
- function injectCanvasConstructors() {
202
- if (!resolvedCanvasModule) return;
203
- globalThis.DOMMatrix = resolvedCanvasModule.DOMMatrix;
204
- if (typeof globalThis.ImageData === "undefined") globalThis.ImageData = resolvedCanvasModule.ImageData;
205
- if (typeof globalThis.Path2D === "undefined") globalThis.Path2D = resolvedCanvasModule.Path2D;
206
- }
207
- //#endregion
208
- //#region src/image.ts
209
- /**
210
- * Extracts images from a specific page of a PDF document, including necessary metadata,
211
- * such as width, height, and calculated color channels.
212
- */
213
- async function extractImages$1(data, pageNumber) {
214
- return await withDocument(data, async (pdf) => {
215
- if (pageNumber < 1 || pageNumber > pdf.numPages) throw new Error(`Invalid page number. Must be between 1 and ${pdf.numPages}.`);
216
- const page = await pdf.getPage(pageNumber);
217
- const operatorList = await page.getOperatorList();
218
- const { OPS } = await getResolvedPDFJS();
219
- const images = [];
220
- for (let i = 0; i < operatorList.fnArray.length; i++) {
221
- if (operatorList.fnArray[i] !== OPS.paintImageXObject) continue;
222
- const imageKey = operatorList.argsArray[i][0];
223
- const image = await new Promise((resolve) => (imageKey.startsWith("g_") ? page.commonObjs : page.objs).get(imageKey, resolve));
224
- if (!image || !image.data || !image.width || !image.height) continue;
225
- const { width, height, data } = image;
226
- const calculatedChannels = data.length / (width * height);
227
- if (![
228
- 1,
229
- 3,
230
- 4
231
- ].includes(calculatedChannels)) continue;
232
- const channels = calculatedChannels;
233
- images.push({
234
- data,
235
- width,
236
- height,
237
- channels,
238
- key: imageKey
239
- });
240
- }
241
- return images;
242
- });
243
- }
244
- async function renderPageAsImage$1(data, pageNumber, options = {}) {
245
- const CanvasFactory = await createIsomorphicCanvasFactory(options.canvasImport);
246
- return await withDocument(data, async (pdf) => {
247
- if (pageNumber < 1 || pageNumber > pdf.numPages) throw new Error(`Invalid page number. Must be between 1 and ${pdf.numPages}.`);
248
- const page = await pdf.getPage(pageNumber);
249
- const defaultViewport = page.getViewport({ scale: 1 });
250
- let scale = options.scale || 1;
251
- if (options.width) scale = options.width / defaultViewport.width;
252
- else if (options.height) scale = options.height / defaultViewport.height;
253
- const viewport = page.getViewport({ scale: Math.max(0, scale) });
254
- const canvasFactory = new CanvasFactory();
255
- const drawingContext = canvasFactory.create(viewport.width, viewport.height);
256
- try {
257
- await page.render({
258
- canvas: drawingContext.canvas,
259
- canvasContext: drawingContext.context,
260
- viewport
261
- }).promise;
262
- const { canvas } = drawingContext;
263
- if (options.toDataURL) return canvas.toDataURL();
264
- if ("encode" in canvas) {
265
- const buffer = await canvas.encode("png");
266
- return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
267
- }
268
- const blob = await new Promise((resolve) => {
269
- canvas.toBlob(resolve);
270
- });
271
- if (!blob) throw new Error("Failed to encode canvas to a PNG blob.");
272
- return await blob.arrayBuffer();
273
- } finally {
274
- canvasFactory.destroy(drawingContext);
275
- }
276
- }, { CanvasFactory });
277
- }
278
- async function createIsomorphicCanvasFactory(canvasImport) {
279
- if (isBrowser) return DOMCanvasFactory;
280
- if (isNode) {
281
- if (!canvasImport) throw new Error("Parameter \"canvasImport\" is required in Node.js environment.");
282
- await resolveCanvasModule(canvasImport);
283
- injectCanvasConstructors();
284
- return NodeCanvasFactory;
285
- }
286
- throw new Error("Unsupported environment for canvas creation.");
287
- }
288
- //#endregion
289
- //#region src/links.ts
290
- async function extractLinks$1(data) {
291
- return await withDocument(data, async (pdf) => {
292
- const pageLinks = await Promise.all(Array.from({ length: pdf.numPages }, (_, i) => getPageLinks(pdf, i + 1)));
293
- return {
294
- totalPages: pdf.numPages,
295
- links: pageLinks.flat()
296
- };
297
- });
298
- }
299
- async function getPageLinks(document, pageNumber) {
300
- const annotations = await (await document.getPage(pageNumber)).getAnnotations();
301
- const links = [];
302
- for (const annotation of annotations) if (annotation.subtype === "Link" && annotation.url) links.push(annotation.url);
303
- return links;
304
- }
305
- //#endregion
306
- //#region src/meta.ts
307
- const XMP_DATE_PROPERTIES = [
308
- "xmp:createdate",
309
- "xmp:modifydate",
310
- "xmp:metadatadate",
311
- "xap:createdate",
312
- "xap:modifydate",
313
- "xap:metadatadate"
314
- ];
315
- async function getMeta$1(data, options = {}) {
316
- return await withDocument(data, async (pdf) => {
317
- const meta = await pdf.getMetadata();
318
- const info = { ...meta.info };
319
- let metadata = meta.metadata;
320
- if (options.parseDates) {
321
- const { PDFDateString } = await getResolvedPDFJS();
322
- if (info.CreationDate) info.CreationDate = PDFDateString.toDateObject(info.CreationDate);
323
- if (info.ModDate) info.ModDate = PDFDateString.toDateObject(info.ModDate);
324
- if (metadata) {
325
- const Metadata = metadata.constructor;
326
- metadata = new Metadata({
327
- parsedData: new Map(Array.from(metadata, ([name, value]) => [name, XMP_DATE_PROPERTIES.includes(name) && value ? parseISODateString(value) : value])),
328
- rawData: metadata.getRaw()
329
- });
330
- }
331
- }
332
- return {
333
- info,
334
- metadata: metadata || {}
335
- };
336
- });
337
- }
338
- function parseISODateString(isoDateString) {
339
- if (!isoDateString) return;
340
- const parsedDate = Date.parse(isoDateString);
341
- if (!Number.isNaN(parsedDate)) return new Date(parsedDate);
342
- }
343
- //#endregion
344
- //#region src/text.ts
345
- async function extractTextItems$1(data) {
346
- return await withDocument(data, async (pdf) => {
347
- const items = await Promise.all(Array.from({ length: pdf.numPages }, (_, i) => getPageTextItems(pdf, i + 1)));
348
- return {
349
- totalPages: pdf.numPages,
350
- items
351
- };
352
- });
353
- }
354
- async function getPageTextItems(document, pageNumber) {
355
- const content = await (await document.getPage(pageNumber)).getTextContent();
356
- const styles = content.styles;
357
- return content.items.filter((item) => item.str != null).map((item) => {
358
- const [_a, _b, c, d, e, f] = item.transform;
359
- return {
360
- str: item.str,
361
- x: e,
362
- y: f,
363
- width: item.width,
364
- height: item.height,
365
- fontSize: Math.hypot(c, d),
366
- fontFamily: styles[item.fontName]?.fontFamily ?? "",
367
- dir: item.dir,
368
- hasEOL: item.hasEOL
369
- };
370
- });
371
- }
372
- async function extractText$1(data, options = {}) {
373
- const { mergePages = false } = options;
374
- return await withDocument(data, async (pdf) => {
375
- const texts = await Promise.all(Array.from({ length: pdf.numPages }, (_, i) => getPageText(pdf, i + 1)));
376
- return {
377
- totalPages: pdf.numPages,
378
- text: mergePages ? normalizeMergedText(texts) : texts
379
- };
380
- });
381
- }
382
- async function getPageText(document, pageNumber) {
383
- return (await (await document.getPage(pageNumber)).getTextContent()).items.filter((item) => item.str != null).map((item) => item.str + (item.hasEOL ? "\n" : "")).join("");
384
- }
385
- /**
386
- * Collapses whitespace without destroying the line structure: `hasEOL` and
387
- * page-join line breaks survive, but at most one blank line remains.
388
- */
389
- function normalizeMergedText(texts) {
390
- return texts.join("\n").replace(/[^\S\n]+/g, " ").replace(/ ?\n ?/g, "\n").replace(/\n{3,}/g, "\n\n");
391
- }
392
- //#endregion
393
- //#region src/config.ts
394
- /**
395
- * Sets the PDF.js build every other method uses – call it before any of them.
396
- * Without it, the serverless build is used.
397
- *
398
- * @example
399
- * // In Node.js, the legacy build of `pdfjs-dist` (install it first)
400
- * import { definePDFJSModule } from 'unpdf'
401
- *
402
- * await definePDFJSModule(() => import('pdfjs-dist/legacy/build/pdf.mjs'))
403
- */
404
- async function definePDFJSModule(pdfjs) {
405
- await resolvePDFJSImport(pdfjs, { reload: true });
406
- }
407
- /** @deprecated Use `definePDFJSModule` instead. Will be removed in v2. */
408
- async function configureUnPDF(options) {
409
- await resolvePDFJSImport(options.pdfjs, { reload: true });
410
- }
411
- //#endregion
412
- //#region src/index.ts
413
- const getMeta = async (...args) => {
414
- await resolvePDFJSImport();
415
- return await getMeta$1(...args);
416
- };
417
- const extractText = async (...args) => {
418
- await resolvePDFJSImport();
419
- return await extractText$1(...args);
420
- };
421
- const extractTextItems = async (...args) => {
422
- await resolvePDFJSImport();
423
- return await extractTextItems$1(...args);
424
- };
425
- const extractImages = async (...args) => {
426
- await resolvePDFJSImport();
427
- return await extractImages$1(...args);
428
- };
429
- const renderPageAsImage = async (...args) => {
430
- await resolvePDFJSImport();
431
- return await renderPageAsImage$1(...args);
432
- };
433
- const extractLinks = async (...args) => {
434
- await resolvePDFJSImport();
435
- return await extractLinks$1(...args);
436
- };
437
- //#endregion
438
- exports.configureUnPDF = configureUnPDF;
439
- exports.createIsomorphicCanvasFactory = createIsomorphicCanvasFactory;
440
- exports.definePDFJSModule = definePDFJSModule;
441
- exports.extractImages = extractImages;
442
- exports.extractLinks = extractLinks;
443
- exports.extractText = extractText;
444
- exports.extractTextItems = extractTextItems;
445
- exports.getDocumentProxy = getDocumentProxy;
446
- exports.getMeta = getMeta;
447
- exports.getResolvedPDFJS = getResolvedPDFJS;
448
- exports.renderPageAsImage = renderPageAsImage;
449
- exports.resolvePDFJSImport = resolvePDFJSImport;