@open-artifact/wasm-export 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/run.js ADDED
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Runs export jobs on the WebAssembly module (`crates/open-artifact-export`). The
3
+ * Worker runs them off the page's thread; where there are no Workers (Node
4
+ * tests, the CLI) the client runs them here in-thread.
5
+ *
6
+ * The module's bytes are embedded, so it instantiates synchronously
7
+ * wherever this runs.
8
+ */
9
+ import * as glue from '../generated/open_artifact_export.js';
10
+ import { WASM_BASE64 } from '../generated/bytes.js';
11
+ let ready = false;
12
+ function decode(base64) {
13
+ const binary = atob(base64);
14
+ const bytes = new Uint8Array(binary.length);
15
+ for (let index = 0; index < binary.length; index++)
16
+ bytes[index] = binary.charCodeAt(index);
17
+ return bytes;
18
+ }
19
+ /** The module's exports, instantiating it on the first call. */
20
+ export function exportModule() {
21
+ if (!ready) {
22
+ glue.initSync({ module: decode(WASM_BASE64) });
23
+ ready = true;
24
+ }
25
+ return glue;
26
+ }
27
+ const encoder = new TextEncoder();
28
+ /** The bytes of an entry's data. */
29
+ async function bytesOf(data) {
30
+ if (typeof data === 'string')
31
+ return encoder.encode(data);
32
+ if (data instanceof Uint8Array)
33
+ return data;
34
+ return new Uint8Array(await data.arrayBuffer());
35
+ }
36
+ /** Names of files that are compressed already: stored, not deflated again. */
37
+ const COMPRESSED = /\.(png|jpe?g|gif|webp|avif|heic|zip|gz|br|woff2?|mp[34]|m4[av]|mov|webm|ogg|opus)$/i;
38
+ /** A URI safe to write as ASCII (as `encodeURI` writes it). */
39
+ function asciiUri(uri) {
40
+ try {
41
+ return encodeURI(decodeURI(uri));
42
+ }
43
+ catch {
44
+ try {
45
+ return encodeURI(uri);
46
+ }
47
+ catch {
48
+ return '';
49
+ }
50
+ }
51
+ }
52
+ const noNul = (text) => text.replaceAll('\0', '');
53
+ async function runZip(job, progress) {
54
+ const wasm = exportModule();
55
+ const writer = new wasm.ZipWriter(job.time, job.date);
56
+ try {
57
+ const total = job.entries.length;
58
+ for (const [index, entry] of job.entries.entries()) {
59
+ let data = await bytesOf(entry.data);
60
+ const png = /\.png$/i.test(entry.name);
61
+ if (png && job.optimizePng) {
62
+ const smaller = wasm.optimizePng(data, 9);
63
+ if (smaller.length > 0)
64
+ data = smaller;
65
+ }
66
+ const store = entry.store ?? COMPRESSED.test(entry.name);
67
+ writer.add(entry.name, data, store ? 0 : job.level);
68
+ progress(index + 1, total);
69
+ }
70
+ return writer.finish();
71
+ }
72
+ finally {
73
+ writer.free();
74
+ }
75
+ }
76
+ async function runPdf(job, progress) {
77
+ const wasm = exportModule();
78
+ const writer = new wasm.PdfWriter();
79
+ try {
80
+ const total = job.pages.length;
81
+ for (const [index, page] of job.pages.entries()) {
82
+ const text = page.text ?? [];
83
+ const links = page.links ?? [];
84
+ writer.addPage(await bytesOf(page.jpeg), page.pixelWidth, page.pixelHeight, page.width, page.height, text.map((run) => noNul(run.text)).join('\0'), Float64Array.from(text.flatMap((run) => [run.x, run.baseline, run.size, run.width])), links.map((link) => noNul(asciiUri(link.uri))).join('\0'), Float64Array.from(links.flatMap((link) => [link.x, link.y, link.width, link.height])), page.bookmark || undefined);
85
+ progress(index + 1, total);
86
+ }
87
+ return writer.finish(job.title || undefined, job.date);
88
+ }
89
+ finally {
90
+ writer.free();
91
+ }
92
+ }
93
+ async function runPng(job) {
94
+ const data = await bytesOf(job.data);
95
+ const smaller = exportModule().optimizePng(data, job.level);
96
+ return smaller.length > 0 ? smaller : data;
97
+ }
98
+ /** Runs a job, reporting progress as entries or pages are packed. */
99
+ export function runJob(job, progress = () => { }) {
100
+ switch (job.kind) {
101
+ case 'zip':
102
+ return runZip(job, progress);
103
+ case 'pdf':
104
+ return runPdf(job, progress);
105
+ case 'png':
106
+ return runPng(job);
107
+ }
108
+ }
package/src/types.d.ts ADDED
@@ -0,0 +1,110 @@
1
+ /**
2
+ * What the export packer takes and the messages between the page and its
3
+ * Worker.
4
+ */
5
+ /** Bytes as the editors have them: in memory, as text (written as UTF-8), or a Blob (read in the Worker). */
6
+ export type ExportBytes = Uint8Array | string | Blob;
7
+ /** One file in a zip. */
8
+ export interface ZipEntry {
9
+ name: string;
10
+ data: ExportBytes;
11
+ /** Store the entry as it is (already compressed data). By default entries are deflated unless their name says they are compressed (PNG, JPEG, fonts…). */
12
+ store?: boolean;
13
+ }
14
+ /** Options of a zip. */
15
+ export interface ZipOptions {
16
+ /** Modification time of every entry (default: now). */
17
+ date?: Date;
18
+ /** Deflate level, 1–10 (default 6). */
19
+ level?: number;
20
+ /** Re-compress `.png` entries losslessly before storing them (default: no). */
21
+ optimizePng?: boolean;
22
+ }
23
+ /** A run of invisible text: one line of words as rendered. */
24
+ export interface PdfTextRun {
25
+ text: string;
26
+ /** Left edge, pt from the page's left. */
27
+ x: number;
28
+ /** Baseline, pt from the page's top. */
29
+ baseline: number;
30
+ /** Font size in pt. */
31
+ size: number;
32
+ /** Rendered width in pt (the run is stretched to it). */
33
+ width: number;
34
+ }
35
+ /** A clickable area that opens a web address (http, https or mailto; others are left out). */
36
+ export interface PdfLink {
37
+ uri: string;
38
+ /** Top-left corner and size, in pt from the page's top left. */
39
+ x: number;
40
+ y: number;
41
+ width: number;
42
+ height: number;
43
+ }
44
+ /** One page: a JPEG filling the page, the page size in points, and what lies over it. */
45
+ export interface PdfPage {
46
+ jpeg: Uint8Array | Blob;
47
+ /** Pixel size of the JPEG. */
48
+ pixelWidth: number;
49
+ pixelHeight: number;
50
+ /** Page size in points (1/72 inch). */
51
+ width: number;
52
+ height: number;
53
+ /** Invisible, selectable text. */
54
+ text?: readonly PdfTextRun[];
55
+ links?: readonly PdfLink[];
56
+ /** Title of the page's entry in the document outline. */
57
+ bookmark?: string;
58
+ }
59
+ /** Options of a PDF. */
60
+ export interface PdfOptions {
61
+ title?: string;
62
+ /** Creation time (default: now). */
63
+ date?: Date;
64
+ }
65
+ /** Options of a PNG re-compression. */
66
+ export interface PngOptions {
67
+ /** Deflate level, 1–10 (default 9). */
68
+ level?: number;
69
+ }
70
+ /** Reports how much of a job is done (entries or pages). */
71
+ export type Progress = (done: number, total: number) => void;
72
+ /** A job as it travels to the Worker. */
73
+ export type Job = {
74
+ kind: 'zip';
75
+ entries: readonly ZipEntry[];
76
+ time: number;
77
+ date: number;
78
+ level: number;
79
+ optimizePng: boolean;
80
+ } | {
81
+ kind: 'pdf';
82
+ pages: readonly PdfPage[];
83
+ title: string | undefined;
84
+ date: number;
85
+ } | {
86
+ kind: 'png';
87
+ data: Uint8Array | Blob;
88
+ level: number;
89
+ };
90
+ /** Page → Worker. */
91
+ export interface JobMessage {
92
+ id: number;
93
+ job: Job;
94
+ }
95
+ /** Worker → page. */
96
+ export type WorkerMessage = {
97
+ id: number;
98
+ type: 'progress';
99
+ done: number;
100
+ total: number;
101
+ } | {
102
+ id: number;
103
+ type: 'done';
104
+ bytes: Uint8Array;
105
+ } | {
106
+ id: number;
107
+ type: 'failed';
108
+ message: string;
109
+ fatal: boolean;
110
+ };
package/src/types.js ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * What the export packer takes and the messages between the page and its
3
+ * Worker.
4
+ */
5
+ export {};
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The export Worker: runs packing jobs (zip, PDF, PNG) on the WebAssembly
3
+ * module so the page's thread stays free. Results travel back transferred.
4
+ *
5
+ * A job that traps the module reports itself `fatal`: the page then drops
6
+ * this Worker and starts a fresh one for the next job.
7
+ */
8
+ export {};
package/src/worker.js ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The export Worker: runs packing jobs (zip, PDF, PNG) on the WebAssembly
3
+ * module so the page's thread stays free. Results travel back transferred.
4
+ *
5
+ * A job that traps the module reports itself `fatal`: the page then drops
6
+ * this Worker and starts a fresh one for the next job.
7
+ */
8
+ import { runJob } from "./run.js";
9
+ const scope = globalThis;
10
+ scope.onmessage = (event) => {
11
+ const { id, job } = event.data;
12
+ const progress = (done, total) => scope.postMessage({ id, type: 'progress', done, total });
13
+ runJob(job, progress).then((bytes) => scope.postMessage({ id, type: 'done', bytes }, [bytes.buffer]), (error) => scope.postMessage({
14
+ id,
15
+ type: 'failed',
16
+ message: error instanceof Error ? error.message : String(error),
17
+ fatal: error instanceof WebAssembly.RuntimeError,
18
+ }));
19
+ };