@hussmartinez/pdf-sdk 0.2.0 → 0.4.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/README.md +36 -7
- package/dist/assets/processing/processing.worker.js +1 -1
- package/dist/index.d.ts +359 -53
- package/dist/index.js +233 -1
- package/dist/index.js.map +1 -0
- package/dist/lazy/{processing-worker-DU8GEYFs.js → processing-worker-DIP9ck2l.js} +2 -2
- package/dist/lazy/{processing-worker-DU8GEYFs.js.map → processing-worker-DIP9ck2l.js.map} +1 -1
- package/dist/react.d.ts +198 -172
- package/dist/react.js +487 -78
- package/dist/react.js.map +1 -1
- package/dist/shared/{en-BYB_GHqG.js → en-DKR-ngAZ.js} +391 -217
- package/dist/shared/en-DKR-ngAZ.js.map +1 -0
- package/dist/styles.css +19 -0
- package/formats/hm-pdf-command/v1.schema.json +162 -0
- package/formats/hm-pdf-plan/v1.schema.json +259 -0
- package/package.json +18 -10
- package/dist/shared/en-BYB_GHqG.js.map +0 -1
package/README.md
CHANGED
|
@@ -28,10 +28,22 @@ const bytes = await editor.current?.export();
|
|
|
28
28
|
|
|
29
29
|
**A bounded height.** `PdfEditor` fills the height of its container, and its viewer and thumbnails scroll within it, so give it a bounded height: a fixed height, or a grid row such as `minmax(0, 1fr)`. The same goes for `PdfViewer` and `PdfThumbnails` used on their own.
|
|
30
30
|
|
|
31
|
-
**Text.** `messages` overrides any text the editor shows, by key, including ui's, such as `"spinner.label"`. The editor builds one set of text from them and your `locale`, for its own components and for ui's ([sdk-core ADR 0046](https://github.com/ie-huss-martinez/sdk-core/blob/main/docs/adr/0046-ui-text-through-the-sdk.md)). `pdfEditorMessages
|
|
31
|
+
**Text.** `messages` overrides any text the editor shows, by key, including ui's, such as `"spinner.label"`. The editor builds one set of text from them and your `locale`, for its own components and for ui's ([sdk-core ADR 0046](https://github.com/ie-huss-martinez/sdk-core/blob/main/docs/adr/0046-ui-text-through-the-sdk.md)). `pdfEditorMessages`, from `@hussmartinez/pdf-sdk/react`, is the English catalogue, and `MessageOverrides<PdfEditorMessageCatalogue>` types your overrides. `pdfMessages`, from the server-safe entry, holds only error and warning text, for hosts that show the session's errors themselves ([ADR 0010](docs/adr/0010-interface-text-outside-the-server-safe-entry.md)).
|
|
32
32
|
|
|
33
33
|
`file` opens a document, and a different one replaces it; `null` closes it. Users can also open one with the editor's button or by dropping it on the editor. `onChange` reports each `open`, `edit` and `close`, and the ref's `PdfEditorHandle` exports, undoes, redoes and closes.
|
|
34
34
|
|
|
35
|
+
**The file's name.** On `open`, `onChange` also gives the opened file's `fileName`, from the `File`, or from the `name` option of `handle.open(bytes, { name })`. The session's `sources` carry it as `name`. It's cleaned first: one path segment, with no control or bidirectional formatting characters and at most 128 code points ([ADR 0009](docs/adr/0009-saving-the-document.md)). It comes from the file, so show it only as text. It's never sent to `onEvent`.
|
|
36
|
+
|
|
37
|
+
### Saving
|
|
38
|
+
|
|
39
|
+
The download tool builds the document in the processing worker and downloads it. The file is named after the opened file, or `document.pdf` ([ADR 0009](docs/adr/0009-saving-the-document.md)). The download uses a `blob:` URL, so it makes no request and needs nothing more in your Content Security Policy.
|
|
40
|
+
|
|
41
|
+
- **`downloadName(info)`** names the file yourself. `info` has the opened file's `sourceName` and the `pageCount`. The result is cleaned as a file name and gets a `.pdf` extension.
|
|
42
|
+
- **`onExport(bytes, info)`** receives the bytes instead of the browser downloading them, for example to keep them in your app's storage. `info` has the `fileName` the download would have had, and the `pageCount`. If it throws or rejects, the editor says the PDF couldn't be saved. Your error is yours to log, and the editor doesn't read it.
|
|
43
|
+
- **While it builds,** the button is disabled but keeps focus, and the header says "Preparing the PDF…". After a second, a Cancel button appears beside it.
|
|
44
|
+
- **Cancelling:** cancelling, or opening or closing a document, stops the build quietly.
|
|
45
|
+
- **Failures:** a failed build shows its error's text in the header.
|
|
46
|
+
|
|
35
47
|
### Tools, the toolbar and shortcuts
|
|
36
48
|
|
|
37
49
|
The editor's tools are in `pdfTools`:
|
|
@@ -39,10 +51,15 @@ The editor's tools are in `pdfTools`:
|
|
|
39
51
|
| Tool | Shortcut | What it does |
|
|
40
52
|
|---|---|---|
|
|
41
53
|
| `pdf.open` | none: `Ctrl+O` is the browser's own | Opens a PDF, replacing the current one |
|
|
54
|
+
| `pdf.insert-pages` | none | Inserts every page of another PDF after the current page, which merges the two |
|
|
42
55
|
| `pdf.undo` | `Ctrl+Z`, or `⌘Z` on Apple platforms | Undoes the last edit |
|
|
43
56
|
| `pdf.redo` | `Ctrl+Shift+Z` or `Ctrl+Y`, or `⇧⌘Z` | Redoes the last undone edit |
|
|
44
57
|
| `pdf.rotate-left` | `[` | Turns the selected pages, or the current one, a quarter turn anticlockwise |
|
|
45
58
|
| `pdf.rotate-right` | `]` | Turns them a quarter turn clockwise |
|
|
59
|
+
| `pdf.move-earlier` | `Alt+↑` (`Option+↑` on macOS), in the thumbnails only | Moves the selected pages, or the current one, one position earlier |
|
|
60
|
+
| `pdf.move-later` | `Alt+↓` (`Option+↓`), in the thumbnails only | Moves them one position later |
|
|
61
|
+
| `pdf.delete-pages` | `Delete` or `Backspace`, in the thumbnails only | Deletes the selected pages, or the current one; a document keeps at least one page |
|
|
62
|
+
| `pdf.download` | none: `Ctrl+S` is the browser's own | Builds the document and downloads it, or hands it to `onExport` |
|
|
46
63
|
|
|
47
64
|
Choose which tools are present with `tools`, and arrange the toolbar with `toolbar`, as groups of tool ids; `toolbar={[]}` hides it and keeps the shortcuts. An unknown id throws when the editor renders, so a typo never leaves a tool silently missing. `icons` replaces any icon by name with your own component.
|
|
48
65
|
|
|
@@ -53,7 +70,17 @@ Choose which tools are present with `tools`, and arrange the toolbar with `toolb
|
|
|
53
70
|
/>
|
|
54
71
|
```
|
|
55
72
|
|
|
56
|
-
Shortcuts work only while focus is inside the editor, never on the rest of your page, and never while typing in a field. The toolbar is one tab stop, with arrow keys between its buttons; each button names its shortcut in `aria-keyshortcuts`. Undoing, redoing and
|
|
73
|
+
Shortcuts work only while focus is inside the editor, never on the rest of your page, and never while typing in a field. The toolbar is one tab stop, with arrow keys between its buttons; each button names its shortcut in `aria-keyshortcuts`. A button that can't run is disabled with `aria-disabled`, so it keeps focus. Undoing, redoing, rotating and deleting are announced to screen readers.
|
|
74
|
+
|
|
75
|
+
Inserting puts every page of the chosen PDF after the current page, selects the inserted pages and shows the first. The file policy's limits apply to the combined document: `maxPages` counts the pages after the insert, and `maxSessionSize` counts every document held. A failed insert leaves the document unchanged and shows why in the header. When undo steps had to be dropped to make room within `maxSessionSize`, the header says so.
|
|
76
|
+
|
|
77
|
+
Moving gathers pages that aren't next to each other into one block, in their order, and moves the block one position. The moved pages stay selected, and focus stays on them. The keys were chosen so they don't clash with browser or system shortcuts; ADR 0008 records the check.
|
|
78
|
+
|
|
79
|
+
Deleting and moving work on the thumbnails' selection, so their keys work only while focus is in the thumbnails ([ADR 0008](docs/adr/0008-page-organisation-in-the-editor.md)). The page that takes the first deleted page's place is selected, and focus moves to it if its thumbnail had focus. Undo and redo bring back the selection and the current page with the pages. `PdfThumbnails` used on its own takes `onDelete` and `onMove` props for those keys.
|
|
80
|
+
|
|
81
|
+
## Saving a project
|
|
82
|
+
|
|
83
|
+
`toPdfPlanDocument(plan, sources)` writes the session's plan as portable JSON, `hm-pdf-plan` version 1: the pages in order, their rotations and annotations, and form values, with each source's page count. It holds no PDF bytes and no file names, so store the source files alongside it. `readPdfPlanDocument(json)` reads one back, refusing another format or a later version with `UNSUPPORTED_FORMAT`, and anything invalid with `INVALID_DOCUMENT`, each with a stable `details.reason`. The JSON Schemas ship with the package, under `@hussmartinez/pdf-sdk/formats/`, for validating documents elsewhere, such as on a server. [The format record](docs/formats/hm-pdf-plan.md) describes the format, how to load its schemas, and its conformance vectors ([sdk-core ADR 0045](https://github.com/ie-huss-martinez/sdk-core/blob/main/docs/adr/0045-portable-formats-and-conformance-vectors.md)).
|
|
57
84
|
|
|
58
85
|
## Assets and Content Security Policy
|
|
59
86
|
|
|
@@ -72,7 +99,7 @@ The SDK runs two workers: pdf.js's, which renders, and one with qpdf and pdf-lib
|
|
|
72
99
|
|
|
73
100
|
**In self-hosted mode, copy the whole directory again whenever you upgrade the package.** A worker left over from another version is refused with `WORKER_START_FAILED`, whose `details` name the file and both versions, `{ asset, expected, actual }`: the processing worker checks the package's version, pdf.js checks its own, and the processing worker also refuses a `qpdf.wasm` from another version.
|
|
74
101
|
|
|
75
|
-
`assetsUrl` can be absolute or relative to the page, such as `/pdf-sdk/`.
|
|
102
|
+
`assetsUrl` can be absolute or relative to the page, such as `/pdf-sdk/`. A relative one is resolved when a worker first starts, in the browser, so `PdfEditor`, `PdfSessionProvider`, `createPdfJsEngine` and `createPdfProcessor` all accept it on a server. A URL with a query or a fragment is refused, because the files resolved from it would lose them: the components throw `TypeError` as they render, and `createPdfJsEngine` and `createPdfProcessor` throw it when you call them.
|
|
76
103
|
|
|
77
104
|
## Development
|
|
78
105
|
|
|
@@ -88,21 +115,23 @@ pnpm verify:fast # the subset the pre-push hook runs
|
|
|
88
115
|
|
|
89
116
|
The examples use the built package as an application would: [`examples/next`](examples/next) renders the editor in a Next.js App Router Server Component, and [`examples/vite`](examples/vite) has one page per asset mode, each under the Content Security Policy this README gives for it. The plain HTML example joins them with the standalone script.
|
|
90
117
|
|
|
91
|
-
|
|
118
|
+
The browser and end-to-end tests also need Docker. They run in the pinned browser test image from [`ci/Dockerfile`](ci/Dockerfile), as in CI, through `hm-in-image` from `@hussmartinez/sdk-config` ([sdk-core ADR 0049](https://github.com/ie-huss-martinez/sdk-core/blob/main/docs/adr/0049-local-browser-tests-in-the-pinned-image.md)). The first run builds the image and installs the dependencies into its volumes. `pnpm test:browser:all` runs all three engines, as CI does.
|
|
92
119
|
|
|
93
120
|
`pnpm verify` runs, in order:
|
|
94
121
|
|
|
95
122
|
| Step | Script | Tool |
|
|
96
123
|
|---|---|---|
|
|
97
|
-
| Format and lint | `lint` | Biome |
|
|
124
|
+
| Format and lint | `lint` | Biome, then `tools/check-hidden-unicode.ts`, which fails on bidirectional formatting and zero-width characters in tracked files outside `test/fixtures`; write them as escapes |
|
|
98
125
|
| CSS rules | `lint:css` | stylelint, with the `hm-` namespace and token rules |
|
|
99
126
|
| Types | `typecheck` | TypeScript |
|
|
100
127
|
| Dependency rules | `lint:deps` | dependency-cruiser, through `hm-lint-deps` |
|
|
128
|
+
| Playwright pinned to the browser test image | `check:playwright-image` | `hm-check-playwright-image` (sdk-core ADR 0025) |
|
|
101
129
|
| Build | `build` | Vite, then api-extractor for the type declarations |
|
|
102
130
|
| Unit tests | `test` | Vitest |
|
|
103
|
-
| Browser tests | `test:browser` | Vitest in Chromium, and in Firefox and WebKit too in CI |
|
|
131
|
+
| Browser tests | `test:browser` | Vitest in Chromium in the browser test image, and in Firefox and WebKit too in CI |
|
|
104
132
|
| Examples | `build:examples` | Production builds of the Next.js and Vite examples, against the built package |
|
|
105
|
-
| End-to-end tests | `test:e2e` | Playwright against the examples: server rendering and hydration, axe, no foreign requests, and both asset modes under the Content Security Policies above |
|
|
133
|
+
| End-to-end tests | `test:e2e` | Playwright in the browser test image, against the examples: server rendering and hydration, axe, no foreign requests, and both asset modes under the Content Security Policies above |
|
|
134
|
+
| Visual regression | `test:visual` | `hm-test-visual`: screenshots of the editor's states in [`e2e/visual`](e2e/visual), on Chromium in the browser test image, in light and dark, compact and comfortable (sdk-core ADR 0048). `pnpm test:visual:update` rewrites the baselines |
|
|
106
135
|
| Size budgets | `check:size` | size-limit, brotli size of each entry point |
|
|
107
136
|
| API reports | `check:api` | api-extractor, one report per entry point in [`api`](api), and `hm-check-api-reports` across them |
|
|
108
137
|
| Package checks | `check:package` | publint and Are the Types Wrong? |
|
|
@@ -54,4 +54,4 @@ end\
|
|
|
54
54
|
endstream
|
|
55
55
|
endobj
|
|
56
56
|
`))}finish(e){let t=this.offsets.size+1,n=this.length,r=`xref\n0 ${t}\n0000000000 65535 f \n`,i=[...this.offsets.entries()].sort(([e],[t])=>e-t);for(let[,e]of i)r+=`${String(e).padStart(10,`0`)} 00000 n \n`;r+=`trailer\n<< /Size ${t} /Root ${e} 0 R >>\nstartxref\n${n}\n%%EOF\n`,this.push(ev(r));let a=new Uint8Array(this.length),o=0;for(let e of this.chunks)a.set(e,o),o+=e.length;return a}push(e){this.chunks.push(e),this.length+=e.length}}})),iv=/* @__PURE__ */ c({PdfError:()=>Y_,PdfPasswordError:()=>X_,PdfToolkit:()=>mv,createPdfToolkit:()=>av,imagesToPdf:()=>Q_});function av(e={}){return mv.create(e)}function ov(e){return typeof e==`object`&&e&&`data`in e?e:{data:e}}function sv(e){return e.replace(/[^\w.-]/g,`_`)||`attachment`}function cv(e){return Number.parseInt(e.replace(/^part-/,``),10)}function lv(e){return`--password=${e}`}function uv(e){return typeof e==`number`?String(e):typeof e==`string`?e:e.map(String).join(`,`)}function dv(e){let{userPassword:t,ownerPassword:n=t,keyLength:r=256,permissions:i={}}=e,a=[];r===40&&a.push(`--allow-weak-crypto`),a.push(`--encrypt`,`--user-password=${t}`,`--owner-password=${n}`,`--bits=${r}`),r===128&&a.push(`--use-aes=y`);let{print:o,modify:s,extract:c,accessibility:l}=i;return r===40?(o!==void 0&&a.push(`--print=${o===`none`?`n`:`y`}`),s!==void 0&&a.push(`--modify=${s===`none`?`n`:`y`}`),c!==void 0&&a.push(`--extract=${c?`y`:`n`}`)):(o!==void 0&&a.push(`--print=${o}`),s!==void 0&&a.push(`--modify=${s}`),c!==void 0&&a.push(`--extract=${c?`y`:`n`}`),l!==void 0&&a.push(`--accessibility=${l?`y`:`n`}`)),a.push(`--`),a}function fv(e){if(e.exitCode!==0&&e.exitCode!==3)throw pv(e)}function pv(e){let t=e.stderr.trim(),n=t.split(`
|
|
57
|
-
`).at(-1)??`qpdf failed with exit code ${e.exitCode}`;return/invalid password|password.*(required|incorrect)/i.test(t)?new X_(n,e.exitCode,t):new Y_(n,e.exitCode,t)}var mv,hv=o((()=>{J_(),Z_(),rv(),mv=class e{runner;constructor(e){this.runner=e}static async create(t={}){return new e(await G_.create(t))}unlock(e,t){return this.transform(e,[lv(t.password),`--decrypt`])}removePassword(e,t){return this.unlock(e,t)}lock(e,t){return this.transform(e,dv(t))}changePassword(e,t){let n={userPassword:t.newPassword,ownerPassword:t.newOwnerPassword??t.newPassword,...t.keyLength!==void 0&&{keyLength:t.keyLength},...t.permissions!==void 0&&{permissions:t.permissions}};return this.transform(e,[lv(t.currentPassword),...dv(n)])}async merge(e){if(e.length===0)throw TypeError(`merge() needs at least one source document`);let t=e.map(ov);return this.runner.run(t.map(e=>e.data),({dir:e,inputPaths:n,exec:r,fs:i})=>{let a=[`--empty`,`--pages`];t.forEach((e,t)=>{a.push(n[t]),e.password!==void 0&&a.push(`--password=${e.password}`),a.push(e.pages===void 0?`1-z`:uv(e.pages))});let o=`${e}/out.pdf`;return a.push(`--`,o),fv(r(a)),i.readFile(o)})}async split(e,t={}){let n=t.pagesPerFile??1;if(!Number.isInteger(n)||n<1)throw TypeError(`pagesPerFile must be a positive integer, got ${n}`);return this.runner.run([e],({dir:e,inputPaths:r,exec:i,fs:a})=>{let o=[];return t.password!==void 0&&o.push(lv(t.password)),o.push(`--split-pages=${n}`,r[0],`${e}/part-%d.pdf`),fv(i(o)),a.readdir(e).filter(e=>e.startsWith(`part-`)).sort((e,t)=>cv(e)-cv(t)).map(t=>a.readFile(`${e}/${t}`))})}extractPages(e,t){let n=[];return t.password!==void 0&&n.push(lv(t.password)),n.push(`--pages`,`.`,uv(t.pages),`--`),this.transform(e,n)}async rotate(e,t){let{angle:n,absolute:r=!1,pages:i,password:a}=t;if(r&&n<0)throw TypeError(`absolute rotation must use a non-negative angle (90, 180, or 270)`);let o=`${r?``:n<0?`-`:`+`}${Math.abs(n)}${i===void 0?``:`:${uv(i)}`}`,s=[];return a!==void 0&&s.push(lv(a)),s.push(`--rotate=${o}`),this.transform(e,s)}async pageCount(e,t={}){return this.runner.run([e],({inputPaths:e,exec:n})=>{let r=[];t.password!==void 0&&r.push(lv(t.password)),r.push(`--show-npages`,e[0]);let i=n(r);return fv(i),Number.parseInt(i.stdoutText.trim(),10)})}async isEncrypted(e){return this.runner.run([e],({inputPaths:e,exec:t})=>{let n=t([`--is-encrypted`,e[0]]);if(n.exitCode===0)return!0;if(n.exitCode===2)return!1;throw pv(n)})}async requiresPassword(e){return this.runner.run([e],({inputPaths:e,exec:t})=>{let n=t([`--requires-password`,e[0]]);if(n.exitCode===0)return!0;if(n.exitCode===2||n.exitCode===3)return!1;throw pv(n)})}compress(e,t={}){let{password:n,compressionLevel:r=9,objectStreams:i=!0,linearize:a=!1}=t;if(!Number.isInteger(r)||r<1||r>9)throw TypeError(`compressionLevel must be 1-9, got ${r}`);let o=[];return n!==void 0&&o.push(lv(n)),o.push(`--compress-streams=y`,`--recompress-flate`,`--compression-level=${r}`,`--object-streams=${i?`generate`:`preserve`}`),a&&o.push(`--linearize`),this.transform(e,o)}linearize(e,t={}){let n=[];return t.password!==void 0&&n.push(lv(t.password)),n.push(`--linearize`),this.transform(e,n)}repair(e,t={}){let n=[];return t.password!==void 0&&n.push(lv(t.password)),this.transform(e,n)}async watermark(e,t,n={}){let{mode:r=`overlay`,password:i,stampPassword:a,to:o,from:s,repeat:c}=n;return this.runner.run([e,t],({dir:e,inputPaths:t,exec:n,fs:l})=>{let u=[];i!==void 0&&u.push(lv(i)),u.push(`--${r}`,t[1]),a!==void 0&&u.push(`--password=${a}`),o!==void 0&&u.push(`--to=${uv(o)}`),s!==void 0&&u.push(`--from=${uv(s)}`),c!==void 0&&u.push(`--repeat=${uv(c)}`);let d=`${e}/out.pdf`;return u.push(`--`,t[0],d),fv(n(u)),l.readFile(d)})}deletePages(e,t){let n={pages:`1-z,${uv(t.pages).split(`,`).map(e=>`x${e}`).join(`,`)}`,...t.password!==void 0&&{password:t.password}};return this.extractPages(e,n)}reversePages(e,t={}){return this.extractPages(e,{pages:`z-1`,...t})}async collate(e,t={}){let n=t.groupSize??1;if(!Number.isInteger(n)||n<1)throw TypeError(`groupSize must be a positive integer, got ${n}`);if(e.length<2)throw TypeError(`collate() needs at least two source documents`);let r=e.map(ov);return this.runner.run(r.map(e=>e.data),({dir:e,inputPaths:t,exec:i,fs:a})=>{let o=[`--empty`,`--collate=${n}`,`--pages`];r.forEach((e,n)=>{o.push(t[n]),e.password!==void 0&&o.push(`--password=${e.password}`),o.push(e.pages===void 0?`1-z`:uv(e.pages))});let s=`${e}/out.pdf`;return o.push(`--`,s),fv(i(o)),a.readFile(s)})}flatten(e,t={}){let n=[];return t.password!==void 0&&n.push(lv(t.password)),n.push(`--generate-appearances`,`--flatten-annotations=${t.annotations??`all`}`),this.transform(e,n)}async addAttachment(e,t){let{data:n,name:r,mimeType:i,description:a,password:o}=t;return this.runner.run([e],async({dir:e,inputPaths:t,exec:s,fs:c})=>{let l=`${e}/${sv(r)}`;c.writeFile(l,await W_(n));let u=[];o!==void 0&&u.push(lv(o)),u.push(`--add-attachment`,l,`--key=${r}`,`--filename=${r}`),i!==void 0&&u.push(`--mimetype=${i}`),a!==void 0&&u.push(`--description=${a}`);let d=`${e}/out.pdf`;return u.push(`--`,t[0],d),fv(s(u)),c.readFile(d)})}removeAttachment(e,t){let n=[];return t.password!==void 0&&n.push(lv(t.password)),n.push(`--remove-attachment=${t.name}`),this.transform(e,n)}async getAttachment(e,t){return this.runner.run([e],({inputPaths:e,exec:n})=>{let r=[];t.password!==void 0&&r.push(lv(t.password)),r.push(`--show-attachment=${t.name}`,e[0]);let i=n(r);return fv(i),i.stdout})}async listAttachments(e,t={}){return(await this.getInfo(e,t)).attachments}async getInfo(e,t={}){return this.runner.run([e],({inputPaths:e,exec:n,fs:r})=>{let i=n([...t.password===void 0?[]:[lv(t.password)],`--json`,`--json-key=encrypt`,`--json-key=attachments`,`--json-key=pages`,e[0]]);fv(i);let a=JSON.parse(i.stdoutText),o=new TextDecoder(`latin1`).decode(r.readFile(e[0]).slice(0,1024)),s=/%PDF-(\d+\.\d+)/.exec(o)?.[1]??`unknown`,c=Object.entries(a.attachments??{}).map(([e,t])=>({name:e,...t.preferredname!==void 0&&{filename:t.preferredname},...t.description!==void 0&&{description:t.description}})),l=a.encrypt,u={pdfVersion:s,pageCount:a.pages?.length??0,encrypted:l?.encrypted??!1,attachments:c};if(l?.encrypted){let e=l.capabilities??{};u.encryption={bits:l.parameters?.bits??0,method:l.parameters?.method??`unknown`,userPasswordMatched:l.userpasswordmatched??!1,ownerPasswordMatched:l.ownerpasswordmatched??!1,permissions:{accessibility:e.accessibility??!1,extract:e.extract??!1,print:e.printhigh??e.printlow??!1,modify:e.modify??!1,annotate:e.modifyannotations??!1,fillForms:e.modifyforms??!1,assemble:e.modifyassembly??!1}}}return u})}async raw(e,t){return this.runner.run(e,({dir:e,inputPaths:n,exec:r,fs:i})=>{let a=`${e}/out.pdf`;return fv(r(t.map(e=>e.replace(/\$out/g,a).replace(/\$in(\d+)/g,(e,t)=>{let r=n[Number(t)];if(r===void 0)throw TypeError(`no input for placeholder $in${t}`);return r})))),i.readFile(a)})}async transform(e,t){return this.runner.run([e],({dir:e,inputPaths:n,exec:r,fs:i})=>{let a=`${e}/out.pdf`;return fv(r([...t,n[0],a])),i.readFile(a)})}}})),gv;function _v(e){return gv??=(async()=>{let[{createPdfToolkit:t},n]=await Promise.all([Promise.resolve().then(()=>(hv(),iv)),e()]);return t({wasmModule:await WebAssembly.compile(n)})})(),gv.catch(()=>{gv=void 0}),gv}function vv(e){de({async build(t,n){try{return{ok:!0,bytes:await F_(t,{toolkit:()=>_v(e),signal:n.signal,progress:e=>n.progress(e)})}}catch(e){if(e instanceof TypeError||e instanceof RangeError)return{ok:!1,error:e.name,message:e.message};throw e}}},{packageVersion:`0.
|
|
57
|
+
`).at(-1)??`qpdf failed with exit code ${e.exitCode}`;return/invalid password|password.*(required|incorrect)/i.test(t)?new X_(n,e.exitCode,t):new Y_(n,e.exitCode,t)}var mv,hv=o((()=>{J_(),Z_(),rv(),mv=class e{runner;constructor(e){this.runner=e}static async create(t={}){return new e(await G_.create(t))}unlock(e,t){return this.transform(e,[lv(t.password),`--decrypt`])}removePassword(e,t){return this.unlock(e,t)}lock(e,t){return this.transform(e,dv(t))}changePassword(e,t){let n={userPassword:t.newPassword,ownerPassword:t.newOwnerPassword??t.newPassword,...t.keyLength!==void 0&&{keyLength:t.keyLength},...t.permissions!==void 0&&{permissions:t.permissions}};return this.transform(e,[lv(t.currentPassword),...dv(n)])}async merge(e){if(e.length===0)throw TypeError(`merge() needs at least one source document`);let t=e.map(ov);return this.runner.run(t.map(e=>e.data),({dir:e,inputPaths:n,exec:r,fs:i})=>{let a=[`--empty`,`--pages`];t.forEach((e,t)=>{a.push(n[t]),e.password!==void 0&&a.push(`--password=${e.password}`),a.push(e.pages===void 0?`1-z`:uv(e.pages))});let o=`${e}/out.pdf`;return a.push(`--`,o),fv(r(a)),i.readFile(o)})}async split(e,t={}){let n=t.pagesPerFile??1;if(!Number.isInteger(n)||n<1)throw TypeError(`pagesPerFile must be a positive integer, got ${n}`);return this.runner.run([e],({dir:e,inputPaths:r,exec:i,fs:a})=>{let o=[];return t.password!==void 0&&o.push(lv(t.password)),o.push(`--split-pages=${n}`,r[0],`${e}/part-%d.pdf`),fv(i(o)),a.readdir(e).filter(e=>e.startsWith(`part-`)).sort((e,t)=>cv(e)-cv(t)).map(t=>a.readFile(`${e}/${t}`))})}extractPages(e,t){let n=[];return t.password!==void 0&&n.push(lv(t.password)),n.push(`--pages`,`.`,uv(t.pages),`--`),this.transform(e,n)}async rotate(e,t){let{angle:n,absolute:r=!1,pages:i,password:a}=t;if(r&&n<0)throw TypeError(`absolute rotation must use a non-negative angle (90, 180, or 270)`);let o=`${r?``:n<0?`-`:`+`}${Math.abs(n)}${i===void 0?``:`:${uv(i)}`}`,s=[];return a!==void 0&&s.push(lv(a)),s.push(`--rotate=${o}`),this.transform(e,s)}async pageCount(e,t={}){return this.runner.run([e],({inputPaths:e,exec:n})=>{let r=[];t.password!==void 0&&r.push(lv(t.password)),r.push(`--show-npages`,e[0]);let i=n(r);return fv(i),Number.parseInt(i.stdoutText.trim(),10)})}async isEncrypted(e){return this.runner.run([e],({inputPaths:e,exec:t})=>{let n=t([`--is-encrypted`,e[0]]);if(n.exitCode===0)return!0;if(n.exitCode===2)return!1;throw pv(n)})}async requiresPassword(e){return this.runner.run([e],({inputPaths:e,exec:t})=>{let n=t([`--requires-password`,e[0]]);if(n.exitCode===0)return!0;if(n.exitCode===2||n.exitCode===3)return!1;throw pv(n)})}compress(e,t={}){let{password:n,compressionLevel:r=9,objectStreams:i=!0,linearize:a=!1}=t;if(!Number.isInteger(r)||r<1||r>9)throw TypeError(`compressionLevel must be 1-9, got ${r}`);let o=[];return n!==void 0&&o.push(lv(n)),o.push(`--compress-streams=y`,`--recompress-flate`,`--compression-level=${r}`,`--object-streams=${i?`generate`:`preserve`}`),a&&o.push(`--linearize`),this.transform(e,o)}linearize(e,t={}){let n=[];return t.password!==void 0&&n.push(lv(t.password)),n.push(`--linearize`),this.transform(e,n)}repair(e,t={}){let n=[];return t.password!==void 0&&n.push(lv(t.password)),this.transform(e,n)}async watermark(e,t,n={}){let{mode:r=`overlay`,password:i,stampPassword:a,to:o,from:s,repeat:c}=n;return this.runner.run([e,t],({dir:e,inputPaths:t,exec:n,fs:l})=>{let u=[];i!==void 0&&u.push(lv(i)),u.push(`--${r}`,t[1]),a!==void 0&&u.push(`--password=${a}`),o!==void 0&&u.push(`--to=${uv(o)}`),s!==void 0&&u.push(`--from=${uv(s)}`),c!==void 0&&u.push(`--repeat=${uv(c)}`);let d=`${e}/out.pdf`;return u.push(`--`,t[0],d),fv(n(u)),l.readFile(d)})}deletePages(e,t){let n={pages:`1-z,${uv(t.pages).split(`,`).map(e=>`x${e}`).join(`,`)}`,...t.password!==void 0&&{password:t.password}};return this.extractPages(e,n)}reversePages(e,t={}){return this.extractPages(e,{pages:`z-1`,...t})}async collate(e,t={}){let n=t.groupSize??1;if(!Number.isInteger(n)||n<1)throw TypeError(`groupSize must be a positive integer, got ${n}`);if(e.length<2)throw TypeError(`collate() needs at least two source documents`);let r=e.map(ov);return this.runner.run(r.map(e=>e.data),({dir:e,inputPaths:t,exec:i,fs:a})=>{let o=[`--empty`,`--collate=${n}`,`--pages`];r.forEach((e,n)=>{o.push(t[n]),e.password!==void 0&&o.push(`--password=${e.password}`),o.push(e.pages===void 0?`1-z`:uv(e.pages))});let s=`${e}/out.pdf`;return o.push(`--`,s),fv(i(o)),a.readFile(s)})}flatten(e,t={}){let n=[];return t.password!==void 0&&n.push(lv(t.password)),n.push(`--generate-appearances`,`--flatten-annotations=${t.annotations??`all`}`),this.transform(e,n)}async addAttachment(e,t){let{data:n,name:r,mimeType:i,description:a,password:o}=t;return this.runner.run([e],async({dir:e,inputPaths:t,exec:s,fs:c})=>{let l=`${e}/${sv(r)}`;c.writeFile(l,await W_(n));let u=[];o!==void 0&&u.push(lv(o)),u.push(`--add-attachment`,l,`--key=${r}`,`--filename=${r}`),i!==void 0&&u.push(`--mimetype=${i}`),a!==void 0&&u.push(`--description=${a}`);let d=`${e}/out.pdf`;return u.push(`--`,t[0],d),fv(s(u)),c.readFile(d)})}removeAttachment(e,t){let n=[];return t.password!==void 0&&n.push(lv(t.password)),n.push(`--remove-attachment=${t.name}`),this.transform(e,n)}async getAttachment(e,t){return this.runner.run([e],({inputPaths:e,exec:n})=>{let r=[];t.password!==void 0&&r.push(lv(t.password)),r.push(`--show-attachment=${t.name}`,e[0]);let i=n(r);return fv(i),i.stdout})}async listAttachments(e,t={}){return(await this.getInfo(e,t)).attachments}async getInfo(e,t={}){return this.runner.run([e],({inputPaths:e,exec:n,fs:r})=>{let i=n([...t.password===void 0?[]:[lv(t.password)],`--json`,`--json-key=encrypt`,`--json-key=attachments`,`--json-key=pages`,e[0]]);fv(i);let a=JSON.parse(i.stdoutText),o=new TextDecoder(`latin1`).decode(r.readFile(e[0]).slice(0,1024)),s=/%PDF-(\d+\.\d+)/.exec(o)?.[1]??`unknown`,c=Object.entries(a.attachments??{}).map(([e,t])=>({name:e,...t.preferredname!==void 0&&{filename:t.preferredname},...t.description!==void 0&&{description:t.description}})),l=a.encrypt,u={pdfVersion:s,pageCount:a.pages?.length??0,encrypted:l?.encrypted??!1,attachments:c};if(l?.encrypted){let e=l.capabilities??{};u.encryption={bits:l.parameters?.bits??0,method:l.parameters?.method??`unknown`,userPasswordMatched:l.userpasswordmatched??!1,ownerPasswordMatched:l.ownerpasswordmatched??!1,permissions:{accessibility:e.accessibility??!1,extract:e.extract??!1,print:e.printhigh??e.printlow??!1,modify:e.modify??!1,annotate:e.modifyannotations??!1,fillForms:e.modifyforms??!1,assemble:e.modifyassembly??!1}}}return u})}async raw(e,t){return this.runner.run(e,({dir:e,inputPaths:n,exec:r,fs:i})=>{let a=`${e}/out.pdf`;return fv(r(t.map(e=>e.replace(/\$out/g,a).replace(/\$in(\d+)/g,(e,t)=>{let r=n[Number(t)];if(r===void 0)throw TypeError(`no input for placeholder $in${t}`);return r})))),i.readFile(a)})}async transform(e,t){return this.runner.run([e],({dir:e,inputPaths:n,exec:r,fs:i})=>{let a=`${e}/out.pdf`;return fv(r([...t,n[0],a])),i.readFile(a)})}}})),gv;function _v(e){return gv??=(async()=>{let[{createPdfToolkit:t},n]=await Promise.all([Promise.resolve().then(()=>(hv(),iv)),e()]);return t({wasmModule:await WebAssembly.compile(n)})})(),gv.catch(()=>{gv=void 0}),gv}function vv(e){de({async build(t,n){try{return{ok:!0,bytes:await F_(t,{toolkit:()=>_v(e),signal:n.signal,progress:e=>n.progress(e)})}}catch(e){if(e instanceof TypeError||e instanceof RangeError)return{ok:!1,error:e.name,message:e.message};throw e}}},{packageVersion:`0.4.0`})}async function yv(){let e=new URL(`qpdf.wasm`,self.location.href),t=await fetch(e);if(!t.ok)throw new T_(`WORKER_START_FAILED`,`qpdf.wasm couldn't be loaded from ${e}.`,{details:{asset:`qpdf.wasm`,status:t.status}});let n=new Uint8Array(await t.arrayBuffer()),r=[...new Uint8Array(await crypto.subtle.digest(`SHA-256`,n))].map(e=>e.toString(16).padStart(2,`0`)).join(``);if(r!==`48a6044e2b5abb32295fa1682e26f20338181bb2423b2ab6e8456b7c4a8c9756`)throw new T_(`WORKER_START_FAILED`,`qpdf.wasm doesn't match this version of the SDK. Copy dist/assets again after upgrading.`,{details:{asset:`qpdf.wasm`,expected:d,actual:r}});return n}vv(yv);
|