@swc/anyformat-pdf-wasm32-wasi 0.0.0 → 0.2.1

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.
@@ -0,0 +1,69 @@
1
+ /* auto-generated by NAPI-RS */
2
+ /* eslint-disable */
3
+
4
+ /** The WASI flavor this loader instantiates. */
5
+ export declare const __napiBindingTarget: 'wasm32-wasi'
6
+
7
+ /**
8
+ * Reads the version, for example `"1.7"`, from the PDF header of `data`, on
9
+ * the thread pool. Copies only the first 1031 bytes, so the caller can
10
+ * change `data` after the call.
11
+ *
12
+ * Returns `null` when the first 1024 bytes of `data` do not contain a PDF
13
+ * header.
14
+ */
15
+ export declare function detectVersion(data: Uint8Array): Promise<string | null>
16
+
17
+ /**
18
+ * Reads the version, for example `"1.7"`, from the PDF header of the file at
19
+ * `path`, on the thread pool. Reads only the first 1031 bytes.
20
+ *
21
+ * Returns `null` when the first 1024 bytes of the file do not contain a PDF
22
+ * header.
23
+ */
24
+ export declare function detectVersionFile(path: string): Promise<string | null>
25
+
26
+ /**
27
+ * Reads the version, for example `"1.7"`, from the PDF header of the file at
28
+ * `path`. Reads only the first 1031 bytes.
29
+ *
30
+ * Returns `null` when the first 1024 bytes of the file do not contain a PDF
31
+ * header.
32
+ */
33
+ export declare function detectVersionFileSync(path: string): string | null
34
+
35
+ /**
36
+ * Reads the version, for example `"1.7"`, from the PDF header of `data`.
37
+ *
38
+ * Returns `null` when the first 1024 bytes of `data` do not contain a PDF
39
+ * header.
40
+ */
41
+ export declare function detectVersionSync(data: Uint8Array): string | null
42
+
43
+ /**
44
+ * The number of leading bytes that `isPdf` and `detectVersion` read. The
45
+ * public API uses it for `isPdfStream` and does not export it.
46
+ */
47
+ export declare const HEADER_PREFIX_LEN: number
48
+
49
+ /**
50
+ * Returns `true` when `data` starts with a PDF file header, on the thread
51
+ * pool. Copies only the first 1031 bytes, so the caller can change `data`
52
+ * after the call.
53
+ */
54
+ export declare function isPdf(data: Uint8Array): Promise<boolean>
55
+
56
+ /**
57
+ * Returns `true` when the file at `path` starts with a PDF file header, on
58
+ * the thread pool. Reads only the first 1031 bytes.
59
+ */
60
+ export declare function isPdfFile(path: string): Promise<boolean>
61
+
62
+ /**
63
+ * Returns `true` when the file at `path` starts with a PDF file header.
64
+ * Reads only the first 1031 bytes.
65
+ */
66
+ export declare function isPdfFileSync(path: string): boolean
67
+
68
+ /** Returns `true` when `data` starts with a PDF file header. */
69
+ export declare function isPdfSync(data: Uint8Array): boolean
Binary file
package/package.json CHANGED
@@ -1,8 +1,23 @@
1
1
  {
2
2
  "name": "@swc/anyformat-pdf-wasm32-wasi",
3
- "version": "0.0.0",
4
- "description": "WebAssembly build of @swc/anyformat-pdf. Install @swc/anyformat-pdf, not this package.",
3
+ "version": "0.2.1",
4
+ "cpu": [
5
+ "wasm32"
6
+ ],
7
+ "main": "anyformat-pdf.wasi.cjs",
8
+ "files": [
9
+ "anyformat-pdf.wasm32-wasi.wasm",
10
+ "anyformat-pdf.wasi.cjs",
11
+ "anyformat-pdf.wasi.d.cts",
12
+ "anyformat-pdf.wasi-browser.js",
13
+ "wasi-worker.mjs",
14
+ "wasi-worker-browser.mjs"
15
+ ],
16
+ "description": "High-performance PDF processing for Node.js",
5
17
  "license": "Apache-2.0",
18
+ "engines": {
19
+ "node": "^20.19.0 || ^22.13.0 || >=23.5.0"
20
+ },
6
21
  "repository": {
7
22
  "type": "git",
8
23
  "url": "git+https://github.com/swc-project/anyformat.git",
@@ -10,5 +25,13 @@
10
25
  },
11
26
  "publishConfig": {
12
27
  "access": "public"
28
+ },
29
+ "types": "anyformat-pdf.wasi.d.cts",
30
+ "browser": "anyformat-pdf.wasi-browser.js",
31
+ "type": "module",
32
+ "dependencies": {
33
+ "@napi-rs/wasm-runtime": "~1.2.7",
34
+ "@emnapi/core": "2.0.0-beta.3",
35
+ "@emnapi/runtime": "2.0.0-beta.3"
13
36
  }
14
37
  }
@@ -0,0 +1,67 @@
1
+ import {
2
+ instantiateNapiModuleSync,
3
+ MessageHandler,
4
+ WASI,
5
+ emnapiAsyncWorkPlugin,
6
+ emnapiTSFNPlugin,
7
+ } from '@napi-rs/wasm-runtime'
8
+
9
+ const handler = new MessageHandler({
10
+ onLoad({ wasmModule, wasmMemory }) {
11
+ const wasi = new WASI({
12
+ print: function () {
13
+ // eslint-disable-next-line no-console
14
+ console.log.apply(console, arguments)
15
+ },
16
+ printErr: function () {
17
+ // eslint-disable-next-line no-console
18
+ console.error.apply(console, arguments)
19
+ },
20
+ })
21
+ return instantiateNapiModuleSync(wasmModule, {
22
+ childThread: true,
23
+ wasi,
24
+ // The wasm links a "basic" emnapi archive (no C async-work /
25
+ // threadsafe-function implementations), so every thread that
26
+ // instantiates it must provide the JavaScript implementations
27
+ // through the emnapi plugins.
28
+ plugins: [emnapiAsyncWorkPlugin, emnapiTSFNPlugin],
29
+ overwriteImports(importObject) {
30
+ importObject.env = {
31
+ ...importObject.env,
32
+ ...importObject.napi,
33
+ ...importObject.emnapi,
34
+ memory: wasmMemory,
35
+ }
36
+ },
37
+ })
38
+ },
39
+ })
40
+
41
+ // When this wasm thread dies, raise the addon's crash flag before emnapi reports
42
+ // it. The loader thread may be inside wasm, in a cleanup call that waits on this
43
+ // thread; the flag is what those waits check between short slices, and once it
44
+ // is up they trap instead of waiting for good. It is a word in the shared wasm
45
+ // memory, and the loader posts a view of it (see
46
+ // napi_wasm_thread_crash_flag_address) after it instantiated the wasm, or right
47
+ // after it created this worker. No view, no flag: an addon built with an older
48
+ // napi, or a failure before the view arrived.
49
+ let __addonCrashFlag
50
+ const __beforeReportError = handler.beforeReportError
51
+ handler.beforeReportError = function (...args) {
52
+ if (__addonCrashFlag !== undefined) {
53
+ try {
54
+ Atomics.store(__addonCrashFlag, 0, 1)
55
+ } catch {}
56
+ }
57
+ return __beforeReportError.apply(this, args)
58
+ }
59
+
60
+ globalThis.onmessage = function (e) {
61
+ const data = e && e.data
62
+ if (data && data.__napiRsAddonCrashFlag instanceof Int32Array) {
63
+ __addonCrashFlag = data.__napiRsAddonCrashFlag
64
+ return
65
+ }
66
+ handler.handle(e)
67
+ }
@@ -0,0 +1,186 @@
1
+ import fs from 'node:fs'
2
+ import { createRequire } from 'node:module'
3
+ import { parse } from 'node:path'
4
+ import { WASI } from 'node:wasi'
5
+ import { parentPort, threadId, Worker, workerData } from 'node:worker_threads'
6
+
7
+ const require = createRequire(import.meta.url)
8
+
9
+ // The thread spawn that created this worker has already returned, so the loader
10
+ // thread may be waiting on this thread. A failure before the crash hook below is
11
+ // in place (a missing '@napi-rs/wasm-runtime', say) has to raise the crash flags
12
+ // too, then fail the worker as before.
13
+ let handler
14
+ try {
15
+ const {
16
+ instantiateNapiModuleSync,
17
+ MessageHandler,
18
+ getDefaultContext,
19
+ emnapiAsyncWorkPlugin,
20
+ emnapiTSFNPlugin,
21
+ } = require('@napi-rs/wasm-runtime')
22
+
23
+ if (parentPort) {
24
+ parentPort.on('message', (data) => {
25
+ globalThis.onmessage({ data })
26
+ })
27
+ }
28
+
29
+ Object.assign(globalThis, {
30
+ self: globalThis,
31
+ require,
32
+ Worker,
33
+ importScripts: function (f) {
34
+ // oxlint-disable-next-line no-eval -- WASI importScripts polyfill
35
+ ;(0, eval)(fs.readFileSync(f, 'utf8') + '//# sourceURL=' + f)
36
+ },
37
+ postMessage: function (msg) {
38
+ if (parentPort) {
39
+ parentPort.postMessage(msg)
40
+ }
41
+ },
42
+ })
43
+
44
+ const emnapiContext = getDefaultContext()
45
+
46
+ const __cwd = process.cwd()
47
+ const __rootDir =
48
+ (workerData && typeof workerData.rootDir === 'string' && workerData.rootDir) ||
49
+ parse(__cwd).root
50
+ const __hostRoot =
51
+ (workerData && typeof workerData.hostRoot === 'string' && workerData.hostRoot) ||
52
+ (process.platform === 'android' ? __cwd : __rootDir)
53
+
54
+ handler = new MessageHandler({
55
+ onLoad({ wasmModule, wasmMemory }) {
56
+ const wasi = new WASI({
57
+ version: 'preview1',
58
+ env: process.env,
59
+ preopens: {
60
+ [__rootDir]: __hostRoot,
61
+ [__hostRoot]: __hostRoot,
62
+ },
63
+ })
64
+
65
+ return instantiateNapiModuleSync(wasmModule, {
66
+ childThread: true,
67
+ wasi,
68
+ context: emnapiContext,
69
+ // The wasm links a "basic" emnapi archive (no C async-work /
70
+ // threadsafe-function implementations), so every thread that
71
+ // instantiates it must provide the JavaScript implementations
72
+ // through the emnapi plugins.
73
+ plugins: [emnapiAsyncWorkPlugin, emnapiTSFNPlugin],
74
+ overwriteImports(importObject) {
75
+ importObject.env = {
76
+ ...importObject.env,
77
+ ...importObject.napi,
78
+ ...importObject.emnapi,
79
+ memory: wasmMemory,
80
+ }
81
+ },
82
+ })
83
+ },
84
+ })
85
+ } catch (error) {
86
+ if (workerData && workerData.crashFlag instanceof Int32Array) {
87
+ __raiseWasiThreadCrashFlags(error)
88
+ }
89
+ throw error
90
+ }
91
+
92
+ // Tell the loader thread synchronously that this wasm thread died, so its 'exit'
93
+ // teardown does not re-enter wasm and wait on this thread forever. emnapi calls
94
+ // beforeReportError (which runs emnapi_thread_crashed, so the main thread may
95
+ // throw 'unwind' and start exiting) before the 'error' event is even posted.
96
+ // A loader that predates the flag passes none.
97
+ if (workerData && workerData.crashFlag instanceof Int32Array) {
98
+ const __beforeReportError = handler.beforeReportError
99
+ handler.beforeReportError = function (...args) {
100
+ if (!__raiseWasiThreadCrashFlags(args[0])) {
101
+ // No view (the thread was spawned before the loader read the address,
102
+ // say): the export stores into the same word, but only a worker that
103
+ // loaded has an instance to call it on.
104
+ try {
105
+ const __napiThreadCrashed = this.instance?.exports?.napi_wasm_thread_crashed
106
+ if (typeof __napiThreadCrashed === 'function') {
107
+ __napiThreadCrashed()
108
+ }
109
+ } catch {}
110
+ }
111
+ return __beforeReportError.apply(this, args)
112
+ }
113
+ }
114
+
115
+ // The error goes into the shared crash report first. The 'error' event that
116
+ // would carry it is dropped when the loader terminates this worker before the
117
+ // event is sent, so the report is the only copy the loader can count on.
118
+ // Layout: three Int32 words — state (0 empty, 1 writing, 2 written), byte
119
+ // length, threadId — then the UTF-8 JSON of { name, message, stack }. Only the
120
+ // first worker to crash writes it, and it is complete before the flag is raised.
121
+ //
122
+ // Then the loader's flag, then the addon's. The loader thread may already be
123
+ // inside wasm, in a cleanup call that waits on this thread; the addon's flag is
124
+ // what those waits check between short slices. It is a word in the shared wasm
125
+ // memory (the loader passes a view of it, see napi_wasm_thread_crash_flag_address),
126
+ // so no instance is needed: a worker that failed while loading raises it too.
127
+ // Once it is up the waits trap, and the loader, whose flag is already up, turns
128
+ // the throw into its crash rejection. Returns whether the addon's flag was raised.
129
+ function __raiseWasiThreadCrashFlags(error) {
130
+ try {
131
+ __writeCrashReport(workerData.crashReport, error)
132
+ } catch {}
133
+ try {
134
+ Atomics.store(workerData.crashFlag, 0, 1)
135
+ } catch {}
136
+ const addonCrashFlag = workerData.addonCrashFlag
137
+ if (!(addonCrashFlag instanceof Int32Array)) {
138
+ return false
139
+ }
140
+ try {
141
+ Atomics.store(addonCrashFlag, 0, 1)
142
+ return true
143
+ } catch {
144
+ return false
145
+ }
146
+ }
147
+
148
+ function __writeCrashReport(report, error) {
149
+ if (!(report instanceof SharedArrayBuffer) || report.byteLength <= 12) {
150
+ return
151
+ }
152
+ const header = new Int32Array(report, 0, 3)
153
+ if (Atomics.compareExchange(header, 0, 0, 1) !== 0) {
154
+ return
155
+ }
156
+ let length = 0
157
+ try {
158
+ const body = new Uint8Array(report, 12)
159
+ const isObject =
160
+ error !== null && (typeof error === 'object' || typeof error === 'function')
161
+ const name = isObject && typeof error.name === 'string' ? error.name : 'Error'
162
+ const message = isObject && typeof error.message === 'string'
163
+ ? error.message
164
+ : String(error)
165
+ const stack = isObject && typeof error.stack === 'string' ? error.stack : undefined
166
+ const encoder = new TextEncoder()
167
+ let bytes = encoder.encode(JSON.stringify({ name, message, stack }))
168
+ if (bytes.length > body.length) {
169
+ bytes = encoder.encode(
170
+ JSON.stringify({ name, message: message.slice(0, body.length >> 3) }),
171
+ )
172
+ }
173
+ if (bytes.length <= body.length) {
174
+ body.set(bytes)
175
+ length = bytes.length
176
+ }
177
+ Atomics.store(header, 2, threadId)
178
+ } finally {
179
+ Atomics.store(header, 1, length)
180
+ Atomics.store(header, 0, 2)
181
+ }
182
+ }
183
+
184
+ globalThis.onmessage = function (e) {
185
+ handler.handle(e)
186
+ }