@hussmartinez/pdf-sdk 0.4.5 → 0.5.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 CHANGED
@@ -101,6 +101,30 @@ The SDK runs two workers: pdf.js's, which renders, and one with qpdf and pdf-lib
101
101
 
102
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.
103
103
 
104
+ ### Leaving the inlined workers out
105
+
106
+ An app that passes `assetsUrl` never loads the inlined workers, decoders and data files, but its bundler still emits them: about 5 MB of chunks that are never used. Set the `hm-self-hosted` resolve condition in the app's bundler to leave them out. The SDK reaches them through its package's `imports`, and the condition maps each one to a small stub instead ([sdk-core ADR 0060](https://github.com/ie-huss-martinez/sdk-core/blob/main/docs/adr/0060-leaving-inlined-workers-out-of-a-self-hosted-build.md)).
107
+
108
+ With Vite, which replaces its default conditions with the list you give, so keep them:
109
+
110
+ ```ts
111
+ import { defaultClientConditions, defineConfig } from "vite";
112
+
113
+ export default defineConfig({
114
+ resolve: { conditions: [...defaultClientConditions, "hm-self-hosted"] },
115
+ });
116
+ ```
117
+
118
+ With esbuild, which drops its `module` condition once you set any, so keep it:
119
+
120
+ ```js
121
+ await build({ /* ... */ conditions: ["hm-self-hosted", "module"] });
122
+ ```
123
+
124
+ webpack (`resolve.conditionNames: ["hm-self-hosted", "..."]`), Rollup (`nodeResolve({ exportConditions: ["hm-self-hosted"] })`) and Next.js through its webpack configuration should work the same way, but they aren't tested yet.
125
+
126
+ Set the condition only in a build that passes `assetsUrl` everywhere it creates an engine or a processor. A worker started without it in such a build fails with `WORKER_START_FAILED`, whose `details` are `{ condition: "hm-self-hosted", missing: "assetsUrl" }`.
127
+
104
128
  ## Development
105
129
 
106
130
  The repository root is the published package, laid out as in the family's [standard layout](https://github.com/ie-huss-martinez/sdk-core/blob/main/STANDARDS.md#repository-layout): the source is in [`src`](src), and the pnpm workspace adds the examples in [`examples`](examples) and the end-to-end tests in [`e2e`](e2e) ([sdk-core ADR 0039](https://github.com/ie-huss-martinez/sdk-core/blob/main/docs/adr/0039-test-applications-in-each-repository.md)).
@@ -132,7 +156,7 @@ The browser and end-to-end tests also need Docker. They run in the pinned browse
132
156
  | Examples | `build:examples` | Production builds of the Next.js and Vite examples, against the built package |
133
157
  | 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
158
  | 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 |
135
- | Size budgets | `check:size` | size-limit, brotli size of each entry point |
159
+ | Size budgets | `check:size` | size-limit, in brotli: each entry's ceiling as built, what an application ships when it imports part of the core or React entry, and each lazy chunk ([`.size-limit.js`](.size-limit.js), sdk-core ADR 0055 and ADR 0056). `pnpm exec hm-size --exports dist/react.js` shows what each export costs |
136
160
  | API reports | `check:api` | api-extractor, one report per entry point in [`api`](api), and `hm-check-api-reports` across them |
137
161
  | Package checks | `check:package` | publint and Are the Types Wrong? |
138
162
 
@@ -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.4.5`})}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);
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.5.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);
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
- import { C as PdfError, S as pdfLimits, _ as PDF_MAX_CANVAS_PIXELS, a as checkId, b as addRotation, c as isRecord, d as PDF_MAX_STROKE_POINTS, f as PDF_MAX_TEXT_LENGTH, g as createPdfJsEngine, h as createPdfProcessor, i as checkAnnotation, l as PDF_MAX_FIELD_NAME_LENGTH, m as longerThan, n as createPdfSession, o as fields, p as PDF_POSITION_GRID, r as Invalid, s as invalid, t as pdfMessages, u as PDF_MAX_ID_LENGTH, v as linkDestination, w as isPdfError, x as pdfLimitDefinitions, y as safeLinkUrl } from "./shared/en-DAmVF5wH.js";
1
+ import { S as pdfLimits, _ as PDF_MAX_CANVAS_PIXELS, a as checkId, b as addRotation, c as isRecord, d as PDF_MAX_STROKE_POINTS, f as PDF_MAX_TEXT_LENGTH, g as createPdfJsEngine, h as createPdfProcessor, i as checkAnnotation, l as PDF_MAX_FIELD_NAME_LENGTH, m as longerThan, n as createPdfSession, o as fields, p as PDF_POSITION_GRID, r as Invalid, s as invalid, t as pdfMessages, u as PDF_MAX_ID_LENGTH, v as linkDestination, x as pdfLimitDefinitions, y as safeLinkUrl } from "./shared/en-COnsYGXV.js";
2
+ import { n as isPdfError, t as PdfError } from "./shared/pdf-error-DzxHQvrO.js";
2
3
  // src/core/format/plan-document.ts
3
4
  var PDF_PLAN_FORMAT = "hm-pdf-plan";
4
5
  var PDF_PLAN_VERSION = 1;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/core/format/plan-document.ts"],"sourcesContent":["import { PdfError } from \"../errors/pdf-error.js\";\nimport type { PdfAnnotation, PdfColor } from \"../model/annotations.js\";\nimport type { PdfFieldValue } from \"../model/document.js\";\nimport type { PdfRotation } from \"../model/geometry.js\";\nimport type { PdfPlan, PdfPlanPage } from \"../model/plan.js\";\nimport {\n longerThan,\n PDF_MAX_FIELD_NAME_LENGTH,\n PDF_MAX_TEXT_LENGTH,\n PDF_POSITION_GRID,\n} from \"../model/portable.js\";\nimport {\n checkAnnotation,\n checkId,\n fields,\n Invalid,\n invalid,\n isRecord,\n type PdfAddAnnotationCommand,\n type PdfCommand,\n type PdfRestorePagesCommand,\n} from \"../operations/commands.js\";\n\n/**\n * The name of the plan's portable format (sdk-core ADR 0045).\n *\n * @public\n */\nexport const PDF_PLAN_FORMAT = \"hm-pdf-plan\";\n\n/**\n * The version of {@link PDF_PLAN_FORMAT} this release writes, and the latest\n * it reads.\n *\n * @public\n */\nexport const PDF_PLAN_VERSION = 1;\n\n/**\n * A content-addressed reference to binary data, such as a source's file\n * (sdk-core ADR 0045). Documents never inline bytes.\n *\n * @public\n */\nexport interface PdfAssetReference {\n /** `sha256:` and the lowercase hex SHA-256 of the bytes. */\n readonly asset: string;\n /** The bytes' media type, such as `application/pdf`, in lowercase. */\n readonly mediaType: string;\n /** The size of the bytes. */\n readonly size: number;\n}\n\n/**\n * A source, as a plan document records it: its page count, which the pages\n * that use it must fit, and, once documents travel with their files, its\n * content.\n *\n * @public\n */\nexport interface PdfPlanDocumentSource {\n readonly pageCount: number;\n readonly asset?: PdfAssetReference;\n}\n\n/**\n * A point in a plan document: whole millionths of the page, from 0 to\n * {@link PDF_POSITION_GRID}.\n *\n * @public\n */\nexport interface PdfDocumentPoint {\n readonly x: number;\n readonly y: number;\n}\n\n/**\n * A pen or highlighter stroke in a plan document. Its points and width are\n * whole millionths of the page.\n *\n * @public\n */\nexport interface PdfStrokeAnnotationDocument {\n readonly id: string;\n readonly type: \"pen\" | \"highlight\";\n readonly points: readonly PdfDocumentPoint[];\n readonly color: PdfColor;\n readonly width: number;\n}\n\n/**\n * A text note in a plan document. Its position and size are whole\n * millionths of the page.\n *\n * @public\n */\nexport interface PdfTextAnnotationDocument {\n readonly id: string;\n readonly type: \"text\";\n readonly at: PdfDocumentPoint;\n readonly text: string;\n readonly size: number;\n readonly color: PdfColor;\n}\n\n/**\n * An annotation in a plan document. Version 1 has no signatures: their image\n * needs an asset, whose design comes with the signature tool (docs/adr/0003).\n *\n * @public\n */\nexport type PdfAnnotationDocument = PdfStrokeAnnotationDocument | PdfTextAnnotationDocument;\n\n/**\n * A page in a plan document.\n *\n * @public\n */\nexport interface PdfPlanDocumentPage {\n readonly key: string;\n readonly source: string;\n readonly pageIndex: number;\n readonly rotation: PdfRotation;\n readonly annotations: readonly PdfAnnotationDocument[];\n}\n\n/**\n * The plan as portable JSON: `hm-pdf-plan` version 1, which\n * `formats/hm-pdf-plan/v1.schema.json` describes\n * (docs/formats/hm-pdf-plan.md). Positions and sizes are whole millionths of\n * the page, and pages name their sources by ids the document lists.\n *\n * @public\n */\nexport interface PdfPlanDocument {\n readonly format: typeof PDF_PLAN_FORMAT;\n readonly version: typeof PDF_PLAN_VERSION;\n readonly sources: Readonly<Record<string, PdfPlanDocumentSource>>;\n readonly pages: readonly PdfPlanDocumentPage[];\n readonly formValues: Readonly<Record<string, Readonly<Record<string, PdfFieldValue>>>>;\n}\n\n/**\n * `pdf.addAnnotation` as `hm-pdf-command` writes it, with the annotation's\n * positions and sizes in whole millionths of the page.\n *\n * @public\n */\nexport interface PdfAddAnnotationCommandDocument {\n readonly type: \"pdf.addAnnotation\";\n readonly page: string;\n readonly annotation: PdfAnnotationDocument;\n readonly index?: number;\n}\n\n/**\n * A user-level command as portable JSON: `hm-pdf-command` version 1, which\n * `formats/hm-pdf-command/v1.schema.json` describes. Every command but\n * `pdf.restorePages`, an inverse that carries whole pages; only\n * `pdf.addAnnotation` differs from the command in memory.\n *\n * @public\n */\nexport type PdfCommandDocument =\n | Exclude<PdfCommand, PdfRestorePagesCommand | PdfAddAnnotationCommand>\n | PdfAddAnnotationCommandDocument;\n\n/**\n * Why a plan document was refused, as a stable token: `details.reason` on\n * the error (sdk-core ADR 0045).\n *\n * - With `UNSUPPORTED_FORMAT`: `unknown-format`, a document of another\n * format, and `unknown-format-version`, a later version than this release\n * reads.\n * - With `INVALID_DOCUMENT`: `malformed-document`, a document that isn't\n * shaped as the schema says; `unknown-source`, a page or form values for a\n * source the document doesn't list; `page-out-of-range`, a page index its\n * source doesn't have; `duplicate-key`, two pages with one key;\n * `duplicate-annotation`, two annotations with one id on a page; and, as\n * for commands, `invalid-rotation`, `outside-page`, `invalid-size`,\n * `too-many-points`, `invalid-color`, `unsupported-annotation`,\n * `field-name-too-long` and `text-too-long`.\n *\n * @public\n */\nexport type PdfDocumentRejection =\n | \"unknown-format\"\n | \"unknown-format-version\"\n | \"malformed-document\"\n | \"unknown-source\"\n | \"page-out-of-range\"\n | \"duplicate-key\"\n | \"duplicate-annotation\"\n | \"invalid-rotation\"\n | \"outside-page\"\n | \"invalid-size\"\n | \"too-many-points\"\n | \"invalid-color\"\n | \"unsupported-annotation\"\n | \"field-name-too-long\"\n | \"text-too-long\";\n\nconst DOCUMENT_FIELDS = [\"format\", \"version\", \"sources\", \"pages\", \"formValues\"];\nconst PAGE_FIELDS = [\"key\", \"source\", \"pageIndex\", \"rotation\", \"annotations\"];\nconst ASSET_FIELDS = [\"asset\", \"mediaType\", \"size\"];\n/** The patterns the schema uses too, so both accept the same documents. */\nconst ASSET_ID = /^sha256:[0-9a-f]{64}$/;\nconst MEDIA_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\\/[a-z0-9][a-z0-9!#$&^_.+-]*$/;\nconst ROTATIONS: readonly number[] = [0, 90, 180, 270];\n\nfunction malformed(message: string): never {\n return invalid(\"malformed-command\", message);\n}\n\nconst isCount = (value: unknown, min: number): value is number =>\n Number.isSafeInteger(value) && (value as number) >= min;\n\n/** Millionths to a fraction. The reducer's checks then see the fraction. */\nfunction fromGrid(value: unknown, what: string): number {\n if (!Number.isSafeInteger(value)) malformed(`${what} is whole millionths of the page`);\n return (value as number) / PDF_POSITION_GRID;\n}\n\nconst toGridUnits = (fraction: number) => Math.round(fraction * PDF_POSITION_GRID);\n\nfunction pointFromDocument(value: unknown, what: string): unknown {\n if (!isRecord<Record<string, unknown>>(value)) return value;\n return Object.fromEntries(\n Object.entries(value).map(([name, entry]) => [\n name,\n name === \"x\" || name === \"y\" ? fromGrid(entry, `${what}.${name}`) : entry,\n ]),\n );\n}\n\n/**\n * An annotation's JSON form in memory: its millionths become fractions, and\n * everything else is left for {@link checkAnnotation}, which refuses what\n * doesn't fit.\n */\nfunction annotationFromDocument(value: unknown): unknown {\n if (!isRecord<Record<string, unknown>>(value)) return value;\n const { type } = value;\n if (type !== \"pen\" && type !== \"highlight\" && type !== \"text\") return value;\n return Object.fromEntries(\n Object.entries(value).map(([name, entry]) => {\n if (name === \"width\" || name === \"size\") return [name, fromGrid(entry, name)];\n if (name === \"at\") return [name, pointFromDocument(entry, \"at\")];\n if (name === \"points\" && Array.isArray(entry)) {\n return [name, entry.map((point) => pointFromDocument(point, \"a point\"))];\n }\n return [name, entry];\n }),\n );\n}\n\nfunction annotationToDocument(annotation: PdfAnnotation): PdfAnnotationDocument {\n const point = ({ x, y }: { x: number; y: number }) => ({ x: toGridUnits(x), y: toGridUnits(y) });\n switch (annotation.type) {\n case \"pen\":\n case \"highlight\":\n return {\n id: annotation.id,\n type: annotation.type,\n points: annotation.points.map(point),\n color: annotation.color,\n width: toGridUnits(annotation.width),\n };\n case \"text\":\n return {\n id: annotation.id,\n type: \"text\",\n at: point(annotation.at),\n text: annotation.text,\n size: toGridUnits(annotation.size),\n color: annotation.color,\n };\n default:\n throw new TypeError(\"hm-pdf-plan version 1 can't hold signature annotations.\");\n }\n}\n\nfunction readAsset(value: unknown): PdfAssetReference {\n if (!isRecord<PdfAssetReference>(value)) malformed(\"an asset is an object\");\n fields(value, ASSET_FIELDS, \"an asset\");\n const { asset, mediaType, size } = value;\n if (typeof asset !== \"string\" || !ASSET_ID.test(asset)) malformed(\"an asset id is sha256:<hex>\");\n if (typeof mediaType !== \"string\" || mediaType.length > 255 || !MEDIA_TYPE.test(mediaType)) {\n malformed(\"a media type is type/subtype, in lowercase\");\n }\n if (!isCount(size, 0)) malformed(\"an asset's size is a whole number of bytes\");\n return { asset, mediaType, size };\n}\n\nfunction readSources(value: unknown): Record<string, PdfPlanDocumentSource> {\n if (!isRecord<Record<string, unknown>>(value)) malformed(\"sources is an object\");\n // Object.fromEntries keeps ids such as __proto__ as own, ordinary keys.\n return Object.fromEntries(\n Object.entries(value).map(([id, source]) => {\n checkId(id, \"a source id\");\n if (!isRecord<PdfPlanDocumentSource>(source)) malformed(\"a source is an object\");\n fields(source, [\"pageCount\"], \"a source\", [\"asset\"]);\n if (!isCount(source.pageCount, 1)) malformed(\"a source's page count is at least 1\");\n const entry: PdfPlanDocumentSource =\n source.asset === undefined\n ? { pageCount: source.pageCount }\n : { pageCount: source.pageCount, asset: readAsset(source.asset) };\n return [id, entry];\n }),\n );\n}\n\n/** A page's shape, before what depends on the rest of the document. */\nfunction readPage(value: unknown): PdfPlanPage {\n if (!isRecord<PdfPlanDocumentPage>(value)) malformed(\"a page is an object\");\n fields(value, PAGE_FIELDS, \"a page\");\n const key = checkId(value.key, \"a page key\");\n const source = checkId(value.source, \"a source id\");\n if (!isCount(value.pageIndex, 0)) malformed(\"a page index is a whole number from 0\");\n if (typeof value.rotation !== \"number\") malformed(\"a page's rotation is a number\");\n if (!ROTATIONS.includes(value.rotation)) {\n invalid(\"invalid-rotation\", \"a page's rotation is 0, 90, 180 or 270\");\n }\n if (!Array.isArray(value.annotations)) malformed(\"a page's annotations are a list\");\n const annotations = value.annotations.map((annotation) =>\n checkAnnotation(annotationFromDocument(annotation)),\n );\n return { key, source, pageIndex: value.pageIndex, rotation: value.rotation, annotations };\n}\n\nfunction readFieldValue(value: unknown): PdfFieldValue {\n if (typeof value === \"boolean\") return value;\n if (typeof value !== \"string\") malformed(\"a field's value is text or a boolean\");\n if (longerThan(value, PDF_MAX_TEXT_LENGTH)) {\n invalid(\"text-too-long\", `a field's value has more than ${PDF_MAX_TEXT_LENGTH} code points`);\n }\n return value;\n}\n\nfunction readFormValues(value: unknown): PdfPlan[\"formValues\"] {\n if (!isRecord<Record<string, unknown>>(value)) malformed(\"formValues is an object\");\n return Object.fromEntries(\n Object.entries(value).map(([source, values]) => {\n checkId(source, \"a source id\");\n if (!isRecord<Record<string, unknown>>(values) || Object.keys(values).length === 0) {\n malformed(\"a source's form values are an object with at least one field\");\n }\n return [\n source,\n Object.fromEntries(\n Object.entries(values).map(([field, entry]) => {\n if (field === \"\") malformed(\"a field's name is text\");\n if (longerThan(field, PDF_MAX_FIELD_NAME_LENGTH)) {\n invalid(\n \"field-name-too-long\",\n `a field's name has at most ${PDF_MAX_FIELD_NAME_LENGTH} code points`,\n );\n }\n return [field, readFieldValue(entry)];\n }),\n ),\n ];\n }),\n );\n}\n\nfunction read(value: unknown): {\n plan: PdfPlan;\n sources: Record<string, PdfPlanDocumentSource>;\n} {\n if (!isRecord<PdfPlanDocument>(value)) malformed(\"a document is an object\");\n const { format, version } = value;\n if (typeof format !== \"string\") malformed(\"format is text\");\n if (format !== PDF_PLAN_FORMAT) {\n throw new PdfError(\"UNSUPPORTED_FORMAT\", `This isn't an ${PDF_PLAN_FORMAT} document.`, {\n details: { format: PDF_PLAN_FORMAT, reason: \"unknown-format\" },\n });\n }\n if (Number.isSafeInteger(version) && (version as number) > PDF_PLAN_VERSION) {\n throw new PdfError(\n \"UNSUPPORTED_FORMAT\",\n `This ${PDF_PLAN_FORMAT} document is a later version than this release reads.`,\n { details: { format: PDF_PLAN_FORMAT, reason: \"unknown-format-version\" } },\n );\n }\n if (version !== PDF_PLAN_VERSION) malformed(\"version is 1\");\n fields(value, DOCUMENT_FIELDS, \"a document\");\n\n // First everything a schema checks, then what depends on the whole\n // document, so a refusal's reason says whether the schema refuses it too.\n const sources = readSources(value.sources);\n if (!Array.isArray(value.pages) || value.pages.length === 0) {\n malformed(\"pages is a list of at least one page\");\n }\n const pages = value.pages.map(readPage);\n const formValues = readFormValues(value.formValues);\n\n const keys = new Set<string>();\n for (const page of pages) {\n if (keys.has(page.key)) invalid(\"duplicate-key\", `two pages have the key ${page.key}`);\n keys.add(page.key);\n const source = Object.hasOwn(sources, page.source) ? sources[page.source] : undefined;\n if (source === undefined) {\n invalid(\"unknown-source\", `the document doesn't list source ${page.source}`);\n }\n if (page.pageIndex >= source.pageCount) {\n invalid(\"page-out-of-range\", `source ${page.source} has no page index ${page.pageIndex}`);\n }\n const ids = new Set(page.annotations.map(({ id }) => id));\n if (ids.size !== page.annotations.length) {\n invalid(\"duplicate-annotation\", `page ${page.key} has two annotations with one id`);\n }\n }\n for (const source of Object.keys(formValues)) {\n if (!Object.hasOwn(sources, source)) {\n invalid(\"unknown-source\", `the document doesn't list source ${source}`);\n }\n }\n return { plan: { pages, formValues }, sources };\n}\n\n/**\n * Reads a plan document, such as one parsed from JSON, checking it as\n * {@link PdfPlanDocument}'s schema does and more: every page's source must\n * be one the document lists, with the page's index, and page keys and each\n * page's annotation ids must be unique. Unknown fields are refused, never\n * dropped.\n *\n * @param value - The parsed JSON.\n * @returns The plan, with positions as fractions of the page, and its\n * sources by id.\n * @throws `PdfError` with `UNSUPPORTED_FORMAT` for another format or a later\n * version, and `INVALID_DOCUMENT` for anything else that's wrong, with a\n * {@link PdfDocumentRejection} as `details.reason`.\n * @public\n */\nexport function readPdfPlanDocument(value: unknown): {\n readonly plan: PdfPlan;\n readonly sources: Readonly<Record<string, PdfPlanDocumentSource>>;\n} {\n try {\n return read(value);\n } catch (error) {\n if (!(error instanceof Invalid)) throw error;\n const reason = error.reason === \"malformed-command\" ? \"malformed-document\" : error.reason;\n throw new PdfError(\n \"INVALID_DOCUMENT\",\n `Invalid ${PDF_PLAN_FORMAT} document: ${error.message}.`,\n {\n details: { format: PDF_PLAN_FORMAT, reason },\n },\n );\n }\n}\n\n/**\n * Writes a plan as a {@link PdfPlanDocument}, plain JSON-ready data, with\n * positions and sizes in whole millionths of the page.\n *\n * @param plan - The plan, such as a session snapshot's.\n * @param sources - The sources by id, with at least every one the plan's\n * pages and form values use. They're written as given.\n * @throws `TypeError` if a source the plan uses is missing from `sources`,\n * or the plan has a signature annotation, which version 1 can't hold.\n * @public\n */\nexport function toPdfPlanDocument(\n plan: PdfPlan,\n sources: Readonly<Record<string, PdfPlanDocumentSource>>,\n): PdfPlanDocument {\n for (const source of [\n ...plan.pages.map((page) => page.source),\n ...Object.keys(plan.formValues),\n ]) {\n if (!Object.hasOwn(sources, source)) {\n throw new TypeError(`The sources don't include ${source}, which the plan uses.`);\n }\n }\n return {\n format: PDF_PLAN_FORMAT,\n version: PDF_PLAN_VERSION,\n sources: Object.fromEntries(\n Object.entries(sources).map(([id, { pageCount, asset }]) => [\n id,\n asset === undefined ? { pageCount } : { pageCount, asset: { ...asset } },\n ]),\n ),\n pages: plan.pages.map((page) => ({\n key: page.key,\n source: page.source,\n pageIndex: page.pageIndex,\n rotation: page.rotation,\n annotations: page.annotations.map(annotationToDocument),\n })),\n formValues: Object.fromEntries(\n Object.entries(plan.formValues).map(([source, values]) => [\n source,\n Object.fromEntries(Object.entries(values)),\n ]),\n ),\n };\n}\n\n/**\n * Reads a command in its portable form, `hm-pdf-command` version 1, such as\n * one parsed from JSON, into the command the session executes: an\n * annotation's millionths become fractions of the page. The session's\n * reducer checks everything else when the command runs.\n *\n * @param value - The parsed JSON.\n * @throws `PdfError` with `INVALID_COMMAND` and `malformed-command` for a\n * position or size that isn't whole millionths, and `unknown-command` for\n * `pdf.restorePages`, which isn't part of the format.\n * @public\n */\nexport function readPdfCommandDocument(value: unknown): PdfCommand {\n try {\n if (!isRecord<Record<string, unknown>>(value)) return value as PdfCommand;\n if (value[\"type\"] === \"pdf.restorePages\") {\n invalid(\"unknown-command\", \"pdf.restorePages isn't a command of the portable format\");\n }\n if (value[\"type\"] !== \"pdf.addAnnotation\") return value as unknown as PdfCommand;\n return Object.fromEntries(\n Object.entries(value).map(([name, entry]) => [\n name,\n name === \"annotation\" ? annotationFromDocument(entry) : entry,\n ]),\n ) as unknown as PdfCommand;\n } catch (error) {\n if (!(error instanceof Invalid)) throw error;\n throw new PdfError(\"INVALID_COMMAND\", `Invalid command: ${error.message}.`, {\n details: { reason: error.reason },\n });\n }\n}\n\n/**\n * Writes a command in its portable form, `hm-pdf-command` version 1, with an\n * annotation's positions and sizes in whole millionths of the page.\n *\n * @param command - A command the session applied, so its values are on the\n * grid.\n * @throws `TypeError` for `pdf.restorePages`, which isn't part of the\n * format, and for a signature annotation, which version 1 can't hold.\n * @public\n */\nexport function toPdfCommandDocument(command: PdfCommand): PdfCommandDocument {\n if (command.type === \"pdf.restorePages\") {\n throw new TypeError(\"pdf.restorePages isn't a command of the portable format.\");\n }\n if (command.type !== \"pdf.addAnnotation\") return structuredClone(command);\n return {\n type: \"pdf.addAnnotation\",\n page: command.page,\n annotation: annotationToDocument(command.annotation),\n ...(command.index === undefined ? {} : { index: command.index }),\n };\n}\n"],"mappings":";;AA4BA,IAAa,kBAAkB;AAQ/B,IAAa,mBAAmB;AAsKhC,IAAM,kBAAkB;CAAC;CAAU;CAAW;CAAW;CAAS;AAAY;AAC9E,IAAM,cAAc;CAAC;CAAO;CAAU;CAAa;CAAY;AAAa;AAC5E,IAAM,eAAe;CAAC;CAAS;CAAa;AAAM;AAElD,IAAM,WAAW;AACjB,IAAM,aAAa;AACnB,IAAM,YAA+B;CAAC;CAAG;CAAI;CAAK;AAAG;AAErD,SAAS,UAAU,SAAwB;CACzC,OAAO,QAAQ,qBAAqB,OAAO;AAC7C;AAEA,IA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AQ,KAAK;GACb,WAAW,KAAK;GAChB,UAAU,KAAK;GACf,aAAa,KAAK,YAAY,IAAI,oBAAoB;EACxD,EAAE;EACF,YAAY,OAAO,YACjB,OAAO,QAAQ,KAAK,UAAU,CAAC,CAAC,KAAK,CAAC,QAAQ,YAAY,CACxD,QACA,OAAO,YAAY,OAAO,QAAQ,MAAM,CAAC,CAC3C,CAAC,CACH;CACF;AACF;AAcA,SAAgB,uBAAuB,OAA4B;CACjE,IAAI;EACF,IAAI,CAAC,SAAkC,KAAK,GAAG,OAAO;EACtD,IAAI,MAAM,YAAY,oBACpB,QAAQ,mBAAmB,yDAAyD;EAEtF,IAAI,MAAM,YAAY,qBAAqB,OAAO;EAClD,OAAO,OAAO,YACZ,OAAO,QAAQ,KAAK,CAAC,CAAC,KAAK,CAAC,MAAM,WAAW,CAC3C,MACA,SAAS,eAAe,uBAAuB,KAAK,IAAI,KAC1D,CAAC,CACH;CACF,SAAS,OAAO;EACd,IAAI,EAAE,iBAAiB,UAAU,MAAM;EACvC,MAAM,IAAI,SAAS,mBAAmB,oBAAoB,MAAM,QAAQ,IAAI,EAC1E,SAAS,EAAE,QAAQ,MAAM,OAAO,EAClC,CAAC;CACH;AACF;AAYA,SAAgB,qBAAqB,SAAyC;CAC5E,IAAI,QAAQ,SAAS,oBACnB,MAAM,IAAI,UAAU,0DAA0D;CAEhF,IAAI,QAAQ,SAAS,qBAAqB,OAAO,gBAAgB,OAAO;CACxE,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;EACd,YAAY,qBAAqB,QAAQ,UAAU;EACnD,GAAI,QAAQ,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,QAAQ,MAAM;CAChE;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/core/format/plan-document.ts"],"sourcesContent":["import { PdfError } from \"../errors/pdf-error.js\";\nimport type { PdfAnnotation, PdfColor } from \"../model/annotations.js\";\nimport type { PdfFieldValue } from \"../model/document.js\";\nimport type { PdfRotation } from \"../model/geometry.js\";\nimport type { PdfPlan, PdfPlanPage } from \"../model/plan.js\";\nimport {\n longerThan,\n PDF_MAX_FIELD_NAME_LENGTH,\n PDF_MAX_TEXT_LENGTH,\n PDF_POSITION_GRID,\n} from \"../model/portable.js\";\nimport {\n checkAnnotation,\n checkId,\n fields,\n Invalid,\n invalid,\n isRecord,\n type PdfAddAnnotationCommand,\n type PdfCommand,\n type PdfRestorePagesCommand,\n} from \"../operations/commands.js\";\n\n/**\n * The name of the plan's portable format (sdk-core ADR 0045).\n *\n * @public\n */\nexport const PDF_PLAN_FORMAT = \"hm-pdf-plan\";\n\n/**\n * The version of {@link PDF_PLAN_FORMAT} this release writes, and the latest\n * it reads.\n *\n * @public\n */\nexport const PDF_PLAN_VERSION = 1;\n\n/**\n * A content-addressed reference to binary data, such as a source's file\n * (sdk-core ADR 0045). Documents never inline bytes.\n *\n * @public\n */\nexport interface PdfAssetReference {\n /** `sha256:` and the lowercase hex SHA-256 of the bytes. */\n readonly asset: string;\n /** The bytes' media type, such as `application/pdf`, in lowercase. */\n readonly mediaType: string;\n /** The size of the bytes. */\n readonly size: number;\n}\n\n/**\n * A source, as a plan document records it: its page count, which the pages\n * that use it must fit, and, once documents travel with their files, its\n * content.\n *\n * @public\n */\nexport interface PdfPlanDocumentSource {\n readonly pageCount: number;\n readonly asset?: PdfAssetReference;\n}\n\n/**\n * A point in a plan document: whole millionths of the page, from 0 to\n * {@link PDF_POSITION_GRID}.\n *\n * @public\n */\nexport interface PdfDocumentPoint {\n readonly x: number;\n readonly y: number;\n}\n\n/**\n * A pen or highlighter stroke in a plan document. Its points and width are\n * whole millionths of the page.\n *\n * @public\n */\nexport interface PdfStrokeAnnotationDocument {\n readonly id: string;\n readonly type: \"pen\" | \"highlight\";\n readonly points: readonly PdfDocumentPoint[];\n readonly color: PdfColor;\n readonly width: number;\n}\n\n/**\n * A text note in a plan document. Its position and size are whole\n * millionths of the page.\n *\n * @public\n */\nexport interface PdfTextAnnotationDocument {\n readonly id: string;\n readonly type: \"text\";\n readonly at: PdfDocumentPoint;\n readonly text: string;\n readonly size: number;\n readonly color: PdfColor;\n}\n\n/**\n * An annotation in a plan document. Version 1 has no signatures: their image\n * needs an asset, whose design comes with the signature tool (docs/adr/0003).\n *\n * @public\n */\nexport type PdfAnnotationDocument = PdfStrokeAnnotationDocument | PdfTextAnnotationDocument;\n\n/**\n * A page in a plan document.\n *\n * @public\n */\nexport interface PdfPlanDocumentPage {\n readonly key: string;\n readonly source: string;\n readonly pageIndex: number;\n readonly rotation: PdfRotation;\n readonly annotations: readonly PdfAnnotationDocument[];\n}\n\n/**\n * The plan as portable JSON: `hm-pdf-plan` version 1, which\n * `formats/hm-pdf-plan/v1.schema.json` describes\n * (docs/formats/hm-pdf-plan.md). Positions and sizes are whole millionths of\n * the page, and pages name their sources by ids the document lists.\n *\n * @public\n */\nexport interface PdfPlanDocument {\n readonly format: typeof PDF_PLAN_FORMAT;\n readonly version: typeof PDF_PLAN_VERSION;\n readonly sources: Readonly<Record<string, PdfPlanDocumentSource>>;\n readonly pages: readonly PdfPlanDocumentPage[];\n readonly formValues: Readonly<Record<string, Readonly<Record<string, PdfFieldValue>>>>;\n}\n\n/**\n * `pdf.addAnnotation` as `hm-pdf-command` writes it, with the annotation's\n * positions and sizes in whole millionths of the page.\n *\n * @public\n */\nexport interface PdfAddAnnotationCommandDocument {\n readonly type: \"pdf.addAnnotation\";\n readonly page: string;\n readonly annotation: PdfAnnotationDocument;\n readonly index?: number;\n}\n\n/**\n * A user-level command as portable JSON: `hm-pdf-command` version 1, which\n * `formats/hm-pdf-command/v1.schema.json` describes. Every command but\n * `pdf.restorePages`, an inverse that carries whole pages; only\n * `pdf.addAnnotation` differs from the command in memory.\n *\n * @public\n */\nexport type PdfCommandDocument =\n | Exclude<PdfCommand, PdfRestorePagesCommand | PdfAddAnnotationCommand>\n | PdfAddAnnotationCommandDocument;\n\n/**\n * Why a plan document was refused, as a stable token: `details.reason` on\n * the error (sdk-core ADR 0045).\n *\n * - With `UNSUPPORTED_FORMAT`: `unknown-format`, a document of another\n * format, and `unknown-format-version`, a later version than this release\n * reads.\n * - With `INVALID_DOCUMENT`: `malformed-document`, a document that isn't\n * shaped as the schema says; `unknown-source`, a page or form values for a\n * source the document doesn't list; `page-out-of-range`, a page index its\n * source doesn't have; `duplicate-key`, two pages with one key;\n * `duplicate-annotation`, two annotations with one id on a page; and, as\n * for commands, `invalid-rotation`, `outside-page`, `invalid-size`,\n * `too-many-points`, `invalid-color`, `unsupported-annotation`,\n * `field-name-too-long` and `text-too-long`.\n *\n * @public\n */\nexport type PdfDocumentRejection =\n | \"unknown-format\"\n | \"unknown-format-version\"\n | \"malformed-document\"\n | \"unknown-source\"\n | \"page-out-of-range\"\n | \"duplicate-key\"\n | \"duplicate-annotation\"\n | \"invalid-rotation\"\n | \"outside-page\"\n | \"invalid-size\"\n | \"too-many-points\"\n | \"invalid-color\"\n | \"unsupported-annotation\"\n | \"field-name-too-long\"\n | \"text-too-long\";\n\nconst DOCUMENT_FIELDS = [\"format\", \"version\", \"sources\", \"pages\", \"formValues\"];\nconst PAGE_FIELDS = [\"key\", \"source\", \"pageIndex\", \"rotation\", \"annotations\"];\nconst ASSET_FIELDS = [\"asset\", \"mediaType\", \"size\"];\n/** The patterns the schema uses too, so both accept the same documents. */\nconst ASSET_ID = /^sha256:[0-9a-f]{64}$/;\nconst MEDIA_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\\/[a-z0-9][a-z0-9!#$&^_.+-]*$/;\nconst ROTATIONS: readonly number[] = [0, 90, 180, 270];\n\nfunction malformed(message: string): never {\n return invalid(\"malformed-command\", message);\n}\n\nconst isCount = (value: unknown, min: number): value is number =>\n Number.isSafeInteger(value) && (value as number) >= min;\n\n/** Millionths to a fraction. The reducer's checks then see the fraction. */\nfunction fromGrid(value: unknown, what: string): number {\n if (!Number.isSafeInteger(value)) malformed(`${what} is whole millionths of the page`);\n return (value as number) / PDF_POSITION_GRID;\n}\n\nconst toGridUnits = (fraction: number) => Math.round(fraction * PDF_POSITION_GRID);\n\nfunction pointFromDocument(value: unknown, what: string): unknown {\n if (!isRecord<Record<string, unknown>>(value)) return value;\n return Object.fromEntries(\n Object.entries(value).map(([name, entry]) => [\n name,\n name === \"x\" || name === \"y\" ? fromGrid(entry, `${what}.${name}`) : entry,\n ]),\n );\n}\n\n/**\n * An annotation's JSON form in memory: its millionths become fractions, and\n * everything else is left for {@link checkAnnotation}, which refuses what\n * doesn't fit.\n */\nfunction annotationFromDocument(value: unknown): unknown {\n if (!isRecord<Record<string, unknown>>(value)) return value;\n const { type } = value;\n if (type !== \"pen\" && type !== \"highlight\" && type !== \"text\") return value;\n return Object.fromEntries(\n Object.entries(value).map(([name, entry]) => {\n if (name === \"width\" || name === \"size\") return [name, fromGrid(entry, name)];\n if (name === \"at\") return [name, pointFromDocument(entry, \"at\")];\n if (name === \"points\" && Array.isArray(entry)) {\n return [name, entry.map((point) => pointFromDocument(point, \"a point\"))];\n }\n return [name, entry];\n }),\n );\n}\n\nfunction annotationToDocument(annotation: PdfAnnotation): PdfAnnotationDocument {\n const point = ({ x, y }: { x: number; y: number }) => ({ x: toGridUnits(x), y: toGridUnits(y) });\n switch (annotation.type) {\n case \"pen\":\n case \"highlight\":\n return {\n id: annotation.id,\n type: annotation.type,\n points: annotation.points.map(point),\n color: annotation.color,\n width: toGridUnits(annotation.width),\n };\n case \"text\":\n return {\n id: annotation.id,\n type: \"text\",\n at: point(annotation.at),\n text: annotation.text,\n size: toGridUnits(annotation.size),\n color: annotation.color,\n };\n default:\n throw new TypeError(\"hm-pdf-plan version 1 can't hold signature annotations.\");\n }\n}\n\nfunction readAsset(value: unknown): PdfAssetReference {\n if (!isRecord<PdfAssetReference>(value)) malformed(\"an asset is an object\");\n fields(value, ASSET_FIELDS, \"an asset\");\n const { asset, mediaType, size } = value;\n if (typeof asset !== \"string\" || !ASSET_ID.test(asset)) malformed(\"an asset id is sha256:<hex>\");\n if (typeof mediaType !== \"string\" || mediaType.length > 255 || !MEDIA_TYPE.test(mediaType)) {\n malformed(\"a media type is type/subtype, in lowercase\");\n }\n if (!isCount(size, 0)) malformed(\"an asset's size is a whole number of bytes\");\n return { asset, mediaType, size };\n}\n\nfunction readSources(value: unknown): Record<string, PdfPlanDocumentSource> {\n if (!isRecord<Record<string, unknown>>(value)) malformed(\"sources is an object\");\n // Object.fromEntries keeps ids such as __proto__ as own, ordinary keys.\n return Object.fromEntries(\n Object.entries(value).map(([id, source]) => {\n checkId(id, \"a source id\");\n if (!isRecord<PdfPlanDocumentSource>(source)) malformed(\"a source is an object\");\n fields(source, [\"pageCount\"], \"a source\", [\"asset\"]);\n if (!isCount(source.pageCount, 1)) malformed(\"a source's page count is at least 1\");\n const entry: PdfPlanDocumentSource =\n source.asset === undefined\n ? { pageCount: source.pageCount }\n : { pageCount: source.pageCount, asset: readAsset(source.asset) };\n return [id, entry];\n }),\n );\n}\n\n/** A page's shape, before what depends on the rest of the document. */\nfunction readPage(value: unknown): PdfPlanPage {\n if (!isRecord<PdfPlanDocumentPage>(value)) malformed(\"a page is an object\");\n fields(value, PAGE_FIELDS, \"a page\");\n const key = checkId(value.key, \"a page key\");\n const source = checkId(value.source, \"a source id\");\n if (!isCount(value.pageIndex, 0)) malformed(\"a page index is a whole number from 0\");\n if (typeof value.rotation !== \"number\") malformed(\"a page's rotation is a number\");\n if (!ROTATIONS.includes(value.rotation)) {\n invalid(\"invalid-rotation\", \"a page's rotation is 0, 90, 180 or 270\");\n }\n if (!Array.isArray(value.annotations)) malformed(\"a page's annotations are a list\");\n const annotations = value.annotations.map((annotation) =>\n checkAnnotation(annotationFromDocument(annotation)),\n );\n return { key, source, pageIndex: value.pageIndex, rotation: value.rotation, annotations };\n}\n\nfunction readFieldValue(value: unknown): PdfFieldValue {\n if (typeof value === \"boolean\") return value;\n if (typeof value !== \"string\") malformed(\"a field's value is text or a boolean\");\n if (longerThan(value, PDF_MAX_TEXT_LENGTH)) {\n invalid(\"text-too-long\", `a field's value has more than ${PDF_MAX_TEXT_LENGTH} code points`);\n }\n return value;\n}\n\nfunction readFormValues(value: unknown): PdfPlan[\"formValues\"] {\n if (!isRecord<Record<string, unknown>>(value)) malformed(\"formValues is an object\");\n return Object.fromEntries(\n Object.entries(value).map(([source, values]) => {\n checkId(source, \"a source id\");\n if (!isRecord<Record<string, unknown>>(values) || Object.keys(values).length === 0) {\n malformed(\"a source's form values are an object with at least one field\");\n }\n return [\n source,\n Object.fromEntries(\n Object.entries(values).map(([field, entry]) => {\n if (field === \"\") malformed(\"a field's name is text\");\n if (longerThan(field, PDF_MAX_FIELD_NAME_LENGTH)) {\n invalid(\n \"field-name-too-long\",\n `a field's name has at most ${PDF_MAX_FIELD_NAME_LENGTH} code points`,\n );\n }\n return [field, readFieldValue(entry)];\n }),\n ),\n ];\n }),\n );\n}\n\nfunction read(value: unknown): {\n plan: PdfPlan;\n sources: Record<string, PdfPlanDocumentSource>;\n} {\n if (!isRecord<PdfPlanDocument>(value)) malformed(\"a document is an object\");\n const { format, version } = value;\n if (typeof format !== \"string\") malformed(\"format is text\");\n if (format !== PDF_PLAN_FORMAT) {\n throw new PdfError(\"UNSUPPORTED_FORMAT\", `This isn't an ${PDF_PLAN_FORMAT} document.`, {\n details: { format: PDF_PLAN_FORMAT, reason: \"unknown-format\" },\n });\n }\n if (Number.isSafeInteger(version) && (version as number) > PDF_PLAN_VERSION) {\n throw new PdfError(\n \"UNSUPPORTED_FORMAT\",\n `This ${PDF_PLAN_FORMAT} document is a later version than this release reads.`,\n { details: { format: PDF_PLAN_FORMAT, reason: \"unknown-format-version\" } },\n );\n }\n if (version !== PDF_PLAN_VERSION) malformed(\"version is 1\");\n fields(value, DOCUMENT_FIELDS, \"a document\");\n\n // First everything a schema checks, then what depends on the whole\n // document, so a refusal's reason says whether the schema refuses it too.\n const sources = readSources(value.sources);\n if (!Array.isArray(value.pages) || value.pages.length === 0) {\n malformed(\"pages is a list of at least one page\");\n }\n const pages = value.pages.map(readPage);\n const formValues = readFormValues(value.formValues);\n\n const keys = new Set<string>();\n for (const page of pages) {\n if (keys.has(page.key)) invalid(\"duplicate-key\", `two pages have the key ${page.key}`);\n keys.add(page.key);\n const source = Object.hasOwn(sources, page.source) ? sources[page.source] : undefined;\n if (source === undefined) {\n invalid(\"unknown-source\", `the document doesn't list source ${page.source}`);\n }\n if (page.pageIndex >= source.pageCount) {\n invalid(\"page-out-of-range\", `source ${page.source} has no page index ${page.pageIndex}`);\n }\n const ids = new Set(page.annotations.map(({ id }) => id));\n if (ids.size !== page.annotations.length) {\n invalid(\"duplicate-annotation\", `page ${page.key} has two annotations with one id`);\n }\n }\n for (const source of Object.keys(formValues)) {\n if (!Object.hasOwn(sources, source)) {\n invalid(\"unknown-source\", `the document doesn't list source ${source}`);\n }\n }\n return { plan: { pages, formValues }, sources };\n}\n\n/**\n * Reads a plan document, such as one parsed from JSON, checking it as\n * {@link PdfPlanDocument}'s schema does and more: every page's source must\n * be one the document lists, with the page's index, and page keys and each\n * page's annotation ids must be unique. Unknown fields are refused, never\n * dropped.\n *\n * @param value - The parsed JSON.\n * @returns The plan, with positions as fractions of the page, and its\n * sources by id.\n * @throws `PdfError` with `UNSUPPORTED_FORMAT` for another format or a later\n * version, and `INVALID_DOCUMENT` for anything else that's wrong, with a\n * {@link PdfDocumentRejection} as `details.reason`.\n * @public\n */\nexport function readPdfPlanDocument(value: unknown): {\n readonly plan: PdfPlan;\n readonly sources: Readonly<Record<string, PdfPlanDocumentSource>>;\n} {\n try {\n return read(value);\n } catch (error) {\n if (!(error instanceof Invalid)) throw error;\n const reason = error.reason === \"malformed-command\" ? \"malformed-document\" : error.reason;\n throw new PdfError(\n \"INVALID_DOCUMENT\",\n `Invalid ${PDF_PLAN_FORMAT} document: ${error.message}.`,\n {\n details: { format: PDF_PLAN_FORMAT, reason },\n },\n );\n }\n}\n\n/**\n * Writes a plan as a {@link PdfPlanDocument}, plain JSON-ready data, with\n * positions and sizes in whole millionths of the page.\n *\n * @param plan - The plan, such as a session snapshot's.\n * @param sources - The sources by id, with at least every one the plan's\n * pages and form values use. They're written as given.\n * @throws `TypeError` if a source the plan uses is missing from `sources`,\n * or the plan has a signature annotation, which version 1 can't hold.\n * @public\n */\nexport function toPdfPlanDocument(\n plan: PdfPlan,\n sources: Readonly<Record<string, PdfPlanDocumentSource>>,\n): PdfPlanDocument {\n for (const source of [\n ...plan.pages.map((page) => page.source),\n ...Object.keys(plan.formValues),\n ]) {\n if (!Object.hasOwn(sources, source)) {\n throw new TypeError(`The sources don't include ${source}, which the plan uses.`);\n }\n }\n return {\n format: PDF_PLAN_FORMAT,\n version: PDF_PLAN_VERSION,\n sources: Object.fromEntries(\n Object.entries(sources).map(([id, { pageCount, asset }]) => [\n id,\n asset === undefined ? { pageCount } : { pageCount, asset: { ...asset } },\n ]),\n ),\n pages: plan.pages.map((page) => ({\n key: page.key,\n source: page.source,\n pageIndex: page.pageIndex,\n rotation: page.rotation,\n annotations: page.annotations.map(annotationToDocument),\n })),\n formValues: Object.fromEntries(\n Object.entries(plan.formValues).map(([source, values]) => [\n source,\n Object.fromEntries(Object.entries(values)),\n ]),\n ),\n };\n}\n\n/**\n * Reads a command in its portable form, `hm-pdf-command` version 1, such as\n * one parsed from JSON, into the command the session executes: an\n * annotation's millionths become fractions of the page. The session's\n * reducer checks everything else when the command runs.\n *\n * @param value - The parsed JSON.\n * @throws `PdfError` with `INVALID_COMMAND` and `malformed-command` for a\n * position or size that isn't whole millionths, and `unknown-command` for\n * `pdf.restorePages`, which isn't part of the format.\n * @public\n */\nexport function readPdfCommandDocument(value: unknown): PdfCommand {\n try {\n if (!isRecord<Record<string, unknown>>(value)) return value as PdfCommand;\n if (value[\"type\"] === \"pdf.restorePages\") {\n invalid(\"unknown-command\", \"pdf.restorePages isn't a command of the portable format\");\n }\n if (value[\"type\"] !== \"pdf.addAnnotation\") return value as unknown as PdfCommand;\n return Object.fromEntries(\n Object.entries(value).map(([name, entry]) => [\n name,\n name === \"annotation\" ? annotationFromDocument(entry) : entry,\n ]),\n ) as unknown as PdfCommand;\n } catch (error) {\n if (!(error instanceof Invalid)) throw error;\n throw new PdfError(\"INVALID_COMMAND\", `Invalid command: ${error.message}.`, {\n details: { reason: error.reason },\n });\n }\n}\n\n/**\n * Writes a command in its portable form, `hm-pdf-command` version 1, with an\n * annotation's positions and sizes in whole millionths of the page.\n *\n * @param command - A command the session applied, so its values are on the\n * grid.\n * @throws `TypeError` for `pdf.restorePages`, which isn't part of the\n * format, and for a signature annotation, which version 1 can't hold.\n * @public\n */\nexport function toPdfCommandDocument(command: PdfCommand): PdfCommandDocument {\n if (command.type === \"pdf.restorePages\") {\n throw new TypeError(\"pdf.restorePages isn't a command of the portable format.\");\n }\n if (command.type !== \"pdf.addAnnotation\") return structuredClone(command);\n return {\n type: \"pdf.addAnnotation\",\n page: command.page,\n annotation: annotationToDocument(command.annotation),\n ...(command.index === undefined ? {} : { index: command.index }),\n };\n}\n"],"mappings":";;;AA4BA,IAAa,kBAAkB;AAQ/B,IAAa,mBAAmB;AAsKhC,IAAM,kBAAkB;CAAC;CAAU;CAAW;CAAW;CAAS;AAAY;AAC9E,IAAM,cAAc;CAAC;CAAO;CAAU;CAAa;CAAY;AAAa;AAC5E,IAAM,eAAe;CAAC;CAAS;CAAa;AAAM;AAElD,IAAM,WAAW;AACjB,IAAM,aAAa;AACnB,IAAM,YAA+B;CAAC;CAAG;CAAI;CAAK;AAAG;AAErD,SAAS,UAAU,SAAwB;CACzC,OAAO,QAAQ,qBAAqB,OAAO;AAC7C;AAEA,IAAM,WAAW,OAAgB,QAC/B,OAAO,cAAc,KAAK,KAAM,SAAoB;AAGtD,SAAS,SAAS,OAAgB,MAAsB;CACtD,IAAI,CAAC,OAAO,cAAc,KAAK,GAAG,UAAU,GAAG,KAAK,iCAAiC;CACrF,OAAQ,QAAmB;AAC7B;AAEA,IAAM,eAAe,aAAqB,KAAK,MAAM,WAAW,iBAAiB;AAEjF,SAAS,kBAAkB,OAAgB,MAAuB;CAChE,IA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4B;CACjE,IAAI;EACF,IAAI,CAAC,SAAkC,KAAK,GAAG,OAAO;EACtD,IAAI,MAAM,YAAY,oBACpB,QAAQ,mBAAmB,yDAAyD;EAEtF,IAAI,MAAM,YAAY,qBAAqB,OAAO;EAClD,OAAO,OAAO,YACZ,OAAO,QAAQ,KAAK,CAAC,CAAC,KAAK,CAAC,MAAM,WAAW,CAC3C,MACA,SAAS,eAAe,uBAAuB,KAAK,IAAI,KAC1D,CAAC,CACH;CACF,SAAS,OAAO;EACd,IAAI,EAAE,iBAAiB,UAAU,MAAM;EACvC,MAAM,IAAI,SAAS,mBAAmB,oBAAoB,MAAM,QAAQ,IAAI,EAC1E,SAAS,EAAE,QAAQ,MAAM,OAAO,EAClC,CAAC;CACH;AACF;AAYA,SAAgB,qBAAqB,SAAyC;CAC5E,IAAI,QAAQ,SAAS,oBACnB,MAAM,IAAI,UAAU,0DAA0D;CAEhF,IAAI,QAAQ,SAAS,qBAAqB,OAAO,gBAAgB,OAAO;CACxE,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;EACd,YAAY,qBAAqB,QAAQ,UAAU;EACnD,GAAI,QAAQ,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,OAAO,QAAQ,MAAM;CAChE;AACF"}
@@ -191,4 +191,10 @@ var pdfJsData = Object.freeze({
191
191
  "openjpeg.wasm": () => import("./openjpeg.wasm-bdyxAnqz.js").then((m) => m.default)
192
192
  })
193
193
  });
194
- export { pdfJsData };
194
+ // src/adapters/pdfjs/inline-data.ts
195
+ function inlineData() {
196
+ return pdfJsData;
197
+ }
198
+ export { inlineData };
199
+
200
+ //# sourceMappingURL=inline-data.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inline-data.js","names":[],"sources":["../../src/adapters/pdfjs/inline-data.ts"],"sourcesContent":["import { pdfJsData } from \"virtual:hm-pdfjs-data\";\n\n/**\n * pdf.js's data files, inlined: CMaps, standard fonts and the WebAssembly\n * decoders, each loaded from its own chunk when a document needs it\n * (docs/adr/0002). Imported as `#hm-pdf-inline-data`, which a build with the\n * `hm-self-hosted` condition maps to a stub instead (sdk-core ADR 0060).\n */\nexport function inlineData(): typeof pdfJsData {\n return pdfJsData;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQA,SAAgB,aAA+B;CAC7C,OAAO;AACT"}
@@ -0,0 +1,17 @@
1
+ import { t as PdfError } from "../shared/pdf-error-DzxHQvrO.js";
2
+ // src/adapters/no-inline-workers.ts
3
+ function leftOut() {
4
+ return new PdfError("WORKER_START_FAILED", "This build left the PDF SDK's inlined workers out, with the hm-self-hosted condition, so assetsUrl is required.", { details: {
5
+ condition: "hm-self-hosted",
6
+ missing: "assetsUrl"
7
+ } });
8
+ }
9
+ function createInlineWorker() {
10
+ throw leftOut();
11
+ }
12
+ function inlineData() {
13
+ throw leftOut();
14
+ }
15
+ export { createInlineWorker, inlineData };
16
+
17
+ //# sourceMappingURL=no-inline-workers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"no-inline-workers.js","names":[],"sources":["../../src/adapters/no-inline-workers.ts"],"sourcesContent":["import { PdfError } from \"../core/errors/pdf-error.js\";\n\n/**\n * What an application's build gets instead of the inlined workers and data\n * when it sets the `hm-self-hosted` resolve condition (sdk-core ADR 0060):\n * `#hm-pdf-render-worker`, `#hm-pdf-processing-worker` and\n * `#hm-pdf-inline-data` all map here, so none of them is bundled. Such a\n * build must pass `assetsUrl`; without it, starting a worker fails here,\n * loudly, rather than with a bare error from the module system.\n */\nfunction leftOut(): PdfError {\n return new PdfError(\n \"WORKER_START_FAILED\",\n \"This build left the PDF SDK's inlined workers out, with the hm-self-hosted condition, so assetsUrl is required.\",\n { details: { condition: \"hm-self-hosted\", missing: \"assetsUrl\" } },\n );\n}\n\n/** Stands in for the inlined render and processing workers. */\nexport function createInlineWorker(): Worker {\n throw leftOut();\n}\n\n/** Stands in for pdf.js's inlined data files. */\nexport function inlineData(): never {\n throw leftOut();\n}\n"],"mappings":";;AAUA,SAAS,UAAoB;CAC3B,OAAO,IAAI,SACT,uBACA,mHACA,EAAE,SAAS;EAAE,WAAW;EAAkB,SAAS;CAAY,EAAE,CACnE;AACF;AAGA,SAAgB,qBAA6B;CAC3C,MAAM,QAAQ;AAChB;AAGA,SAAgB,aAAoB;CAClC,MAAM,QAAQ;AAChB"}