@andorra-labs/code 0.1.10 → 0.1.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -208
- package/THIRD_PARTY_NOTICES.md +15 -0
- package/dist/src/agent-execution.js +36 -0
- package/dist/src/app-server/protocol.d.ts +1 -0
- package/dist/src/app-server.d.ts +34 -1
- package/dist/src/app-server.js +264 -54
- package/dist/src/automation-service.js +1 -1
- package/dist/src/browser-session.d.ts +8 -0
- package/dist/src/browser-session.js +27 -1
- package/dist/src/browser-ui/app.js +237 -15
- package/dist/src/browser-ui/index.html +5 -5
- package/dist/src/browser-ui/style.css +110 -65
- package/dist/src/browser-ui/tokens.css +27 -26
- package/dist/src/coding-tools.d.ts +24 -0
- package/dist/src/coding-tools.js +71 -8
- package/dist/src/command-screens.js +1 -1
- package/dist/src/commands.js +1 -1
- package/dist/src/completion-gates.d.ts +42 -7
- package/dist/src/completion-gates.js +55 -9
- package/dist/src/completion.d.ts +8 -0
- package/dist/src/completion.js +19 -1
- package/dist/src/dashboard-view.js +2 -2
- package/dist/src/deadline.js +4 -0
- package/dist/src/graph-manager-chat.js +13 -13
- package/dist/src/graph-runner.js +39 -2
- package/dist/src/graph-server.js +9 -9
- package/dist/src/graph-sync.d.ts +8 -0
- package/dist/src/graph-sync.js +54 -3
- package/dist/src/graph-tool.js +1 -1
- package/dist/src/graph-ui/app.js +262 -93
- package/dist/src/graph-ui/controls.css +43 -22
- package/dist/src/graph-ui/controls.js +31 -1
- package/dist/src/graph-ui/embed.js +62 -13
- package/dist/src/graph-ui/icons.js +4 -0
- package/dist/src/graph-ui/index.html +3 -3
- package/dist/src/graph-ui/manager-state.js +2 -2
- package/dist/src/graph-ui/manager.css +19 -18
- package/dist/src/graph-ui/manager.js +11 -11
- package/dist/src/graph-ui/skill-picker.js +1 -1
- package/dist/src/graph-ui/studio-canvas.js +8 -8
- package/dist/src/graph-ui/studio.css +18 -15
- package/dist/src/graph-ui/studio.js +92 -35
- package/dist/src/graph-ui/style.css +122 -79
- package/dist/src/graph-ui/theme.js +2 -2
- package/dist/src/graph-ui/tokens.css +33 -29
- package/dist/src/graphs.d.ts +3 -2
- package/dist/src/graphs.js +3 -2
- package/dist/src/membership-errors.d.ts +7 -1
- package/dist/src/membership-errors.js +9 -3
- package/dist/src/pull-requests.d.ts +42 -6
- package/dist/src/pull-requests.js +11 -3
- package/dist/src/react-runtime.js +121 -14
- package/dist/src/read-document-doc.d.ts +20 -0
- package/dist/src/read-document-doc.js +524 -0
- package/dist/src/read-document-docx.d.ts +21 -0
- package/dist/src/read-document-docx.js +584 -0
- package/dist/src/read-document-text.d.ts +29 -0
- package/dist/src/read-document-text.js +67 -0
- package/dist/src/read-document-tool.d.ts +48 -0
- package/dist/src/read-document-tool.js +162 -0
- package/dist/src/read-document.d.ts +78 -0
- package/dist/src/read-document.js +353 -0
- package/dist/src/read-image.d.ts +29 -2
- package/dist/src/read-image.js +42 -17
- package/dist/src/runtime.d.ts +19 -0
- package/dist/src/runtime.js +10 -1
- package/dist/src/session-changes.d.ts +6 -1
- package/dist/src/session-changes.js +13 -5
- package/dist/src/side-panel.d.ts +6 -1
- package/dist/src/side-panel.js +12 -10
- package/dist/src/skills/bundled/create-skill/SKILL.md +1 -1
- package/dist/src/skills/bundled/diagram/SKILL.md +1 -1
- package/dist/src/skills/bundled/graph-manager/SKILL.md +37 -3
- package/dist/src/skills/bundled/graph-manager/patterns.md +27 -0
- package/dist/src/skills/bundled/provenance.json +4 -4
- package/dist/src/skills/runtime-skills.js +3 -3
- package/dist/src/stall-recovery.d.ts +6 -2
- package/dist/src/stall-recovery.js +7 -2
- package/dist/src/terminal-ui.js +2 -2
- package/dist/src/time-limit.d.ts +53 -0
- package/dist/src/time-limit.js +79 -0
- package/dist/src/tools.js +92 -7
- package/dist/src/transcript.js +1 -1
- package/dist/src/types.d.ts +6 -0
- package/dist/src/usage-analytics.d.ts +3 -1
- package/dist/src/usage-analytics.js +16 -2
- package/package.json +6 -26
- package/docs/README.md +0 -36
- package/docs/agents/README.md +0 -62
- package/docs/agents/install-for-agents.md +0 -56
- package/docs/agents/mcp-server.md +0 -212
- package/docs/agents/subagent-mode.md +0 -149
- package/docs/concepts/README.md +0 -47
- package/docs/concepts/jev-actionable-routing.md +0 -113
- package/docs/concepts/jev-decision-thresholds.md +0 -412
- package/docs/concepts/jev-efficiency.md +0 -217
- package/docs/concepts/jev-eval-2026-11-01.md +0 -78
- package/docs/concepts/limits.md +0 -52
- package/docs/concepts/memory.md +0 -10
- package/docs/concepts/security.md +0 -50
- package/docs/concepts/workspace-instructions.md +0 -29
- package/docs/getting-started/README.md +0 -82
- package/docs/getting-started/accounts.md +0 -78
- package/docs/getting-started/configure-providers.md +0 -132
- package/docs/guides/README.md +0 -13
- package/docs/guides/browser.md +0 -39
- package/docs/guides/desktop-app.md +0 -414
- package/docs/guides/extensions.md +0 -102
- package/docs/guides/graph-builder.md +0 -116
- package/docs/guides/headless.md +0 -46
- package/docs/guides/tui.md +0 -75
- package/docs/guides/update.md +0 -70
- package/docs/guides/web-search.md +0 -51
- package/docs/guides/windows-code-signing.md +0 -319
- package/docs/llms.txt +0 -45
- package/docs/reference/README.md +0 -7
- package/docs/reference/cli.md +0 -76
- package/docs/reference/config.md +0 -91
- package/docs/reference/slash-commands.md +0 -59
- package/docs/superpowers/plans/2026-11-01-claude-console-sign-in.md +0 -111
- package/docs/superpowers/plans/2026-11-01-jev-node-opt-in.md +0 -910
- package/docs/superpowers/plans/2026-11-02-workflow-pane.md +0 -398
- package/docs/superpowers/plans/2026-11-06-graph-soft-delete.md +0 -125
- package/docs/superpowers/plans/2026-11-09-orchestrator-delegation.md +0 -295
- package/docs/superpowers/plans/2026-11-13-graph-manager-chat.md +0 -203
- package/docs/superpowers/plans/2026-11-14-jev-fair-use-pricing.md +0 -79
- package/docs/superpowers/specs/2026-10-31-work-line-summary-design.md +0 -50
- package/docs/superpowers/specs/2026-11-01-claude-console-sign-in-design.md +0 -176
- package/docs/superpowers/specs/2026-11-01-jev-node-opt-in-design.md +0 -164
- package/docs/superpowers/specs/2026-11-01-pr-section-design.md +0 -111
- package/docs/superpowers/specs/2026-11-02-workflow-pane-design.md +0 -130
- package/docs/superpowers/specs/2026-11-06-bundled-skills-design.md +0 -206
- package/docs/superpowers/specs/2026-11-09-orchestrator-delegation-design.md +0 -291
- package/docs/superpowers/specs/2026-11-13-graph-manager-chat-design.md +0 -182
- package/docs/superpowers/specs/2026-11-14-jev-fair-use-pricing-design.md +0 -156
- package/scripts/jev-efficiency-eval.mjs +0 -187
- package/scripts/jev-efficiency-live.mjs +0 -193
- package/scripts/zcode-engine-replay.mjs +0 -223
- package/tests/agent-centric-mcp-test-plan.md +0 -208
- package/tests/analytics-settings-test-plan.md +0 -165
- package/tests/browser-cli-smoke.mjs +0 -276
- package/tests/browser-test-plan.md +0 -280
- package/tests/chat-side-panel-test-plan.md +0 -309
- package/tests/decision-engine-test-plan.md +0 -163
- package/tests/default-active-jev-test-plan.md +0 -85
- package/tests/harness-extensions-test-plan.md +0 -113
- package/tests/jev-all-decisions-test-plan.md +0 -156
- package/tests/jev-efficiency/criteria.json +0 -158
- package/tests/jev-efficiency/workloads.mjs +0 -242
- package/tests/jev-efficiency-test-plan.md +0 -198
- package/tests/permissions-sandbox-probe.mjs +0 -74
- package/tests/permissions-test-plan.md +0 -191
- package/tests/product-telemetry-test-plan.md +0 -536
- package/tests/thinking-stream-preview-test-plan.md +0 -136
- package/tests/zcode-react-engine-test-plan.md +0 -396
|
@@ -0,0 +1,584 @@
|
|
|
1
|
+
import { promisify } from 'node:util';
|
|
2
|
+
import { crc32, inflateRaw } from 'node:zlib';
|
|
3
|
+
import { headingBlock, joinBlocks, listBlock, rowBlock, tidyText } from './read-document-text.js';
|
|
4
|
+
/**
|
|
5
|
+
* Word `.docx` to plain text, without a dependency.
|
|
6
|
+
*
|
|
7
|
+
* A `.docx` is a ZIP of XML parts. Read needs one of them, `word/document.xml`, turned into text a
|
|
8
|
+
* model can follow: paragraphs, headings, list items and table rows. That is a small enough job
|
|
9
|
+
* that a ZIP central-directory reader and a pull tokenizer cover it, where a general OOXML library
|
|
10
|
+
* would add megabytes to every install for layout features Read throws away.
|
|
11
|
+
*
|
|
12
|
+
* The file is untrusted input. Sizes come from the archive itself, so every part is inflated under
|
|
13
|
+
* a hard budget; nothing here trusts a declared length, an offset or a nesting depth.
|
|
14
|
+
*/
|
|
15
|
+
/** Total XML one document may inflate to, across all the parts read from it. */
|
|
16
|
+
export const DOCX_INFLATE_LIMIT = 64 * 1024 * 1024;
|
|
17
|
+
/** Tables in cells in tables: beyond this depth the content is dropped rather than recursed into. */
|
|
18
|
+
const NESTING_LIMIT = 32;
|
|
19
|
+
const inflateRawAsync = promisify(inflateRaw);
|
|
20
|
+
const damaged = (reason) => new Error(`This .docx is damaged (${reason}), so Read cannot open it. Ask for the document to be exported again, or as PDF.`);
|
|
21
|
+
/**
|
|
22
|
+
* The archive's central directory, or undefined when the bytes are not a readable ZIP.
|
|
23
|
+
* ZIP64 is reported as `'zip64'`: a real `.docx` never needs it, and following 64-bit offsets is
|
|
24
|
+
* the kind of rarely exercised path a hostile archive is built to reach.
|
|
25
|
+
*/
|
|
26
|
+
function readZipDirectory(bytes) {
|
|
27
|
+
// The end record is the last thing in the file apart from an optional comment of at most 65535 bytes.
|
|
28
|
+
let end = -1;
|
|
29
|
+
for (let offset = bytes.length - 22, floor = Math.max(0, bytes.length - 22 - 0xffff); offset >= floor; offset--) {
|
|
30
|
+
if (bytes.readUInt32LE(offset) === 0x06054b50 && offset + 22 + bytes.readUInt16LE(offset + 20) <= bytes.length) {
|
|
31
|
+
end = offset;
|
|
32
|
+
break;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
if (end < 0)
|
|
36
|
+
return undefined;
|
|
37
|
+
const count = bytes.readUInt16LE(end + 10);
|
|
38
|
+
const directorySize = bytes.readUInt32LE(end + 12);
|
|
39
|
+
let offset = bytes.readUInt32LE(end + 16);
|
|
40
|
+
if (count === 0xffff || directorySize === 0xffffffff || offset === 0xffffffff)
|
|
41
|
+
return 'zip64';
|
|
42
|
+
const entries = new Map();
|
|
43
|
+
for (let index = 0; index < count; index++) {
|
|
44
|
+
if (offset + 46 > bytes.length || bytes.readUInt32LE(offset) !== 0x02014b50)
|
|
45
|
+
return undefined;
|
|
46
|
+
const nameLength = bytes.readUInt16LE(offset + 28);
|
|
47
|
+
const name = bytes.toString('utf8', offset + 46, offset + 46 + nameLength);
|
|
48
|
+
// The first entry for a name wins; a second one with the same name is how an archive shows
|
|
49
|
+
// one file to a scanner and another to the reader.
|
|
50
|
+
if (!entries.has(name)) {
|
|
51
|
+
entries.set(name, {
|
|
52
|
+
flags: bytes.readUInt16LE(offset + 8), method: bytes.readUInt16LE(offset + 10), crc: bytes.readUInt32LE(offset + 16),
|
|
53
|
+
compressedSize: bytes.readUInt32LE(offset + 20), size: bytes.readUInt32LE(offset + 24), headerOffset: bytes.readUInt32LE(offset + 42),
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
offset += 46 + nameLength + bytes.readUInt16LE(offset + 30) + bytes.readUInt16LE(offset + 32);
|
|
57
|
+
}
|
|
58
|
+
return entries;
|
|
59
|
+
}
|
|
60
|
+
/** Inflate one part, charging its size to the document's budget. */
|
|
61
|
+
async function readZipEntry(bytes, name, entry, budget) {
|
|
62
|
+
const tooLarge = () => new Error(`This .docx expands to more than ${DOCX_INFLATE_LIMIT / 1024 / 1024} MiB of XML, which Read will not load. Unzip it and extract the text you need with a script instead.`);
|
|
63
|
+
if (entry.flags & 1)
|
|
64
|
+
throw new Error('This .docx has password-protected (encrypted) contents, so Read cannot open it. Ask the user for an unprotected copy.');
|
|
65
|
+
if (entry.compressedSize === 0xffffffff || entry.size === 0xffffffff || entry.headerOffset === 0xffffffff) {
|
|
66
|
+
throw new Error('This .docx is a ZIP64 archive, which Read does not support. Unzip it and read word/document.xml with a script instead.');
|
|
67
|
+
}
|
|
68
|
+
if (entry.size > budget.remaining)
|
|
69
|
+
throw tooLarge();
|
|
70
|
+
const header = entry.headerOffset;
|
|
71
|
+
if (header + 30 > bytes.length || bytes.readUInt32LE(header) !== 0x04034b50)
|
|
72
|
+
throw damaged(`no file header for ${name}`);
|
|
73
|
+
const start = header + 30 + bytes.readUInt16LE(header + 26) + bytes.readUInt16LE(header + 28);
|
|
74
|
+
if (start + entry.compressedSize > bytes.length)
|
|
75
|
+
throw damaged(`${name} is cut short`);
|
|
76
|
+
const packed = bytes.subarray(start, start + entry.compressedSize);
|
|
77
|
+
let data;
|
|
78
|
+
if (entry.method === 0)
|
|
79
|
+
data = packed;
|
|
80
|
+
else if (entry.method === 8) {
|
|
81
|
+
try {
|
|
82
|
+
// The declared size is a claim; the output limit is what actually stops a zip bomb.
|
|
83
|
+
data = await inflateRawAsync(packed, { maxOutputLength: Math.max(budget.remaining, 1) });
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
if (error.code === 'ERR_BUFFER_TOO_LARGE')
|
|
87
|
+
throw tooLarge();
|
|
88
|
+
throw damaged(`${name} does not decompress`);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
else
|
|
92
|
+
throw damaged(`${name} uses unsupported compression method ${entry.method}`);
|
|
93
|
+
if (data.length > budget.remaining)
|
|
94
|
+
throw tooLarge();
|
|
95
|
+
if (crc32(data) !== entry.crc)
|
|
96
|
+
throw damaged(`${name} fails its checksum`);
|
|
97
|
+
budget.remaining -= data.length;
|
|
98
|
+
return data;
|
|
99
|
+
}
|
|
100
|
+
function decodeXmlBytes(data) {
|
|
101
|
+
// Parts are UTF-8 in practice; the package format also allows UTF-16 with a byte-order mark.
|
|
102
|
+
if (data[0] === 0xff && data[1] === 0xfe)
|
|
103
|
+
return data.toString('utf16le', 2);
|
|
104
|
+
if (data[0] === 0xfe && data[1] === 0xff)
|
|
105
|
+
return Buffer.from(data.subarray(2, 2 + ((data.length - 2) & ~1))).swap16().toString('utf16le');
|
|
106
|
+
return data.toString('utf8', data[0] === 0xef && data[1] === 0xbb && data[2] === 0xbf ? 3 : 0);
|
|
107
|
+
}
|
|
108
|
+
const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };
|
|
109
|
+
function decodeEntities(text) {
|
|
110
|
+
if (!text.includes('&'))
|
|
111
|
+
return text;
|
|
112
|
+
// Only the five predefined entities and character references: a document cannot define its own
|
|
113
|
+
// here, so there is nothing to expand recursively.
|
|
114
|
+
return text.replace(/&(#x[0-9a-fA-F]{1,6}|#[0-9]{1,7}|[a-z]+);/g, (whole, body) => {
|
|
115
|
+
if (body[0] !== '#')
|
|
116
|
+
return ENTITIES[body] ?? whole;
|
|
117
|
+
const code = body[1] === 'x' ? Number.parseInt(body.slice(2), 16) : Number.parseInt(body.slice(1), 10);
|
|
118
|
+
return code > 0 && code <= 0x10ffff && (code < 0xd800 || code > 0xdfff) ? String.fromCodePoint(code) : '';
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* A pull tokenizer rather than a tree: `document.xml` can be tens of megabytes, and a node per
|
|
123
|
+
* element would multiply that several times over in memory for a single pass that keeps only text.
|
|
124
|
+
*/
|
|
125
|
+
class XmlReader {
|
|
126
|
+
xml;
|
|
127
|
+
position = 0;
|
|
128
|
+
/**
|
|
129
|
+
* The prefix this part binds to the WordprocessingML namespace; element names are reported with
|
|
130
|
+
* `w:`. Empty when the part binds no prefix to it and uses it as the default namespace instead.
|
|
131
|
+
*/
|
|
132
|
+
prefix;
|
|
133
|
+
/** The part declares WordprocessingML as its default namespace, so unprefixed elements belong to it. */
|
|
134
|
+
defaulted;
|
|
135
|
+
constructor(xml) {
|
|
136
|
+
this.xml = xml;
|
|
137
|
+
const head = xml.slice(0, 16384);
|
|
138
|
+
const bound = /xmlns:([A-Za-z_][\w.-]*)\s*=\s*["'](?:http:\/\/schemas\.openxmlformats\.org\/wordprocessingml\/2006\/main|http:\/\/purl\.oclc\.org\/ooxml\/wordprocessingml\/main)["']/.exec(head);
|
|
139
|
+
// `<document xmlns="…/wordprocessingml/2006/main">` is as valid as `<w:document xmlns:w="…">`.
|
|
140
|
+
// Without this an unprefixed `body` was never recognized and a full document read as empty.
|
|
141
|
+
this.defaulted = /\sxmlns\s*=\s*["'](?:http:\/\/schemas\.openxmlformats\.org\/wordprocessingml\/2006\/main|http:\/\/purl\.oclc\.org\/ooxml\/wordprocessingml\/main)["']/.test(head);
|
|
142
|
+
this.prefix = bound?.[1] ?? (this.defaulted ? '' : 'w');
|
|
143
|
+
}
|
|
144
|
+
next() {
|
|
145
|
+
const xml = this.xml;
|
|
146
|
+
while (this.position < xml.length) {
|
|
147
|
+
const start = this.position;
|
|
148
|
+
if (xml.charCodeAt(start) !== 60 /* < */) {
|
|
149
|
+
const end = xml.indexOf('<', start);
|
|
150
|
+
this.position = end < 0 ? xml.length : end;
|
|
151
|
+
return { kind: 'text', name: '', attributes: '', selfClosing: false, text: decodeEntities(xml.slice(start, this.position)) };
|
|
152
|
+
}
|
|
153
|
+
if (xml.startsWith('<!--', start)) {
|
|
154
|
+
this.skipPast('-->', start + 4);
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
if (xml.startsWith('<![CDATA[', start)) {
|
|
158
|
+
const end = xml.indexOf(']]>', start + 9);
|
|
159
|
+
this.position = end < 0 ? xml.length : end + 3;
|
|
160
|
+
return { kind: 'text', name: '', attributes: '', selfClosing: false, text: xml.slice(start + 9, end < 0 ? xml.length : end) };
|
|
161
|
+
}
|
|
162
|
+
if (xml.startsWith('<?', start)) {
|
|
163
|
+
this.skipPast('?>', start + 2);
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
if (xml.startsWith('<!', start)) {
|
|
167
|
+
this.skipPast('>', start + 2);
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
// A quoted attribute value may contain '>', so the tag ends at the first '>' outside quotes.
|
|
171
|
+
let end = start + 1;
|
|
172
|
+
let quote = 0;
|
|
173
|
+
for (; end < xml.length; end++) {
|
|
174
|
+
const code = xml.charCodeAt(end);
|
|
175
|
+
if (quote) {
|
|
176
|
+
if (code === quote)
|
|
177
|
+
quote = 0;
|
|
178
|
+
}
|
|
179
|
+
else if (code === 34 || code === 39)
|
|
180
|
+
quote = code;
|
|
181
|
+
else if (code === 62)
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
this.position = Math.min(end + 1, xml.length);
|
|
185
|
+
const closing = xml.charCodeAt(start + 1) === 47 /* / */;
|
|
186
|
+
const selfClosing = !closing && xml.charCodeAt(end - 1) === 47;
|
|
187
|
+
const body = xml.slice(start + (closing ? 2 : 1), selfClosing ? end - 1 : end);
|
|
188
|
+
const space = body.search(/\s/);
|
|
189
|
+
const name = this.normalise(space < 0 ? body : body.slice(0, space));
|
|
190
|
+
return { kind: closing ? 'close' : 'open', name, attributes: space < 0 ? '' : body.slice(space), selfClosing, text: '' };
|
|
191
|
+
}
|
|
192
|
+
return undefined;
|
|
193
|
+
}
|
|
194
|
+
/** Skip to the matching close of an element whose open tag was just returned. */
|
|
195
|
+
skip(name) {
|
|
196
|
+
let depth = 1;
|
|
197
|
+
for (let token = this.next(); token; token = this.next()) {
|
|
198
|
+
if (token.name !== name)
|
|
199
|
+
continue;
|
|
200
|
+
if (token.kind === 'open' && !token.selfClosing)
|
|
201
|
+
depth++;
|
|
202
|
+
else if (token.kind === 'close' && --depth === 0)
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
skipPast(marker, from) {
|
|
207
|
+
const end = this.xml.indexOf(marker, from);
|
|
208
|
+
this.position = end < 0 ? this.xml.length : end + marker.length;
|
|
209
|
+
}
|
|
210
|
+
normalise(name) {
|
|
211
|
+
const colon = name.indexOf(':');
|
|
212
|
+
if (colon < 0)
|
|
213
|
+
return this.defaulted ? `w:${name}` : name;
|
|
214
|
+
if (this.prefix === 'w')
|
|
215
|
+
return name;
|
|
216
|
+
const prefix = name.slice(0, colon);
|
|
217
|
+
if (prefix === this.prefix)
|
|
218
|
+
return `w:${name.slice(colon + 1)}`;
|
|
219
|
+
// Whatever else this part calls `w` is not WordprocessingML and must not be mistaken for it.
|
|
220
|
+
return prefix === 'w' ? `other:${name.slice(colon + 1)}` : name;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
const attributePatterns = new Map();
|
|
224
|
+
/** An attribute by local name, whatever prefix the part uses for it. */
|
|
225
|
+
function attribute(token, localName) {
|
|
226
|
+
if (!token.attributes)
|
|
227
|
+
return undefined;
|
|
228
|
+
let pattern = attributePatterns.get(localName);
|
|
229
|
+
if (!pattern) {
|
|
230
|
+
pattern = new RegExp(`(?:^|[\\s:])${localName}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`);
|
|
231
|
+
attributePatterns.set(localName, pattern);
|
|
232
|
+
}
|
|
233
|
+
const match = pattern.exec(token.attributes);
|
|
234
|
+
return match ? decodeEntities(match[1] ?? match[2] ?? '') : undefined;
|
|
235
|
+
}
|
|
236
|
+
/** `styles.xml` reduced to what decides whether a paragraph is a heading or a list item. */
|
|
237
|
+
function readStyles(xml) {
|
|
238
|
+
const styles = new Map();
|
|
239
|
+
const reader = new XmlReader(xml);
|
|
240
|
+
for (let token = reader.next(); token; token = reader.next()) {
|
|
241
|
+
if (token.kind !== 'open' || token.name !== 'w:style' || token.selfClosing)
|
|
242
|
+
continue;
|
|
243
|
+
const id = attribute(token, 'styleId');
|
|
244
|
+
const style = {};
|
|
245
|
+
for (let inner = reader.next(); inner && !(inner.kind === 'close' && inner.name === 'w:style'); inner = reader.next()) {
|
|
246
|
+
if (inner.kind !== 'open')
|
|
247
|
+
continue;
|
|
248
|
+
if (inner.name === 'w:name')
|
|
249
|
+
style.name = attribute(inner, 'val');
|
|
250
|
+
else if (inner.name === 'w:basedOn')
|
|
251
|
+
style.basedOn = attribute(inner, 'val');
|
|
252
|
+
else if (inner.name === 'w:outlineLvl')
|
|
253
|
+
style.outline = Number(attribute(inner, 'val'));
|
|
254
|
+
else if (inner.name === 'w:numId')
|
|
255
|
+
style.numbered = attribute(inner, 'val') !== '0';
|
|
256
|
+
}
|
|
257
|
+
if (id !== undefined)
|
|
258
|
+
styles.set(id, style);
|
|
259
|
+
}
|
|
260
|
+
return styles;
|
|
261
|
+
}
|
|
262
|
+
/** External hyperlink targets by relationship id. */
|
|
263
|
+
function readRelationships(xml) {
|
|
264
|
+
const links = new Map();
|
|
265
|
+
const reader = new XmlReader(xml);
|
|
266
|
+
for (let token = reader.next(); token; token = reader.next()) {
|
|
267
|
+
if (token.kind !== 'open' || !/(?:^|:)Relationship$/.test(token.name))
|
|
268
|
+
continue;
|
|
269
|
+
const id = attribute(token, 'Id');
|
|
270
|
+
const target = attribute(token, 'Target');
|
|
271
|
+
if (id && target && attribute(token, 'Type')?.endsWith('/hyperlink') && attribute(token, 'TargetMode') === 'External')
|
|
272
|
+
links.set(id, target);
|
|
273
|
+
}
|
|
274
|
+
return links;
|
|
275
|
+
}
|
|
276
|
+
/** Subtrees that hold no document text, or text that must not be read as part of the document. */
|
|
277
|
+
const SKIPPED = new Set([
|
|
278
|
+
// The legacy rendering of a drawing: its text is already present in the mc:Choice branch.
|
|
279
|
+
'mc:Fallback',
|
|
280
|
+
// Tracked changes: the text as it reads once every change is accepted.
|
|
281
|
+
'w:del', 'w:moveFrom', 'w:pPrChange', 'w:rPrChange', 'w:tblPrChange', 'w:sectPrChange',
|
|
282
|
+
// Field instructions, binary payloads and properties.
|
|
283
|
+
'w:instrText', 'w:delText', 'w:delInstrText', 'w:fldData', 'w:binData', 'w:rPr', 'w:sectPr',
|
|
284
|
+
'w:tblPr', 'w:tblGrid', 'w:tblPrEx', 'w:trPr', 'w:tcPr', 'w:sdtPr', 'w:sdtEndPr',
|
|
285
|
+
]);
|
|
286
|
+
class DocxConverter {
|
|
287
|
+
reader;
|
|
288
|
+
styles;
|
|
289
|
+
links;
|
|
290
|
+
counts = { footnotes: 0, endnotes: 0, comments: 0, drawings: 0, equations: 0 };
|
|
291
|
+
constructor(reader, styles, links) {
|
|
292
|
+
this.reader = reader;
|
|
293
|
+
this.styles = styles;
|
|
294
|
+
this.links = links;
|
|
295
|
+
}
|
|
296
|
+
convert() {
|
|
297
|
+
const blocks = [];
|
|
298
|
+
for (let token = this.reader.next(); token; token = this.reader.next()) {
|
|
299
|
+
if (token.kind === 'open' && token.name === 'w:body' && !token.selfClosing) {
|
|
300
|
+
this.readBlocks('w:body', blocks, 0, false);
|
|
301
|
+
break;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return blocks;
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Paragraphs and tables up to the close of `container`. Anything else at this level (content
|
|
308
|
+
* controls, custom XML, tracked insertions) is a wrapper, so the loop simply reads through it.
|
|
309
|
+
*/
|
|
310
|
+
readBlocks(container, out, depth, inCell) {
|
|
311
|
+
for (let token = this.reader.next(); token; token = this.reader.next()) {
|
|
312
|
+
if (token.kind === 'close') {
|
|
313
|
+
if (token.name === container)
|
|
314
|
+
return;
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
if (token.kind !== 'open' || token.selfClosing)
|
|
318
|
+
continue;
|
|
319
|
+
if (SKIPPED.has(token.name) || depth > NESTING_LIMIT)
|
|
320
|
+
this.reader.skip(token.name);
|
|
321
|
+
else if (token.name === 'w:p')
|
|
322
|
+
this.readParagraph(out, depth, inCell);
|
|
323
|
+
else if (token.name === 'w:tbl')
|
|
324
|
+
this.readTable(out, depth);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
readTable(out, depth) {
|
|
328
|
+
let cells;
|
|
329
|
+
for (let token = this.reader.next(); token; token = this.reader.next()) {
|
|
330
|
+
if (token.kind === 'close') {
|
|
331
|
+
if (token.name === 'w:tbl')
|
|
332
|
+
return;
|
|
333
|
+
if (token.name === 'w:tr' && cells) {
|
|
334
|
+
const row = rowBlock(cells);
|
|
335
|
+
if (row)
|
|
336
|
+
out.push(row);
|
|
337
|
+
cells = undefined;
|
|
338
|
+
}
|
|
339
|
+
continue;
|
|
340
|
+
}
|
|
341
|
+
if (token.kind !== 'open' || token.selfClosing)
|
|
342
|
+
continue;
|
|
343
|
+
if (SKIPPED.has(token.name))
|
|
344
|
+
this.reader.skip(token.name);
|
|
345
|
+
else if (token.name === 'w:tr')
|
|
346
|
+
cells = [];
|
|
347
|
+
else if (token.name === 'w:tc' && cells) {
|
|
348
|
+
const content = [];
|
|
349
|
+
this.readBlocks('w:tc', content, depth + 1, true);
|
|
350
|
+
cells.push(content.map(block => block.text).join(' '));
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
readParagraph(out, depth, inCell) {
|
|
355
|
+
let text = '';
|
|
356
|
+
let style;
|
|
357
|
+
let outline;
|
|
358
|
+
// Undefined until the paragraph says so itself; numbering id 0 is how a paragraph opts out of its style's list.
|
|
359
|
+
let numbered;
|
|
360
|
+
let level = 0;
|
|
361
|
+
// Text boxes are anchored inside a run; their paragraphs follow the one that anchors them.
|
|
362
|
+
const anchored = [];
|
|
363
|
+
const openLinks = [];
|
|
364
|
+
const reader = this.reader;
|
|
365
|
+
for (let token = reader.next(); token; token = reader.next()) {
|
|
366
|
+
if (token.kind === 'text')
|
|
367
|
+
continue;
|
|
368
|
+
if (token.kind === 'close') {
|
|
369
|
+
if (token.name === 'w:p')
|
|
370
|
+
break;
|
|
371
|
+
if (token.name === 'w:hyperlink') {
|
|
372
|
+
const link = openLinks.pop();
|
|
373
|
+
const label = link ? text.slice(link.start) : '';
|
|
374
|
+
if (link?.url && label.trim() && !label.includes('\f'))
|
|
375
|
+
text = text.slice(0, link.start) + (label.trim() === link.url ? link.url : `[${label}](${link.url})`);
|
|
376
|
+
}
|
|
377
|
+
continue;
|
|
378
|
+
}
|
|
379
|
+
switch (token.name) {
|
|
380
|
+
case 'w:pPr':
|
|
381
|
+
if (token.selfClosing)
|
|
382
|
+
break;
|
|
383
|
+
for (let inner = reader.next(); inner && !(inner.kind === 'close' && inner.name === 'w:pPr'); inner = reader.next()) {
|
|
384
|
+
if (inner.kind !== 'open')
|
|
385
|
+
continue;
|
|
386
|
+
if (inner.name === 'w:pStyle')
|
|
387
|
+
style = attribute(inner, 'val');
|
|
388
|
+
else if (inner.name === 'w:outlineLvl')
|
|
389
|
+
outline = Number(attribute(inner, 'val'));
|
|
390
|
+
else if (inner.name === 'w:numId')
|
|
391
|
+
numbered = attribute(inner, 'val') !== '0';
|
|
392
|
+
else if (inner.name === 'w:ilvl')
|
|
393
|
+
level = Number(attribute(inner, 'val')) || 0;
|
|
394
|
+
else if (!inner.selfClosing && SKIPPED.has(inner.name))
|
|
395
|
+
reader.skip(inner.name);
|
|
396
|
+
}
|
|
397
|
+
break;
|
|
398
|
+
case 'w:t':
|
|
399
|
+
case 'm:t':
|
|
400
|
+
if (token.selfClosing)
|
|
401
|
+
break;
|
|
402
|
+
for (let inner = reader.next(); inner && inner.kind !== 'close'; inner = reader.next())
|
|
403
|
+
if (inner.kind === 'text')
|
|
404
|
+
text += inner.text;
|
|
405
|
+
break;
|
|
406
|
+
case 'w:tab':
|
|
407
|
+
case 'w:ptab':
|
|
408
|
+
text += '\t';
|
|
409
|
+
break;
|
|
410
|
+
// A form feed stands in for a forced page break until the paragraph is split below.
|
|
411
|
+
case 'w:br':
|
|
412
|
+
text += attribute(token, 'type') === 'page' ? '\f' : '\n';
|
|
413
|
+
break;
|
|
414
|
+
case 'w:cr':
|
|
415
|
+
text += '\n';
|
|
416
|
+
break;
|
|
417
|
+
case 'w:noBreakHyphen':
|
|
418
|
+
text += '-';
|
|
419
|
+
break;
|
|
420
|
+
case 'w:footnoteReference':
|
|
421
|
+
this.counts.footnotes++;
|
|
422
|
+
break;
|
|
423
|
+
case 'w:endnoteReference':
|
|
424
|
+
this.counts.endnotes++;
|
|
425
|
+
break;
|
|
426
|
+
case 'w:commentReference':
|
|
427
|
+
this.counts.comments++;
|
|
428
|
+
break;
|
|
429
|
+
case 'w:drawing':
|
|
430
|
+
case 'w:pict':
|
|
431
|
+
case 'w:object':
|
|
432
|
+
this.counts.drawings++;
|
|
433
|
+
break;
|
|
434
|
+
case 'm:oMath':
|
|
435
|
+
if (!token.selfClosing)
|
|
436
|
+
this.counts.equations++;
|
|
437
|
+
break;
|
|
438
|
+
case 'w:hyperlink':
|
|
439
|
+
if (!token.selfClosing)
|
|
440
|
+
openLinks.push({ start: text.length, url: this.links.get(attribute(token, 'id') ?? '') });
|
|
441
|
+
break;
|
|
442
|
+
case 'w:txbxContent':
|
|
443
|
+
if (token.selfClosing)
|
|
444
|
+
break;
|
|
445
|
+
if (depth >= NESTING_LIMIT)
|
|
446
|
+
reader.skip(token.name);
|
|
447
|
+
else
|
|
448
|
+
this.readBlocks('w:txbxContent', anchored, depth + 1, inCell);
|
|
449
|
+
break;
|
|
450
|
+
default:
|
|
451
|
+
if (!token.selfClosing && SKIPPED.has(token.name))
|
|
452
|
+
reader.skip(token.name);
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
const heading = inCell ? undefined : this.headingLevel(style, outline);
|
|
456
|
+
const listItem = heading === undefined && (numbered ?? this.inheritsNumbering(style));
|
|
457
|
+
text.split('\f').forEach((part, index) => {
|
|
458
|
+
if (index > 0)
|
|
459
|
+
out.push({ kind: 'break', text: '' });
|
|
460
|
+
const clean = tidyText(part);
|
|
461
|
+
if (!clean)
|
|
462
|
+
return;
|
|
463
|
+
if (heading !== undefined)
|
|
464
|
+
out.push(headingBlock(heading, clean.replace(/\s*\n\s*/g, ' ')));
|
|
465
|
+
else
|
|
466
|
+
out.push(listItem ? listBlock(level, clean) : { kind: 'paragraph', text: clean });
|
|
467
|
+
});
|
|
468
|
+
out.push(...anchored);
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* Heading level from the paragraph's own outline level, else from its style. The style's *name*
|
|
472
|
+
* is the stable signal: ids are localised ("berschrift1", "Titre1", "1") while Word keeps the
|
|
473
|
+
* built-in names "heading 1".."heading 9" in every language.
|
|
474
|
+
*/
|
|
475
|
+
headingLevel(styleId, outline) {
|
|
476
|
+
if (outline !== undefined && outline >= 0 && outline < 9)
|
|
477
|
+
return outline + 1;
|
|
478
|
+
for (let id = styleId, hops = 0; id !== undefined && hops < 16; hops++) {
|
|
479
|
+
const style = this.styles.get(id);
|
|
480
|
+
const named = /^heading\s*([1-9])$/i.exec(style?.name ?? id);
|
|
481
|
+
if (named)
|
|
482
|
+
return Number(named[1]);
|
|
483
|
+
if (/^title$/i.test(style?.name ?? id))
|
|
484
|
+
return 1;
|
|
485
|
+
if (style?.outline !== undefined && style.outline >= 0 && style.outline < 9)
|
|
486
|
+
return style.outline + 1;
|
|
487
|
+
id = style?.basedOn;
|
|
488
|
+
}
|
|
489
|
+
return undefined;
|
|
490
|
+
}
|
|
491
|
+
inheritsNumbering(styleId) {
|
|
492
|
+
for (let id = styleId, hops = 0; id !== undefined && hops < 16; hops++) {
|
|
493
|
+
const style = this.styles.get(id);
|
|
494
|
+
if (style?.numbered !== undefined)
|
|
495
|
+
return style.numbered;
|
|
496
|
+
id = style?.basedOn;
|
|
497
|
+
}
|
|
498
|
+
return false;
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
/** Content types of a main document part: documents and templates, with or without macros. */
|
|
502
|
+
const MAIN_PART_TYPE = /^application\/vnd\.(?:openxmlformats-officedocument\.wordprocessingml\.(?:document|template)|ms-word\.(?:document|template)\.macroEnabled(?:Template)?)\.main\+xml$/;
|
|
503
|
+
const plural = (count, noun) => `${count} ${noun}${count === 1 ? '' : 's'}`;
|
|
504
|
+
/**
|
|
505
|
+
* Text of a `.docx`, or undefined when the ZIP is not a Word document (a `.xlsx`, a `.jar`, any
|
|
506
|
+
* other archive), so the caller can report it as the binary file it is.
|
|
507
|
+
*/
|
|
508
|
+
export async function extractDocx(bytes, signal) {
|
|
509
|
+
const directory = readZipDirectory(bytes);
|
|
510
|
+
// Entry names are stored uncompressed, so even an unreadable archive shows whether it was a Word document.
|
|
511
|
+
const namesDocument = () => bytes.includes('word/document.xml');
|
|
512
|
+
if (directory === 'zip64') {
|
|
513
|
+
if (namesDocument())
|
|
514
|
+
throw new Error('This .docx is a ZIP64 archive, which Read does not support. Unzip it and read word/document.xml with a script instead.');
|
|
515
|
+
return undefined;
|
|
516
|
+
}
|
|
517
|
+
if (!directory) {
|
|
518
|
+
if (namesDocument())
|
|
519
|
+
throw damaged('the ZIP directory is missing or cut short');
|
|
520
|
+
return undefined;
|
|
521
|
+
}
|
|
522
|
+
const budget = { remaining: DOCX_INFLATE_LIMIT };
|
|
523
|
+
const part = async (name) => {
|
|
524
|
+
const entry = directory.get(name);
|
|
525
|
+
return entry ? decodeXmlBytes(await readZipEntry(bytes, name, entry, budget)) : undefined;
|
|
526
|
+
};
|
|
527
|
+
// Supporting parts only refine the output, so one that cannot be read is ignored, not fatal.
|
|
528
|
+
const optionalPart = async (name) => { try {
|
|
529
|
+
return await part(name);
|
|
530
|
+
}
|
|
531
|
+
catch {
|
|
532
|
+
return undefined;
|
|
533
|
+
} };
|
|
534
|
+
// The package's content types name the main part; Word writes word/document.xml, other producers need not.
|
|
535
|
+
let main = 'word/document.xml';
|
|
536
|
+
const types = await optionalPart('[Content_Types].xml');
|
|
537
|
+
if (types) {
|
|
538
|
+
const reader = new XmlReader(types);
|
|
539
|
+
for (let token = reader.next(); token; token = reader.next()) {
|
|
540
|
+
if (token.kind !== 'open' || !/(?:^|:)Override$/.test(token.name) || !MAIN_PART_TYPE.test(attribute(token, 'ContentType') ?? ''))
|
|
541
|
+
continue;
|
|
542
|
+
const name = attribute(token, 'PartName')?.replace(/^\//, '');
|
|
543
|
+
if (name && directory.has(name)) {
|
|
544
|
+
main = name;
|
|
545
|
+
break;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
if (!directory.has(main))
|
|
550
|
+
return undefined;
|
|
551
|
+
signal?.throwIfAborted();
|
|
552
|
+
const xml = await part(main);
|
|
553
|
+
signal?.throwIfAborted();
|
|
554
|
+
const slash = main.lastIndexOf('/');
|
|
555
|
+
const folder = main.slice(0, slash + 1);
|
|
556
|
+
const styles = await optionalPart(`${folder}styles.xml`);
|
|
557
|
+
const relationships = await optionalPart(`${folder}_rels/${main.slice(slash + 1)}.rels`);
|
|
558
|
+
const converter = new DocxConverter(new XmlReader(xml ?? ''), styles ? readStyles(styles) : new Map(), relationships ? readRelationships(relationships) : new Map());
|
|
559
|
+
const text = joinBlocks(converter.convert());
|
|
560
|
+
signal?.throwIfAborted();
|
|
561
|
+
const notes = [];
|
|
562
|
+
const { counts } = converter;
|
|
563
|
+
if (counts.footnotes)
|
|
564
|
+
notes.push(`${plural(counts.footnotes, 'footnote')} not included`);
|
|
565
|
+
if (counts.endnotes)
|
|
566
|
+
notes.push(`${plural(counts.endnotes, 'endnote')} not included`);
|
|
567
|
+
if (counts.comments)
|
|
568
|
+
notes.push(`${plural(counts.comments, 'review comment')} not included`);
|
|
569
|
+
let margins = false;
|
|
570
|
+
for (const name of directory.keys()) {
|
|
571
|
+
if (margins || !name.startsWith(folder) || !/^(?:header|footer)\d*\.xml$/.test(name.slice(folder.length)))
|
|
572
|
+
continue;
|
|
573
|
+
margins = /<w:t(?:\s[^>]*)?>[^<]*[^<\s]/.test(await optionalPart(name) ?? '');
|
|
574
|
+
}
|
|
575
|
+
if (margins)
|
|
576
|
+
notes.push('page headers and footers not included');
|
|
577
|
+
if (counts.drawings)
|
|
578
|
+
notes.push(`${plural(counts.drawings, 'embedded image or drawing')} not shown`);
|
|
579
|
+
if (counts.equations)
|
|
580
|
+
notes.push(`${plural(counts.equations, 'equation')} flattened to plain text`);
|
|
581
|
+
if (!text)
|
|
582
|
+
notes.push('the document contains no text');
|
|
583
|
+
return { text, notes };
|
|
584
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Text plumbing shared by the document readers behind Read.
|
|
3
|
+
*
|
|
4
|
+
* The Word readers (`read-document-docx.ts`, `read-document-doc.ts`) both reduce a document to the
|
|
5
|
+
* same few block shapes, and both the legacy `.doc` reader and the non-UTF-8 text path need
|
|
6
|
+
* Windows-1252. Keeping those here stops the two Word formats drifting apart in how a paragraph,
|
|
7
|
+
* a list item or a table row reads to the model.
|
|
8
|
+
*/
|
|
9
|
+
/** One UTF-16 code unit per input byte, which the `.doc` reader relies on to index text by character position. */
|
|
10
|
+
export declare function decodeWindows1252(bytes: Uint8Array): string;
|
|
11
|
+
/** The marker both Word readers print where the author forced a new page. */
|
|
12
|
+
export declare const PAGE_BREAK_LINE = "--- page break ---";
|
|
13
|
+
/**
|
|
14
|
+
* `list` and `row` blocks sit on consecutive lines; everything else is separated by a blank line.
|
|
15
|
+
* `break` is an explicit page break and carries no text of its own.
|
|
16
|
+
*/
|
|
17
|
+
export interface DocumentBlock {
|
|
18
|
+
kind: 'paragraph' | 'list' | 'row' | 'break';
|
|
19
|
+
text: string;
|
|
20
|
+
}
|
|
21
|
+
export declare function headingBlock(level: number, text: string): DocumentBlock;
|
|
22
|
+
export declare function listBlock(level: number, text: string): DocumentBlock;
|
|
23
|
+
/** A table row on one line. Cell text is flattened because a line break inside a cell would split the row. */
|
|
24
|
+
export declare function rowBlock(cells: string[]): DocumentBlock | undefined;
|
|
25
|
+
/** Trailing whitespace per line and blank lines at either end carry nothing for a reader. */
|
|
26
|
+
export declare function tidyText(text: string): string;
|
|
27
|
+
export declare function joinBlocks(blocks: DocumentBlock[]): string;
|
|
28
|
+
/** "2, 5-7" for a sorted list of page numbers, so a note about many pages stays one short line. */
|
|
29
|
+
export declare function formatRanges(numbers: number[]): string;
|