office-oxide 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/LICENSE-APACHE ADDED
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
package/LICENSE-MIT ADDED
@@ -0,0 +1,25 @@
1
+ Copyright (c) 2026 Yury Fedoseev
2
+
3
+ Permission is hereby granted, free of charge, to any
4
+ person obtaining a copy of this software and associated
5
+ documentation files (the "Software"), to deal in the
6
+ Software without restriction, including without
7
+ limitation the rights to use, copy, modify, merge,
8
+ publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software
10
+ is furnished to do so, subject to the following
11
+ conditions:
12
+
13
+ The above copyright notice and this permission notice
14
+ shall be included in all copies or substantial portions
15
+ of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18
+ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19
+ TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20
+ PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21
+ SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24
+ IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25
+ DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,155 @@
1
+ # office-oxide for Node.js — The Fastest Office Document Library for JavaScript & TypeScript
2
+
3
+ Native Node.js bindings for [office_oxide](https://github.com/yfedoseev/office_oxide) — a fast Rust library for parsing, converting, and editing Office documents (DOCX, XLSX, PPTX, DOC, XLS, PPT).
4
+
5
+ Links directly against the Rust C FFI via [koffi](https://koffi.dev). No `node-gyp` build step. Pre-built native libraries are shipped for Linux, macOS, and Windows (x64 + arm64).
6
+
7
+ [![npm](https://img.shields.io/npm/v/office-oxide?label=npm%20native)](https://www.npmjs.com/package/office-oxide)
8
+ [![License: MIT OR Apache-2.0](https://img.shields.io/badge/License-MIT%20OR%20Apache--2.0-blue.svg)](https://opensource.org/licenses)
9
+
10
+ > **Part of the [office_oxide](https://github.com/yfedoseev/office_oxide) toolkit.** Same Rust core, same pass rate as the
11
+ > [Rust](https://docs.rs/office_oxide), [Python](../python/README.md),
12
+ > [Go](../go/README.md), [C# / .NET](../csharp/OfficeOxide/README.md),
13
+ > and [WASM](../wasm-pkg/README.md) bindings.
14
+ >
15
+ > For running in browsers, Deno, Bun, or edge runtimes, use the sibling [`office-oxide-wasm`](../wasm-pkg) package instead.
16
+
17
+ ## Quick Start
18
+
19
+ ```bash
20
+ npm install office-oxide
21
+ ```
22
+
23
+ ```js
24
+ import { Document } from 'office-oxide';
25
+
26
+ const doc = Document.open('report.docx');
27
+ try {
28
+ console.log(doc.format); // "docx"
29
+ console.log(doc.plainText());
30
+ console.log(doc.toMarkdown());
31
+ console.log(doc.toIr()); // structured, format-agnostic IR
32
+ } finally { doc.close(); }
33
+ ```
34
+
35
+ With the disposable protocol (Node 22+):
36
+
37
+ ```js
38
+ using doc = Document.open('report.docx');
39
+ console.log(doc.plainText());
40
+ ```
41
+
42
+ ## Why office-oxide?
43
+
44
+ - **Fast** — 0.8ms mean DOCX, 5.0ms mean XLSX, 0.7ms mean PPTX; up to 100× faster than python-docx / openpyxl / python-pptx
45
+ - **Reliable** — 100% pass rate on valid Office files (6,062-file corpus); zero failures on legitimate documents
46
+ - **Complete** — 6 formats: DOCX, XLSX, PPTX + legacy DOC, XLS, PPT
47
+ - **Permissive** — MIT / Apache-2.0, no AGPL or GPL restrictions
48
+ - **No node-gyp** — Ships pre-built native libraries; no C++ build toolchain required
49
+ - **Full TypeScript support** — Type definitions ship in the package
50
+
51
+ ## Performance
52
+
53
+ Benchmarked on 6,062 files from 11 independent public test suites. Single-thread, release build, warm disk cache.
54
+
55
+ | Library | Format | Mean | Pass Rate | License |
56
+ |---------|--------|------|-----------|---------|
57
+ | **office_oxide** | **DOCX** | **0.8ms** | **98.9%** | **MIT** |
58
+ | python-docx | DOCX | 11.8ms | 95.1% | MIT |
59
+ | **office_oxide** | **XLSX** | **5.0ms** | **97.8%** | **MIT** |
60
+ | openpyxl | XLSX | 94.5ms | 96.2% | MIT |
61
+ | **office_oxide** | **PPTX** | **0.7ms** | **98.4%** | **MIT** |
62
+ | python-pptx | PPTX | 32.5ms | 86.7% | MIT |
63
+
64
+ ## Installation
65
+
66
+ ```bash
67
+ npm install office-oxide
68
+ ```
69
+
70
+ The native shared library is resolved (in order):
71
+
72
+ 1. `OFFICE_OXIDE_LIB` environment variable (absolute path).
73
+ 2. `prebuilds/<platform>-<arch>/liboffice_oxide.{so|dylib|dll}` inside the npm package.
74
+ 3. The system library search path.
75
+
76
+ | Platform | x64 | ARM64 |
77
+ |---|---|---|
78
+ | Linux (glibc) | Yes | Yes |
79
+ | macOS | Yes | Yes (Apple Silicon) |
80
+ | Windows | Yes | Yes |
81
+
82
+ Requires Node.js 18 or newer. TypeScript definitions ship in the package.
83
+
84
+ ## Editing
85
+
86
+ ```js
87
+ import { EditableDocument } from 'office-oxide';
88
+
89
+ using ed = EditableDocument.open('template.docx');
90
+ ed.replaceText('{{NAME}}', 'Alice');
91
+ ed.save('out.docx');
92
+ ```
93
+
94
+ ### Spreadsheet cells
95
+
96
+ ```js
97
+ using ed = EditableDocument.open('report.xlsx');
98
+ ed.setCell(0, 'A1', 'Revenue');
99
+ ed.setCell(0, 'B1', 12345.67);
100
+ ed.setCell(0, 'C1', true);
101
+ ed.save('report.edited.xlsx');
102
+ ```
103
+
104
+ ## One-shot helpers
105
+
106
+ ```js
107
+ import { extractText, toMarkdown, toHtml } from 'office-oxide';
108
+
109
+ console.log(extractText('doc.docx'));
110
+ console.log(toMarkdown('deck.pptx'));
111
+ console.log(toHtml('data.xlsx'));
112
+ ```
113
+
114
+ ## API
115
+
116
+ TypeScript definitions ship with the package (`office-oxide/lib/index.d.ts`).
117
+
118
+ | Export | Description |
119
+ | --- | --- |
120
+ | `Document.open(path)` / `fromBytes(data, format)` | Parse a read-only document. |
121
+ | `Document#format` | `"docx" \| "xlsx" \| …` |
122
+ | `Document#plainText()` / `toMarkdown()` / `toHtml()` / `toIr()` | Extraction methods. |
123
+ | `Document#saveAs(path)` | Save/convert to a different format. |
124
+ | `EditableDocument.open(path)` | Open DOCX/XLSX/PPTX for editing. |
125
+ | `EditableDocument#replaceText(find, replace)` | In-place replace. Returns count. |
126
+ | `EditableDocument#setCell(sheet, ref, value)` | Write an XLSX cell. |
127
+ | `EditableDocument#save(path)` | Persist to disk. |
128
+ | `version()` / `detectFormat(path)` | Library info. |
129
+ | `extractText(path)` / `toMarkdown(path)` / `toHtml(path)` | One-shot helpers. |
130
+
131
+ ## Other languages
132
+
133
+ office_oxide ships the same Rust core through six bindings:
134
+
135
+ - **Rust** — `cargo add office_oxide` — see [docs.rs/office_oxide](https://docs.rs/office_oxide)
136
+ - **Python** — `pip install office-oxide` — see [python/README.md](../python/README.md)
137
+ - **Go** — `go get github.com/yfedoseev/office_oxide/go` — see [go/README.md](../go/README.md)
138
+ - **C# / .NET** — `dotnet add package OfficeOxide` — see [csharp/OfficeOxide/README.md](../csharp/OfficeOxide/README.md)
139
+ - **WASM** — `npm install office-oxide-wasm` — see [wasm-pkg/README.md](../wasm-pkg/README.md)
140
+
141
+ ## Why I built this
142
+
143
+ I needed a library that could read all six Office formats at once — not six separate packages — and I needed it without pulling in a JVM, a Python runtime, or a GPL-licensed dependency. The same Rust binary powers Python via PyO3, Node.js via koffi, Go via cgo, C# via P/Invoke, and the browser via WASM — one fix lands everywhere.
144
+
145
+ If something's broken or missing, [open an issue](https://github.com/yfedoseev/office_oxide/issues).
146
+
147
+ — Yury
148
+
149
+ ## License
150
+
151
+ MIT OR Apache-2.0
152
+
153
+ ---
154
+
155
+ **Node.js** + **Rust core** | MIT / Apache-2.0 | 100% pass rate on valid Office files (6,062-file corpus) | Up to 100× faster than alternatives | 6 formats
package/lib/index.cjs ADDED
@@ -0,0 +1,165 @@
1
+ // CommonJS entry point — mirrors lib/index.js (ESM) exactly.
2
+ 'use strict';
3
+
4
+ const koffi = require('koffi');
5
+ const path = require('node:path');
6
+ const process = require('node:process');
7
+
8
+ const ext =
9
+ process.platform === 'win32' ? '.dll' :
10
+ process.platform === 'darwin' ? '.dylib' : '.so';
11
+ const prefix = process.platform === 'win32' ? '' : 'lib';
12
+
13
+ function candidatePaths() {
14
+ const paths = [];
15
+ if (process.env.OFFICE_OXIDE_LIB) paths.push(process.env.OFFICE_OXIDE_LIB);
16
+ const hereDir = path.dirname(require.resolve('../package.json'));
17
+ paths.push(path.join(
18
+ hereDir, 'prebuilds',
19
+ `${process.platform}-${process.arch}`,
20
+ `${prefix}office_oxide${ext}`,
21
+ ));
22
+ paths.push(`${prefix}office_oxide${ext}`);
23
+ return paths;
24
+ }
25
+
26
+ function loadLib() {
27
+ let lastErr;
28
+ for (const p of candidatePaths()) {
29
+ try { return koffi.load(p); }
30
+ catch (e) { lastErr = e; }
31
+ }
32
+ throw new Error(
33
+ `office-oxide: failed to load native library. Tried:\n ${candidatePaths().join('\n ')}\n` +
34
+ `Original error: ${lastErr ? lastErr.message : 'unknown'}`,
35
+ );
36
+ }
37
+
38
+ const lib = loadLib();
39
+ const freeStringRaw = lib.func('void office_oxide_free_string(void* ptr)');
40
+ const freeBytesRaw = lib.func('void office_oxide_free_bytes(void* ptr, size_t len)');
41
+ koffi.disposable('HeapStr', 'char*', freeStringRaw);
42
+
43
+ const n = {
44
+ version: lib.func('const char* office_oxide_version()'),
45
+ detectFormat: lib.func('const char* office_oxide_detect_format(const char* path)'),
46
+ documentOpen: lib.func('void* office_document_open(const char* path, _Out_ int* error_code)'),
47
+ documentOpenFromBytes: lib.func('void* office_document_open_from_bytes(const uint8_t* data, size_t len, const char* format, _Out_ int* error_code)'),
48
+ documentFree: lib.func('void office_document_free(void* handle)'),
49
+ documentFormat: lib.func('const char* office_document_format(void* handle)'),
50
+ documentPlainText: lib.func('HeapStr office_document_plain_text(void* handle, _Out_ int* error_code)'),
51
+ documentToMarkdown: lib.func('HeapStr office_document_to_markdown(void* handle, _Out_ int* error_code)'),
52
+ documentToHtml: lib.func('HeapStr office_document_to_html(void* handle, _Out_ int* error_code)'),
53
+ documentToIrJson: lib.func('HeapStr office_document_to_ir_json(void* handle, _Out_ int* error_code)'),
54
+ documentSaveAs: lib.func('int32_t office_document_save_as(void* handle, const char* path, _Out_ int* error_code)'),
55
+ editableOpen: lib.func('void* office_editable_open(const char* path, _Out_ int* error_code)'),
56
+ editableFree: lib.func('void office_editable_free(void* handle)'),
57
+ editableReplaceText: lib.func('int64_t office_editable_replace_text(void* handle, const char* find, const char* replace, _Out_ int* error_code)'),
58
+ editableSetCell: lib.func('int32_t office_editable_set_cell(void* handle, uint32_t sheet_index, const char* cell_ref, int32_t value_type, const char* value_str, double value_num, _Out_ int* error_code)'),
59
+ editableSave: lib.func('int32_t office_editable_save(void* handle, const char* path, _Out_ int* error_code)'),
60
+ extractText: lib.func('HeapStr office_extract_text(const char* path, _Out_ int* error_code)'),
61
+ toMarkdown: lib.func('HeapStr office_to_markdown(const char* path, _Out_ int* error_code)'),
62
+ toHtml: lib.func('HeapStr office_to_html(const char* path, _Out_ int* error_code)'),
63
+ };
64
+
65
+ class OfficeOxideError extends Error {
66
+ constructor(code, operation) {
67
+ const kind = ({
68
+ 0: 'ok', 1: 'invalid argument', 2: 'io error', 3: 'parse error',
69
+ 4: 'extraction failed', 5: 'internal error', 6: 'unsupported format',
70
+ })[code] || `code=${code}`;
71
+ super(`office_oxide: ${operation}: ${kind}`);
72
+ this.name = 'OfficeOxideError';
73
+ this.code = code;
74
+ this.operation = operation;
75
+ }
76
+ }
77
+
78
+ const emptyToNull = (v) => (v === null || v === undefined || v === '' ? null : v);
79
+
80
+ function version() { return n.version() || ''; }
81
+ function detectFormat(p) { return emptyToNull(n.detectFormat(p)); }
82
+
83
+ class Document {
84
+ constructor(h, src = null) { this._h = h; this._src = src; }
85
+ static open(p) {
86
+ const e = [0]; const h = n.documentOpen(p, e);
87
+ if (!h) throw new OfficeOxideError(e[0], 'open');
88
+ return new Document(h, p);
89
+ }
90
+ static fromBytes(data, fmt) {
91
+ if (!(data instanceof Uint8Array)) throw new TypeError('data must be Uint8Array/Buffer');
92
+ const e = [0]; const h = n.documentOpenFromBytes(data, data.length, fmt, e);
93
+ if (!h) throw new OfficeOxideError(e[0], 'fromBytes');
94
+ return new Document(h);
95
+ }
96
+ _ensure() { if (!this._h) throw new Error('Document is closed'); }
97
+ get format() { this._ensure(); return emptyToNull(n.documentFormat(this._h)); }
98
+ _call(fn, op) {
99
+ this._ensure();
100
+ const e = [0]; const s = fn(this._h, e);
101
+ if (s === null || s === undefined) throw new OfficeOxideError(e[0], op);
102
+ return s;
103
+ }
104
+ plainText() { return this._call(n.documentPlainText, 'plainText'); }
105
+ toMarkdown() { return this._call(n.documentToMarkdown, 'toMarkdown'); }
106
+ toHtml() { return this._call(n.documentToHtml, 'toHtml'); }
107
+ toIr() { return JSON.parse(this._call(n.documentToIrJson, 'toIr')); }
108
+ saveAs(p) {
109
+ this._ensure(); const e = [0];
110
+ const rc = n.documentSaveAs(this._h, p, e);
111
+ if (rc !== 0) throw new OfficeOxideError(e[0], 'saveAs');
112
+ }
113
+ close() { if (this._h) { n.documentFree(this._h); this._h = null; } }
114
+ [Symbol.dispose]() { this.close(); }
115
+ }
116
+
117
+ class EditableDocument {
118
+ constructor(h) { this._h = h; }
119
+ static open(p) {
120
+ const e = [0]; const h = n.editableOpen(p, e);
121
+ if (!h) throw new OfficeOxideError(e[0], 'open');
122
+ return new EditableDocument(h);
123
+ }
124
+ _ensure() { if (!this._h) throw new Error('EditableDocument is closed'); }
125
+ replaceText(find, repl) {
126
+ this._ensure(); const e = [0];
127
+ const x = n.editableReplaceText(this._h, find, repl, e);
128
+ if (x < 0) throw new OfficeOxideError(e[0], 'replaceText');
129
+ return Number(x);
130
+ }
131
+ setCell(sheetIndex, cellRef, value) {
132
+ this._ensure();
133
+ let t, s = '', num = 0.0;
134
+ if (value === null || value === undefined) t = 0;
135
+ else if (typeof value === 'string') { t = 1; s = value; }
136
+ else if (typeof value === 'number') { t = 2; num = value; }
137
+ else if (typeof value === 'boolean') { t = 3; num = value ? 1 : 0; }
138
+ else throw new TypeError('value must be null, string, number, or boolean');
139
+ const e = [0];
140
+ const rc = n.editableSetCell(this._h, sheetIndex, cellRef, t, s, num, e);
141
+ if (rc !== 0) throw new OfficeOxideError(e[0], 'setCell');
142
+ }
143
+ save(p) {
144
+ this._ensure(); const e = [0];
145
+ const rc = n.editableSave(this._h, p, e);
146
+ if (rc !== 0) throw new OfficeOxideError(e[0], 'save');
147
+ }
148
+ close() { if (this._h) { n.editableFree(this._h); this._h = null; } }
149
+ [Symbol.dispose]() { this.close(); }
150
+ }
151
+
152
+ function oneShot(fn, name, p) {
153
+ const e = [0]; const s = fn(p, e);
154
+ if (s === null || s === undefined) throw new OfficeOxideError(e[0], name);
155
+ return s;
156
+ }
157
+
158
+ function extractText(p) { return oneShot(n.extractText, 'extractText', p); }
159
+ function toMarkdown(p) { return oneShot(n.toMarkdown, 'toMarkdown', p); }
160
+ function toHtml(p) { return oneShot(n.toHtml, 'toHtml', p); }
161
+
162
+ module.exports = {
163
+ OfficeOxideError, Document, EditableDocument,
164
+ version, detectFormat, extractText, toMarkdown, toHtml,
165
+ };
package/lib/index.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ // Type definitions for office-oxide (Node native bindings).
2
+
3
+ export type DocumentFormat = 'docx' | 'xlsx' | 'pptx' | 'doc' | 'xls' | 'ppt';
4
+ export type CellValue = null | string | number | boolean;
5
+
6
+ export class OfficeOxideError extends Error {
7
+ readonly code: number;
8
+ readonly operation: string;
9
+ }
10
+
11
+ export class Document implements Disposable {
12
+ static open(path: string): Document;
13
+ static fromBytes(data: Uint8Array, format: DocumentFormat): Document;
14
+ readonly format: DocumentFormat | null;
15
+ plainText(): string;
16
+ toMarkdown(): string;
17
+ toHtml(): string;
18
+ toIr(): unknown;
19
+ saveAs(path: string): void;
20
+ close(): void;
21
+ [Symbol.dispose](): void;
22
+ }
23
+
24
+ export class EditableDocument implements Disposable {
25
+ static open(path: string): EditableDocument;
26
+ replaceText(find: string, replace: string): number;
27
+ setCell(sheetIndex: number, cellRef: string, value: CellValue): void;
28
+ save(path: string): void;
29
+ close(): void;
30
+ [Symbol.dispose](): void;
31
+ }
32
+
33
+ export function version(): string;
34
+ export function detectFormat(path: string): DocumentFormat | null;
35
+ export function extractText(path: string): string;
36
+ export function toMarkdown(path: string): string;
37
+ export function toHtml(path: string): string;
package/lib/index.js ADDED
@@ -0,0 +1,173 @@
1
+ // SPDX-License-Identifier: MIT OR Apache-2.0
2
+ // ESM entry point for office-oxide.
3
+ //
4
+ // The native functions that allocate C strings already return JS strings
5
+ // (decoded and auto-freed via the `HeapStr` disposable type registered in
6
+ // native.js). Errors surface as null returns + a non-zero error code.
7
+
8
+ import { native } from './native.js';
9
+
10
+ export class OfficeOxideError extends Error {
11
+ constructor(code, operation) {
12
+ const kind = ({
13
+ 0: 'ok', 1: 'invalid argument', 2: 'io error', 3: 'parse error',
14
+ 4: 'extraction failed', 5: 'internal error', 6: 'unsupported format',
15
+ })[code] ?? `code=${code}`;
16
+ super(`office_oxide: ${operation}: ${kind}`);
17
+ this.name = 'OfficeOxideError';
18
+ this.code = code;
19
+ this.operation = operation;
20
+ }
21
+ }
22
+
23
+ // koffi normalises null C strings to either null, undefined or ''; treat all as absent.
24
+ const emptyToNull = (v) => (v === null || v === undefined || v === '' ? null : v);
25
+
26
+ export function version() {
27
+ return native.version() ?? '';
28
+ }
29
+
30
+ export function detectFormat(path) {
31
+ return emptyToNull(native.detectFormat(path));
32
+ }
33
+
34
+ export class Document {
35
+ #handle;
36
+ #source;
37
+
38
+ constructor(handle, source = null) {
39
+ this.#handle = handle;
40
+ this.#source = source;
41
+ }
42
+
43
+ static open(path) {
44
+ const err = [0];
45
+ const h = native.documentOpen(path, err);
46
+ if (!h) throw new OfficeOxideError(err[0], 'open');
47
+ return new Document(h, path);
48
+ }
49
+
50
+ static fromBytes(data, format) {
51
+ if (!(data instanceof Uint8Array))
52
+ throw new TypeError('data must be a Uint8Array or Buffer');
53
+ const err = [0];
54
+ const h = native.documentOpenFromBytes(data, data.length, format, err);
55
+ if (!h) throw new OfficeOxideError(err[0], 'fromBytes');
56
+ return new Document(h, null);
57
+ }
58
+
59
+ #ensure() {
60
+ if (!this.#handle) throw new Error('Document is closed');
61
+ }
62
+
63
+ get format() {
64
+ this.#ensure();
65
+ return emptyToNull(native.documentFormat(this.#handle));
66
+ }
67
+
68
+ #callStr(fn, op) {
69
+ this.#ensure();
70
+ const err = [0];
71
+ const s = fn(this.#handle, err);
72
+ if (s === null || s === undefined) throw new OfficeOxideError(err[0], op);
73
+ return s;
74
+ }
75
+
76
+ plainText() { return this.#callStr(native.documentPlainText, 'plainText'); }
77
+ toMarkdown() { return this.#callStr(native.documentToMarkdown, 'toMarkdown'); }
78
+ toHtml() { return this.#callStr(native.documentToHtml, 'toHtml'); }
79
+ toIr() { return JSON.parse(this.#callStr(native.documentToIrJson, 'toIr')); }
80
+
81
+ saveAs(path) {
82
+ this.#ensure();
83
+ const err = [0];
84
+ const rc = native.documentSaveAs(this.#handle, path, err);
85
+ if (rc !== 0) throw new OfficeOxideError(err[0], 'saveAs');
86
+ }
87
+
88
+ close() {
89
+ if (this.#handle) {
90
+ native.documentFree(this.#handle);
91
+ this.#handle = null;
92
+ }
93
+ }
94
+
95
+ [Symbol.dispose]() { this.close(); }
96
+ }
97
+
98
+ export class EditableDocument {
99
+ #handle;
100
+
101
+ constructor(handle) { this.#handle = handle; }
102
+
103
+ static open(path) {
104
+ const err = [0];
105
+ const h = native.editableOpen(path, err);
106
+ if (!h) throw new OfficeOxideError(err[0], 'open');
107
+ return new EditableDocument(h);
108
+ }
109
+
110
+ #ensure() {
111
+ if (!this.#handle) throw new Error('EditableDocument is closed');
112
+ }
113
+
114
+ replaceText(find, replace) {
115
+ this.#ensure();
116
+ const err = [0];
117
+ const n = native.editableReplaceText(this.#handle, find, replace, err);
118
+ if (n < 0) throw new OfficeOxideError(err[0], 'replaceText');
119
+ return Number(n);
120
+ }
121
+
122
+ setCell(sheetIndex, cellRef, value) {
123
+ this.#ensure();
124
+ let t, s = '', num = 0.0;
125
+ if (value === null || value === undefined) t = 0;
126
+ else if (typeof value === 'string') { t = 1; s = value; }
127
+ else if (typeof value === 'number') { t = 2; num = value; }
128
+ else if (typeof value === 'boolean') { t = 3; num = value ? 1 : 0; }
129
+ else throw new TypeError('value must be null, string, number, or boolean');
130
+ const err = [0];
131
+ const rc = native.editableSetCell(this.#handle, sheetIndex, cellRef, t, s, num, err);
132
+ if (rc !== 0) throw new OfficeOxideError(err[0], 'setCell');
133
+ }
134
+
135
+ save(path) {
136
+ this.#ensure();
137
+ const err = [0];
138
+ const rc = native.editableSave(this.#handle, path, err);
139
+ if (rc !== 0) throw new OfficeOxideError(err[0], 'save');
140
+ }
141
+
142
+ close() {
143
+ if (this.#handle) {
144
+ native.editableFree(this.#handle);
145
+ this.#handle = null;
146
+ }
147
+ }
148
+
149
+ [Symbol.dispose]() { this.close(); }
150
+ }
151
+
152
+ function oneShot(fn, name, path) {
153
+ const err = [0];
154
+ const s = fn(path, err);
155
+ if (s === null || s === undefined) throw new OfficeOxideError(err[0], name);
156
+ return s;
157
+ }
158
+
159
+ export function extractText(path) { return oneShot(native.extractText, 'extractText', path); }
160
+ export function toMarkdown(path) { return oneShot(native.toMarkdown, 'toMarkdown', path); }
161
+ export function toHtml(path) { return oneShot(native.toHtml, 'toHtml', path); }
162
+
163
+ /**
164
+ * Convert a Markdown string to an Office document file.
165
+ * @param {string} markdown - The Markdown content.
166
+ * @param {string} format - One of "docx", "xlsx", or "pptx".
167
+ * @param {string} path - Output file path.
168
+ */
169
+ export function createFromMarkdown(markdown, format, path) {
170
+ const err = [0];
171
+ const rc = native.createFromMarkdown(markdown, format, path, err);
172
+ if (rc !== 0) throw new OfficeOxideError(err[0], 'createFromMarkdown');
173
+ }
package/lib/native.js ADDED
@@ -0,0 +1,81 @@
1
+ // Native-library loader + FFI bindings for office_oxide.
2
+ //
3
+ // Uses koffi's `disposable()` pattern so that C strings allocated by the
4
+ // library are auto-decoded to JS strings *and* freed via office_oxide_free_string.
5
+
6
+ import koffi from 'koffi';
7
+ import { createRequire } from 'node:module';
8
+ import path from 'node:path';
9
+ import process from 'node:process';
10
+
11
+ const require = createRequire(import.meta.url);
12
+
13
+ const ext =
14
+ process.platform === 'win32' ? '.dll' :
15
+ process.platform === 'darwin' ? '.dylib' : '.so';
16
+ const prefix = process.platform === 'win32' ? '' : 'lib';
17
+
18
+ function candidatePaths() {
19
+ const paths = [];
20
+ if (process.env.OFFICE_OXIDE_LIB) paths.push(process.env.OFFICE_OXIDE_LIB);
21
+ const hereDir = path.dirname(require.resolve('../package.json'));
22
+ paths.push(path.join(
23
+ hereDir, 'prebuilds',
24
+ `${process.platform}-${process.arch}`,
25
+ `${prefix}office_oxide${ext}`,
26
+ ));
27
+ paths.push(`${prefix}office_oxide${ext}`);
28
+ return paths;
29
+ }
30
+
31
+ function loadLib() {
32
+ let lastErr;
33
+ for (const p of candidatePaths()) {
34
+ try { return koffi.load(p); }
35
+ catch (e) { lastErr = e; }
36
+ }
37
+ throw new Error(
38
+ `office-oxide: failed to load native library. Tried:\n ${candidatePaths().join('\n ')}\n` +
39
+ `Original error: ${lastErr?.message ?? 'unknown'}`,
40
+ );
41
+ }
42
+
43
+ const lib = loadLib();
44
+
45
+ // Declare the raw string-freeing function first so we can compose it into a
46
+ // disposable type. Heap strings are returned as `HeapStr` — koffi decodes
47
+ // them to JS strings and automatically calls office_oxide_free_string.
48
+ const freeStringRaw = lib.func('void office_oxide_free_string(void* ptr)');
49
+ const freeBytesRaw = lib.func('void office_oxide_free_bytes(void* ptr, size_t len)');
50
+
51
+ // Register a disposable `HeapStr` type. koffi keeps the type table global,
52
+ // so the type name (registered here) is usable by name in function prototypes.
53
+ koffi.disposable('HeapStr', 'char*', freeStringRaw);
54
+
55
+ export const native = {
56
+ version: lib.func('const char* office_oxide_version()'),
57
+ detectFormat: lib.func('const char* office_oxide_detect_format(const char* path)'),
58
+ freeString: freeStringRaw,
59
+ freeBytes: freeBytesRaw,
60
+
61
+ documentOpen: lib.func('void* office_document_open(const char* path, _Out_ int* error_code)'),
62
+ documentOpenFromBytes: lib.func('void* office_document_open_from_bytes(const uint8_t* data, size_t len, const char* format, _Out_ int* error_code)'),
63
+ documentFree: lib.func('void office_document_free(void* handle)'),
64
+ documentFormat: lib.func('const char* office_document_format(void* handle)'),
65
+ documentPlainText: lib.func('HeapStr office_document_plain_text(void* handle, _Out_ int* error_code)'),
66
+ documentToMarkdown: lib.func('HeapStr office_document_to_markdown(void* handle, _Out_ int* error_code)'),
67
+ documentToHtml: lib.func('HeapStr office_document_to_html(void* handle, _Out_ int* error_code)'),
68
+ documentToIrJson: lib.func('HeapStr office_document_to_ir_json(void* handle, _Out_ int* error_code)'),
69
+ documentSaveAs: lib.func('int32_t office_document_save_as(void* handle, const char* path, _Out_ int* error_code)'),
70
+
71
+ editableOpen: lib.func('void* office_editable_open(const char* path, _Out_ int* error_code)'),
72
+ editableFree: lib.func('void office_editable_free(void* handle)'),
73
+ editableReplaceText: lib.func('int64_t office_editable_replace_text(void* handle, const char* find, const char* replace, _Out_ int* error_code)'),
74
+ editableSetCell: lib.func('int32_t office_editable_set_cell(void* handle, uint32_t sheet_index, const char* cell_ref, int32_t value_type, const char* value_str, double value_num, _Out_ int* error_code)'),
75
+ editableSave: lib.func('int32_t office_editable_save(void* handle, const char* path, _Out_ int* error_code)'),
76
+
77
+ extractText: lib.func('HeapStr office_extract_text(const char* path, _Out_ int* error_code)'),
78
+ toMarkdown: lib.func('HeapStr office_to_markdown(const char* path, _Out_ int* error_code)'),
79
+ toHtml: lib.func('HeapStr office_to_html(const char* path, _Out_ int* error_code)'),
80
+ createFromMarkdown: lib.func('int32_t office_create_from_markdown(const char* markdown, const char* format, const char* path, _Out_ int* error_code)'),
81
+ };
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "office-oxide",
3
+ "version": "0.1.0",
4
+ "description": "Fast Office document processing (DOCX/XLSX/PPTX/DOC/XLS/PPT) for Node.js — native bindings backed by the Rust office_oxide library.",
5
+ "license": "MIT OR Apache-2.0",
6
+ "author": "Yury Fedoseev",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/yfedoseev/office_oxide.git"
10
+ },
11
+ "homepage": "https://oxide.fyi",
12
+ "bugs": {
13
+ "url": "https://github.com/yfedoseev/office_oxide/issues"
14
+ },
15
+ "engines": {
16
+ "node": ">=18"
17
+ },
18
+ "type": "module",
19
+ "main": "./lib/index.cjs",
20
+ "module": "./lib/index.js",
21
+ "types": "./lib/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./lib/index.d.ts",
25
+ "import": "./lib/index.js",
26
+ "require": "./lib/index.cjs"
27
+ },
28
+ "./package.json": "./package.json"
29
+ },
30
+ "files": [
31
+ "lib/",
32
+ "prebuilds/",
33
+ "scripts/",
34
+ "README.md",
35
+ "LICENSE-MIT",
36
+ "LICENSE-APACHE"
37
+ ],
38
+ "scripts": {
39
+ "postinstall": "node scripts/check-prebuild.cjs",
40
+ "test": "node --test test/*.mjs"
41
+ },
42
+ "dependencies": {
43
+ "koffi": "^2.9.0"
44
+ },
45
+ "keywords": [
46
+ "docx",
47
+ "xlsx",
48
+ "pptx",
49
+ "doc",
50
+ "xls",
51
+ "ppt",
52
+ "office",
53
+ "text-extraction",
54
+ "document-parser",
55
+ "markdown",
56
+ "rust",
57
+ "native",
58
+ "nodejs"
59
+ ]
60
+ }
@@ -0,0 +1,36 @@
1
+ #!/usr/bin/env node
2
+ // Post-install guard. When a user installs office-oxide via npm, we expect a
3
+ // prebuilt native library for their platform under prebuilds/<platform>-<arch>/.
4
+ // If none exists, fall back to a clear error — but don't fail the install
5
+ // itself, so downstream consumers who intend to set OFFICE_OXIDE_LIB manually
6
+ // can still complete `npm install`.
7
+ 'use strict';
8
+
9
+ const fs = require('node:fs');
10
+ const path = require('node:path');
11
+ const process = require('node:process');
12
+
13
+ const ext =
14
+ process.platform === 'win32' ? '.dll' :
15
+ process.platform === 'darwin' ? '.dylib' : '.so';
16
+ const prefix = process.platform === 'win32' ? '' : 'lib';
17
+ const candidate = path.join(
18
+ __dirname, '..', 'prebuilds',
19
+ `${process.platform}-${process.arch}`,
20
+ `${prefix}office_oxide${ext}`,
21
+ );
22
+
23
+ if (fs.existsSync(candidate)) {
24
+ process.exit(0);
25
+ }
26
+
27
+ process.stderr.write(
28
+ `\n[office-oxide] No prebuilt native library for ${process.platform}-${process.arch}.\n` +
29
+ ` Tried: ${candidate}\n` +
30
+ ` Set OFFICE_OXIDE_LIB=/path/to/liboffice_oxide.{so,dylib,dll}\n` +
31
+ ` or build from source in the office_oxide monorepo:\n` +
32
+ ` cargo build --release --lib\n` +
33
+ ` export OFFICE_OXIDE_LIB=$(pwd)/target/release/liboffice_oxide.so\n\n`,
34
+ );
35
+ // Exit 0 so `npm install` still succeeds for headless CI / custom setups.
36
+ process.exit(0);