@swc/anyformat-pdf 0.2.0 → 0.2.2

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/index.js CHANGED
@@ -6,8 +6,22 @@
6
6
  // exports of the generated binding that are the public API. Optional feature
7
7
  // packages will connect to the public API here.
8
8
 
9
+ const { resolve } = require('node:path')
10
+
9
11
  const binding = require('./binding.js')
10
- const { fileFunction, fileFunctionSync, streamFunction } = require('@swc/anyformat-utils')
12
+ const {
13
+ BOOLEAN,
14
+ NUMBER,
15
+ STRING,
16
+ fileFunction,
17
+ fileFunctionSync,
18
+ invalidType,
19
+ isUint8Array,
20
+ normalizeOptions,
21
+ streamFunction,
22
+ toPath,
23
+ wrap,
24
+ } = require('@swc/anyformat-utils')
11
25
 
12
26
  const headerPrefixLen = () => binding.HEADER_PREFIX_LEN
13
27
 
@@ -26,3 +40,414 @@ module.exports.isPdfSync = binding.isPdfSync
26
40
  module.exports.isPdfFile = fileFunction(binding.isPdfFile, binding)
27
41
  module.exports.isPdfFileSync = fileFunctionSync(binding.isPdfFileSync, binding)
28
42
  module.exports.isPdfStream = streamFunction(headerPrefixLen, binding.isPdfSync)
43
+
44
+ // ---------------------------------------------------------------------------
45
+ // Argument checks of the page functions
46
+ // ---------------------------------------------------------------------------
47
+
48
+ function invalidValue(message) {
49
+ const error = new Error(message)
50
+ error.code = 'ERR_INVALID_ARG_VALUE'
51
+ return error
52
+ }
53
+
54
+ function isArrayBuffer(value) {
55
+ return Object.prototype.toString.call(value) === '[object ArrayBuffer]'
56
+ }
57
+
58
+ // The label of a value in an error message: `"data" argument` or
59
+ // `"options.pages" property`.
60
+ function label(name) {
61
+ return /[.[]/.test(name) ? `"${name}" property` : `"${name}" argument`
62
+ }
63
+
64
+ // The string prefixes that are not paths, with a hint for each one.
65
+ const NOT_A_PATH = [
66
+ {
67
+ test: (text) => text.startsWith('%PDF'),
68
+ what: 'the content of a PDF file',
69
+ hint: 'pass the bytes of the file, for example the Buffer that fs.readFile() gives without an encoding',
70
+ },
71
+ {
72
+ test: (text) => text.startsWith('JVBER'),
73
+ what: 'a PDF file in base64',
74
+ hint: "pass Buffer.from(text, 'base64')",
75
+ },
76
+ {
77
+ test: (text) => /^data:/i.test(text),
78
+ what: 'a data URI',
79
+ hint: "pass Buffer.from(text.slice(text.indexOf(',') + 1), 'base64')",
80
+ },
81
+ {
82
+ test: (text) => /^https?:\/\//i.test(text),
83
+ what: 'a URL',
84
+ hint: 'pass new Uint8Array(await (await fetch(url)).arrayBuffer())',
85
+ },
86
+ ]
87
+
88
+ // Checks a source and returns it for the native code (a Uint8Array or a
89
+ // path string) with the key of its identity: the same Uint8Array or
90
+ // ArrayBuffer object, or the same path after `path.resolve`. Symbolic links
91
+ // are not resolved.
92
+ function normalizeSource(value, name) {
93
+ if (isUint8Array(value)) return { native: value, key: value }
94
+ if (isArrayBuffer(value)) return { native: new Uint8Array(value), key: value }
95
+ if (typeof value === 'string') {
96
+ for (const { test, what, hint } of NOT_A_PATH) {
97
+ if (test(value)) {
98
+ throw invalidValue(
99
+ `The ${label(name)} is a string that looks like ${what}, but a string is a file path. ` +
100
+ `To pass the file, ${hint}. To pass a path that starts with this text, write ./ in front of ` +
101
+ 'it or pass pathToFileURL(path).',
102
+ )
103
+ }
104
+ }
105
+ } else if (!(value instanceof URL)) {
106
+ throw invalidType(label(name), 'a Uint8Array, an ArrayBuffer, a path string, or a file URL', value)
107
+ }
108
+ // `toPath` converts a file URL, fails with ERR_INVALID_URL_SCHEME for
109
+ // another URL, and makes a relative path absolute for the WebAssembly
110
+ // build.
111
+ const path = toPath(value, binding)
112
+ return { native: path, key: `path:${resolve(path)}` }
113
+ }
114
+
115
+ // The value types of the options. See the schemas of `wrap` in
116
+ // @swc/anyformat-utils.
117
+ const PASSWORD = {
118
+ name: 'a string or a Uint8Array',
119
+ test: (value) => typeof value === 'string' || isUint8Array(value),
120
+ }
121
+
122
+ // A value that a function checks itself after `normalizeOptions` copied it.
123
+ const ANY = { name: 'a value', test: () => true }
124
+
125
+ const READ_INFO_OPTIONS = { password: PASSWORD }
126
+ const PARSE_PAGE_RANGES_OPTIONS = { pageCount: NUMBER }
127
+ const WRITE_OPTIONS = { objectStreams: BOOLEAN, version: STRING }
128
+ const COPY_OPTIONS = { ...WRITE_OPTIONS, outlines: BOOLEAN, pageLabels: BOOLEAN, formFields: STRING }
129
+ const MERGE_OPTIONS = { ...COPY_OPTIONS, base: NUMBER }
130
+ const SELECT_OPTIONS = { ...COPY_OPTIONS, password: PASSWORD }
131
+ const REMOVE_OPTIONS = { ...WRITE_OPTIONS, password: PASSWORD }
132
+ const SPLIT_OPTIONS = {
133
+ ...COPY_OPTIONS,
134
+ ranges: { name: 'an array of page selections', test: Array.isArray },
135
+ every: NUMBER,
136
+ password: PASSWORD,
137
+ documentData: BOOLEAN,
138
+ }
139
+ const ROTATE_OPTIONS = { ...WRITE_OPTIONS, pages: ANY, mode: STRING, password: PASSWORD }
140
+ // The properties of a PdfPart other than `data` and `pages`.
141
+ const PART_OPTIONS = {
142
+ rotate: NUMBER,
143
+ rotateMode: STRING,
144
+ password: PASSWORD,
145
+ outline: STRING,
146
+ outlines: BOOLEAN,
147
+ separate: BOOLEAN,
148
+ }
149
+
150
+ // Checks that an angle is an integer. The native code checks that it is a
151
+ // multiple of 90.
152
+ function checkAngle(angle, name) {
153
+ if (!Number.isInteger(angle)) {
154
+ throw invalidValue(`The ${label(name)} must be a multiple of 90. Received ${angle}`)
155
+ }
156
+ return angle
157
+ }
158
+
159
+ // Returns true for an object that a selection reads as a PageRange. An
160
+ // iterable, for example a Set or a typed array, is not a PageRange.
161
+ function isPageRange(value) {
162
+ return (
163
+ value !== null &&
164
+ typeof value === 'object' &&
165
+ !isArrayBuffer(value) &&
166
+ !ArrayBuffer.isView(value) &&
167
+ typeof value[Symbol.iterator] !== 'function'
168
+ )
169
+ }
170
+
171
+ // Reads a bound of a PageRange: an integer or ±Infinity, or NaN for the
172
+ // default value.
173
+ function rangeBound(value, name) {
174
+ if (value === undefined || value === null) return NaN
175
+ if (typeof value !== 'number') throw invalidType(label(name), 'a number', value)
176
+ if (Number.isInteger(value) || value === Infinity || value === -Infinity) return value
177
+ throw invalidValue(`The ${label(name)} must be an integer, Infinity, or -Infinity. Received ${value}`)
178
+ }
179
+
180
+ function pushIndex(out, value, name) {
181
+ if (!Number.isInteger(value)) {
182
+ throw invalidValue(`The ${label(name)} must be an integer page index. Received ${value}`)
183
+ }
184
+ out.push(0, value, 0, 0)
185
+ }
186
+
187
+ function pushRange(out, value, name) {
188
+ const { start, end, step } = value
189
+ const bounds = [rangeBound(start, `${name}.start`), rangeBound(end, `${name}.end`)]
190
+ let stepValue = NaN
191
+ if (step !== undefined && step !== null) {
192
+ if (typeof step !== 'number') throw invalidType(label(`${name}.step`), 'a number', step)
193
+ if (!Number.isInteger(step) || step === 0) {
194
+ throw invalidValue(`The ${label(`${name}.step`)} must be a non-zero integer. Received ${step}`)
195
+ }
196
+ stepValue = step
197
+ }
198
+ out.push(1, bounds[0], bounds[1], stepValue)
199
+ }
200
+
201
+ // Checks a page selection and encodes it for the native code, as
202
+ // `decodeSelection` reads it.
203
+ function encodeSelection(value, name) {
204
+ const out = []
205
+ if (typeof value === 'number') {
206
+ pushIndex(out, value, name)
207
+ } else if (Array.isArray(value)) {
208
+ for (let index = 0; index < value.length; index++) {
209
+ const item = value[index]
210
+ const itemName = `${name}[${index}]`
211
+ if (typeof item === 'number') pushIndex(out, item, itemName)
212
+ else if (isPageRange(item)) pushRange(out, item, itemName)
213
+ else throw invalidType(label(itemName), 'a number or a PageRange object', item)
214
+ }
215
+ } else if (isPageRange(value)) {
216
+ pushRange(out, value, name)
217
+ } else {
218
+ throw invalidType(label(name), 'a number, a PageRange object, or an array of them', value)
219
+ }
220
+ return new Float64Array(out)
221
+ }
222
+
223
+ // Checks the options of a function that writes a PDF file. `pages` and
224
+ // `ranges` become encoded selections.
225
+ function normalizeWriteOptions(options, schema) {
226
+ const copy = normalizeOptions(options, schema, 'options')
227
+ if (copy === undefined) return undefined
228
+ if (copy.base !== undefined && !Number.isInteger(copy.base)) {
229
+ throw invalidValue(`The "options.base" property must be an integer. Received ${copy.base}`)
230
+ }
231
+ if (copy.every !== undefined && !(Number.isInteger(copy.every) && copy.every > 0)) {
232
+ throw invalidValue(`The "options.every" property must be a positive integer. Received ${copy.every}`)
233
+ }
234
+ if (copy.ranges !== undefined) {
235
+ if (copy.every !== undefined) {
236
+ throw invalidValue('The "options.ranges" and "options.every" properties must not be set together')
237
+ }
238
+ // Read the items by index into a plain array, so that a `map` method or
239
+ // the species of an array subclass has no effect.
240
+ const ranges = []
241
+ for (let index = 0; index < copy.ranges.length; index++) {
242
+ ranges.push(encodeSelection(copy.ranges[index], `options.ranges[${index}]`))
243
+ }
244
+ copy.ranges = ranges
245
+ }
246
+ return copy
247
+ }
248
+
249
+ // Checks an input of `mergePdfs` and returns its part for the native code.
250
+ // `sources` collects the distinct sources, and `indices` maps the key of
251
+ // each source to its index.
252
+ function normalizeInput(value, index, sources, indices) {
253
+ const name = `inputs[${index}]`
254
+ let data = value
255
+ let part = { source: 0 }
256
+ const isPart =
257
+ value !== null &&
258
+ typeof value === 'object' &&
259
+ !isUint8Array(value) &&
260
+ !isArrayBuffer(value) &&
261
+ !(value instanceof URL) &&
262
+ !ArrayBuffer.isView(value) &&
263
+ !Array.isArray(value)
264
+ if (isPart) {
265
+ part = { ...normalizeOptions(value, PART_OPTIONS, name), source: 0 }
266
+ data = value.data
267
+ const pages = value.pages
268
+ if (pages !== undefined && pages !== null) part.pages = encodeSelection(pages, `${name}.pages`)
269
+ if (part.rotate !== undefined) checkAngle(part.rotate, `${name}.rotate`)
270
+ if (data === undefined || data === null) {
271
+ throw invalidType(label(`${name}.data`), 'a Uint8Array, an ArrayBuffer, a path string, or a file URL', data)
272
+ }
273
+ }
274
+ const source = normalizeSource(data, isPart ? `${name}.data` : name)
275
+ let sourceIndex = indices.get(source.key)
276
+ if (sourceIndex === undefined) {
277
+ sourceIndex = sources.length
278
+ sources.push(source.native)
279
+ indices.set(source.key, sourceIndex)
280
+ }
281
+ part.source = sourceIndex
282
+ return part
283
+ }
284
+
285
+ // Checks the arguments of `mergePdfs`: `(inputs, options)` becomes
286
+ // `(sources, parts, options)`.
287
+ const prepareMerge = (args) => {
288
+ const [inputs, options] = args
289
+ if (!Array.isArray(inputs)) throw invalidType(label('inputs'), 'an array', inputs)
290
+ const sources = []
291
+ const indices = new Map()
292
+ const parts = []
293
+ for (let index = 0; index < inputs.length; index++) {
294
+ try {
295
+ parts.push(normalizeInput(inputs[index], index, sources, indices))
296
+ } catch (error) {
297
+ if (error !== null && typeof error === 'object' && error.input === undefined) error.input = index
298
+ throw error
299
+ }
300
+ }
301
+ args[0] = sources
302
+ args[1] = parts
303
+ args[2] = normalizeWriteOptions(options, MERGE_OPTIONS)
304
+ args.length = 3
305
+ }
306
+
307
+ const prepareSelect = (schema) => (args) => {
308
+ args[0] = normalizeSource(args[0], 'data').native
309
+ args[1] = encodeSelection(args[1], 'pages')
310
+ args[2] = normalizeWriteOptions(args[2], schema)
311
+ args.length = 3
312
+ }
313
+
314
+ const prepareSplit = (args) => {
315
+ args[0] = normalizeSource(args[0], 'data').native
316
+ args[1] = normalizeWriteOptions(args[1], SPLIT_OPTIONS)
317
+ args.length = 2
318
+ }
319
+
320
+ // A key of a Record of angles: an integer, also a negative one.
321
+ const INTEGER_KEY = /^-?(0|[1-9][0-9]*)$/
322
+
323
+ function mapAngle(angle, name) {
324
+ if (typeof angle !== 'number') throw invalidType(label(name), 'a number', angle)
325
+ return checkAngle(angle, name)
326
+ }
327
+
328
+ // Checks the angles of `rotatePages` and encodes them for the native code.
329
+ function normalizeAngles(angles, pages) {
330
+ if (typeof angles === 'number') {
331
+ const result = { kind: 'number', angle: checkAngle(angles, 'angles') }
332
+ if (pages !== undefined) result.values = encodeSelection(pages, 'options.pages')
333
+ return result
334
+ }
335
+ const isMap = angles instanceof Map
336
+ const isArray = Array.isArray(angles)
337
+ const isRecord =
338
+ !isMap &&
339
+ !isArray &&
340
+ angles !== null &&
341
+ typeof angles === 'object' &&
342
+ !ArrayBuffer.isView(angles) &&
343
+ !isArrayBuffer(angles)
344
+ if (!isMap && !isArray && !isRecord) {
345
+ throw invalidType(label('angles'), 'a number, an array, a Map, or an object', angles)
346
+ }
347
+ if (pages !== undefined) {
348
+ throw invalidValue(
349
+ 'The "options.pages" property must not be set when "angles" is an array or a map: the map or the array gives the pages',
350
+ )
351
+ }
352
+ const values = []
353
+ if (isArray) {
354
+ for (let index = 0; index < angles.length; index++) {
355
+ const angle = angles[index]
356
+ values.push(angle === undefined || angle === null ? NaN : mapAngle(angle, `angles[${index}]`))
357
+ }
358
+ return { kind: 'list', values: new Float64Array(values) }
359
+ }
360
+ if (isMap) {
361
+ for (const [key, angle] of angles) {
362
+ if (typeof key !== 'number') throw invalidType('keys of the "angles" map', 'numbers', key)
363
+ if (!Number.isInteger(key)) {
364
+ throw invalidValue(`The keys of the "angles" map must be integer page indices. Received ${key}`)
365
+ }
366
+ values.push(key, mapAngle(angle, `angles[${key}]`))
367
+ }
368
+ return { kind: 'map', values: new Float64Array(values) }
369
+ }
370
+ for (const key of Object.keys(angles)) {
371
+ if (!INTEGER_KEY.test(key)) {
372
+ const angle = angles.angle
373
+ const hint =
374
+ typeof angle === 'number' && 'type' in angles
375
+ ? `; for a degrees() object of pdf-lib, pass its angle: rotatePages(data, ${angle})`
376
+ : ''
377
+ throw invalidValue(
378
+ `The keys of the "angles" object must be integer page indices. Received "${key}"${hint}`,
379
+ )
380
+ }
381
+ values.push(Number(key), mapAngle(angles[key], `angles[${key}]`))
382
+ }
383
+ return { kind: 'map', values: new Float64Array(values) }
384
+ }
385
+
386
+ const prepareRotate = (args) => {
387
+ args[0] = normalizeSource(args[0], 'data').native
388
+ const options = normalizeWriteOptions(args[2], ROTATE_OPTIONS)
389
+ const pages = options === undefined ? undefined : options.pages
390
+ if (options !== undefined) delete options.pages
391
+ args[1] = normalizeAngles(args[1], pages)
392
+ args[2] = options
393
+ args.length = 3
394
+ }
395
+
396
+ // Makes the JavaScript selection of the encoded selection of the native
397
+ // code: four numbers for each item, `[0, index, 0, 0]` for a page index and
398
+ // `[1, start, end, step]` for a range, where NaN is a default value.
399
+ function decodeSelection(values) {
400
+ const items = []
401
+ for (let offset = 0; offset < values.length; offset += 4) {
402
+ if (values[offset] === 0) {
403
+ items.push(values[offset + 1])
404
+ continue
405
+ }
406
+ const [start, end, step] = [values[offset + 1], values[offset + 2], values[offset + 3]]
407
+ const range = {}
408
+ if (!Number.isNaN(start)) range.start = start
409
+ // With a negative step, a default end is before the first page. Show it,
410
+ // so that the range does not look like it ends at the last page.
411
+ if (!Number.isNaN(end)) range.end = end
412
+ else if (step < 0) range.end = null
413
+ if (!Number.isNaN(step)) range.step = step
414
+ items.push(range)
415
+ }
416
+ return items
417
+ }
418
+
419
+ // ---------------------------------------------------------------------------
420
+ // Page functions
421
+ // ---------------------------------------------------------------------------
422
+
423
+ const prepareReadInfo = (args) => {
424
+ args[0] = normalizeSource(args[0], 'data').native
425
+ args[1] = normalizeOptions(args[1], READ_INFO_OPTIONS, 'options')
426
+ }
427
+
428
+ module.exports.readPdfInfo = wrap(binding.readPdfInfo, true, prepareReadInfo)
429
+ module.exports.readPdfInfoSync = wrap(binding.readPdfInfoSync, false, prepareReadInfo)
430
+
431
+ module.exports.parsePageRanges = wrap(
432
+ function parsePageRanges(text, pageCount) {
433
+ return decodeSelection(binding.parsePageRanges(text, pageCount))
434
+ },
435
+ false,
436
+ (args) => {
437
+ if (typeof args[0] !== 'string') throw invalidType(label('text'), 'of type string', args[0])
438
+ const options = normalizeOptions(args[1], PARSE_PAGE_RANGES_OPTIONS, 'options')
439
+ args[1] = options === undefined ? undefined : options.pageCount
440
+ args.length = 2
441
+ },
442
+ )
443
+
444
+ module.exports.mergePdfs = wrap(binding.mergePdfs, true, prepareMerge)
445
+ module.exports.mergePdfsSync = wrap(binding.mergePdfsSync, false, prepareMerge)
446
+ module.exports.selectPages = wrap(binding.selectPages, true, prepareSelect(SELECT_OPTIONS))
447
+ module.exports.selectPagesSync = wrap(binding.selectPagesSync, false, prepareSelect(SELECT_OPTIONS))
448
+ module.exports.removePages = wrap(binding.removePages, true, prepareSelect(REMOVE_OPTIONS))
449
+ module.exports.removePagesSync = wrap(binding.removePagesSync, false, prepareSelect(REMOVE_OPTIONS))
450
+ module.exports.splitPdf = wrap(binding.splitPdf, true, prepareSplit)
451
+ module.exports.splitPdfSync = wrap(binding.splitPdfSync, false, prepareSplit)
452
+ module.exports.rotatePages = wrap(binding.rotatePages, true, prepareRotate)
453
+ module.exports.rotatePagesSync = wrap(binding.rotatePagesSync, false, prepareRotate)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swc/anyformat-pdf",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "High-performance PDF processing for Node.js",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -42,7 +42,7 @@
42
42
  "access": "public"
43
43
  },
44
44
  "dependencies": {
45
- "@swc/anyformat-utils": "0.2.0"
45
+ "@swc/anyformat-utils": "0.2.1"
46
46
  },
47
47
  "devDependencies": {
48
48
  "@emnapi/core": "2.0.0-beta.3",
@@ -52,20 +52,20 @@
52
52
  "emnapi": "2.0.0-beta.3"
53
53
  },
54
54
  "optionalDependencies": {
55
- "@swc/anyformat-pdf-darwin-x64": "0.2.0",
56
- "@swc/anyformat-pdf-darwin-arm64": "0.2.0",
57
- "@swc/anyformat-pdf-win32-x64-msvc": "0.2.0",
58
- "@swc/anyformat-pdf-win32-arm64-msvc": "0.2.0",
59
- "@swc/anyformat-pdf-win32-ia32-msvc": "0.2.0",
60
- "@swc/anyformat-pdf-linux-x64-gnu": "0.2.0",
61
- "@swc/anyformat-pdf-linux-arm64-gnu": "0.2.0",
62
- "@swc/anyformat-pdf-linux-x64-musl": "0.2.0",
63
- "@swc/anyformat-pdf-linux-arm64-musl": "0.2.0",
64
- "@swc/anyformat-pdf-linux-arm-gnueabihf": "0.2.0",
65
- "@swc/anyformat-pdf-android-arm64": "0.2.0",
66
- "@swc/anyformat-pdf-android-arm-eabi": "0.2.0",
67
- "@swc/anyformat-pdf-freebsd-x64": "0.2.0",
68
- "@swc/anyformat-pdf-wasm32-wasi": "0.2.0"
55
+ "@swc/anyformat-pdf-darwin-x64": "0.2.2",
56
+ "@swc/anyformat-pdf-darwin-arm64": "0.2.2",
57
+ "@swc/anyformat-pdf-win32-x64-msvc": "0.2.2",
58
+ "@swc/anyformat-pdf-win32-arm64-msvc": "0.2.2",
59
+ "@swc/anyformat-pdf-win32-ia32-msvc": "0.2.2",
60
+ "@swc/anyformat-pdf-linux-x64-gnu": "0.2.2",
61
+ "@swc/anyformat-pdf-linux-arm64-gnu": "0.2.2",
62
+ "@swc/anyformat-pdf-linux-x64-musl": "0.2.2",
63
+ "@swc/anyformat-pdf-linux-arm64-musl": "0.2.2",
64
+ "@swc/anyformat-pdf-linux-arm-gnueabihf": "0.2.2",
65
+ "@swc/anyformat-pdf-android-arm64": "0.2.2",
66
+ "@swc/anyformat-pdf-android-arm-eabi": "0.2.2",
67
+ "@swc/anyformat-pdf-freebsd-x64": "0.2.2",
68
+ "@swc/anyformat-pdf-wasm32-wasi": "0.2.2"
69
69
  },
70
70
  "scripts": {
71
71
  "build": "napi build --platform --js binding.js --dts binding.d.ts --release",