@file-viewer/renderer-wordperfect 2.3.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/LICENSE +7 -0
- package/README.en.md +5 -0
- package/README.md +5 -0
- package/THIRD_PARTY_NOTICES.md +7 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +16 -0
- package/dist/libwpd.d.ts +2 -0
- package/dist/libwpd.js +302 -0
- package/dist/libwpd.mjs +2 -0
- package/dist/libwpd.wasm +0 -0
- package/dist/parser.d.ts +42 -0
- package/dist/parser.js +69 -0
- package/dist/wordperfect.d.ts +2 -0
- package/dist/wordperfect.js +98 -0
- package/dist/wordperfect.worker.d.ts +1 -0
- package/dist/wordperfect.worker.js +5 -0
- package/dist/workerClient.d.ts +3 -0
- package/dist/workerClient.js +41 -0
- package/package.json +74 -0
- package/vendor/libwpd-src/LICENSE.boost-BSL-1.0.txt +23 -0
- package/vendor/libwpd-src/LICENSE.xberg-shim-MIT.txt +21 -0
- package/vendor/libwpd-src/PROVENANCE.md +16 -0
- package/vendor/libwpd-src/boost-subset.tar.gz +0 -0
- package/vendor/libwpd-src/librevenge-0.0.6.tar.gz +0 -0
- package/vendor/libwpd-src/libwpd-0.10.3.tar.gz +0 -0
- package/vendor/libwpd-src/shim.cpp +1047 -0
package/LICENSE
ADDED
package/README.en.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
# @file-viewer/renderer-wordperfect
|
|
2
|
+
|
|
3
|
+
Independent WordPerfect `.wpd/.wp/.wp5/.wp6` renderer. Files are routed by the `FF 57 50 43` content signature and macros are never executed. Its Worker lazily loads a WebAssembly build of `libwpd 0.10.3` and `librevenge 0.0.6` under MPL-2.0 to recover paragraphs, headings, lists, inline styles, tables, headers, footers, and notes. A bounded text preview is used only when WASM is unavailable.
|
|
4
|
+
|
|
5
|
+
See `vendor/libwpd-src/PROVENANCE.md` for source attribution, checksums, and the reproducible build command. Licensed genuine WP 4.2, 5.0, 5.1, and 6.x fixtures pass parser assertions and Chromium, Firefox, and WebKit smoke, so the public catalog classifies this renderer as `structured / stable`. `.wp5/.wp6` remain content-signature routing aliases; renamed files do not count as fixture evidence.
|
package/README.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
# @file-viewer/renderer-wordperfect
|
|
2
|
+
|
|
3
|
+
WordPerfect `.wpd/.wp/.wp5/.wp6` 独立 renderer。文件按 `FF 57 50 43` 内容签名路由,不执行宏。Worker 按需加载以 MPL-2.0 构建的 `libwpd 0.10.3` / `librevenge 0.0.6` WebAssembly,提取段落、标题、列表、内联样式、表格、页眉页脚和脚注;WASM 不可用时才退回有界文本预览。
|
|
4
|
+
|
|
5
|
+
源码归属、校验和和复现命令见 `vendor/libwpd-src/PROVENANCE.md`。许可明确的 WP 4.2、5.0、5.1、6.x 真实 fixture 已通过解析断言和 Chromium、Firefox、WebKit 浏览器 smoke,公开格式目录标记为 `structured / stable`;`.wp5/.wp6` 是内容签名路由别名,不以改后缀文件计作证据。
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# Third-party notices
|
|
2
|
+
|
|
3
|
+
- `libwpd` 0.10.3 and `librevenge` 0.0.6 are compiled to WebAssembly under their MPL-2.0 license arm. Their checksum-pinned source archives and reproducible build instructions ship in `vendor/libwpd-src/`.
|
|
4
|
+
- The callback bridge is derived from the MIT-licensed `xberg-libwpd` shim. Its license is included verbatim in `vendor/libwpd-src/LICENSE.xberg-shim-MIT.txt`.
|
|
5
|
+
- A header-only Boost 1.90 subset is present at build time under BSL-1.0. It is checksum-pinned and described in `vendor/libwpd-src/PROVENANCE.md`.
|
|
6
|
+
|
|
7
|
+
The WebAssembly runtime is lazy-loaded by the WordPerfect Worker. The bounded TypeScript signature/text fallback remains separate and is not presented as equivalent fidelity.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type FileRenderHandler, type FileViewerRenderedInstance, type FileViewerRendererPlugin, type RendererDefinition } from '@file-viewer/core';
|
|
2
|
+
export declare const wordPerfectRendererDefinition: RendererDefinition;
|
|
3
|
+
export declare const renderFileViewerWordPerfect: FileRenderHandler<FileViewerRenderedInstance, HTMLDivElement>;
|
|
4
|
+
export declare const wordPerfectRenderer: FileViewerRendererPlugin<FileRenderHandler<FileViewerRenderedInstance, HTMLDivElement>>;
|
|
5
|
+
/** Lowercase compound alias kept in sync with the renderer package id and contract generator. */
|
|
6
|
+
export declare const wordperfectRenderer: FileViewerRendererPlugin<FileRenderHandler<FileViewerRenderedInstance, HTMLDivElement>>;
|
|
7
|
+
export { isWordPerfectDocument, parseWordPerfectDocument, type WordPerfectDocument, type WordPerfectParagraph, type WordPerfectRun, type WordPerfectTable, } from './parser.js';
|
|
8
|
+
export default wordPerfectRenderer;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { DEFAULT_RENDERER_DEFINITIONS, } from '@file-viewer/core';
|
|
2
|
+
const definition = DEFAULT_RENDERER_DEFINITIONS.find(item => item.id === 'office-wordperfect');
|
|
3
|
+
if (!definition)
|
|
4
|
+
throw new Error('@file-viewer/renderer-wordperfect could not locate the shared WordPerfect definition.');
|
|
5
|
+
export const wordPerfectRendererDefinition = definition;
|
|
6
|
+
export const renderFileViewerWordPerfect = (buffer, target, type, context) => import('./wordperfect.js').then(({ default: renderWordPerfect }) => renderWordPerfect(buffer, target, type, context));
|
|
7
|
+
export const wordPerfectRenderer = {
|
|
8
|
+
id: 'file-viewer-renderer-wordperfect',
|
|
9
|
+
label: 'Flyfish File Viewer WordPerfect renderer',
|
|
10
|
+
definitions: [wordPerfectRendererDefinition],
|
|
11
|
+
handlers: [{ rendererId: wordPerfectRendererDefinition.id, handler: renderFileViewerWordPerfect }],
|
|
12
|
+
};
|
|
13
|
+
/** Lowercase compound alias kept in sync with the renderer package id and contract generator. */
|
|
14
|
+
export const wordperfectRenderer = wordPerfectRenderer;
|
|
15
|
+
export { isWordPerfectDocument, parseWordPerfectDocument, } from './parser.js';
|
|
16
|
+
export default wordPerfectRenderer;
|
package/dist/libwpd.d.ts
ADDED
package/dist/libwpd.js
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
const MAX_WIRE_EVENTS = 1000000;
|
|
2
|
+
const MAX_WIRE_STRING_BYTES = 128 * 1024 * 1024;
|
|
3
|
+
class WireReader {
|
|
4
|
+
constructor(bytes) {
|
|
5
|
+
this.bytes = bytes;
|
|
6
|
+
this.offset = 0;
|
|
7
|
+
}
|
|
8
|
+
get remaining() { return this.bytes.length - this.offset; }
|
|
9
|
+
u8() {
|
|
10
|
+
if (this.remaining < 1)
|
|
11
|
+
throw new Error('Truncated libwpd event stream.');
|
|
12
|
+
return this.bytes[this.offset++];
|
|
13
|
+
}
|
|
14
|
+
bool() {
|
|
15
|
+
const value = this.u8();
|
|
16
|
+
if (value !== 0 && value !== 1)
|
|
17
|
+
throw new Error('Invalid boolean in libwpd event stream.');
|
|
18
|
+
return value === 1;
|
|
19
|
+
}
|
|
20
|
+
u32() {
|
|
21
|
+
if (this.remaining < 4)
|
|
22
|
+
throw new Error('Truncated libwpd event stream.');
|
|
23
|
+
const value = new DataView(this.bytes.buffer, this.bytes.byteOffset + this.offset, 4).getUint32(0, true);
|
|
24
|
+
this.offset += 4;
|
|
25
|
+
return value;
|
|
26
|
+
}
|
|
27
|
+
i32() {
|
|
28
|
+
const value = this.u32();
|
|
29
|
+
return value > 0x7fffffff ? value - 4294967296 : value;
|
|
30
|
+
}
|
|
31
|
+
string() {
|
|
32
|
+
const length = this.u32();
|
|
33
|
+
if (length > MAX_WIRE_STRING_BYTES || length > this.remaining)
|
|
34
|
+
throw new Error('Invalid string length in libwpd event stream.');
|
|
35
|
+
const start = this.offset;
|
|
36
|
+
this.offset += length;
|
|
37
|
+
return new TextDecoder().decode(this.bytes.subarray(start, start + length));
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
const readCString = (heap, pointer) => {
|
|
41
|
+
if (!pointer)
|
|
42
|
+
return '';
|
|
43
|
+
let end = pointer;
|
|
44
|
+
while (end < heap.length && heap[end] !== 0 && end - pointer < 16384)
|
|
45
|
+
end += 1;
|
|
46
|
+
return new TextDecoder().decode(heap.subarray(pointer, end));
|
|
47
|
+
};
|
|
48
|
+
const generationFromHeader = (bytes) => {
|
|
49
|
+
if (bytes[0] !== 0xff || bytes[1] !== 0x57 || bytes[2] !== 0x50 || bytes[3] !== 0x43)
|
|
50
|
+
return 'unknown';
|
|
51
|
+
return (bytes[10] || 0) >= 2 ? 'wp6' : 'wp5';
|
|
52
|
+
};
|
|
53
|
+
const decodeStructuredDocument = (wire, source) => {
|
|
54
|
+
const reader = new WireReader(wire);
|
|
55
|
+
if (reader.u8() !== 1)
|
|
56
|
+
throw new Error('Unsupported libwpd event-stream version.');
|
|
57
|
+
const metadataCount = reader.u32();
|
|
58
|
+
if (metadataCount > MAX_WIRE_EVENTS)
|
|
59
|
+
throw new Error('libwpd metadata count exceeds the safety limit.');
|
|
60
|
+
const metadata = {};
|
|
61
|
+
for (let index = 0; index < metadataCount; index += 1)
|
|
62
|
+
metadata[reader.string()] = reader.string();
|
|
63
|
+
const eventCount = reader.u32();
|
|
64
|
+
if (eventCount > MAX_WIRE_EVENTS)
|
|
65
|
+
throw new Error('libwpd event count exceeds the safety limit.');
|
|
66
|
+
const paragraphs = [];
|
|
67
|
+
const headers = [];
|
|
68
|
+
const footers = [];
|
|
69
|
+
const notes = [];
|
|
70
|
+
const tables = [];
|
|
71
|
+
let destination = paragraphs;
|
|
72
|
+
let paragraph = { kind: 'paragraph', runs: [] };
|
|
73
|
+
let styles = new Set();
|
|
74
|
+
let activeLink;
|
|
75
|
+
let list;
|
|
76
|
+
let currentTable;
|
|
77
|
+
let currentRow;
|
|
78
|
+
let currentCell;
|
|
79
|
+
const addText = (value) => {
|
|
80
|
+
if (!value)
|
|
81
|
+
return;
|
|
82
|
+
if (currentCell) {
|
|
83
|
+
currentCell.text += value;
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const run = { text: value, styles: [...styles] };
|
|
87
|
+
if (activeLink && /^(?:https?:|mailto:)/i.test(activeLink))
|
|
88
|
+
run.href = activeLink;
|
|
89
|
+
paragraph.runs.push(run);
|
|
90
|
+
};
|
|
91
|
+
const flushParagraph = () => {
|
|
92
|
+
const value = paragraph.runs.map(run => run.text).join('').trim();
|
|
93
|
+
if (value)
|
|
94
|
+
destination.push({ ...paragraph, list, runs: paragraph.runs });
|
|
95
|
+
paragraph = { kind: 'paragraph', runs: [] };
|
|
96
|
+
list = undefined;
|
|
97
|
+
};
|
|
98
|
+
const style = (name, enabled) => {
|
|
99
|
+
styles = new Set(styles);
|
|
100
|
+
enabled ? styles.add(name) : styles.delete(name);
|
|
101
|
+
};
|
|
102
|
+
for (let index = 0; index < eventCount; index += 1) {
|
|
103
|
+
const tag = reader.u8();
|
|
104
|
+
switch (tag) {
|
|
105
|
+
case 0:
|
|
106
|
+
addText(reader.string());
|
|
107
|
+
break;
|
|
108
|
+
case 1:
|
|
109
|
+
addText('\t');
|
|
110
|
+
break;
|
|
111
|
+
case 2:
|
|
112
|
+
addText(' ');
|
|
113
|
+
break;
|
|
114
|
+
case 3:
|
|
115
|
+
addText('\n');
|
|
116
|
+
break;
|
|
117
|
+
case 4:
|
|
118
|
+
flushParagraph();
|
|
119
|
+
break;
|
|
120
|
+
case 5:
|
|
121
|
+
list = { ordered: reader.bool(), level: reader.u8(), counter: reader.u32() };
|
|
122
|
+
break;
|
|
123
|
+
case 6:
|
|
124
|
+
flushParagraph();
|
|
125
|
+
break;
|
|
126
|
+
case 7:
|
|
127
|
+
paragraph.kind = 'heading';
|
|
128
|
+
paragraph.level = reader.u8();
|
|
129
|
+
break;
|
|
130
|
+
case 8:
|
|
131
|
+
style('bold', true);
|
|
132
|
+
break;
|
|
133
|
+
case 9:
|
|
134
|
+
style('bold', false);
|
|
135
|
+
break;
|
|
136
|
+
case 10:
|
|
137
|
+
style('italic', true);
|
|
138
|
+
break;
|
|
139
|
+
case 11:
|
|
140
|
+
style('italic', false);
|
|
141
|
+
break;
|
|
142
|
+
case 12:
|
|
143
|
+
style('underline', true);
|
|
144
|
+
break;
|
|
145
|
+
case 13:
|
|
146
|
+
style('underline', false);
|
|
147
|
+
break;
|
|
148
|
+
case 14:
|
|
149
|
+
style('strikethrough', true);
|
|
150
|
+
break;
|
|
151
|
+
case 15:
|
|
152
|
+
style('strikethrough', false);
|
|
153
|
+
break;
|
|
154
|
+
case 16:
|
|
155
|
+
style('superscript', true);
|
|
156
|
+
break;
|
|
157
|
+
case 17:
|
|
158
|
+
style('superscript', false);
|
|
159
|
+
break;
|
|
160
|
+
case 18:
|
|
161
|
+
style('subscript', true);
|
|
162
|
+
break;
|
|
163
|
+
case 19:
|
|
164
|
+
style('subscript', false);
|
|
165
|
+
break;
|
|
166
|
+
case 20:
|
|
167
|
+
currentTable = { rows: [] };
|
|
168
|
+
tables.push(currentTable);
|
|
169
|
+
break;
|
|
170
|
+
case 21:
|
|
171
|
+
currentRow = [];
|
|
172
|
+
currentTable === null || currentTable === void 0 ? void 0 : currentTable.rows.push(currentRow);
|
|
173
|
+
reader.bool();
|
|
174
|
+
break;
|
|
175
|
+
case 22:
|
|
176
|
+
currentCell = { text: '', column: reader.i32(), colSpan: reader.u32(), rowSpan: reader.u32() };
|
|
177
|
+
currentRow === null || currentRow === void 0 ? void 0 : currentRow.push(currentCell);
|
|
178
|
+
break;
|
|
179
|
+
case 23:
|
|
180
|
+
currentRow === null || currentRow === void 0 ? void 0 : currentRow.push({ text: '', column: reader.i32(), colSpan: 1, rowSpan: 1, covered: true });
|
|
181
|
+
break;
|
|
182
|
+
case 24:
|
|
183
|
+
currentCell = undefined;
|
|
184
|
+
break;
|
|
185
|
+
case 25:
|
|
186
|
+
currentRow = undefined;
|
|
187
|
+
break;
|
|
188
|
+
case 26:
|
|
189
|
+
currentTable = undefined;
|
|
190
|
+
break;
|
|
191
|
+
case 27:
|
|
192
|
+
flushParagraph();
|
|
193
|
+
destination = headers;
|
|
194
|
+
break;
|
|
195
|
+
case 28:
|
|
196
|
+
flushParagraph();
|
|
197
|
+
destination = paragraphs;
|
|
198
|
+
break;
|
|
199
|
+
case 29:
|
|
200
|
+
flushParagraph();
|
|
201
|
+
destination = footers;
|
|
202
|
+
break;
|
|
203
|
+
case 30:
|
|
204
|
+
flushParagraph();
|
|
205
|
+
destination = paragraphs;
|
|
206
|
+
break;
|
|
207
|
+
case 31:
|
|
208
|
+
flushParagraph();
|
|
209
|
+
destination = notes;
|
|
210
|
+
reader.bool();
|
|
211
|
+
break;
|
|
212
|
+
case 32:
|
|
213
|
+
flushParagraph();
|
|
214
|
+
destination = paragraphs;
|
|
215
|
+
break;
|
|
216
|
+
case 33:
|
|
217
|
+
flushParagraph();
|
|
218
|
+
destination = notes;
|
|
219
|
+
reader.string();
|
|
220
|
+
break;
|
|
221
|
+
case 34:
|
|
222
|
+
flushParagraph();
|
|
223
|
+
destination = paragraphs;
|
|
224
|
+
break;
|
|
225
|
+
case 35:
|
|
226
|
+
activeLink = reader.string();
|
|
227
|
+
break;
|
|
228
|
+
case 36:
|
|
229
|
+
activeLink = undefined;
|
|
230
|
+
break;
|
|
231
|
+
case 37:
|
|
232
|
+
addText(`[${reader.string()}]`);
|
|
233
|
+
break;
|
|
234
|
+
default: throw new Error(`Unknown libwpd event tag ${tag}.`);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
flushParagraph();
|
|
238
|
+
if (reader.remaining !== 0)
|
|
239
|
+
throw new Error('Unexpected trailing bytes in libwpd event stream.');
|
|
240
|
+
return {
|
|
241
|
+
format: 'wordperfect',
|
|
242
|
+
generation: generationFromHeader(source),
|
|
243
|
+
documentOffset: source.length >= 8 ? new DataView(source.buffer, source.byteOffset + 4, 4).getUint32(0, true) : 0,
|
|
244
|
+
encrypted: false,
|
|
245
|
+
engine: 'libwpd-wasm',
|
|
246
|
+
paragraphs: paragraphs.map(item => item.runs.map(run => run.text).join('')),
|
|
247
|
+
structuredParagraphs: paragraphs,
|
|
248
|
+
tables,
|
|
249
|
+
headers,
|
|
250
|
+
footers,
|
|
251
|
+
notes,
|
|
252
|
+
metadata,
|
|
253
|
+
warnings: [],
|
|
254
|
+
};
|
|
255
|
+
};
|
|
256
|
+
export const parseWordPerfectWithLibWpd = async (buffer, moduleUrl, wasmUrl, wasmBinary) => {
|
|
257
|
+
const imported = await import(/* @vite-ignore */ moduleUrl);
|
|
258
|
+
let resolvedBinary = wasmBinary;
|
|
259
|
+
if (!resolvedBinary) {
|
|
260
|
+
const response = await fetch(wasmUrl, { credentials: 'same-origin' });
|
|
261
|
+
if (!response.ok)
|
|
262
|
+
throw new Error(`libwpd WebAssembly returned HTTP ${response.status}.`);
|
|
263
|
+
resolvedBinary = new Uint8Array(await response.arrayBuffer());
|
|
264
|
+
}
|
|
265
|
+
const module = await imported.default({ locateFile: path => path.endsWith('.wasm') ? wasmUrl : path, wasmBinary: resolvedBinary });
|
|
266
|
+
const bytes = new Uint8Array(buffer);
|
|
267
|
+
const input = module._malloc(bytes.length);
|
|
268
|
+
const output = module._malloc(4);
|
|
269
|
+
const outputLength = module._malloc(4);
|
|
270
|
+
const error = module._malloc(4);
|
|
271
|
+
module.HEAPU8.set(bytes, input);
|
|
272
|
+
module.HEAPU32[output >>> 2] = 0;
|
|
273
|
+
module.HEAPU32[outputLength >>> 2] = 0;
|
|
274
|
+
module.HEAPU32[error >>> 2] = 0;
|
|
275
|
+
let extracted = 0;
|
|
276
|
+
let errorPointer = 0;
|
|
277
|
+
try {
|
|
278
|
+
if (!module._xberg_wpd_is_supported(input, bytes.length))
|
|
279
|
+
throw new Error('libwpd does not recognize this WordPerfect document.');
|
|
280
|
+
const result = module._xberg_wpd_extract_document(input, bytes.length, output, outputLength, error);
|
|
281
|
+
extracted = module.HEAPU32[output >>> 2];
|
|
282
|
+
const length = module.HEAPU32[outputLength >>> 2];
|
|
283
|
+
errorPointer = module.HEAPU32[error >>> 2];
|
|
284
|
+
if (result === 6)
|
|
285
|
+
throw new Error('Encrypted WordPerfect documents are detected but cannot be decrypted.');
|
|
286
|
+
if (result !== 0 || !extracted || !length) {
|
|
287
|
+
const detail = readCString(module.HEAPU8, errorPointer);
|
|
288
|
+
throw new Error(`libwpd could not parse the document${detail ? `: ${detail}` : ''}.`);
|
|
289
|
+
}
|
|
290
|
+
return decodeStructuredDocument(module.HEAPU8.slice(extracted, extracted + length), bytes);
|
|
291
|
+
}
|
|
292
|
+
finally {
|
|
293
|
+
if (extracted)
|
|
294
|
+
module._xberg_wpd_free_string(extracted);
|
|
295
|
+
if (errorPointer)
|
|
296
|
+
module._xberg_wpd_free_string(errorPointer);
|
|
297
|
+
module._free(input);
|
|
298
|
+
module._free(output);
|
|
299
|
+
module._free(outputLength);
|
|
300
|
+
module._free(error);
|
|
301
|
+
}
|
|
302
|
+
};
|
package/dist/libwpd.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
async function createFileViewerLibWpd(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer";if(ENVIRONMENT_IS_NODE){const{createRequire}=await import("node:module");var require=createRequire(import.meta.url)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(process.argv.length>1){thisProgram=process.argv[1].replace(/\\/g,"/")}programArgs=process.argv.slice(2);quit_=(status,toThrow)=>{process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}class CppException extends EmscriptenEH{constructor(excPtr){super();this.excPtr=excPtr}}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAP32=new Int32Array(b);Module["HEAPU32"]=HEAPU32=new Uint32Array(b)}function preRun(){}function initRuntime(){runtimeInitialized=true;wasmExports["O"]()}function postRun(){}function abort(what){what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("libwpd.wasm")}return new URL("libwpd.wasm",import.meta.url).href}function getBinarySync(file){if(file==wasmBinaryFile&&wasmBinary){return new Uint8Array(wasmBinary)}if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var stackRestore=val=>__emscripten_stack_restore(val);var stackSave=()=>_emscripten_stack_get_current();var exceptionCaught=[];var uncaughtExceptionCount=0;var ___cxa_begin_catch=ptr=>{var info=new ExceptionInfo(ptr);if(!info.get_caught()){info.set_caught(true);uncaughtExceptionCount--}info.set_rethrown(false);exceptionCaught.push(info);return ___cxa_get_exception_ptr(ptr)};var exceptionLast=null;var ___cxa_end_catch=()=>{_setThrew(0,0);var info=exceptionCaught.pop();___cxa_decrement_exception_refcount(info.excPtr);exceptionLast=null};var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var setTempRet0=val=>__emscripten_tempret_set(val);var findMatchingCatch=args=>{var thrown=exceptionLast?.excPtr;if(!thrown){setTempRet0(0);return 0}var info=new ExceptionInfo(thrown);info.set_adjusted_ptr(thrown);var thrownType=info.get_type();if(!thrownType){setTempRet0(0);return thrown}for(var caughtType of args){if(!caughtType||caughtType===thrownType){break}var adjusted_ptr_addr=info.ptr+16;if(___cxa_can_catch(caughtType,thrownType,adjusted_ptr_addr)){setTempRet0(caughtType);return thrown}}setTempRet0(thrownType);return thrown};var ___cxa_find_matching_catch_2=()=>findMatchingCatch([]);var ___cxa_find_matching_catch_3=arg0=>findMatchingCatch([arg0]);var ___cxa_find_matching_catch_4=(arg0,arg1)=>findMatchingCatch([arg0,arg1]);var ___cxa_find_matching_catch_6=(arg0,arg1,arg2,arg3)=>findMatchingCatch([arg0,arg1,arg2,arg3]);var ___cxa_rethrow=()=>{if(!exceptionCaught.length){abort("no exception to throw")}var info=exceptionCaught.at(-1);var ptr=info.excPtr;info.set_rethrown(true);info.set_caught(false);uncaughtExceptionCount++;___cxa_increment_exception_refcount(ptr);exceptionLast=new CppException(ptr);throw exceptionLast};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);___cxa_increment_exception_refcount(ptr);exceptionLast=new CppException(ptr);uncaughtExceptionCount++;throw exceptionLast};var ___resumeException=ptr=>{if(!exceptionLast){exceptionLast=new CppException(ptr)}throw exceptionLast};var __abort_js=()=>abort("");var stringToUTF8Array=(str,heap,outIdx,maxBytesToWrite)=>{if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.codePointAt(i);if(u<=127){if(outIdx>=endIdx)break;heap[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;heap[outIdx++]=192|u>>6;heap[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;heap[outIdx++]=224|u>>12;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63}else{if(outIdx+3>=endIdx)break;heap[outIdx++]=240|u>>18;heap[outIdx++]=128|u>>12&63;heap[outIdx++]=128|u>>6&63;heap[outIdx++]=128|u&63;i++}}heap[outIdx]=0;return outIdx-startIdx};var HEAPU8;var stringToUTF8=(str,outPtr,maxBytesToWrite)=>stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite);var HEAP32;var __tzset_js=(timezone,daylight,std_name,dst_name)=>{var currentYear=(new Date).getFullYear();var winter=new Date(currentYear,0,1);var summer=new Date(currentYear,6,1);var winterOffset=winter.getTimezoneOffset();var summerOffset=summer.getTimezoneOffset();var stdTimezoneOffset=Math.max(winterOffset,summerOffset);HEAPU32[timezone>>2]=stdTimezoneOffset*60;HEAP32[daylight>>2]=Number(winterOffset!=summerOffset);var extractZone=timezoneOffset=>{var sign=timezoneOffset>=0?"-":"+";var absOffset=Math.abs(timezoneOffset);var hours=String(Math.floor(absOffset/60)).padStart(2,"0");var minutes=String(absOffset%60).padStart(2,"0");return`UTC${sign}${hours}${minutes}`};var winterName=extractZone(winterOffset);var summerName=extractZone(summerOffset);if(summerOffset<winterOffset){stringToUTF8(winterName,std_name,17);stringToUTF8(summerName,dst_name,17)}else{stringToUTF8(winterName,dst_name,17);stringToUTF8(summerName,std_name,17)}};var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};var _llvm_eh_typeid_for=type=>type;var wasmTableMirror=[];var getWasmTableEntry=funcPtr=>{var func=wasmTableMirror[funcPtr];if(!func){wasmTableMirror[funcPtr]=func=wasmTable.get(funcPtr)}return func};{if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["wasmBinary"])wasmBinary=Module["wasmBinary"]}var _malloc,_xberg_wpd_is_supported,_xberg_wpd_extract_document,_xberg_wpd_free_string,_free,_setThrew,__emscripten_tempret_set,__emscripten_stack_restore,_emscripten_stack_get_current,___cxa_decrement_exception_refcount,___cxa_increment_exception_refcount,___cxa_can_catch,___cxa_get_exception_ptr,memory,__indirect_function_table,wasmMemory,wasmTable;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["P"];_xberg_wpd_is_supported=Module["_xberg_wpd_is_supported"]=wasmExports["Q"];_xberg_wpd_extract_document=Module["_xberg_wpd_extract_document"]=wasmExports["R"];_xberg_wpd_free_string=Module["_xberg_wpd_free_string"]=wasmExports["T"];_free=Module["_free"]=wasmExports["U"];_setThrew=wasmExports["V"];__emscripten_tempret_set=wasmExports["W"];__emscripten_stack_restore=wasmExports["X"];_emscripten_stack_get_current=wasmExports["Y"];___cxa_decrement_exception_refcount=wasmExports["Z"];___cxa_increment_exception_refcount=wasmExports["_"];___cxa_can_catch=wasmExports["$"];___cxa_get_exception_ptr=wasmExports["aa"];memory=wasmMemory=wasmExports["N"];__indirect_function_table=wasmTable=wasmExports["S"]}var wasmImports={m:___cxa_begin_catch,o:___cxa_end_catch,a:___cxa_find_matching_catch_2,g:___cxa_find_matching_catch_3,u:___cxa_find_matching_catch_4,r:___cxa_find_matching_catch_6,M:___cxa_rethrow,n:___cxa_throw,b:___resumeException,I:__abort_js,J:__tzset_js,H:_emscripten_resize_heap,x:invoke_di,d:invoke_ii,h:invoke_iii,A:invoke_iiidd,c:invoke_iiii,k:invoke_iiiii,w:invoke_iiiiii,v:invoke_iiiiiii,F:invoke_iiiiiiii,C:invoke_iiiiiiiiii,j:invoke_v,i:invoke_vi,E:invoke_vid,G:invoke_viddddiiii,f:invoke_vii,z:invoke_viid,D:invoke_viiddddiii,l:invoke_viidi,e:invoke_viii,t:invoke_viiii,y:invoke_viiiid,p:invoke_viiiii,s:invoke_viiiiii,B:invoke_viiiiiii,K:invoke_viiiiiiiiiii,L:invoke_viiiiiiiiiiiiiiiii,q:_llvm_eh_typeid_for};function invoke_iiii(index,a1,a2,a3){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_ii(index,a1){var sp=stackSave();try{return getWasmTableEntry(index)(a1)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_vii(index,a1,a2){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_v(index){var sp=stackSave();try{getWasmTableEntry(index)()}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_vi(index,a1){var sp=stackSave();try{getWasmTableEntry(index)(a1)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_iii(index,a1,a2){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_viii(index,a1,a2,a3){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_viiii(index,a1,a2,a3,a4){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_iiiii(index,a1,a2,a3,a4){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_iiiiii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_di(index,a1){var sp=stackSave();try{return getWasmTableEntry(index)(a1)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_vid(index,a1,a2){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_iiiiiii(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_viiiiii(index,a1,a2,a3,a4,a5,a6){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_viiiiiii(index,a1,a2,a3,a4,a5,a6,a7){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_viiiii(index,a1,a2,a3,a4,a5){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_viidi(index,a1,a2,a3,a4){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_iiidd(index,a1,a2,a3,a4){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_viiddddiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_viddddiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_viid(index,a1,a2,a3){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_iiiiiiii(index,a1,a2,a3,a4,a5,a6,a7){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_viiiiiiiiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15,a16,a17)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_viiiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_viiiid(index,a1,a2,a3,a4,a5){var sp=stackSave();try{getWasmTableEntry(index)(a1,a2,a3,a4,a5)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}function invoke_iiiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8,a9){var sp=stackSave();try{return getWasmTableEntry(index)(a1,a2,a3,a4,a5,a6,a7,a8,a9)}catch(e){stackRestore(sp);if(!(e instanceof EmscriptenEH))throw e;_setThrew(1,0)}}async function run(){preRun();if(ABORT)return;initRuntime();postRun()}var wasmExports;wasmExports=await createWasm();await run();
|
|
2
|
+
;return Module}export default createFileViewerLibWpd;
|
package/dist/libwpd.wasm
ADDED
|
Binary file
|
package/dist/parser.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
export interface WordPerfectDocument {
|
|
2
|
+
format: 'wordperfect';
|
|
3
|
+
generation: 'wp5' | 'wp6' | 'unknown';
|
|
4
|
+
documentOffset: number;
|
|
5
|
+
encrypted: boolean;
|
|
6
|
+
engine: 'libwpd-wasm' | 'bounded-fallback';
|
|
7
|
+
paragraphs: string[];
|
|
8
|
+
structuredParagraphs: WordPerfectParagraph[];
|
|
9
|
+
tables: WordPerfectTable[];
|
|
10
|
+
headers: WordPerfectParagraph[];
|
|
11
|
+
footers: WordPerfectParagraph[];
|
|
12
|
+
notes: WordPerfectParagraph[];
|
|
13
|
+
metadata: Record<string, string>;
|
|
14
|
+
warnings: string[];
|
|
15
|
+
}
|
|
16
|
+
export interface WordPerfectRun {
|
|
17
|
+
text: string;
|
|
18
|
+
styles: Array<'bold' | 'italic' | 'underline' | 'strikethrough' | 'superscript' | 'subscript'>;
|
|
19
|
+
href?: string;
|
|
20
|
+
}
|
|
21
|
+
export interface WordPerfectParagraph {
|
|
22
|
+
kind: 'paragraph' | 'heading';
|
|
23
|
+
level?: number;
|
|
24
|
+
list?: {
|
|
25
|
+
ordered: boolean;
|
|
26
|
+
level: number;
|
|
27
|
+
counter: number;
|
|
28
|
+
};
|
|
29
|
+
runs: WordPerfectRun[];
|
|
30
|
+
}
|
|
31
|
+
export interface WordPerfectTableCell {
|
|
32
|
+
text: string;
|
|
33
|
+
column: number;
|
|
34
|
+
colSpan: number;
|
|
35
|
+
rowSpan: number;
|
|
36
|
+
covered?: boolean;
|
|
37
|
+
}
|
|
38
|
+
export interface WordPerfectTable {
|
|
39
|
+
rows: WordPerfectTableCell[][];
|
|
40
|
+
}
|
|
41
|
+
export declare const isWordPerfectDocument: (bytes: Uint8Array) => boolean;
|
|
42
|
+
export declare const parseWordPerfectDocument: (buffer: ArrayBuffer) => WordPerfectDocument;
|
package/dist/parser.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
const SIGNATURE = [0xff, 0x57, 0x50, 0x43];
|
|
2
|
+
const MAX_INPUT_BYTES = 128 * 1024 * 1024;
|
|
3
|
+
const MAX_PARAGRAPHS = 100000;
|
|
4
|
+
export const isWordPerfectDocument = (bytes) => SIGNATURE.every((value, index) => bytes[index] === value);
|
|
5
|
+
const readDocumentOffset = (bytes) => {
|
|
6
|
+
if (bytes.length < 8)
|
|
7
|
+
return 0;
|
|
8
|
+
const value = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(4, true);
|
|
9
|
+
return value >= 16 && value < bytes.length ? value : Math.min(16, bytes.length);
|
|
10
|
+
};
|
|
11
|
+
const decodeWordPerfectText = (bytes) => {
|
|
12
|
+
const output = [];
|
|
13
|
+
for (let index = 0; index < bytes.length; index += 1) {
|
|
14
|
+
const value = bytes[index];
|
|
15
|
+
if (value === 0x0a || value === 0x0d) {
|
|
16
|
+
output.push('\n');
|
|
17
|
+
continue;
|
|
18
|
+
}
|
|
19
|
+
if (value === 0x09) {
|
|
20
|
+
output.push('\t');
|
|
21
|
+
continue;
|
|
22
|
+
}
|
|
23
|
+
if (value >= 0x20 && value <= 0x7e) {
|
|
24
|
+
output.push(String.fromCharCode(value));
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
if (value >= 0x80 && value <= 0xcf) {
|
|
28
|
+
output.push(new TextDecoder('windows-1252').decode(Uint8Array.of(value)));
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
// 0xd0-0xff are WordPerfect function/group markers. Do not expose their
|
|
32
|
+
// binary payload as text in the bounded fallback.
|
|
33
|
+
if (value >= 0xd0)
|
|
34
|
+
output.push(' ');
|
|
35
|
+
}
|
|
36
|
+
return output.join('').replace(/[\t ]+/g, ' ').replace(/\n{3,}/g, '\n\n').trim();
|
|
37
|
+
};
|
|
38
|
+
export const parseWordPerfectDocument = (buffer) => {
|
|
39
|
+
if (buffer.byteLength > MAX_INPUT_BYTES)
|
|
40
|
+
throw new Error('WordPerfect file exceeds the 128 MiB safety limit.');
|
|
41
|
+
const bytes = new Uint8Array(buffer);
|
|
42
|
+
if (!isWordPerfectDocument(bytes))
|
|
43
|
+
throw new Error('The extension does not match a WordPerfect WPC signature.');
|
|
44
|
+
const documentOffset = readDocumentOffset(bytes);
|
|
45
|
+
const major = bytes[10] || 0;
|
|
46
|
+
const encrypted = bytes[12] !== 0;
|
|
47
|
+
if (encrypted)
|
|
48
|
+
throw new Error('Encrypted WordPerfect documents are detected but cannot be decrypted.');
|
|
49
|
+
const generation = major >= 6 ? 'wp6' : major > 0 ? 'wp5' : 'unknown';
|
|
50
|
+
const decoded = decodeWordPerfectText(bytes.slice(documentOffset));
|
|
51
|
+
const paragraphs = decoded.split(/\n+/).map(value => value.trim()).filter(Boolean).slice(0, MAX_PARAGRAPHS);
|
|
52
|
+
if (!paragraphs.length)
|
|
53
|
+
throw new Error('No readable text was produced by the bounded WordPerfect fallback.');
|
|
54
|
+
return {
|
|
55
|
+
format: 'wordperfect',
|
|
56
|
+
generation,
|
|
57
|
+
documentOffset,
|
|
58
|
+
encrypted,
|
|
59
|
+
engine: 'bounded-fallback',
|
|
60
|
+
paragraphs,
|
|
61
|
+
structuredParagraphs: paragraphs.map(value => ({ kind: 'paragraph', runs: [{ text: value, styles: [] }] })),
|
|
62
|
+
tables: [],
|
|
63
|
+
headers: [],
|
|
64
|
+
footers: [],
|
|
65
|
+
notes: [],
|
|
66
|
+
metadata: {},
|
|
67
|
+
warnings: ['Limited text preview: the optional libwpd/librevenge WebAssembly parser is not active.'],
|
|
68
|
+
};
|
|
69
|
+
};
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { parseWordPerfectWithWorker } from './workerClient.js';
|
|
2
|
+
const styleText = `
|
|
3
|
+
.wpd-viewer{width:100%;height:100%;overflow:auto;padding:28px;background:var(--file-viewer-render-surface-background,#dfe5eb);box-sizing:border-box;color:#1f2937}.wpd-page{width:min(100%,880px);min-height:1040px;margin:0 auto;padding:56px 64px;background:#fff;box-shadow:0 16px 38px rgba(15,23,42,.12);box-sizing:border-box;font:16px/1.85 Georgia,'Times New Roman',serif}.wpd-page p,.wpd-page h1,.wpd-page h2,.wpd-page h3,.wpd-page h4,.wpd-page h5,.wpd-page h6{margin:0 0 13px;white-space:pre-wrap}.wpd-page h1{font-size:1.65em}.wpd-page h2{font-size:1.4em}.wpd-page h3{font-size:1.2em}.wpd-page a{color:#2563eb}.wpd-table{width:100%;margin:18px 0;border-collapse:collapse}.wpd-table td{padding:7px 9px;border:1px solid #94a3b8;vertical-align:top}.wpd-running{margin:0 0 24px;padding:0 0 12px;border-bottom:1px solid #cbd5e1;color:#475569;font-size:.85em}.wpd-footer{margin-top:28px;padding-top:12px;border-top:1px solid #cbd5e1}.wpd-notes{margin-top:28px;padding:16px;background:#f8fafc;border-left:4px solid #94a3b8;font-size:.9em}
|
|
4
|
+
[data-viewer-theme='dark'] .wpd-viewer{background:var(--file-viewer-render-surface-background,#0d1117)}.wpd-page{color-scheme:light}
|
|
5
|
+
@media(max-width:720px){.wpd-viewer{padding:10px}.wpd-page{min-height:0;padding:34px 24px}}
|
|
6
|
+
`;
|
|
7
|
+
const appendParagraph = (parent, paragraph) => {
|
|
8
|
+
const level = Math.min(6, Math.max(1, paragraph.level || 1));
|
|
9
|
+
const element = document.createElement(paragraph.kind === 'heading' ? `h${level}` : 'p');
|
|
10
|
+
if (paragraph.list) {
|
|
11
|
+
const marker = paragraph.list.ordered ? `${paragraph.list.counter}. ` : '• ';
|
|
12
|
+
element.append(document.createTextNode(`${' '.repeat(Math.max(0, paragraph.list.level - 1))}${marker}`));
|
|
13
|
+
}
|
|
14
|
+
paragraph.runs.forEach(run => {
|
|
15
|
+
let node = document.createElement('span');
|
|
16
|
+
node.textContent = run.text;
|
|
17
|
+
const styles = new Set(run.styles);
|
|
18
|
+
if (styles.has('bold'))
|
|
19
|
+
node.style.fontWeight = '700';
|
|
20
|
+
if (styles.has('italic'))
|
|
21
|
+
node.style.fontStyle = 'italic';
|
|
22
|
+
const decorations = [styles.has('underline') ? 'underline' : '', styles.has('strikethrough') ? 'line-through' : ''].filter(Boolean);
|
|
23
|
+
if (decorations.length)
|
|
24
|
+
node.style.textDecoration = decorations.join(' ');
|
|
25
|
+
if (styles.has('superscript'))
|
|
26
|
+
node.style.verticalAlign = 'super';
|
|
27
|
+
if (styles.has('subscript'))
|
|
28
|
+
node.style.verticalAlign = 'sub';
|
|
29
|
+
if (run.href) {
|
|
30
|
+
const link = document.createElement('a');
|
|
31
|
+
link.href = run.href;
|
|
32
|
+
link.rel = 'noopener noreferrer';
|
|
33
|
+
link.target = '_blank';
|
|
34
|
+
link.appendChild(node);
|
|
35
|
+
node = link;
|
|
36
|
+
}
|
|
37
|
+
element.appendChild(node);
|
|
38
|
+
});
|
|
39
|
+
parent.appendChild(element);
|
|
40
|
+
};
|
|
41
|
+
const appendTable = (parent, table) => {
|
|
42
|
+
const element = document.createElement('table');
|
|
43
|
+
element.className = 'wpd-table';
|
|
44
|
+
table.rows.forEach(row => {
|
|
45
|
+
const tr = document.createElement('tr');
|
|
46
|
+
row.filter(cell => !cell.covered).forEach(cell => {
|
|
47
|
+
const td = document.createElement('td');
|
|
48
|
+
td.textContent = cell.text;
|
|
49
|
+
td.colSpan = Math.max(1, cell.colSpan);
|
|
50
|
+
td.rowSpan = Math.max(1, cell.rowSpan);
|
|
51
|
+
tr.appendChild(td);
|
|
52
|
+
});
|
|
53
|
+
element.appendChild(tr);
|
|
54
|
+
});
|
|
55
|
+
parent.appendChild(element);
|
|
56
|
+
};
|
|
57
|
+
export default async function renderWordPerfect(buffer, target, _type, context) {
|
|
58
|
+
var _a, _b;
|
|
59
|
+
const model = await parseWordPerfectWithWorker(buffer.slice(0), (_a = context === null || context === void 0 ? void 0 : context.options) === null || _a === void 0 ? void 0 : _a.wordPerfect, context === null || context === void 0 ? void 0 : context.signal);
|
|
60
|
+
const style = document.createElement('style');
|
|
61
|
+
style.textContent = styleText;
|
|
62
|
+
const root = document.createElement('div');
|
|
63
|
+
root.className = 'wpd-viewer';
|
|
64
|
+
const page = document.createElement('article');
|
|
65
|
+
page.className = 'wpd-page';
|
|
66
|
+
page.dataset.viewerAnchorId = 'wordperfect-body';
|
|
67
|
+
if (model.headers.length) {
|
|
68
|
+
const header = document.createElement('header');
|
|
69
|
+
header.className = 'wpd-running';
|
|
70
|
+
model.headers.forEach(paragraph => appendParagraph(header, paragraph));
|
|
71
|
+
page.appendChild(header);
|
|
72
|
+
}
|
|
73
|
+
model.structuredParagraphs.forEach(paragraph => appendParagraph(page, paragraph));
|
|
74
|
+
model.tables.forEach(table => appendTable(page, table));
|
|
75
|
+
if (model.notes.length) {
|
|
76
|
+
const notes = document.createElement('aside');
|
|
77
|
+
notes.className = 'wpd-notes';
|
|
78
|
+
model.notes.forEach(paragraph => appendParagraph(notes, paragraph));
|
|
79
|
+
page.appendChild(notes);
|
|
80
|
+
}
|
|
81
|
+
if (model.footers.length) {
|
|
82
|
+
const footer = document.createElement('footer');
|
|
83
|
+
footer.className = 'wpd-running wpd-footer';
|
|
84
|
+
model.footers.forEach(paragraph => appendParagraph(footer, paragraph));
|
|
85
|
+
page.appendChild(footer);
|
|
86
|
+
}
|
|
87
|
+
root.appendChild(page);
|
|
88
|
+
target.replaceChildren(style, root);
|
|
89
|
+
(_b = context === null || context === void 0 ? void 0 : context.registerThumbnailAdapter) === null || _b === void 0 ? void 0 : _b.call(context, { getTarget: () => page });
|
|
90
|
+
return {
|
|
91
|
+
$el: target,
|
|
92
|
+
unmount() {
|
|
93
|
+
var _a;
|
|
94
|
+
(_a = context === null || context === void 0 ? void 0 : context.registerThumbnailAdapter) === null || _a === void 0 ? void 0 : _a.call(context, null);
|
|
95
|
+
target.replaceChildren();
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
var v=[255,87,80,67],T=128*1024*1024,S=1e5,R=n=>v.every((e,r)=>n[r]===e),D=n=>{if(n.length<8)return 0;let e=new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(4,!0);return e>=16&&e<n.length?e:Math.min(16,n.length)},M=n=>{let e=[];for(let r=0;r<n.length;r+=1){let a=n[r];if(a===10||a===13){e.push(`
|
|
2
|
+
`);continue}if(a===9){e.push(" ");continue}if(a>=32&&a<=126){e.push(String.fromCharCode(a));continue}if(a>=128&&a<=207){e.push(new TextDecoder("windows-1252").decode(Uint8Array.of(a)));continue}a>=208&&e.push(" ")}return e.join("").replace(/[\t ]+/g," ").replace(/\n{3,}/g,`
|
|
3
|
+
|
|
4
|
+
`).trim()},A=n=>{if(n.byteLength>T)throw new Error("WordPerfect file exceeds the 128 MiB safety limit.");let e=new Uint8Array(n);if(!R(e))throw new Error("The extension does not match a WordPerfect WPC signature.");let r=D(e),a=e[10]||0,g=e[12]!==0;if(g)throw new Error("Encrypted WordPerfect documents are detected but cannot be decrypted.");let d=a>=6?"wp6":a>0?"wp5":"unknown",u=M(e.slice(r)).split(/\n+/).map(l=>l.trim()).filter(Boolean).slice(0,S);if(!u.length)throw new Error("No readable text was produced by the bounded WordPerfect fallback.");return{format:"wordperfect",generation:d,documentOffset:r,encrypted:g,engine:"bounded-fallback",paragraphs:u,structuredParagraphs:u.map(l=>({kind:"paragraph",runs:[{text:l,styles:[]}]})),tables:[],headers:[],footers:[],notes:[],metadata:{},warnings:["Limited text preview: the optional libwpd/librevenge WebAssembly parser is not active."]}};var E=class{constructor(e){this.bytes=e;this.offset=0}get remaining(){return this.bytes.length-this.offset}u8(){if(this.remaining<1)throw new Error("Truncated libwpd event stream.");return this.bytes[this.offset++]}bool(){let e=this.u8();if(e!==0&&e!==1)throw new Error("Invalid boolean in libwpd event stream.");return e===1}u32(){if(this.remaining<4)throw new Error("Truncated libwpd event stream.");let e=new DataView(this.bytes.buffer,this.bytes.byteOffset+this.offset,4).getUint32(0,!0);return this.offset+=4,e}i32(){let e=this.u32();return e>2147483647?e-4294967296:e}string(){let e=this.u32();if(e>134217728||e>this.remaining)throw new Error("Invalid string length in libwpd event stream.");let r=this.offset;return this.offset+=e,new TextDecoder().decode(this.bytes.subarray(r,r+e))}},L=(n,e)=>{if(!e)return"";let r=e;for(;r<n.length&&n[r]!==0&&r-e<16384;)r+=1;return new TextDecoder().decode(n.subarray(e,r))},H=n=>n[0]!==255||n[1]!==87||n[2]!==80||n[3]!==67?"unknown":(n[10]||0)>=2?"wp6":"wp5",B=(n,e)=>{let r=new E(n);if(r.u8()!==1)throw new Error("Unsupported libwpd event-stream version.");let a=r.u32();if(a>1e6)throw new Error("libwpd metadata count exceeds the safety limit.");let g={};for(let s=0;s<a;s+=1)g[r.string()]=r.string();let d=r.u32();if(d>1e6)throw new Error("libwpd event count exceeds the safety limit.");let t=[],u=[],l=[],w=[],m=[],i=t,c={kind:"paragraph",runs:[]},h=new Set,o,W,P,y,k,x=s=>{if(!s)return;if(k){k.text+=s;return}let b={text:s,styles:[...h]};o&&/^(?:https?:|mailto:)/i.test(o)&&(b.href=o),c.runs.push(b)},p=()=>{c.runs.map(b=>b.text).join("").trim()&&i.push({...c,list:W,runs:c.runs}),c={kind:"paragraph",runs:[]},W=void 0},f=(s,b)=>{h=new Set(h),b?h.add(s):h.delete(s)};for(let s=0;s<d;s+=1){let b=r.u8();switch(b){case 0:x(r.string());break;case 1:x(" ");break;case 2:x(" ");break;case 3:x(`
|
|
5
|
+
`);break;case 4:p();break;case 5:W={ordered:r.bool(),level:r.u8(),counter:r.u32()};break;case 6:p();break;case 7:c.kind="heading",c.level=r.u8();break;case 8:f("bold",!0);break;case 9:f("bold",!1);break;case 10:f("italic",!0);break;case 11:f("italic",!1);break;case 12:f("underline",!0);break;case 13:f("underline",!1);break;case 14:f("strikethrough",!0);break;case 15:f("strikethrough",!1);break;case 16:f("superscript",!0);break;case 17:f("superscript",!1);break;case 18:f("subscript",!0);break;case 19:f("subscript",!1);break;case 20:P={rows:[]},m.push(P);break;case 21:y=[],P?.rows.push(y),r.bool();break;case 22:k={text:"",column:r.i32(),colSpan:r.u32(),rowSpan:r.u32()},y?.push(k);break;case 23:y?.push({text:"",column:r.i32(),colSpan:1,rowSpan:1,covered:!0});break;case 24:k=void 0;break;case 25:y=void 0;break;case 26:P=void 0;break;case 27:p(),i=u;break;case 28:p(),i=t;break;case 29:p(),i=l;break;case 30:p(),i=t;break;case 31:p(),i=w,r.bool();break;case 32:p(),i=t;break;case 33:p(),i=w,r.string();break;case 34:p(),i=t;break;case 35:o=r.string();break;case 36:o=void 0;break;case 37:x(`[${r.string()}]`);break;default:throw new Error(`Unknown libwpd event tag ${b}.`)}}if(p(),r.remaining!==0)throw new Error("Unexpected trailing bytes in libwpd event stream.");return{format:"wordperfect",generation:H(e),documentOffset:e.length>=8?new DataView(e.buffer,e.byteOffset+4,4).getUint32(0,!0):0,encrypted:!1,engine:"libwpd-wasm",paragraphs:t.map(s=>s.runs.map(b=>b.text).join("")),structuredParagraphs:t,tables:m,headers:u,footers:l,notes:w,metadata:g,warnings:[]}},U=async(n,e,r,a)=>{let g=await import(e),d=a;if(!d){let o=await fetch(r,{credentials:"same-origin"});if(!o.ok)throw new Error(`libwpd WebAssembly returned HTTP ${o.status}.`);d=new Uint8Array(await o.arrayBuffer())}let t=await g.default({locateFile:o=>o.endsWith(".wasm")?r:o,wasmBinary:d}),u=new Uint8Array(n),l=t._malloc(u.length),w=t._malloc(4),m=t._malloc(4),i=t._malloc(4);t.HEAPU8.set(u,l),t.HEAPU32[w>>>2]=0,t.HEAPU32[m>>>2]=0,t.HEAPU32[i>>>2]=0;let c=0,h=0;try{if(!t._xberg_wpd_is_supported(l,u.length))throw new Error("libwpd does not recognize this WordPerfect document.");let o=t._xberg_wpd_extract_document(l,u.length,w,m,i);c=t.HEAPU32[w>>>2];let W=t.HEAPU32[m>>>2];if(h=t.HEAPU32[i>>>2],o===6)throw new Error("Encrypted WordPerfect documents are detected but cannot be decrypted.");if(o!==0||!c||!W){let P=L(t.HEAPU8,h);throw new Error(`libwpd could not parse the document${P?`: ${P}`:""}.`)}return B(t.HEAPU8.slice(c,c+W),u)}finally{c&&t._xberg_wpd_free_string(c),h&&t._xberg_wpd_free_string(h),t._free(l),t._free(w),t._free(m),t._free(i)}};var _=self;_.addEventListener("message",async n=>{let{id:e,buffer:r}=n.data;try{let a=new URL("libwpd.mjs",_.location.href).href,g=n.data.wasmUrl||new URL("libwpd.wasm",_.location.href).href,d;try{d=await U(r,a,g)}catch(t){d=A(r),d.warnings.unshift(`Structured libwpd WebAssembly parsing failed: ${t instanceof Error?t.message:String(t)}`)}_.postMessage({id:e,ok:!0,document:d})}catch(a){_.postMessage({id:e,ok:!1,error:a instanceof Error?a.message:String(a)})}});
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { type FileViewerWordPerfectOptions } from '@file-viewer/core';
|
|
2
|
+
import { type WordPerfectDocument } from './parser.js';
|
|
3
|
+
export declare const parseWordPerfectWithWorker: (buffer: ArrayBuffer, options?: FileViewerWordPerfectOptions, signal?: AbortSignal) => Promise<WordPerfectDocument>;
|