dsh-mineru 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ /**
2
+ * dsh-mineru browser bundle declarations: the Settings tab under
3
+ * Settings -> Plugins and the mineru_* tool-result cards.
4
+ */
5
+ import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client';
6
+
7
+ export declare const inject: string[];
8
+ export declare function apply(ctx: ClientContext): void;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * dsh-mineru host plugin type declarations (hand-written).
3
+ * @module dsh-mineru
4
+ */
5
+ import type { Context } from '@deepseek-ai/cordis';
6
+ import type z from '@deepseek-ai/schemastery';
7
+
8
+ export declare const name: 'mineru';
9
+ export declare const inject: string[];
10
+ export declare const Config: z<object>;
11
+ export declare function apply(ctx: Context, config?: Record<string, unknown>): void;
package/lib/zip.js ADDED
@@ -0,0 +1,337 @@
1
+ /**
2
+ * Minimal dependency-free ZIP reader for MinerU result archives.
3
+ *
4
+ * Supports the formats MinerU's CDN actually produces: single-disk zips with
5
+ * STORED (0) and DEFLATE (8) entries. Reads the End Of Central Directory, walks
6
+ * central directory records, and extracts entries with traversal-safe name
7
+ * sanitization and byte caps. ZIP64 and encrypted entries fail loudly instead
8
+ * of being misparsed.
9
+ * @module dsh-mineru/zip
10
+ */
11
+ import { open } from 'node:fs/promises';
12
+ import { createInflateRaw, inflateRawSync, constants as zlibConstants } from 'node:zlib';
13
+ import { dirname, join, resolve, sep } from 'node:path';
14
+ import { mkdir, writeFile } from 'node:fs/promises';
15
+
16
+ const EOCD_SIGNATURE = 0x06054b50;
17
+ const EOCD_MIN_SIZE = 22;
18
+ const EOCD_MAX_COMMENT = 0xffff;
19
+ const CENTRAL_SIGNATURE = 0x02014b50;
20
+ const LOCAL_SIGNATURE = 0x04034b50;
21
+
22
+ /** @param {number} v @param {number} at @returns {number} little-endian uint32 */
23
+ function u32(view, at) { return view.readUInt32LE(at); }
24
+ /** @param {number} v @param {number} at @returns {number} little-endian uint16 */
25
+ function u16(view, at) { return view.readUInt16LE(at); }
26
+
27
+ /** Standard CRC-32 (IEEE, as stored in ZIP entries), table-driven. */
28
+ const CRC_TABLE = (() => {
29
+ const table = new Uint32Array(256);
30
+ for (let n = 0; n < 256; n++) {
31
+ let crc = n;
32
+ for (let k = 0; k < 8; k++) crc = crc & 1 ? 0xedb88320 ^ (crc >>> 1) : crc >>> 1;
33
+ table[n] = crc >>> 0;
34
+ }
35
+ return table;
36
+ })();
37
+
38
+ /** @param {Buffer} buf @returns {number} */
39
+ function crc32(buf) {
40
+ let crc = 0xffffffff;
41
+ for (let i = 0; i < buf.length; i++) crc = CRC_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
42
+ return (crc ^ 0xffffffff) >>> 0;
43
+ }
44
+
45
+ /**
46
+ * Stream-decompress at most maxBytes of output from a deflate entry without
47
+ * loading the whole compressed stream. A truncated stream (as produced by
48
+ * bounded reads) yields its partial output instead of throwing.
49
+ * @param {import('node:fs/promises').FileHandle} fh
50
+ * @param {number} start absolute data start offset
51
+ * @param {number} compressedSize
52
+ * @param {number} maxBytes
53
+ * @param {AbortSignal} [signal]
54
+ * @returns {Promise<Buffer>}
55
+ */
56
+ async function inflatePrefix(fh, start, compressedSize, maxBytes, signal) {
57
+ const inflate = createInflateRaw();
58
+ const chunks = [];
59
+ let out = 0;
60
+ let settled = false;
61
+ const finish = () => { settled = true; };
62
+ inflate.on('data', (chunk) => {
63
+ if (out >= maxBytes) return;
64
+ const take = Math.min(chunk.length, maxBytes - out);
65
+ if (take > 0) { chunks.push(chunk.subarray(0, take)); out += take; }
66
+ if (out >= maxBytes) { finish(); inflate.destroy(); }
67
+ });
68
+ inflate.on('error', finish);
69
+ inflate.on('end', finish);
70
+ const CHUNK = 1 << 16;
71
+ let pos = 0;
72
+ while (pos < compressedSize && !settled) {
73
+ checkAbort(signal);
74
+ const len = Math.min(CHUNK, compressedSize - pos);
75
+ const buf = Buffer.alloc(len);
76
+ await fh.read(buf, 0, len, start + pos);
77
+ pos += len;
78
+ inflate.write(buf);
79
+ }
80
+ if (!settled) inflate.end();
81
+ await new Promise((resolve) => setTimeout(resolve, 0));
82
+ return Buffer.concat(chunks);
83
+ }
84
+
85
+ export class ZipError extends Error {
86
+ constructor(message, code = 'ZIP_ERROR') {
87
+ super(message);
88
+ this.name = 'ZipError';
89
+ this.code = code;
90
+ }
91
+ }
92
+
93
+ function checkAbort(signal) {
94
+ if (signal?.aborted) {
95
+ const err = new Error('zip operation aborted');
96
+ err.name = 'AbortError';
97
+ throw err;
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Locate and parse the End Of Central Directory record.
103
+ * @param {import('node:fs/promises').FileHandle} fh
104
+ * @param {number} fileSize
105
+ * @param {AbortSignal} [signal]
106
+ * @returns {Promise<{cdOffset:number, cdSize:number, entryCount:number}>}
107
+ */
108
+ async function readEocd(fh, fileSize, signal) {
109
+ if (fileSize < EOCD_MIN_SIZE) throw new ZipError('file too small to be a zip archive');
110
+ const tailSize = Math.min(fileSize, EOCD_MIN_SIZE + EOCD_MAX_COMMENT);
111
+ const buf = Buffer.alloc(tailSize);
112
+ await fh.read(buf, 0, tailSize, fileSize - tailSize);
113
+ checkAbort(signal);
114
+ let found = -1;
115
+ for (let i = tailSize - EOCD_MIN_SIZE; i >= 0; i--) {
116
+ if (u32(buf, i) === EOCD_SIGNATURE) { found = i; break; }
117
+ }
118
+ if (found < 0) throw new ZipError('end of central directory not found');
119
+ const diskNumber = u16(buf, found + 4);
120
+ const cdDisk = u16(buf, found + 6);
121
+ const diskEntries = u16(buf, found + 8);
122
+ const totalEntries = u16(buf, found + 10);
123
+ const cdSize = u32(buf, found + 12);
124
+ const cdOffset = u32(buf, found + 16);
125
+ if (diskNumber !== 0 || cdDisk !== 0 || diskEntries !== totalEntries) {
126
+ throw new ZipError('multi-disk zip archives are not supported', 'ZIP_UNSUPPORTED');
127
+ }
128
+ if (totalEntries === 0xffff || cdSize === 0xffffffff || cdOffset === 0xffffffff) {
129
+ throw new ZipError('ZIP64 archives are not supported by the built-in extractor', 'ZIP_UNSUPPORTED');
130
+ }
131
+ return { cdOffset, cdSize, entryCount: totalEntries };
132
+ }
133
+
134
+ /** @typedef {{name:string, method:number, flags:number, compressedSize:number, uncompressedSize:number, localOffset:number, crc32:number, externalAttr:number}} ZipEntry */
135
+
136
+ /**
137
+ * Read the central directory.
138
+ * @param {import('node:fs/promises').FileHandle} fh
139
+ * @param {number} cdOffset
140
+ * @param {number} cdSize
141
+ * @param {number} entryCount
142
+ * @param {AbortSignal} [signal]
143
+ * @returns {Promise<ZipEntry[]>}
144
+ */
145
+ async function readCentralDirectory(fh, cdOffset, cdSize, entryCount, signal) {
146
+ const buf = Buffer.alloc(cdSize);
147
+ await fh.read(buf, 0, cdSize, cdOffset);
148
+ checkAbort(signal);
149
+ const entries = [];
150
+ let at = 0;
151
+ for (let n = 0; n < entryCount; n++) {
152
+ if (at + 46 > cdSize || u32(buf, at) !== CENTRAL_SIGNATURE) {
153
+ throw new ZipError('corrupt central directory record ' + n, 'ZIP_CORRUPT');
154
+ }
155
+ const flags = u16(buf, at + 8);
156
+ const method = u16(buf, at + 10);
157
+ const crc32 = u32(buf, at + 16);
158
+ const compressedSize = u32(buf, at + 20);
159
+ const uncompressedSize = u32(buf, at + 24);
160
+ const nameLen = u16(buf, at + 28);
161
+ const extraLen = u16(buf, at + 30);
162
+ const commentLen = u16(buf, at + 32);
163
+ const externalAttr = u32(buf, at + 38);
164
+ const localOffset = u32(buf, at + 42);
165
+ if (at + 46 + nameLen + extraLen + commentLen > cdSize) {
166
+ throw new ZipError('corrupt central directory name for entry ' + n, 'ZIP_CORRUPT');
167
+ }
168
+ const name = buf.toString('utf8', at + 46, at + 46 + nameLen);
169
+ if (compressedSize === 0xffffffff || uncompressedSize === 0xffffffff || localOffset === 0xffffffff) {
170
+ throw new ZipError('ZIP64 entries are not supported (' + name + ')', 'ZIP_UNSUPPORTED');
171
+ }
172
+ entries.push({ name, method, flags, compressedSize, uncompressedSize, localOffset, crc32, externalAttr });
173
+ at += 46 + nameLen + extraLen + commentLen;
174
+ }
175
+ return entries;
176
+ }
177
+
178
+ /**
179
+ * Sanitize one archive entry name into a relative path, rejecting traversal.
180
+ * @param {string} name
181
+ * @returns {string}
182
+ */
183
+ export function sanitizeEntryName(name) {
184
+ if (typeof name !== 'string' || name.length === 0) throw new ZipError('empty entry name');
185
+ let p = name.replace(/\\/g, '/');
186
+ if (/^[a-zA-Z]:/.test(p) || p.startsWith('/') || p.startsWith('//')) {
187
+ throw new ZipError('entry with absolute path rejected: ' + name, 'ZIP_UNSAFE');
188
+ }
189
+ const parts = p.split('/');
190
+ const out = [];
191
+ for (const part of parts) {
192
+ if (part === '' || part === '.') continue;
193
+ if (part === '..') throw new ZipError('entry with parent traversal rejected: ' + name, 'ZIP_UNSAFE');
194
+ out.push(part);
195
+ }
196
+ if (out.length === 0) throw new ZipError('entry resolves to empty path: ' + name, 'ZIP_UNSAFE');
197
+ return out.join('/');
198
+ }
199
+
200
+ /**
201
+ * Extract every safe entry of a zip file into destDir.
202
+ * @param {string} zipPath
203
+ * @param {string} destDir
204
+ * @param {{signal?: AbortSignal, maxEntries?: number, maxTotalBytes?: number, maxEntryBytes?: number}} [opts]
205
+ * @returns {Promise<{files: {name:string, path:string, bytes:number}[], totalBytes:number}>}
206
+ */
207
+ export async function extractZip(zipPath, destDir, opts = {}) {
208
+ const signal = opts.signal;
209
+ const maxEntries = opts.maxEntries ?? 4096;
210
+ const maxTotalBytes = opts.maxTotalBytes ?? (1 << 30);
211
+ const maxEntryBytes = opts.maxEntryBytes ?? (256 << 20);
212
+ const fh = await open(zipPath, 'r');
213
+ let fileSize = 0;
214
+ try {
215
+ fileSize = (await fh.stat()).size;
216
+ const eocd = await readEocd(fh, fileSize, signal);
217
+ if (eocd.entryCount > maxEntries) throw new ZipError('too many zip entries: ' + eocd.entryCount, 'ZIP_TOO_MANY');
218
+ const entries = await readCentralDirectory(fh, eocd.cdOffset, eocd.cdSize, eocd.entryCount, signal);
219
+ const files = [];
220
+ let totalBytes = 0;
221
+ for (const entry of entries) {
222
+ checkAbort(signal);
223
+ const rel = sanitizeEntryName(entry.name);
224
+ const isDir = entry.name.endsWith('/') || (entry.externalAttr & 0x10) !== 0;
225
+ if (isDir) continue;
226
+ if (entry.method !== 0 && entry.method !== 8) {
227
+ throw new ZipError('unsupported compression method ' + entry.method + ' for ' + entry.name, 'ZIP_UNSUPPORTED');
228
+ }
229
+ if ((entry.flags & 0x1) !== 0) {
230
+ throw new ZipError('encrypted zip entries are not supported: ' + entry.name, 'ZIP_UNSUPPORTED');
231
+ }
232
+ if (entry.uncompressedSize > maxEntryBytes) {
233
+ throw new ZipError('zip entry too large: ' + entry.name + ' (' + entry.uncompressedSize + ' bytes)', 'ZIP_TOO_LARGE');
234
+ }
235
+ if (totalBytes + entry.uncompressedSize > maxTotalBytes) {
236
+ throw new ZipError('zip extraction exceeds ' + maxTotalBytes + ' bytes total', 'ZIP_TOO_LARGE');
237
+ }
238
+ // Local file header: 30 fixed bytes + name + extra.
239
+ const localHead = Buffer.alloc(30);
240
+ await fh.read(localHead, 0, 30, entry.localOffset);
241
+ checkAbort(signal);
242
+ if (u32(localHead, 0) !== LOCAL_SIGNATURE) {
243
+ throw new ZipError('corrupt local header for ' + entry.name, 'ZIP_CORRUPT');
244
+ }
245
+ const nameLen = u16(localHead, 26);
246
+ const extraLen = u16(localHead, 28);
247
+ const dataStart = entry.localOffset + 30 + nameLen + extraLen;
248
+ if (dataStart + entry.compressedSize > fileSize) {
249
+ throw new ZipError('entry data outside file bounds: ' + entry.name, 'ZIP_CORRUPT');
250
+ }
251
+ const raw = Buffer.alloc(entry.compressedSize);
252
+ await fh.read(raw, 0, entry.compressedSize, dataStart);
253
+ checkAbort(signal);
254
+ let data;
255
+ if (entry.method === 0) {
256
+ data = raw;
257
+ } else {
258
+ data = inflateRawSync(raw, {
259
+ maxOutputLength: entry.uncompressedSize + 1,
260
+ finishFlush: zlibConstants.Z_FINISH,
261
+ });
262
+ }
263
+ if (data.length !== entry.uncompressedSize) {
264
+ throw new ZipError('size mismatch for ' + entry.name, 'ZIP_CORRUPT');
265
+ }
266
+ if (crc32(data) !== entry.crc32) {
267
+ throw new ZipError('CRC 校验失败, 文件可能已损坏: ' + entry.name, 'ZIP_CORRUPT');
268
+ }
269
+ const target = resolve(destDir, rel);
270
+ const root = resolve(destDir) + sep;
271
+ if (!target.startsWith(root)) throw new ZipError('entry escapes destination: ' + entry.name, 'ZIP_UNSAFE');
272
+ await mkdir(dirname(target), { recursive: true });
273
+ await writeFile(target, data);
274
+ totalBytes += data.length;
275
+ files.push({ name: rel, path: target, bytes: data.length });
276
+ }
277
+ return { files, totalBytes };
278
+ } finally {
279
+ await fh.close();
280
+ }
281
+ }
282
+
283
+ /**
284
+ * Read one entry as text without extracting the whole archive.
285
+ * @param {string} zipPath
286
+ * @param {string} entryName normalized archive name (forward slashes)
287
+ * @param {{signal?: AbortSignal, maxBytes?: number}} [opts]
288
+ * @returns {Promise<{text: string, bytes: number, truncated: boolean} | undefined>}
289
+ */
290
+ export async function readZipEntryText(zipPath, entryName, opts = {}) {
291
+ const signal = opts.signal;
292
+ const maxBytes = opts.maxBytes ?? (64 << 20);
293
+ const fh = await open(zipPath, 'r');
294
+ try {
295
+ const fileSize = (await fh.stat()).size;
296
+ const eocd = await readEocd(fh, fileSize, signal);
297
+ const entries = await readCentralDirectory(fh, eocd.cdOffset, eocd.cdSize, eocd.entryCount, signal);
298
+ for (const entry of entries) {
299
+ if (sanitizeEntryName(entry.name) !== entryName) continue;
300
+ if (entry.method !== 0 && entry.method !== 8) throw new ZipError('unsupported compression method ' + entry.method, 'ZIP_UNSUPPORTED');
301
+ if (entry.uncompressedSize > maxBytes) {
302
+ // Bounded prefix: stored entries read directly; deflate streams decode
303
+ // incrementally so a mid-stream cut still yields its partial output.
304
+ const localHead = Buffer.alloc(30);
305
+ await fh.read(localHead, 0, 30, entry.localOffset);
306
+ const dataStart = entry.localOffset + 30 + u16(localHead, 26) + u16(localHead, 28);
307
+ let data;
308
+ if (entry.method === 0) {
309
+ const want = Math.min(maxBytes, entry.compressedSize);
310
+ const raw = Buffer.alloc(want);
311
+ await fh.read(raw, 0, want, dataStart);
312
+ data = raw;
313
+ } else {
314
+ data = await inflatePrefix(fh, dataStart, entry.compressedSize, maxBytes, signal);
315
+ }
316
+ return { text: data.toString('utf8'), bytes: entry.uncompressedSize, truncated: true };
317
+ }
318
+ const localHead = Buffer.alloc(30);
319
+ await fh.read(localHead, 0, 30, entry.localOffset);
320
+ const dataStart = entry.localOffset + 30 + u16(localHead, 26) + u16(localHead, 28);
321
+ const raw = Buffer.alloc(entry.compressedSize);
322
+ await fh.read(raw, 0, entry.compressedSize, dataStart);
323
+ checkAbort(signal);
324
+ const data = entry.method === 0 ? raw : inflateRawSync(raw, { maxOutputLength: entry.uncompressedSize + 1 });
325
+ if (data.length !== entry.uncompressedSize) {
326
+ throw new ZipError('size mismatch for ' + entry.name, 'ZIP_CORRUPT');
327
+ }
328
+ if (crc32(data) !== entry.crc32) {
329
+ throw new ZipError('CRC 校验失败, 文件可能已损坏: ' + entry.name, 'ZIP_CORRUPT');
330
+ }
331
+ return { text: data.toString('utf8'), bytes: data.length, truncated: false };
332
+ }
333
+ return undefined;
334
+ } finally {
335
+ await fh.close();
336
+ }
337
+ }
package/package.json ADDED
@@ -0,0 +1,77 @@
1
+ {
2
+ "name": "dsh-mineru",
3
+ "version": "0.1.7",
4
+ "description": "dsh-mineru: MinerU 文档解析插件 for DeepSeek Harness — 多模态全格式 (PDF/Word/PPT/Excel/HTML/图片) → 结构化 Markdown. 填 Token 走精准解析 API, 留空走 Agent 轻量解析 API.",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "types": "lib/types/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./lib/types/index.d.ts",
11
+ "default": "./lib/index.js"
12
+ },
13
+ "./client": {
14
+ "types": "./lib/types/client.d.ts",
15
+ "default": "./lib/client.js"
16
+ },
17
+ "./package.json": "./package.json"
18
+ },
19
+ "files": [
20
+ "lib/",
21
+ "cordis.patch.yml",
22
+ "README.md",
23
+ "README.zh.md",
24
+ "CHANGELOG.md",
25
+ "RELEASE.md",
26
+ "CONTRIBUTING.md",
27
+ "LICENSE"
28
+ ],
29
+ "dsh": {
30
+ "bundle": {
31
+ "patch": "./cordis.patch.yml"
32
+ },
33
+ "client": {
34
+ "inject": [
35
+ "slots",
36
+ "connection",
37
+ "sessions",
38
+ "conversation"
39
+ ],
40
+ "platform": "web"
41
+ }
42
+ },
43
+ "peerDependencies": {
44
+ "@deepseek-ai/cordis": "^4.0.1",
45
+ "@deepseek-ai/schemastery": "^3.18.0",
46
+ "@deepseek-ai/dsh-tools": "^0.1.0-rc.6",
47
+ "@deepseek-ai/dsh-settings": "^0.1.0-rc.6",
48
+ "@deepseek-ai/dsh-credentials": "^0.1.0-rc.6",
49
+ "@deepseek-ai/dsh-skill": "^0.1.0-rc.6",
50
+ "@deepseek-ai/dsh-host-webserver": "^0.1.0-rc.6",
51
+ "@deepseek-ai/dsh-llm": "^0.1.0-rc.6"
52
+ },
53
+ "license": "MIT",
54
+ "keywords": [
55
+ "deepseek-harness",
56
+ "dsh",
57
+ "dsh-plugin",
58
+ "mineru",
59
+ "document-parsing",
60
+ "pdf",
61
+ "ocr",
62
+ "markdown",
63
+ "multimodal"
64
+ ],
65
+ "repository": {
66
+ "type": "git",
67
+ "url": "git+https://github.com/Lee-Hilex/dsh-mineru.git"
68
+ },
69
+ "homepage": "https://github.com/Lee-Hilex/dsh-mineru#readme",
70
+ "bugs": {
71
+ "url": "https://github.com/Lee-Hilex/dsh-mineru/issues"
72
+ },
73
+ "author": {
74
+ "name": "Lee-Hilex",
75
+ "email": "niuniu910417@163.com"
76
+ }
77
+ }