@patrickdk77/xfa-flatten 0.0.0-stage → 0.1.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.
Files changed (74) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSE-APACHE-2.0 +202 -0
  3. package/NOTICE +14 -0
  4. package/README.md +112 -2
  5. package/dist/barcode-paint.d.ts +11 -0
  6. package/dist/barcode-paint.js +135 -0
  7. package/dist/barcode.d.ts +45 -0
  8. package/dist/barcode.js +750 -0
  9. package/dist/canvas.d.ts +59 -0
  10. package/dist/canvas.js +179 -0
  11. package/dist/cli.d.ts +2 -0
  12. package/dist/cli.js +34 -0
  13. package/dist/css.d.ts +48 -0
  14. package/dist/css.js +288 -0
  15. package/dist/deadline.d.ts +6 -0
  16. package/dist/deadline.js +18 -0
  17. package/dist/filters.d.ts +21 -0
  18. package/dist/filters.js +296 -0
  19. package/dist/flatten.d.ts +25 -0
  20. package/dist/flatten.js +319 -0
  21. package/dist/font-metrics.d.ts +9 -0
  22. package/dist/font-metrics.js +215 -0
  23. package/dist/fonts.d.ts +36 -0
  24. package/dist/fonts.js +144 -0
  25. package/dist/images.d.ts +23 -0
  26. package/dist/images.js +519 -0
  27. package/dist/index.d.ts +2 -0
  28. package/dist/index.js +5 -0
  29. package/dist/index.mjs +3 -0
  30. package/dist/layout.d.ts +64 -0
  31. package/dist/layout.js +779 -0
  32. package/dist/limits.d.ts +2 -0
  33. package/dist/limits.js +6 -0
  34. package/dist/locale.d.ts +29 -0
  35. package/dist/locale.js +97 -0
  36. package/dist/paint.d.ts +15 -0
  37. package/dist/paint.js +533 -0
  38. package/dist/pdf-crypt.d.ts +35 -0
  39. package/dist/pdf-crypt.js +261 -0
  40. package/dist/pdf-read.d.ts +140 -0
  41. package/dist/pdf-read.js +1026 -0
  42. package/dist/pdf417-table.d.ts +2 -0
  43. package/dist/pdf417-table.js +146 -0
  44. package/dist/pdfjs-repair.d.ts +13 -0
  45. package/dist/pdfjs-repair.js +257 -0
  46. package/dist/pdfjs.d.ts +16 -0
  47. package/dist/pdfjs.js +62 -0
  48. package/dist/picture.d.ts +40 -0
  49. package/dist/picture.js +678 -0
  50. package/dist/saslprep.d.ts +11 -0
  51. package/dist/saslprep.js +178 -0
  52. package/dist/style.d.ts +29 -0
  53. package/dist/style.js +178 -0
  54. package/dist/text.d.ts +44 -0
  55. package/dist/text.js +199 -0
  56. package/dist/tiff.d.ts +3 -0
  57. package/dist/tiff.js +270 -0
  58. package/dist/tree.d.ts +23 -0
  59. package/dist/tree.js +54 -0
  60. package/dist/types.d.ts +31 -0
  61. package/dist/types.js +2 -0
  62. package/dist/writer.d.ts +38 -0
  63. package/dist/writer.js +145 -0
  64. package/dist/xfa-apply.d.ts +49 -0
  65. package/dist/xfa-apply.js +617 -0
  66. package/dist/xfa-model.d.ts +42 -0
  67. package/dist/xfa-model.js +227 -0
  68. package/dist/xfa-paint.d.ts +24 -0
  69. package/dist/xfa-paint.js +275 -0
  70. package/dist/xfa-spec.d.ts +47 -0
  71. package/dist/xfa-spec.js +3 -0
  72. package/dist/xml.d.ts +30 -0
  73. package/dist/xml.js +211 -0
  74. package/package.json +83 -4
@@ -0,0 +1,59 @@
1
+ import type { Matrix, Rgb } from './css';
2
+ import type { FontName } from './fonts';
3
+ export interface ShadingSpec {
4
+ type: 2 | 3;
5
+ coords: number[];
6
+ colors: Rgb[];
7
+ }
8
+ /** Painted-area bounds outside the page, collected for the corpus checks. */
9
+ export interface Overflow {
10
+ count: number;
11
+ worst: number;
12
+ }
13
+ export declare class Canvas {
14
+ readonly width: number;
15
+ readonly height: number;
16
+ private readonly ops;
17
+ private ctm;
18
+ private readonly stack;
19
+ /** The current clip in page coordinates, not counting the page clip, for the bounds check. */
20
+ private clip;
21
+ readonly fonts: Set<FontName>;
22
+ readonly images: Map<string, number>;
23
+ readonly shadings: ShadingSpec[];
24
+ readonly overflow: Overflow;
25
+ private fillColor;
26
+ private strokeColor;
27
+ constructor(width: number, height: number);
28
+ content(): Uint8Array;
29
+ save(): void;
30
+ restore(): void;
31
+ transform(m: Matrix): void;
32
+ private bounds;
33
+ /** Records the painted bounds of a local rectangle so the corpus run can check nothing lands off the page. */
34
+ private track;
35
+ /** Clips to a rectangle. The page clip passes counted = false so the bounds check still sees off-page drawing. */
36
+ clipRect(x: number, y: number, w: number, h: number, counted?: boolean): void;
37
+ setFill(c: Rgb): void;
38
+ setStroke(c: Rgb): void;
39
+ fillRect(x: number, y: number, w: number, h: number, c: Rgb): void;
40
+ /** Fills a polygon given as x, y pairs. */
41
+ fillPolygon(points: number[], c: Rgb): void;
42
+ private trackPoints;
43
+ /** Adds raw path construction operators; points are tracked for the bounds check. */
44
+ path(ops: string, points: number[]): void;
45
+ strokePath(ops: string, points: number[], c: Rgb, width: number, dash: number[] | null, cap?: number): void;
46
+ fillPath(ops: string, points: number[], c: Rgb, evenOdd?: boolean): void;
47
+ /** Clips to a path and paints a shading over the given bounds. */
48
+ shade(ops: string, points: number[], spec: ShadingSpec): void;
49
+ /** Draws WinAnsi bytes with the baseline at (x, y). */
50
+ text(font: FontName, size: number, x: number, y: number, bytes: readonly number[], c: Rgb, opts?: {
51
+ charSpacing?: number;
52
+ wordSpacing?: number;
53
+ hScale?: number;
54
+ width?: number;
55
+ }): void;
56
+ /** Draws an image XObject into the rectangle. */
57
+ image(key: string, objectIndex: number, x: number, y: number, w: number, h: number): void;
58
+ }
59
+ export declare function fontKey(font: FontName): string;
package/dist/canvas.js ADDED
@@ -0,0 +1,179 @@
1
+ "use strict";
2
+ // Builds one page's content stream. Callers draw in CSS coordinates: origin at the top left, y down, one unit
3
+ // per point. The stream starts with a matrix that flips to PDF's bottom-up space.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.Canvas = void 0;
6
+ exports.fontKey = fontKey;
7
+ const css_1 = require("./css");
8
+ const writer_1 = require("./writer");
9
+ class Canvas {
10
+ width;
11
+ height;
12
+ ops = [];
13
+ ctm = css_1.IDENTITY;
14
+ stack = [];
15
+ /** The current clip in page coordinates, not counting the page clip, for the bounds check. */
16
+ clip = null;
17
+ fonts = new Set();
18
+ images = new Map();
19
+ shadings = [];
20
+ overflow = { count: 0, worst: 0 };
21
+ fillColor = '';
22
+ strokeColor = '';
23
+ constructor(width, height) {
24
+ this.width = width;
25
+ this.height = height;
26
+ this.ops.push(`1 0 0 -1 0 ${(0, writer_1.formatNumber)(height)} cm`);
27
+ }
28
+ content() {
29
+ return Buffer.from(`${this.ops.join('\n')}\n`, 'latin1');
30
+ }
31
+ save() {
32
+ this.ops.push('q');
33
+ this.stack.push({ ctm: this.ctm, fill: this.fillColor, stroke: this.strokeColor, clip: this.clip });
34
+ }
35
+ restore() {
36
+ this.ops.push('Q');
37
+ const top = this.stack.pop();
38
+ if (top) {
39
+ this.ctm = top.ctm;
40
+ this.fillColor = top.fill;
41
+ this.strokeColor = top.stroke;
42
+ this.clip = top.clip;
43
+ }
44
+ }
45
+ transform(m) {
46
+ this.ops.push(`${m.map(writer_1.formatNumber).join(' ')} cm`);
47
+ this.ctm = (0, css_1.multiply)(this.ctm, m);
48
+ }
49
+ bounds(x, y, w, h) {
50
+ const pts = [(0, css_1.applyPoint)(this.ctm, x, y), (0, css_1.applyPoint)(this.ctm, x + w, y), (0, css_1.applyPoint)(this.ctm, x, y + h), (0, css_1.applyPoint)(this.ctm, x + w, y + h)];
51
+ const xs = pts.map(p => p[0]);
52
+ const ys = pts.map(p => p[1]);
53
+ return [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)];
54
+ }
55
+ /** Records the painted bounds of a local rectangle so the corpus run can check nothing lands off the page. */
56
+ track(x, y, w, h) {
57
+ let [x0, y0, x1, y1] = this.bounds(x, y, w, h);
58
+ if (this.clip) {
59
+ x0 = Math.max(x0, this.clip[0]);
60
+ y0 = Math.max(y0, this.clip[1]);
61
+ x1 = Math.min(x1, this.clip[2]);
62
+ y1 = Math.min(y1, this.clip[3]);
63
+ if (x0 >= x1 || y0 >= y1)
64
+ return;
65
+ }
66
+ const out = Math.max(-x0, -y0, x1 - this.width, y1 - this.height);
67
+ if (out > 1) {
68
+ this.overflow.count++;
69
+ this.overflow.worst = Math.max(this.overflow.worst, out);
70
+ }
71
+ }
72
+ /** Clips to a rectangle. The page clip passes counted = false so the bounds check still sees off-page drawing. */
73
+ clipRect(x, y, w, h, counted = true) {
74
+ if (counted) {
75
+ const b = this.bounds(x, y, w, h);
76
+ const c = this.clip;
77
+ this.clip = c ? [Math.max(b[0], c[0]), Math.max(b[1], c[1]), Math.min(b[2], c[2]), Math.min(b[3], c[3])] : b;
78
+ }
79
+ this.ops.push(`${(0, writer_1.formatNumber)(x)} ${(0, writer_1.formatNumber)(y)} ${(0, writer_1.formatNumber)(w)} ${(0, writer_1.formatNumber)(h)} re W n`);
80
+ }
81
+ setFill(c) {
82
+ const s = `${(0, writer_1.formatNumber)(c[0])} ${(0, writer_1.formatNumber)(c[1])} ${(0, writer_1.formatNumber)(c[2])} rg`;
83
+ if (s !== this.fillColor) {
84
+ this.ops.push(s);
85
+ this.fillColor = s;
86
+ }
87
+ }
88
+ setStroke(c) {
89
+ const s = `${(0, writer_1.formatNumber)(c[0])} ${(0, writer_1.formatNumber)(c[1])} ${(0, writer_1.formatNumber)(c[2])} RG`;
90
+ if (s !== this.strokeColor) {
91
+ this.ops.push(s);
92
+ this.strokeColor = s;
93
+ }
94
+ }
95
+ fillRect(x, y, w, h, c) {
96
+ if (w <= 0 || h <= 0)
97
+ return;
98
+ this.track(x, y, w, h);
99
+ this.setFill(c);
100
+ this.ops.push(`${(0, writer_1.formatNumber)(x)} ${(0, writer_1.formatNumber)(y)} ${(0, writer_1.formatNumber)(w)} ${(0, writer_1.formatNumber)(h)} re f`);
101
+ }
102
+ /** Fills a polygon given as x, y pairs. */
103
+ fillPolygon(points, c) {
104
+ if (points.length < 6)
105
+ return;
106
+ this.trackPoints(points);
107
+ this.setFill(c);
108
+ const parts = [`${(0, writer_1.formatNumber)(points[0])} ${(0, writer_1.formatNumber)(points[1])} m`];
109
+ for (let i = 2; i < points.length; i += 2)
110
+ parts.push(`${(0, writer_1.formatNumber)(points[i])} ${(0, writer_1.formatNumber)(points[i + 1])} l`);
111
+ parts.push('h f');
112
+ this.ops.push(parts.join(' '));
113
+ }
114
+ trackPoints(points) {
115
+ let minX = Number.POSITIVE_INFINITY;
116
+ let minY = Number.POSITIVE_INFINITY;
117
+ let maxX = Number.NEGATIVE_INFINITY;
118
+ let maxY = Number.NEGATIVE_INFINITY;
119
+ for (let i = 0; i + 1 < points.length; i += 2) {
120
+ minX = Math.min(minX, points[i]);
121
+ maxX = Math.max(maxX, points[i]);
122
+ minY = Math.min(minY, points[i + 1]);
123
+ maxY = Math.max(maxY, points[i + 1]);
124
+ }
125
+ if (Number.isFinite(minX))
126
+ this.track(minX, minY, maxX - minX, maxY - minY);
127
+ }
128
+ /** Adds raw path construction operators; points are tracked for the bounds check. */
129
+ path(ops, points) {
130
+ this.trackPoints(points);
131
+ this.ops.push(ops);
132
+ }
133
+ strokePath(ops, points, c, width, dash, cap = 0) {
134
+ if (width <= 0)
135
+ return;
136
+ this.trackPoints(points);
137
+ this.setStroke(c);
138
+ this.ops.push(`${(0, writer_1.formatNumber)(width)} w ${cap} J [${(dash ?? []).map(writer_1.formatNumber).join(' ')}] 0 d`);
139
+ this.ops.push(`${ops} S`);
140
+ }
141
+ fillPath(ops, points, c, evenOdd = false) {
142
+ this.trackPoints(points);
143
+ this.setFill(c);
144
+ this.ops.push(`${ops} ${evenOdd ? 'f*' : 'f'}`);
145
+ }
146
+ /** Clips to a path and paints a shading over the given bounds. */
147
+ shade(ops, points, spec) {
148
+ this.trackPoints(points);
149
+ this.shadings.push(spec);
150
+ this.ops.push(`q ${ops} W n /Sh${this.shadings.length} sh Q`);
151
+ }
152
+ /** Draws WinAnsi bytes with the baseline at (x, y). */
153
+ text(font, size, x, y, bytes, c, opts = {}) {
154
+ if (bytes.length === 0 || size <= 0)
155
+ return;
156
+ this.fonts.add(font);
157
+ this.track(x, y - size * 0.8, opts.width ?? size * bytes.length * 0.5, size);
158
+ this.setFill(c);
159
+ let hex = '';
160
+ for (const b of bytes)
161
+ hex += b.toString(16).padStart(2, '0');
162
+ const parts = ['BT', `/${fontKey(font)} ${(0, writer_1.formatNumber)(size)} Tf`];
163
+ parts.push(`${(0, writer_1.formatNumber)(opts.charSpacing ?? 0)} Tc ${(0, writer_1.formatNumber)(opts.wordSpacing ?? 0)} Tw ${(0, writer_1.formatNumber)(opts.hScale ?? 100)} Tz`);
164
+ parts.push(`1 0 0 -1 ${(0, writer_1.formatNumber)(x)} ${(0, writer_1.formatNumber)(y)} Tm`, `<${hex}> Tj`, 'ET');
165
+ this.ops.push(parts.join(' '));
166
+ }
167
+ /** Draws an image XObject into the rectangle. */
168
+ image(key, objectIndex, x, y, w, h) {
169
+ if (w <= 0 || h <= 0)
170
+ return;
171
+ this.track(x, y, w, h);
172
+ this.images.set(key, objectIndex);
173
+ this.ops.push(`q ${(0, writer_1.formatNumber)(w)} 0 0 ${(0, writer_1.formatNumber)(-h)} ${(0, writer_1.formatNumber)(x)} ${(0, writer_1.formatNumber)(y + h)} cm /${key} Do Q`);
174
+ }
175
+ }
176
+ exports.Canvas = Canvas;
177
+ function fontKey(font) {
178
+ return `F${font.replace(/[^A-Za-z]/g, '')}`;
179
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ // xfa-flatten <in> <out>: flattens a dynamic XFA form and prints the status and notes.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ const node_fs_1 = require("node:fs");
6
+ const flatten_1 = require("./flatten");
7
+ async function main(args) {
8
+ const passwords = [];
9
+ const files = [];
10
+ for (let i = 0; i < args.length; i++) {
11
+ if (args[i] === '--password' && i + 1 < args.length)
12
+ passwords.push(args[++i]);
13
+ else
14
+ files.push(args[i]);
15
+ }
16
+ if (files.length !== 2) {
17
+ console.error('usage: xfa-flatten [--password <pw>]... <in.pdf> <out.pdf>');
18
+ return 2;
19
+ }
20
+ const [input, output] = files;
21
+ const result = await (0, flatten_1.flattenXfa)(new Uint8Array((0, node_fs_1.readFileSync)(input)), passwords.length ? { password: passwords } : {});
22
+ console.log(`status: ${result.status}${result.pages !== undefined ? ` (${result.pages} pages)` : ''}`);
23
+ for (const n of result.notes)
24
+ console.log(`${n.kind} [${n.location}]: ${n.detail}`);
25
+ if (result.status === 'flattened' && result.bytes)
26
+ (0, node_fs_1.writeFileSync)(output, result.bytes);
27
+ return result.status === 'failed' ? 1 : 0;
28
+ }
29
+ main(process.argv.slice(2)).then(code => {
30
+ process.exitCode = code;
31
+ }, (e) => {
32
+ console.error(e instanceof Error ? e.message : String(e));
33
+ process.exitCode = 1;
34
+ });
package/dist/css.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ import type { StyleValue } from './tree';
2
+ export type Rgb = readonly [number, number, number];
3
+ /** A length that may depend on a reference size: value = pct / 100 * reference + px. */
4
+ export interface Length {
5
+ pct: number;
6
+ px: number;
7
+ }
8
+ /** Parses a CSS length. Returns null for auto, empty and anything not understood. */
9
+ export declare function parseLength(v: StyleValue | undefined, emSize?: number): Length | null;
10
+ /** Resolves a length against a reference size. A percentage with no reference resolves to null. */
11
+ export declare function resolveLength(len: Length | null, reference: number | null): number | null;
12
+ /** A px number, or the fallback. */
13
+ export declare function px(v: StyleValue | undefined, fallback?: number): number;
14
+ /** Splits a CSS shorthand of one to four parts into top, right, bottom, left. */
15
+ export declare function fourSides<T>(parts: T[]): [T, T, T, T] | null;
16
+ /** Splits on whitespace that is not inside parentheses. */
17
+ export declare function splitTop(s: string, sep?: RegExp): string[];
18
+ /** Parses a CSS color. Returns null for transparent, none and anything not understood. */
19
+ export declare function parseColor(v: StyleValue | undefined): Rgb | null;
20
+ export interface GradientStop {
21
+ color: Rgb;
22
+ }
23
+ /** A background or fill: one color, or a gradient. */
24
+ export type Paint = {
25
+ kind: 'color';
26
+ color: Rgb;
27
+ } | {
28
+ kind: 'linear';
29
+ angle: number;
30
+ colors: Rgb[];
31
+ } | {
32
+ kind: 'radial';
33
+ colors: Rgb[];
34
+ } | {
35
+ kind: 'repeating';
36
+ colors: Rgb[];
37
+ };
38
+ /** Parses a background or SVG fill value: a color, linear-gradient, radial-gradient or a repeating gradient. */
39
+ export declare function parsePaint(v: StyleValue | undefined): Paint | null;
40
+ /** An affine matrix [a b c d e f] in CSS coordinates (y down). */
41
+ export type Matrix = [number, number, number, number, number, number];
42
+ export declare const IDENTITY: Matrix;
43
+ export declare function multiply(m: Matrix, n: Matrix): Matrix;
44
+ export declare function applyPoint(m: Matrix, x: number, y: number): [number, number];
45
+ /** Parses a CSS transform list (translate, rotate, scale) for a box of the given size. */
46
+ export declare function parseTransform(v: StyleValue | undefined, w: number, h: number): Matrix | null;
47
+ /** Parses transform-origin into a point inside a w by h box. The CSS default is the center. */
48
+ export declare function parseOrigin(v: StyleValue | undefined, w: number, h: number): [number, number];
package/dist/css.js ADDED
@@ -0,0 +1,288 @@
1
+ "use strict";
2
+ // Parsing for the CSS values pdf.js puts in its XFA tree. pdf.js writes XFA measurements as CSS px, and one
3
+ // px there is one PDF point: a 612px by 792px page is a US Letter page.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.IDENTITY = void 0;
6
+ exports.parseLength = parseLength;
7
+ exports.resolveLength = resolveLength;
8
+ exports.px = px;
9
+ exports.fourSides = fourSides;
10
+ exports.splitTop = splitTop;
11
+ exports.parseColor = parseColor;
12
+ exports.parsePaint = parsePaint;
13
+ exports.multiply = multiply;
14
+ exports.applyPoint = applyPoint;
15
+ exports.parseTransform = parseTransform;
16
+ exports.parseOrigin = parseOrigin;
17
+ const NUM = String.raw `-?(?:\d+\.?\d*|\.\d+)(?:e-?\d+)?`;
18
+ const PX_RE = new RegExp(`^(${NUM})(px|pt)?$`, 'i');
19
+ const PCT_RE = new RegExp(`^(${NUM})%$`);
20
+ const CALC_RE = new RegExp(String.raw `^calc\(\s*(${NUM})%\s*([+-])\s*(${NUM})px\s*\)$`);
21
+ const CALC_SCALE_RE = new RegExp(String.raw `^calc\(\s*(${NUM})px\s*\*\s*var\([^)]*\)\s*\)$`);
22
+ const UNIT_RE = new RegExp(`^(${NUM})(in|mm|cm|em)$`);
23
+ /** Parses a CSS length. Returns null for auto, empty and anything not understood. */
24
+ function parseLength(v, emSize = 10) {
25
+ if (v === undefined)
26
+ return null;
27
+ if (typeof v === 'number')
28
+ return Number.isFinite(v) ? { pct: 0, px: v } : null;
29
+ const s = v.trim();
30
+ if (s === '' || s === 'auto')
31
+ return null;
32
+ let m = PX_RE.exec(s);
33
+ if (m)
34
+ return { pct: 0, px: Number(m[1]) };
35
+ m = PCT_RE.exec(s);
36
+ if (m)
37
+ return { pct: Number(m[1]), px: 0 };
38
+ m = CALC_RE.exec(s);
39
+ if (m)
40
+ return { pct: Number(m[1]), px: (m[2] === '-' ? -1 : 1) * Number(m[3]) };
41
+ m = CALC_SCALE_RE.exec(s);
42
+ if (m)
43
+ return { pct: 0, px: Number(m[1]) };
44
+ m = UNIT_RE.exec(s);
45
+ if (m) {
46
+ const n = Number(m[1]);
47
+ switch (m[2]) {
48
+ case 'in':
49
+ return { pct: 0, px: n * 72 };
50
+ case 'mm':
51
+ return { pct: 0, px: (n * 72) / 25.4 };
52
+ case 'cm':
53
+ return { pct: 0, px: (n * 72) / 2.54 };
54
+ default:
55
+ return { pct: 0, px: n * emSize };
56
+ }
57
+ }
58
+ return null;
59
+ }
60
+ /** Resolves a length against a reference size. A percentage with no reference resolves to null. */
61
+ function resolveLength(len, reference) {
62
+ if (!len)
63
+ return null;
64
+ if (len.pct === 0)
65
+ return len.px;
66
+ if (reference === null)
67
+ return null;
68
+ return (len.pct / 100) * reference + len.px;
69
+ }
70
+ /** A px number, or the fallback. */
71
+ function px(v, fallback = 0) {
72
+ const l = parseLength(v);
73
+ return l && l.pct === 0 ? l.px : fallback;
74
+ }
75
+ /** Splits a CSS shorthand of one to four parts into top, right, bottom, left. */
76
+ function fourSides(parts) {
77
+ switch (parts.length) {
78
+ case 1:
79
+ return [parts[0], parts[0], parts[0], parts[0]];
80
+ case 2:
81
+ return [parts[0], parts[1], parts[0], parts[1]];
82
+ case 3:
83
+ return [parts[0], parts[1], parts[2], parts[1]];
84
+ case 4:
85
+ return [parts[0], parts[1], parts[2], parts[3]];
86
+ default:
87
+ return null;
88
+ }
89
+ }
90
+ /** Splits on whitespace that is not inside parentheses. */
91
+ function splitTop(s, sep = /\s/) {
92
+ const out = [];
93
+ let depth = 0;
94
+ let cur = '';
95
+ for (const ch of s) {
96
+ if (ch === '(')
97
+ depth++;
98
+ else if (ch === ')')
99
+ depth--;
100
+ if (depth === 0 && sep.test(ch)) {
101
+ if (cur.trim() !== '')
102
+ out.push(cur.trim());
103
+ cur = '';
104
+ continue;
105
+ }
106
+ cur += ch;
107
+ }
108
+ if (cur.trim() !== '')
109
+ out.push(cur.trim());
110
+ return out;
111
+ }
112
+ const NAMED = {
113
+ black: [0, 0, 0],
114
+ white: [1, 1, 1],
115
+ red: [1, 0, 0],
116
+ green: [0, 128 / 255, 0],
117
+ blue: [0, 0, 1],
118
+ yellow: [1, 1, 0],
119
+ gray: [128 / 255, 128 / 255, 128 / 255],
120
+ grey: [128 / 255, 128 / 255, 128 / 255],
121
+ silver: [192 / 255, 192 / 255, 192 / 255],
122
+ navy: [0, 0, 128 / 255],
123
+ maroon: [128 / 255, 0, 0],
124
+ purple: [128 / 255, 0, 128 / 255],
125
+ orange: [1, 165 / 255, 0],
126
+ lightgray: [211 / 255, 211 / 255, 211 / 255],
127
+ lightgrey: [211 / 255, 211 / 255, 211 / 255],
128
+ darkgray: [169 / 255, 169 / 255, 169 / 255],
129
+ darkgrey: [169 / 255, 169 / 255, 169 / 255],
130
+ };
131
+ /** Parses a CSS color. Returns null for transparent, none and anything not understood. */
132
+ function parseColor(v) {
133
+ if (typeof v !== 'string')
134
+ return null;
135
+ const s = v.trim().toLowerCase();
136
+ if (s === '' || s === 'transparent' || s === 'none' || s === 'inherit' || s === 'initial')
137
+ return null;
138
+ if (s.startsWith('#')) {
139
+ const h = s.slice(1);
140
+ if (/^[0-9a-f]{3}$/.test(h))
141
+ return [Number.parseInt(h[0] + h[0], 16) / 255, Number.parseInt(h[1] + h[1], 16) / 255, Number.parseInt(h[2] + h[2], 16) / 255];
142
+ if (/^[0-9a-f]{6}([0-9a-f]{2})?$/.test(h)) {
143
+ if (h.length === 8 && h.slice(6) === '00')
144
+ return null;
145
+ return [Number.parseInt(h.slice(0, 2), 16) / 255, Number.parseInt(h.slice(2, 4), 16) / 255, Number.parseInt(h.slice(4, 6), 16) / 255];
146
+ }
147
+ return null;
148
+ }
149
+ const m = /^rgba?\(\s*(\d+)\s*,?\s*(\d+)\s*,?\s*(\d+)\s*(?:[,/]\s*([\d.]+)\s*)?\)$/.exec(s);
150
+ if (m) {
151
+ if (m[4] !== undefined && Number(m[4]) === 0)
152
+ return null;
153
+ return [Math.min(255, Number(m[1])) / 255, Math.min(255, Number(m[2])) / 255, Math.min(255, Number(m[3])) / 255];
154
+ }
155
+ return NAMED[s] ?? null;
156
+ }
157
+ function gradientColors(args) {
158
+ const colors = [];
159
+ for (const a of args) {
160
+ const c = parseColor(splitTop(a)[0]);
161
+ if (c)
162
+ colors.push(c);
163
+ }
164
+ return colors;
165
+ }
166
+ /** Parses a background or SVG fill value: a color, linear-gradient, radial-gradient or a repeating gradient. */
167
+ function parsePaint(v) {
168
+ if (typeof v !== 'string')
169
+ return null;
170
+ const s = v.trim();
171
+ const g = /^(repeating-)?(linear|radial)-gradient\((.*)\)/.exec(s);
172
+ if (!g) {
173
+ const c = parseColor(splitTop(s)[0] ?? s);
174
+ return c ? { kind: 'color', color: c } : null;
175
+ }
176
+ const args = splitTop(g[3], /,/);
177
+ if (g[1]) {
178
+ const colors = gradientColors(args);
179
+ return colors.length ? { kind: 'repeating', colors } : null;
180
+ }
181
+ if (g[2] === 'radial') {
182
+ const colors = gradientColors(args.filter(a => !/^circle|^ellipse|^at /.test(a.trim())));
183
+ return colors.length ? { kind: 'radial', colors } : null;
184
+ }
185
+ let angle = 180;
186
+ const first = args[0]?.trim() ?? '';
187
+ let rest = args;
188
+ const dir = /^to (top|bottom|left|right)$/.exec(first);
189
+ const deg = /^(-?[\d.]+)deg$/.exec(first);
190
+ if (dir) {
191
+ angle = { top: 0, right: 90, bottom: 180, left: 270 }[dir[1]];
192
+ rest = args.slice(1);
193
+ }
194
+ else if (deg) {
195
+ angle = Number(deg[1]);
196
+ rest = args.slice(1);
197
+ }
198
+ const colors = gradientColors(rest);
199
+ return colors.length ? { kind: 'linear', angle, colors } : null;
200
+ }
201
+ exports.IDENTITY = [1, 0, 0, 1, 0, 0];
202
+ function multiply(m, n) {
203
+ // Applies n first, then m.
204
+ return [m[0] * n[0] + m[2] * n[1], m[1] * n[0] + m[3] * n[1], m[0] * n[2] + m[2] * n[3], m[1] * n[2] + m[3] * n[3], m[0] * n[4] + m[2] * n[5] + m[4], m[1] * n[4] + m[3] * n[5] + m[5]];
205
+ }
206
+ function applyPoint(m, x, y) {
207
+ return [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]];
208
+ }
209
+ /** Parses a CSS transform list (translate, rotate, scale) for a box of the given size. */
210
+ function parseTransform(v, w, h) {
211
+ if (typeof v !== 'string' || v.trim() === '' || v.trim() === 'none')
212
+ return null;
213
+ let m = exports.IDENTITY;
214
+ const re = /(translate[XY]?|rotate|scale[XY]?)\(([^)]*)\)/g;
215
+ let found = false;
216
+ for (let t = re.exec(v); t !== null; t = re.exec(v)) {
217
+ found = true;
218
+ const args = t[2].split(/[\s,]+/).filter(a => a !== '');
219
+ const len = (a, ref) => resolveLength(parseLength(a ?? '0'), ref) ?? 0;
220
+ let n = exports.IDENTITY;
221
+ switch (t[1]) {
222
+ case 'translate':
223
+ n = [1, 0, 0, 1, len(args[0], w), len(args[1], h)];
224
+ break;
225
+ case 'translateX':
226
+ n = [1, 0, 0, 1, len(args[0], w), 0];
227
+ break;
228
+ case 'translateY':
229
+ n = [1, 0, 0, 1, 0, len(args[0], h)];
230
+ break;
231
+ case 'rotate': {
232
+ const a = /(-?[\d.]+)\s*(deg|rad|turn)?/.exec(args[0] ?? '0');
233
+ let rad = a ? Number(a[1]) : 0;
234
+ if (!a || a[2] === undefined || a[2] === 'deg')
235
+ rad = (rad * Math.PI) / 180;
236
+ else if (a[2] === 'turn')
237
+ rad *= 2 * Math.PI;
238
+ const c = Math.cos(rad);
239
+ const s = Math.sin(rad);
240
+ n = [c, s, -s, c, 0, 0];
241
+ break;
242
+ }
243
+ case 'scale': {
244
+ const sx = Number(args[0] ?? 1);
245
+ const sy = Number(args[1] ?? args[0] ?? 1);
246
+ n = [Number.isFinite(sx) ? sx : 1, 0, 0, Number.isFinite(sy) ? sy : 1, 0, 0];
247
+ break;
248
+ }
249
+ case 'scaleX': {
250
+ const sx = Number(args[0] ?? 1);
251
+ n = [Number.isFinite(sx) ? sx : 1, 0, 0, 1, 0, 0];
252
+ break;
253
+ }
254
+ case 'scaleY': {
255
+ const sy = Number(args[0] ?? 1);
256
+ n = [1, 0, 0, Number.isFinite(sy) ? sy : 1, 0, 0];
257
+ break;
258
+ }
259
+ default:
260
+ break;
261
+ }
262
+ m = multiply(m, n);
263
+ }
264
+ return found ? m : null;
265
+ }
266
+ /** Parses transform-origin into a point inside a w by h box. The CSS default is the center. */
267
+ function parseOrigin(v, w, h) {
268
+ if (typeof v !== 'string' || v.trim() === '')
269
+ return [w / 2, h / 2];
270
+ const parts = v.trim().split(/\s+/);
271
+ let x = w / 2;
272
+ let y = h / 2;
273
+ for (const p of parts) {
274
+ if (p === 'left')
275
+ x = 0;
276
+ else if (p === 'right')
277
+ x = w;
278
+ else if (p === 'top')
279
+ y = 0;
280
+ else if (p === 'bottom')
281
+ y = h;
282
+ }
283
+ if (parts.length === 2 && !/^(left|right|top|bottom|center)$/.test(parts[0])) {
284
+ x = resolveLength(parseLength(parts[0]), w) ?? x;
285
+ y = resolveLength(parseLength(parts[1]), h) ?? y;
286
+ }
287
+ return [x, y];
288
+ }
@@ -0,0 +1,6 @@
1
+ /** Thrown when the caller's deadline has passed. */
2
+ export declare class DeadlineError extends Error {
3
+ constructor();
4
+ }
5
+ /** Throws DeadlineError when `deadline` (a Date.now() value) has passed; does nothing without a deadline. */
6
+ export declare function checkDeadline(deadline: number | undefined): void;
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ // The caller's deadline. Long loops call checkDeadline so a run stops soon after the deadline passes, and
3
+ // flattenXfa turns the error into status 'failed' with a 'deadline' note.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.DeadlineError = void 0;
6
+ exports.checkDeadline = checkDeadline;
7
+ /** Thrown when the caller's deadline has passed. */
8
+ class DeadlineError extends Error {
9
+ constructor() {
10
+ super('the deadline passed');
11
+ }
12
+ }
13
+ exports.DeadlineError = DeadlineError;
14
+ /** Throws DeadlineError when `deadline` (a Date.now() value) has passed; does nothing without a deadline. */
15
+ function checkDeadline(deadline) {
16
+ if (deadline !== undefined && Date.now() > deadline)
17
+ throw new DeadlineError();
18
+ }
@@ -0,0 +1,21 @@
1
+ /** Thrown when a decoder's output would pass the limit its caller set. */
2
+ export declare class OutputLimitError extends Error {
3
+ constructor(limit: number);
4
+ }
5
+ /**
6
+ * Inflates zlib data, tolerating a truncated or unterminated stream, then raw deflate data. Output past `limit` bytes
7
+ * throws OutputLimitError instead of being allocated.
8
+ */
9
+ export declare function inflate(data: Uint8Array, limit?: number): Uint8Array;
10
+ /**
11
+ * LZW as PDF and TIFF use it: MSB-first codes of 9 to 12 bits, 256 clears, 257 ends. earlyChange 1 widens the code
12
+ * one entry early, as PDF's default and TIFF do.
13
+ */
14
+ export declare function lzwDecode(data: Uint8Array, earlyChange?: number, limit?: number): Uint8Array;
15
+ export declare function asciiHexDecode(data: Uint8Array): Uint8Array;
16
+ export declare function ascii85Decode(data: Uint8Array): Uint8Array;
17
+ export declare function runLengthDecode(data: Uint8Array, limit?: number): Uint8Array;
18
+ /** Undoes PNG row predictors (predictor 10 to 15) on rows of `columns` samples. */
19
+ export declare function pngUnpredict(data: Uint8Array, columns: number, colors: number, bits: number): Uint8Array;
20
+ /** Undoes TIFF predictor 2 (horizontal differencing) in place, for 8 and 16 bit samples. */
21
+ export declare function tiffUnpredict(data: Uint8Array, columns: number, colors: number, bits: number, littleEndian?: boolean): Uint8Array;