@andorra-labs/code 0.1.10 → 0.1.12

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.
Files changed (238) hide show
  1. package/README.md +31 -205
  2. package/THIRD_PARTY_NOTICES.md +30 -0
  3. package/dist/src/agent-execution.js +50 -2
  4. package/dist/src/agent-mcp.js +5 -0
  5. package/dist/src/app-server/protocol.d.ts +9 -1
  6. package/dist/src/app-server/protocol.js +1 -1
  7. package/dist/src/app-server.d.ts +49 -1
  8. package/dist/src/app-server.js +353 -64
  9. package/dist/src/automation-service.js +1 -1
  10. package/dist/src/browser-panel-tool.d.ts +24 -3
  11. package/dist/src/browser-panel-tool.js +80 -6
  12. package/dist/src/browser-runner.js +3 -1
  13. package/dist/src/browser-session.d.ts +8 -0
  14. package/dist/src/browser-session.js +27 -1
  15. package/dist/src/browser-ui/app.js +237 -15
  16. package/dist/src/browser-ui/index.html +5 -5
  17. package/dist/src/browser-ui/style.css +110 -65
  18. package/dist/src/browser-ui/tokens.css +27 -26
  19. package/dist/src/browser-view.d.ts +16 -0
  20. package/dist/src/browser-view.js +38 -2
  21. package/dist/src/claude-provider.js +15 -2
  22. package/dist/src/cli.d.ts +2 -1
  23. package/dist/src/cli.js +175 -43
  24. package/dist/src/code-intelligence/CodeIntelligenceManager.js +1 -1
  25. package/dist/src/codex-provider.js +6 -3
  26. package/dist/src/coding-tools.d.ts +26 -1
  27. package/dist/src/coding-tools.js +104 -33
  28. package/dist/src/command-screens.js +1 -1
  29. package/dist/src/commands.js +1 -1
  30. package/dist/src/completion-gates.d.ts +42 -7
  31. package/dist/src/completion-gates.js +55 -9
  32. package/dist/src/completion.d.ts +51 -1
  33. package/dist/src/completion.js +164 -5
  34. package/dist/src/config.d.ts +1 -0
  35. package/dist/src/config.js +2 -0
  36. package/dist/src/dashboard-view.js +2 -2
  37. package/dist/src/deadline.js +4 -0
  38. package/dist/src/decision/PreparedSteps.js +1 -1
  39. package/dist/src/delegation-changes.js +19 -2
  40. package/dist/src/diff-preview.d.ts +1 -0
  41. package/dist/src/diff-preview.js +12 -3
  42. package/dist/src/engine-streams.d.ts +22 -0
  43. package/dist/src/engine-streams.js +16 -0
  44. package/dist/src/extensions.js +17 -6
  45. package/dist/src/file-read-key.d.ts +8 -0
  46. package/dist/src/file-read-key.js +12 -0
  47. package/dist/src/graph-editor-session.js +2 -1
  48. package/dist/src/graph-health.d.ts +21 -0
  49. package/dist/src/graph-health.js +46 -0
  50. package/dist/src/graph-manager-chat.d.ts +52 -3
  51. package/dist/src/graph-manager-chat.js +62 -17
  52. package/dist/src/graph-runner.js +62 -5
  53. package/dist/src/graph-server.d.ts +1 -1
  54. package/dist/src/graph-server.js +48 -27
  55. package/dist/src/graph-sync.d.ts +8 -0
  56. package/dist/src/graph-sync.js +54 -3
  57. package/dist/src/graph-tool.js +1 -1
  58. package/dist/src/graph-ui/app.js +362 -123
  59. package/dist/src/graph-ui/controls.css +95 -22
  60. package/dist/src/graph-ui/controls.js +31 -1
  61. package/dist/src/graph-ui/embed.js +62 -13
  62. package/dist/src/graph-ui/icons.js +7 -0
  63. package/dist/src/graph-ui/index.html +4 -4
  64. package/dist/src/graph-ui/manager-state.js +143 -5
  65. package/dist/src/graph-ui/manager.css +21 -20
  66. package/dist/src/graph-ui/manager.js +337 -75
  67. package/dist/src/graph-ui/model-picker.js +279 -0
  68. package/dist/src/graph-ui/provider-glyphs/alibaba-cloud.png +0 -0
  69. package/dist/src/graph-ui/provider-glyphs/anthropic.png +0 -0
  70. package/dist/src/graph-ui/provider-glyphs/aws-bedrock.png +0 -0
  71. package/dist/src/graph-ui/provider-glyphs/claude.png +0 -0
  72. package/dist/src/graph-ui/provider-glyphs/deepseek.png +0 -0
  73. package/dist/src/graph-ui/provider-glyphs/fireworks.png +0 -0
  74. package/dist/src/graph-ui/provider-glyphs/kimi.png +0 -0
  75. package/dist/src/graph-ui/provider-glyphs/minimax.png +0 -0
  76. package/dist/src/graph-ui/provider-glyphs/openai.png +0 -0
  77. package/dist/src/graph-ui/provider-glyphs/opencode.png +0 -0
  78. package/dist/src/graph-ui/provider-glyphs/openrouter.png +0 -0
  79. package/dist/src/graph-ui/provider-glyphs/xai.png +0 -0
  80. package/dist/src/graph-ui/provider-glyphs/xiaomi-mimo.png +0 -0
  81. package/dist/src/graph-ui/provider-glyphs/zai.png +0 -0
  82. package/dist/src/graph-ui/skill-picker.js +1 -1
  83. package/dist/src/graph-ui/studio-canvas.js +8 -8
  84. package/dist/src/graph-ui/studio.css +18 -15
  85. package/dist/src/graph-ui/studio.js +92 -35
  86. package/dist/src/graph-ui/style.css +122 -79
  87. package/dist/src/graph-ui/theme.js +2 -2
  88. package/dist/src/graph-ui/tokens.css +33 -29
  89. package/dist/src/graphs.d.ts +5 -2
  90. package/dist/src/graphs.js +10 -9
  91. package/dist/src/mcp.d.ts +52 -14
  92. package/dist/src/mcp.js +285 -128
  93. package/dist/src/membership-errors.d.ts +7 -1
  94. package/dist/src/membership-errors.js +9 -3
  95. package/dist/src/memory/ProjectMemory.d.ts +77 -0
  96. package/dist/src/memory/ProjectMemory.js +310 -0
  97. package/dist/src/memory/index.d.ts +1 -0
  98. package/dist/src/memory/index.js +1 -0
  99. package/dist/src/opencode-provider.js +5 -6
  100. package/dist/src/package-name.d.ts +3 -0
  101. package/dist/src/package-name.js +3 -0
  102. package/dist/src/provider-engine.js +2 -2
  103. package/dist/src/pull-requests.d.ts +42 -6
  104. package/dist/src/pull-requests.js +11 -3
  105. package/dist/src/qa/runtime/PtyManager.js +2 -1
  106. package/dist/src/react-runtime.js +137 -22
  107. package/dist/src/read-document-doc.d.ts +20 -0
  108. package/dist/src/read-document-doc.js +524 -0
  109. package/dist/src/read-document-docx.d.ts +21 -0
  110. package/dist/src/read-document-docx.js +584 -0
  111. package/dist/src/read-document-text.d.ts +29 -0
  112. package/dist/src/read-document-text.js +67 -0
  113. package/dist/src/read-document-tool.d.ts +48 -0
  114. package/dist/src/read-document-tool.js +162 -0
  115. package/dist/src/read-document.d.ts +78 -0
  116. package/dist/src/read-document.js +353 -0
  117. package/dist/src/read-image.d.ts +29 -2
  118. package/dist/src/read-image.js +42 -17
  119. package/dist/src/remote/cert.d.ts +1 -1
  120. package/dist/src/remote/cert.js +2 -7
  121. package/dist/src/remote/client.js +1 -1
  122. package/dist/src/remote/pem.d.ts +6 -0
  123. package/dist/src/remote/pem.js +11 -0
  124. package/dist/src/run-records.js +49 -10
  125. package/dist/src/runtime.d.ts +21 -0
  126. package/dist/src/runtime.js +10 -1
  127. package/dist/src/session-changes.d.ts +6 -1
  128. package/dist/src/session-changes.js +13 -5
  129. package/dist/src/sessions.d.ts +3 -1
  130. package/dist/src/sessions.js +5 -3
  131. package/dist/src/side-panel.d.ts +6 -1
  132. package/dist/src/side-panel.js +12 -10
  133. package/dist/src/sign-in-detection.d.ts +82 -0
  134. package/dist/src/sign-in-detection.js +197 -0
  135. package/dist/src/sign-in-offer.d.ts +35 -0
  136. package/dist/src/sign-in-offer.js +116 -0
  137. package/dist/src/skills/bundled/create-skill/SKILL.md +1 -1
  138. package/dist/src/skills/bundled/diagram/SKILL.md +1 -1
  139. package/dist/src/skills/bundled/graph-manager/SKILL.md +59 -7
  140. package/dist/src/skills/bundled/graph-manager/patterns.md +27 -0
  141. package/dist/src/skills/bundled/provenance.json +4 -4
  142. package/dist/src/skills/runtime-skills.d.ts +6 -0
  143. package/dist/src/skills/runtime-skills.js +16 -3
  144. package/dist/src/stall-recovery.d.ts +6 -2
  145. package/dist/src/stall-recovery.js +7 -2
  146. package/dist/src/stray-files.d.ts +14 -0
  147. package/dist/src/stray-files.js +81 -0
  148. package/dist/src/subagent-run.js +6 -1
  149. package/dist/src/terminal-ui.d.ts +1 -1
  150. package/dist/src/terminal-ui.js +11 -5
  151. package/dist/src/time-limit.d.ts +53 -0
  152. package/dist/src/time-limit.js +79 -0
  153. package/dist/src/tool-activity.js +1 -1
  154. package/dist/src/tool-schema-compatibility.d.ts +7 -2
  155. package/dist/src/tool-schema-compatibility.js +8 -4
  156. package/dist/src/tools.js +92 -7
  157. package/dist/src/transcript.d.ts +5 -0
  158. package/dist/src/transcript.js +12 -4
  159. package/dist/src/types.d.ts +8 -0
  160. package/dist/src/untracked-file-removal.d.ts +3 -0
  161. package/dist/src/untracked-file-removal.js +125 -0
  162. package/dist/src/update-check.js +1 -1
  163. package/dist/src/update.d.ts +11 -1
  164. package/dist/src/update.js +27 -5
  165. package/dist/src/usage-analytics.d.ts +3 -1
  166. package/dist/src/usage-analytics.js +16 -2
  167. package/dist/src/workspace-git-metadata.d.ts +15 -0
  168. package/dist/src/workspace-git-metadata.js +50 -1
  169. package/dist/src/workspace-instructions.js +1 -1
  170. package/package.json +6 -26
  171. package/docs/README.md +0 -36
  172. package/docs/agents/README.md +0 -62
  173. package/docs/agents/install-for-agents.md +0 -56
  174. package/docs/agents/mcp-server.md +0 -212
  175. package/docs/agents/subagent-mode.md +0 -149
  176. package/docs/concepts/README.md +0 -47
  177. package/docs/concepts/jev-actionable-routing.md +0 -113
  178. package/docs/concepts/jev-decision-thresholds.md +0 -412
  179. package/docs/concepts/jev-efficiency.md +0 -217
  180. package/docs/concepts/jev-eval-2026-11-01.md +0 -78
  181. package/docs/concepts/limits.md +0 -52
  182. package/docs/concepts/memory.md +0 -10
  183. package/docs/concepts/security.md +0 -50
  184. package/docs/concepts/workspace-instructions.md +0 -29
  185. package/docs/getting-started/README.md +0 -82
  186. package/docs/getting-started/accounts.md +0 -78
  187. package/docs/getting-started/configure-providers.md +0 -132
  188. package/docs/guides/README.md +0 -13
  189. package/docs/guides/browser.md +0 -39
  190. package/docs/guides/desktop-app.md +0 -414
  191. package/docs/guides/extensions.md +0 -102
  192. package/docs/guides/graph-builder.md +0 -116
  193. package/docs/guides/headless.md +0 -46
  194. package/docs/guides/tui.md +0 -75
  195. package/docs/guides/update.md +0 -70
  196. package/docs/guides/web-search.md +0 -51
  197. package/docs/guides/windows-code-signing.md +0 -319
  198. package/docs/llms.txt +0 -45
  199. package/docs/reference/README.md +0 -7
  200. package/docs/reference/cli.md +0 -76
  201. package/docs/reference/config.md +0 -91
  202. package/docs/reference/slash-commands.md +0 -59
  203. package/docs/superpowers/plans/2026-11-01-claude-console-sign-in.md +0 -111
  204. package/docs/superpowers/plans/2026-11-01-jev-node-opt-in.md +0 -910
  205. package/docs/superpowers/plans/2026-11-02-workflow-pane.md +0 -398
  206. package/docs/superpowers/plans/2026-11-06-graph-soft-delete.md +0 -125
  207. package/docs/superpowers/plans/2026-11-09-orchestrator-delegation.md +0 -295
  208. package/docs/superpowers/plans/2026-11-13-graph-manager-chat.md +0 -203
  209. package/docs/superpowers/plans/2026-11-14-jev-fair-use-pricing.md +0 -79
  210. package/docs/superpowers/specs/2026-10-31-work-line-summary-design.md +0 -50
  211. package/docs/superpowers/specs/2026-11-01-claude-console-sign-in-design.md +0 -176
  212. package/docs/superpowers/specs/2026-11-01-jev-node-opt-in-design.md +0 -164
  213. package/docs/superpowers/specs/2026-11-01-pr-section-design.md +0 -111
  214. package/docs/superpowers/specs/2026-11-02-workflow-pane-design.md +0 -130
  215. package/docs/superpowers/specs/2026-11-06-bundled-skills-design.md +0 -206
  216. package/docs/superpowers/specs/2026-11-09-orchestrator-delegation-design.md +0 -291
  217. package/docs/superpowers/specs/2026-11-13-graph-manager-chat-design.md +0 -182
  218. package/docs/superpowers/specs/2026-11-14-jev-fair-use-pricing-design.md +0 -156
  219. package/scripts/jev-efficiency-eval.mjs +0 -187
  220. package/scripts/jev-efficiency-live.mjs +0 -193
  221. package/scripts/zcode-engine-replay.mjs +0 -223
  222. package/tests/agent-centric-mcp-test-plan.md +0 -208
  223. package/tests/analytics-settings-test-plan.md +0 -165
  224. package/tests/browser-cli-smoke.mjs +0 -276
  225. package/tests/browser-test-plan.md +0 -280
  226. package/tests/chat-side-panel-test-plan.md +0 -309
  227. package/tests/decision-engine-test-plan.md +0 -163
  228. package/tests/default-active-jev-test-plan.md +0 -85
  229. package/tests/harness-extensions-test-plan.md +0 -113
  230. package/tests/jev-all-decisions-test-plan.md +0 -156
  231. package/tests/jev-efficiency/criteria.json +0 -158
  232. package/tests/jev-efficiency/workloads.mjs +0 -242
  233. package/tests/jev-efficiency-test-plan.md +0 -198
  234. package/tests/permissions-sandbox-probe.mjs +0 -74
  235. package/tests/permissions-test-plan.md +0 -191
  236. package/tests/product-telemetry-test-plan.md +0 -536
  237. package/tests/thinking-stream-preview-test-plan.md +0 -136
  238. package/tests/zcode-react-engine-test-plan.md +0 -396
@@ -0,0 +1,524 @@
1
+ import { decodeWindows1252, headingBlock, joinBlocks, listBlock, rowBlock, tidyText } from './read-document-text.js';
2
+ /**
3
+ * Word 97-2003 `.doc` to plain text, without a dependency.
4
+ *
5
+ * A `.doc` is a Compound File (a small FAT file system in one file) holding a `WordDocument`
6
+ * stream and a table stream. The text is not stored as one run: a piece table in the table stream
7
+ * maps character positions to byte ranges of `WordDocument`, each either 8-bit Windows-1252 or
8
+ * UTF-16. Paragraph properties live in a second structure keyed by file offset, and they are the
9
+ * only way to tell a table row's end mark from an empty cell or a heading from body text, so this
10
+ * reads those too.
11
+ *
12
+ * Structure names and offsets follow Microsoft's [MS-CFB] and [MS-DOC] specifications. Every
13
+ * offset and length comes from the file and is bounds-checked: a wrong one must end in a clear
14
+ * error, never in an endless chain walk or a read past the buffer.
15
+ */
16
+ const corrupt = (reason) => new Error(`This .doc is damaged (${reason}), so Read cannot open it. Ask for the document to be exported again as .docx or PDF.`);
17
+ /** Sector numbers at or above this are markers (free, end of chain, FAT, DIFAT), not sectors. */
18
+ const MAX_REGULAR_SECTOR = 0xfffffffa;
19
+ /** Open a Compound File Binary container. Throws when its structure cannot be followed. */
20
+ export function openCompoundFile(bytes) {
21
+ const broken = (reason) => new Error(`compound file: ${reason}`);
22
+ if (bytes.length < 512)
23
+ throw broken('shorter than its header');
24
+ const sectorShift = bytes.readUInt16LE(30);
25
+ if (bytes.readUInt16LE(28) !== 0xfffe || (sectorShift !== 9 && sectorShift !== 12) || bytes.readUInt16LE(32) !== 6)
26
+ throw broken('unsupported header');
27
+ const sectorSize = 1 << sectorShift;
28
+ const sectorCount = Math.ceil((bytes.length - sectorSize) / sectorSize);
29
+ const perSector = sectorSize / 4;
30
+ const sector = (index) => {
31
+ const offset = (index + 1) * sectorSize;
32
+ // Writers that do not pad the last sector exist, so a short final sector is accepted.
33
+ if (index >= sectorCount || offset >= bytes.length)
34
+ throw broken('a sector lies outside the file');
35
+ return bytes.subarray(offset, offset + sectorSize);
36
+ };
37
+ // The first 109 FAT sector numbers are in the header; larger files chain more through DIFAT sectors.
38
+ const fatSectors = [];
39
+ for (let index = 0; index < 109; index++) {
40
+ const value = bytes.readUInt32LE(76 + index * 4);
41
+ if (value < MAX_REGULAR_SECTOR)
42
+ fatSectors.push(value);
43
+ }
44
+ for (let next = bytes.readUInt32LE(68), hops = 0; next < MAX_REGULAR_SECTOR; hops++) {
45
+ if (hops > sectorCount)
46
+ throw broken('the DIFAT chain loops');
47
+ const block = sector(next);
48
+ if (block.length < sectorSize)
49
+ throw broken('a DIFAT sector is cut short');
50
+ for (let index = 0; index < perSector - 1; index++) {
51
+ const value = block.readUInt32LE(index * 4);
52
+ if (value < MAX_REGULAR_SECTOR)
53
+ fatSectors.push(value);
54
+ }
55
+ next = block.readUInt32LE(sectorSize - 4);
56
+ }
57
+ const following = (index) => {
58
+ const table = fatSectors[Math.floor(index / perSector)];
59
+ if (table === undefined)
60
+ throw broken('a sector has no FAT entry');
61
+ const block = sector(table);
62
+ const offset = (index % perSector) * 4;
63
+ if (offset + 4 > block.length)
64
+ throw broken('the FAT is cut short');
65
+ return block.readUInt32LE(offset);
66
+ };
67
+ const chain = (start, size) => {
68
+ const parts = [];
69
+ let length = 0;
70
+ for (let index = start; index < MAX_REGULAR_SECTOR && (size === undefined || length < size); index = following(index)) {
71
+ // A chain cannot be longer than the file has sectors, so a longer one is a loop.
72
+ if (parts.length > sectorCount)
73
+ throw broken('a sector chain loops');
74
+ const block = sector(index);
75
+ parts.push(block);
76
+ length += block.length;
77
+ }
78
+ if (size !== undefined && length < size)
79
+ throw broken('a stream is cut short');
80
+ const data = Buffer.concat(parts);
81
+ return size === undefined ? data : data.subarray(0, size);
82
+ };
83
+ const directory = chain(bytes.readUInt32LE(48));
84
+ const entryAt = (id) => {
85
+ const offset = id * 128;
86
+ if (offset + 128 > directory.length)
87
+ return undefined;
88
+ const nameBytes = Math.min(Math.max(directory.readUInt16LE(offset + 64) - 2, 0), 62);
89
+ // Version 3 files may leave garbage in the high half of the size; no stream here can exceed 4 GiB anyway.
90
+ if (sectorShift === 12 && directory.readUInt32LE(offset + 124) !== 0)
91
+ throw broken('a stream is larger than 4 GiB');
92
+ return {
93
+ name: directory.toString('utf16le', offset, offset + nameBytes), type: directory[offset + 66],
94
+ left: directory.readUInt32LE(offset + 68), right: directory.readUInt32LE(offset + 72), child: directory.readUInt32LE(offset + 76),
95
+ start: directory.readUInt32LE(offset + 116), size: directory.readUInt32LE(offset + 120),
96
+ };
97
+ };
98
+ const root = entryAt(0);
99
+ if (!root || root.type !== 5)
100
+ throw broken('no root entry');
101
+ // A storage's children form a binary tree linked by sibling ids. Only the root level is needed.
102
+ const streams = new Map();
103
+ const seen = new Set();
104
+ const pending = [root.child];
105
+ while (pending.length) {
106
+ const id = pending.pop();
107
+ if (id === 0xffffffff || seen.has(id))
108
+ continue;
109
+ seen.add(id);
110
+ const entry = entryAt(id);
111
+ if (!entry)
112
+ continue;
113
+ if (entry.type === 2)
114
+ streams.set(entry.name, { start: entry.start, size: entry.size });
115
+ pending.push(entry.left, entry.right);
116
+ }
117
+ // Streams under the cutoff live in 64-byte mini sectors inside the root entry's own stream.
118
+ const miniCutoff = bytes.readUInt32LE(56);
119
+ let mini;
120
+ const read = (entry) => {
121
+ if (entry.size >= miniCutoff)
122
+ return chain(entry.start, entry.size);
123
+ mini ??= { stream: chain(root.start, root.size), fat: chain(bytes.readUInt32LE(60)) };
124
+ const parts = [];
125
+ for (let index = entry.start, length = 0; length < entry.size; length += 64) {
126
+ if (index >= MAX_REGULAR_SECTOR || parts.length > mini.stream.length / 64 || (index + 1) * 64 > mini.stream.length || index * 4 + 4 > mini.fat.length)
127
+ throw broken('a small stream is cut short');
128
+ parts.push(mini.stream.subarray(index * 64, index * 64 + 64));
129
+ index = mini.fat.readUInt32LE(index * 4);
130
+ }
131
+ return Buffer.concat(parts).subarray(0, entry.size);
132
+ };
133
+ return { streams, read };
134
+ }
135
+ const PLAIN = { style: 0, inTable: false, rowEnd: false, list: false, level: 0, innerCell: false, innerRowEnd: false };
136
+ /** Operand bytes by the three size bits of a property modifier; -1 means the operand carries its own length. */
137
+ const OPERAND_SIZE = [1, 1, 2, 4, 2, 2, -1, 3];
138
+ /** One paragraph's style index and the few property modifiers that change how its text should read. */
139
+ function readParagraphProperties(page, offset) {
140
+ const properties = { ...PLAIN };
141
+ if (offset + 1 >= page.length)
142
+ return properties;
143
+ // The size is counted in words; a zero first byte means the real count follows in the next byte.
144
+ let start = offset + 1;
145
+ let length = page[offset] * 2 - 1;
146
+ if (page[offset] === 0) {
147
+ start = offset + 2;
148
+ length = page[offset + 1] * 2;
149
+ }
150
+ const end = Math.min(start + length, page.length - 1);
151
+ if (start + 2 > end)
152
+ return properties;
153
+ properties.style = page.readUInt16LE(start);
154
+ for (let position = start + 2; position + 2 <= end;) {
155
+ const code = page.readUInt16LE(position);
156
+ position += 2;
157
+ let size = OPERAND_SIZE[code >> 13];
158
+ if (size < 0) {
159
+ if (position >= end)
160
+ break;
161
+ // Two modifiers break the one-byte length rule: the table definition counts in a 16-bit
162
+ // field, and a tab change of length 255 is sized by its two inner arrays.
163
+ if (code === 0xd608)
164
+ size = position + 2 <= end ? page.readUInt16LE(position) + 1 : end;
165
+ else if (code === 0xc615 && page[position] === 255) {
166
+ const removed = page[position + 1] ?? 0;
167
+ const added = page[position + 2 + removed * 4] ?? 0;
168
+ size = 3 + removed * 4 + added * 3;
169
+ }
170
+ else
171
+ size = 1 + page[position];
172
+ }
173
+ if (position + size > end)
174
+ break;
175
+ const byte = page[position];
176
+ switch (code) {
177
+ case 0x2416:
178
+ properties.inTable = byte !== 0;
179
+ break;
180
+ case 0x2417:
181
+ properties.rowEnd = byte !== 0;
182
+ break;
183
+ case 0x244b:
184
+ properties.innerCell = byte !== 0;
185
+ break;
186
+ case 0x244c:
187
+ properties.innerRowEnd = byte !== 0;
188
+ break;
189
+ case 0x6649:
190
+ if (page.readUInt32LE(position) > 0)
191
+ properties.inTable = true;
192
+ break;
193
+ case 0x460b:
194
+ properties.list = page.readUInt16LE(position) !== 0;
195
+ break;
196
+ case 0x260a:
197
+ properties.level = byte;
198
+ break;
199
+ case 0x2640:
200
+ properties.outline = byte;
201
+ break;
202
+ case 0x4600:
203
+ properties.style = page.readUInt16LE(position);
204
+ break;
205
+ }
206
+ position += size;
207
+ }
208
+ return properties;
209
+ }
210
+ /** Paragraph properties for every paragraph, as ranges of `WordDocument` file offsets, sorted. */
211
+ function readPropertyRuns(document, table) {
212
+ const offset = document.readUInt32LE(0x102);
213
+ const length = document.readUInt32LE(0x106);
214
+ if (length < 12 || offset + length > table.length)
215
+ return [];
216
+ const count = Math.floor((length - 4) / 8);
217
+ const runs = [];
218
+ for (let index = 0; index < count; index++) {
219
+ const pageOffset = (table.readUInt32LE(offset + (count + 1) * 4 + index * 4) & 0x3fffff) * 512;
220
+ if (pageOffset + 512 > document.length)
221
+ continue;
222
+ const page = document.subarray(pageOffset, pageOffset + 512);
223
+ const entries = page[511];
224
+ if ((entries + 1) * 4 + entries * 13 > 511)
225
+ continue;
226
+ for (let entry = 0; entry < entries; entry++) {
227
+ const wordOffset = page[(entries + 1) * 4 + entry * 13];
228
+ runs.push({ start: page.readUInt32LE(entry * 4), end: page.readUInt32LE(entry * 4 + 4), ...(wordOffset ? readParagraphProperties(page, wordOffset * 2) : PLAIN) });
229
+ }
230
+ }
231
+ return runs.sort((a, b) => a.start - b.start);
232
+ }
233
+ /** The main document's text, one UTF-16 code unit per character position, and where each piece sits in the stream. */
234
+ function readPieces(document, table, characters) {
235
+ const start = document.readUInt32LE(0x1a2);
236
+ const end = start + document.readUInt32LE(0x1a6);
237
+ if (end > table.length || end <= start)
238
+ throw corrupt('the text index is missing');
239
+ // Property modifier blocks come first; the piece table is the block of type 2.
240
+ let position = start;
241
+ while (position < end && table[position] === 1)
242
+ position += 3 + (position + 3 <= end ? table.readUInt16LE(position + 1) : end);
243
+ if (position + 5 > end || table[position] !== 2)
244
+ throw corrupt('the text index is unreadable');
245
+ const length = table.readUInt32LE(position + 1);
246
+ position += 5;
247
+ if (length < 16 || position + length > end)
248
+ throw corrupt('the text index is cut short');
249
+ const count = Math.floor((length - 4) / 12);
250
+ const pieces = [];
251
+ const parts = [];
252
+ let total = 0;
253
+ for (let index = 0; index < count; index++) {
254
+ const first = table.readUInt32LE(position + index * 4);
255
+ const last = Math.min(table.readUInt32LE(position + index * 4 + 4), characters);
256
+ if (first >= characters)
257
+ break;
258
+ if (last <= first)
259
+ continue;
260
+ const descriptor = table.readUInt32LE(position + (count + 1) * 4 + index * 8 + 2);
261
+ // Bit 30 marks 8-bit text, whose stored offset is twice the real one.
262
+ const narrow = (descriptor & 0x40000000) !== 0;
263
+ const offset = narrow ? (descriptor & 0x3fffffff) >>> 1 : descriptor & 0x3fffffff;
264
+ const width = narrow ? 1 : 2;
265
+ const bytes = (last - first) * width;
266
+ if (offset + bytes > document.length)
267
+ throw corrupt('text lies outside the file');
268
+ const slice = document.subarray(offset, offset + bytes);
269
+ parts.push(narrow ? decodeWindows1252(slice) : slice.toString('utf16le'));
270
+ pieces.push({ first: total, last: total + last - first, offset, width });
271
+ total += last - first;
272
+ }
273
+ return { text: parts.join(''), pieces };
274
+ }
275
+ /**
276
+ * Text of a legacy Word document, or undefined when the compound file holds something else
277
+ * (an `.xls`, a `.ppt`, an `.msi`), so the caller can report it as the binary file it is.
278
+ */
279
+ export function extractDoc(bytes) {
280
+ try {
281
+ return readDoc(bytes);
282
+ }
283
+ catch (error) {
284
+ // A read past the end of a stream means an offset in the file was wrong, not that Read is broken.
285
+ if (error instanceof RangeError)
286
+ throw corrupt('an offset points outside the file');
287
+ throw error;
288
+ }
289
+ }
290
+ function readDoc(bytes) {
291
+ let container;
292
+ try {
293
+ container = openCompoundFile(bytes);
294
+ }
295
+ catch (error) {
296
+ // Even a broken container shows whether it was a Word document: stream names are plain UTF-16
297
+ // in the directory, and when the directory itself is gone (Word writes it last, so a cut-off
298
+ // file loses it) the document header is still the first thing after the container header.
299
+ const wordHeader = bytes.length >= 514 && bytes.readUInt16LE(512) === 0xa5ec;
300
+ if (wordHeader || bytes.includes(Buffer.from('WordDocument', 'utf16le')))
301
+ throw corrupt(error.message);
302
+ return undefined;
303
+ }
304
+ // Office saves a password-protected .docx/.xlsx/.pptx as a compound file wrapping the encrypted package.
305
+ if (container.streams.has('EncryptedPackage')) {
306
+ throw new Error('This Office document is password-protected (encrypted), so Read cannot open it. Ask the user for an unprotected copy.');
307
+ }
308
+ const main = container.streams.get('WordDocument');
309
+ if (!main)
310
+ return undefined;
311
+ let document;
312
+ try {
313
+ document = container.read(main);
314
+ }
315
+ catch (error) {
316
+ throw corrupt(error.message);
317
+ }
318
+ if (document.length < 0x1aa)
319
+ throw corrupt('the document header is cut short');
320
+ const identifier = document.readUInt16LE(0);
321
+ if (identifier === 0xa5dc || (identifier === 0xa5ec && document.readUInt16LE(2) < 0xc1)) {
322
+ throw new Error('This is a Word 6 or Word 95 document, which Read does not support. Open it in Word or LibreOffice and save it as .docx or PDF.');
323
+ }
324
+ if (identifier !== 0xa5ec)
325
+ throw corrupt('the document header is not recognised');
326
+ const flags = document.readUInt16LE(0x0a);
327
+ if (flags & 0x0100)
328
+ throw new Error('This .doc is password-protected (encrypted), so Read cannot open it. Ask the user for an unprotected copy.');
329
+ const tableEntry = container.streams.get(flags & 0x0200 ? '1Table' : '0Table');
330
+ if (!tableEntry)
331
+ throw corrupt('the table stream is missing');
332
+ let table;
333
+ try {
334
+ table = container.read(tableEntry);
335
+ }
336
+ catch (error) {
337
+ throw corrupt(error.message);
338
+ }
339
+ const characters = document.readInt32LE(0x4c);
340
+ if (characters < 0 || characters > document.length)
341
+ throw corrupt('the text length is implausible');
342
+ const { text, pieces } = readPieces(document, table, characters);
343
+ const runs = readPropertyRuns(document, table);
344
+ // Character position -> file offset -> the property run covering it. Paragraphs are visited in
345
+ // order, so the piece cursor only moves forward; property runs are found by binary search.
346
+ let pieceIndex = 0;
347
+ const propertiesAt = (position) => {
348
+ while (pieceIndex < pieces.length - 1 && position >= pieces[pieceIndex].last)
349
+ pieceIndex++;
350
+ const piece = pieces[pieceIndex];
351
+ if (!piece || !runs.length)
352
+ return undefined;
353
+ const offset = piece.offset + (position - piece.first) * piece.width;
354
+ let low = 0;
355
+ let high = runs.length - 1;
356
+ while (low < high) {
357
+ const middle = (low + high + 1) >> 1;
358
+ if (runs[middle].start <= offset)
359
+ low = middle;
360
+ else
361
+ high = middle - 1;
362
+ }
363
+ const run = runs[low];
364
+ return offset >= run.start && offset < run.end ? run : undefined;
365
+ };
366
+ const blocks = [];
367
+ let paragraph = '';
368
+ let cells = [];
369
+ let cellParagraphs = [];
370
+ let afterCell = false;
371
+ let drawings = 0;
372
+ // A field is `0x13 instruction 0x14 result 0x15`; only the result is document text. Fields nest.
373
+ const fields = [];
374
+ let hidden = 0;
375
+ let paragraphNumber = 0;
376
+ const endRow = () => { const row = rowBlock(cells); if (row)
377
+ blocks.push(row); cells = []; cellParagraphs = []; };
378
+ const endParagraph = (position, mark) => {
379
+ const properties = propertiesAt(position);
380
+ const clean = tidyText(paragraph);
381
+ paragraph = '';
382
+ paragraphNumber++;
383
+ if (mark === 0x07) {
384
+ // Each cell ends with 0x07 and so does the row, after its last cell. Only the paragraph
385
+ // properties tell the row mark from an empty cell; without them, a mark straight after
386
+ // another one is taken to end the row.
387
+ const rowEnd = properties ? properties.rowEnd : afterCell && !clean && !cellParagraphs.length;
388
+ if (rowEnd)
389
+ endRow();
390
+ else {
391
+ cells.push([...cellParagraphs, clean].filter(Boolean).join(' '));
392
+ cellParagraphs = [];
393
+ }
394
+ afterCell = !rowEnd;
395
+ return;
396
+ }
397
+ afterCell = false;
398
+ if (properties?.inTable && !properties.rowEnd && mark === 0x0d) {
399
+ // A nested table is flattened into its cell, keeping the separator between its own cells.
400
+ // The inner row's end mark carries both flags, so it is tested first.
401
+ if (properties.innerRowEnd) {
402
+ const last = cellParagraphs.pop() ?? '';
403
+ cellParagraphs.push(last.endsWith('|') ? last.slice(0, -1).trimEnd() : last);
404
+ }
405
+ else if (properties.innerCell)
406
+ cellParagraphs.push(`${clean} |`);
407
+ else if (clean)
408
+ cellParagraphs.push(clean);
409
+ return;
410
+ }
411
+ if (cells.length || cellParagraphs.length) {
412
+ if (cellParagraphs.length)
413
+ cells.push(cellParagraphs.join(' '));
414
+ endRow();
415
+ }
416
+ if (clean) {
417
+ // Built-in heading styles keep style indexes 1-9 in every language; other styles can still carry an outline level.
418
+ const style = properties?.style ?? 0;
419
+ const heading = style >= 1 && style <= 9 ? style : properties?.outline !== undefined && properties.outline < 9 ? properties.outline + 1 : undefined;
420
+ if (heading !== undefined)
421
+ blocks.push(headingBlock(heading, clean.replace(/\s*\n\s*/g, ' ')));
422
+ else
423
+ blocks.push(properties?.list ? listBlock(properties.level, clean) : { kind: 'paragraph', text: clean });
424
+ }
425
+ if (mark === 0x0c)
426
+ blocks.push({ kind: 'break', text: '' });
427
+ };
428
+ let runStart = 0;
429
+ for (let position = 0; position <= text.length; position++) {
430
+ const code = position < text.length ? text.charCodeAt(position) : -1;
431
+ // Ordinary characters are copied in runs; only control characters need a decision.
432
+ if (code >= 0x20)
433
+ continue;
434
+ const field = fields[fields.length - 1];
435
+ if (position > runStart) {
436
+ const run = text.slice(runStart, position);
437
+ if (!hidden)
438
+ paragraph += run;
439
+ else if (field?.instruction && field.code.length < 2048)
440
+ field.code += run;
441
+ }
442
+ runStart = position + 1;
443
+ if (code === 0x13) {
444
+ fields.push({ instruction: true, code: '', start: 0, paragraph: paragraphNumber });
445
+ hidden++;
446
+ continue;
447
+ }
448
+ if (code === 0x14) {
449
+ if (field?.instruction) {
450
+ field.instruction = false;
451
+ field.start = paragraph.length;
452
+ field.paragraph = paragraphNumber;
453
+ hidden--;
454
+ }
455
+ continue;
456
+ }
457
+ if (code === 0x15) {
458
+ if (!field)
459
+ continue;
460
+ fields.pop();
461
+ if (field.instruction) {
462
+ hidden--;
463
+ continue;
464
+ }
465
+ // A hyperlink keeps its target in the instruction; the result is only the label.
466
+ const url = /^\s*HYPERLINK\s+"([^"]+)"/i.exec(field.code)?.[1];
467
+ const label = paragraph.slice(field.start);
468
+ if (!hidden && url && field.paragraph === paragraphNumber && label.trim())
469
+ paragraph = paragraph.slice(0, field.start) + (label.trim() === url ? url : `[${label}](${url})`);
470
+ continue;
471
+ }
472
+ if (hidden || code < 0)
473
+ continue;
474
+ switch (code) {
475
+ case 0x0d:
476
+ case 0x07:
477
+ case 0x0c:
478
+ endParagraph(position, code);
479
+ break;
480
+ case 0x09:
481
+ paragraph += '\t';
482
+ break;
483
+ // Manual line break and column break.
484
+ case 0x0b:
485
+ case 0x0e:
486
+ paragraph += '\n';
487
+ break;
488
+ case 0x1e:
489
+ paragraph += '-';
490
+ break;
491
+ // Anchors of inline pictures and floating shapes.
492
+ case 0x01:
493
+ case 0x08:
494
+ drawings++;
495
+ break;
496
+ // The rest (footnote and comment reference marks, optional hyphens) has no text form.
497
+ }
498
+ }
499
+ // A file cut off mid-paragraph or mid-table still gives up what it had.
500
+ if (tidyText(paragraph))
501
+ endParagraph(text.length - 1, 0x0d);
502
+ if (cellParagraphs.length)
503
+ cells.push(cellParagraphs.join(' '));
504
+ if (cells.length)
505
+ endRow();
506
+ const notes = [];
507
+ const count = (offset) => document.readInt32LE(offset) > 0;
508
+ if (count(0x50))
509
+ notes.push('footnotes not included');
510
+ if (count(0x60))
511
+ notes.push('endnotes not included');
512
+ if (count(0x5c))
513
+ notes.push('review comments not included');
514
+ if (count(0x54))
515
+ notes.push('page headers and footers not included');
516
+ if (count(0x64) || count(0x68))
517
+ notes.push('text boxes not included');
518
+ if (drawings)
519
+ notes.push(`${drawings} embedded image${drawings === 1 ? '' : 's'} or drawing${drawings === 1 ? '' : 's'} not shown`);
520
+ const result = joinBlocks(blocks);
521
+ if (!result)
522
+ notes.push('the document contains no text');
523
+ return { text: result, notes };
524
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Word `.docx` to plain text, without a dependency.
3
+ *
4
+ * A `.docx` is a ZIP of XML parts. Read needs one of them, `word/document.xml`, turned into text a
5
+ * model can follow: paragraphs, headings, list items and table rows. That is a small enough job
6
+ * that a ZIP central-directory reader and a pull tokenizer cover it, where a general OOXML library
7
+ * would add megabytes to every install for layout features Read throws away.
8
+ *
9
+ * The file is untrusted input. Sizes come from the archive itself, so every part is inflated under
10
+ * a hard budget; nothing here trusts a declared length, an offset or a nesting depth.
11
+ */
12
+ /** Total XML one document may inflate to, across all the parts read from it. */
13
+ export declare const DOCX_INFLATE_LIMIT: number;
14
+ /**
15
+ * Text of a `.docx`, or undefined when the ZIP is not a Word document (a `.xlsx`, a `.jar`, any
16
+ * other archive), so the caller can report it as the binary file it is.
17
+ */
18
+ export declare function extractDocx(bytes: Buffer, signal?: AbortSignal): Promise<{
19
+ text: string;
20
+ notes: string[];
21
+ } | undefined>;