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,307 @@
1
+ /**
2
+ * Artifact management: per-run directories under
3
+ * <workspace>/.dsh-mineru/artifacts/, metadata writing, and HMAC-signed
4
+ * capability URLs the Web host serves for preview/download.
5
+ * @module dsh-mineru/artifacts
6
+ */
7
+ import { randomBytes, createHmac, timingSafeEqual } from 'node:crypto';
8
+ import { mkdir, writeFile, stat, readdir, realpath } from 'node:fs/promises';
9
+ import { basename, join, resolve, sep } from 'node:path';
10
+
11
+ const SAFE_NAME = /^[A-Za-z0-9._-]+$/;
12
+
13
+ /** MIME map for artifact serving. */
14
+ export const MIME_MAP = Object.freeze({
15
+ '.md': 'text/markdown; charset=utf-8',
16
+ '.json': 'application/json; charset=utf-8',
17
+ '.txt': 'text/plain; charset=utf-8',
18
+ '.png': 'image/png',
19
+ '.jpg': 'image/jpeg',
20
+ '.jpeg': 'image/jpeg',
21
+ '.jp2': 'image/jp2',
22
+ '.webp': 'image/webp',
23
+ '.gif': 'image/gif',
24
+ '.bmp': 'image/bmp',
25
+ '.pdf': 'application/pdf',
26
+ '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
27
+ '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
28
+ '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
29
+ '.doc': 'application/msword',
30
+ '.ppt': 'application/vnd.ms-powerpoint',
31
+ '.xls': 'application/vnd.ms-excel',
32
+ '.zip': 'application/zip',
33
+ '.html': 'text/html; charset=utf-8',
34
+ '.htm': 'text/html; charset=utf-8',
35
+ '.svg': 'image/svg+xml',
36
+ });
37
+
38
+ /** Inline-previewable kinds (everything else serves as attachment). */
39
+ const INLINE_KINDS = new Set(['.md', '.json', '.txt', '.png', '.jpg', '.jpeg', '.jp2', '.webp', '.gif', '.bmp']);
40
+
41
+ function extOf(name) {
42
+ const i = name.lastIndexOf('.');
43
+ return i < 0 ? '' : name.slice(i).toLowerCase();
44
+ }
45
+
46
+ export function mimeFor(name) {
47
+ return MIME_MAP[extOf(name)] ?? 'application/octet-stream';
48
+ }
49
+
50
+ export function inlineable(name) {
51
+ return INLINE_KINDS.has(extOf(name));
52
+ }
53
+
54
+ export class ArtifactError extends Error {
55
+ constructor(message, code = 'ARTIFACT_ERROR') {
56
+ super(message);
57
+ this.name = 'ArtifactError';
58
+ this.code = code;
59
+ }
60
+ }
61
+
62
+ /** @param {string} value @returns {string} */
63
+ export function sanitizeRunName(value) {
64
+ const v = String(value ?? '').replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 80);
65
+ return v || 'parse';
66
+ }
67
+
68
+ /** @param {string} value @returns {string} */
69
+ export function sanitizeFileName(value) {
70
+ const v = String(value ?? '').replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 120);
71
+ if (!v || v === '.' || v === '..') throw new ArtifactError('invalid file name');
72
+ return v;
73
+ }
74
+
75
+ function stamp() {
76
+ const d = new Date();
77
+ const p = (n) => String(n).padStart(2, '0');
78
+ return d.getFullYear() + p(d.getMonth() + 1) + p(d.getDate()) + '-' + p(d.getHours()) + p(d.getMinutes()) + p(d.getSeconds());
79
+ }
80
+
81
+ /**
82
+ * Artifact store rooted at <workspace>/.dsh-mineru.
83
+ */
84
+ export class ArtifactManager {
85
+ /**
86
+ * @param {{rootDir: string, urlTtlSec?: number, pluginVersion?: string}} opts
87
+ */
88
+ constructor(opts) {
89
+ this.rootDir = resolve(opts.rootDir);
90
+ this.urlTtlSec = opts.urlTtlSec ?? 86400;
91
+ this.pluginVersion = opts.pluginVersion ?? '0.1.0';
92
+ this.secret = randomBytes(32);
93
+ }
94
+
95
+ async init() {
96
+ await mkdir(join(this.rootDir, 'artifacts'), { recursive: true });
97
+ await mkdir(join(this.rootDir, 'tmp'), { recursive: true });
98
+ }
99
+
100
+ /** @returns {string} tmp directory under the managed root */
101
+ get tmpDir() { return join(this.rootDir, 'tmp'); }
102
+
103
+ /**
104
+ * Create a fresh run directory and return its paths.
105
+ * @param {string} baseName sanitized base for the run name
106
+ * @returns {Promise<{dir: string, relDir: string, runName: string}>}
107
+ */
108
+ async createRun(baseName) {
109
+ await this.init();
110
+ const safe = sanitizeRunName(baseName);
111
+ const runName = safe + '_' + stamp() + '_' + randomBytes(2).toString('hex');
112
+ const dir = join(this.rootDir, 'artifacts', runName);
113
+ await mkdir(dir, { recursive: true });
114
+ return { dir, relDir: join('artifacts', runName), runName };
115
+ }
116
+
117
+ /** rel path of an artifact inside its run dir. */
118
+ relIn(relDir, fileName) {
119
+ return join(relDir, fileName);
120
+ }
121
+
122
+ /**
123
+ * @param {string} relPath forward-slash path relative to the managed root
124
+ * @param {string} [expSec] explicit expiry override
125
+ * @returns {string} base64url token: hmac(relPath + '.' + exp) + '.' + exp
126
+ */
127
+ capabilityToken(relPath, expSec) {
128
+ const exp = expSec ?? (Math.floor(Date.now() / 1000) + this.urlTtlSec);
129
+ const normalized = relPath.replace(/\\/g, '/');
130
+ const mac = createHmac('sha256', this.secret).update(normalized + '.' + exp).digest('base64url');
131
+ return mac + '.' + exp;
132
+ }
133
+
134
+ /**
135
+ * Verify a capability token for a relative path.
136
+ * @param {string} relPath
137
+ * @param {string} token
138
+ * @returns {{ok:boolean, expired?:boolean}}
139
+ */
140
+ verifyCapability(relPath, token) {
141
+ if (typeof token !== 'string' || typeof relPath !== 'string') return { ok: false };
142
+ const dot = token.lastIndexOf('.');
143
+ if (dot <= 0) return { ok: false };
144
+ const mac = token.slice(0, dot);
145
+ const exp = Number(token.slice(dot + 1));
146
+ if (!Number.isFinite(exp)) return { ok: false };
147
+ const normalized = relPath.replace(/\\/g, '/');
148
+ const expected = createHmac('sha256', this.secret).update(normalized + '.' + exp).digest('base64url');
149
+ const a = Buffer.from(mac);
150
+ const b = Buffer.from(expected);
151
+ if (a.length !== b.length || !timingSafeEqual(a, b)) return { ok: false };
152
+ if (exp < Math.floor(Date.now() / 1000)) return { ok: true, expired: true };
153
+ return { ok: true };
154
+ }
155
+
156
+ /**
157
+ * Resolve and validate a relative artifact path for serving.
158
+ * @param {string} relPath
159
+ * @param {{maxBytes?: number}} [opts]
160
+ * @returns {Promise<{abs: string, bytes: number, mime: string}>}
161
+ */
162
+ async resolveServe(relPath, opts = {}) {
163
+ const normalized = String(relPath ?? '').replace(/\\/g, '/');
164
+ if (!normalized || normalized.includes('..') || normalized.startsWith('/')) {
165
+ throw new ArtifactError('invalid artifact path', 'ARTIFACT_BAD_PATH');
166
+ }
167
+ const abs = resolve(this.rootDir, normalized);
168
+ const root = this.rootDir + sep;
169
+ if (!abs.startsWith(root)) throw new ArtifactError('artifact path escapes managed root', 'ARTIFACT_BAD_PATH');
170
+ let st;
171
+ try { st = await stat(abs); } catch { throw new ArtifactError('artifact not found', 'ARTIFACT_NOT_FOUND'); }
172
+ if (!st.isFile()) throw new ArtifactError('artifact is not a file', 'ARTIFACT_NOT_FOUND');
173
+ if (opts.maxBytes && st.size > opts.maxBytes) throw new ArtifactError('artifact too large to serve', 'ARTIFACT_TOO_LARGE');
174
+ return { abs, bytes: st.size, mime: mimeFor(basename(abs)) };
175
+ }
176
+
177
+ /**
178
+ * Write a UTF-8 metadata/text file inside a run dir.
179
+ * @returns {Promise<string>} absolute path
180
+ */
181
+ async writeFile(runDir, fileName, content) {
182
+ const safe = sanitizeFileName(fileName);
183
+ const abs = join(runDir, safe);
184
+ await writeFile(abs, content, 'utf8');
185
+ return abs;
186
+ }
187
+
188
+ /**
189
+ * Build the artifact descriptor list for one run dir.
190
+ * @param {string} relDir run dir relative to managed root
191
+ * @param {{capabilityFor: (rel: string) => string}} [urls]
192
+ * @returns {Promise<object[]>}
193
+ */
194
+ async describeRun(relDir, urls) {
195
+ const dir = join(this.rootDir, relDir);
196
+ const names = await readdir(dir, { withFileTypes: true });
197
+ const out = [];
198
+ for (const entry of names) {
199
+ if (!entry.isFile()) continue;
200
+ const rel = join(relDir, entry.name);
201
+ const abs = join(dir, entry.name);
202
+ const st = await stat(abs).catch(() => null);
203
+ if (!st) continue;
204
+ // capabilityFor may be async (the Web urlBuilder is) and may throw when
205
+ // the HTTP host is unavailable; a preview URL is optional metadata and
206
+ // must never fail or pollute the canonical result with a non-JSON value.
207
+ let url;
208
+ try {
209
+ url = urls ? await urls.capabilityFor(rel.replace(/\\/g, '/')) : undefined;
210
+ } catch {
211
+ url = undefined;
212
+ }
213
+ out.push({
214
+ name: entry.name,
215
+ path: abs,
216
+ rel: rel.replace(/\\/g, '/'),
217
+ kind: kindFor(entry.name),
218
+ mime: mimeFor(entry.name),
219
+ bytes: st.size,
220
+ ...(url !== undefined ? { url } : {}),
221
+ });
222
+ }
223
+ return out;
224
+ }
225
+ }
226
+
227
+ /** @param {string} name @returns {string} artifact kind label */
228
+ export function kindFor(name) {
229
+ const lower = name.toLowerCase();
230
+ if (lower === 'full.md' || lower.endsWith('.md')) return 'markdown';
231
+ if (lower.endsWith('.json')) return 'json';
232
+ if (lower.endsWith('.zip')) return 'zip';
233
+ if (/.(png|jpe?g|jp2|webp|gif|bmp)$/.test(lower)) return 'image';
234
+ if (lower.endsWith('.docx') || lower.endsWith('.doc')) return 'docx';
235
+ if (lower.endsWith('.html') || lower.endsWith('.htm')) return 'html';
236
+ if (lower.endsWith('.tex') || lower.endsWith('.latex')) return 'latex';
237
+ return 'other';
238
+ }/**
239
+ * Workspace-keyed artifact stores: one ArtifactManager per canonical session
240
+ * workspace, shared between tool execution (writing + capability URLs) and the
241
+ * Web host (serving + verification).
242
+ */
243
+ export class WorkspaceArtifactStore {
244
+ /**
245
+ * @param {{artifactRootName: string, urlTtlSec?: number, pluginVersion?: string}} opts
246
+ */
247
+ constructor(opts) {
248
+ this.artifactRootName = opts.artifactRootName;
249
+ this.urlTtlSec = opts.urlTtlSec ?? 86400;
250
+ this.pluginVersion = opts.pluginVersion ?? '0.1.0';
251
+ /** @type {Map<string, ArtifactManager>} */
252
+ this.managers = new Map();
253
+ }
254
+
255
+ /**
256
+ * @param {string} cwd session workspace
257
+ * @returns {Promise<ArtifactManager>}
258
+ */
259
+ async managerFor(cwd) {
260
+ let canon;
261
+ try { canon = await realpath(resolve(cwd)); } catch { canon = resolve(cwd); }
262
+ let m = this.managers.get(canon);
263
+ if (!m) {
264
+ m = new ArtifactManager({
265
+ rootDir: join(canon, this.artifactRootName),
266
+ urlTtlSec: this.urlTtlSec,
267
+ pluginVersion: this.pluginVersion,
268
+ });
269
+ await m.init();
270
+ this.managers.set(canon, m);
271
+ }
272
+ return m;
273
+ }
274
+
275
+ /** @returns {ArtifactManager[]} */
276
+ list() { return [...this.managers.values()]; }
277
+
278
+ /** @param {number} index @returns {ArtifactManager|null} */
279
+ managerByIndex(index) {
280
+ const all = this.list();
281
+ const i = Number(index);
282
+ return Number.isInteger(i) && i >= 0 && i < all.length ? all[i] : null;
283
+ }
284
+
285
+ /**
286
+ * @param {string} cwd session workspace
287
+ * @returns {Promise<number>} workspace index (stable while the map is unchanged)
288
+ */
289
+ async indexFor(cwd) {
290
+ const m = await this.managerFor(cwd);
291
+ return this.list().indexOf(m);
292
+ }
293
+
294
+ /**
295
+ * Build a capability URL for one artifact relative path.
296
+ * @param {string} cwd session workspace
297
+ * @param {string} rel relative path inside the managed root
298
+ * @returns {Promise<string>}
299
+ */
300
+ async capabilityUrl(cwd, rel) {
301
+ const idx = await this.indexFor(cwd);
302
+ const m = this.managerByIndex(idx);
303
+ const normalized = rel.replace(/\\/g, '/');
304
+ const token = m.capabilityToken(idx + '|' + normalized);
305
+ return '/plugin/mineru/artifact?w=' + idx + '&p=' + encodeURIComponent(normalized) + '&t=' + encodeURIComponent(token);
306
+ }
307
+ }