import fs from "node:fs"; import path from "node:path"; import type { ApprovalRun } from "./types.js"; export interface ApprovalRunAttachment { path: string; fieldPath: string; kind: string; fileName?: string; mimeType?: string; fileId?: string; ossPath?: string; url?: string; ossSignedUrl?: string; token?: unknown; tokenKey?: string; category?: string; ossFileSize?: number; invoiceId?: string; sourceField?: string; } export interface ApprovalRunAttachmentsResult { recordId: string; sourceDocumentSN?: string; sourceDocumentId?: string; count: number; attachments: Array>; } export type FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise; export interface DownloadAttachmentsOptions { record: ApprovalRun; all?: boolean; name?: string; outDir?: string; fetchFn?: FetchLike; } export interface DownloadedAttachmentFile { name: string; fileId?: string; path?: string; size?: number; expectedSize?: number; status: "success" | "failed"; error?: string; sourceField?: string; tokenKey?: string; } export interface DownloadAttachmentsResult { recordId: string; outDir: string; total: number; downloaded: number; failed: number; files: DownloadedAttachmentFile[]; } interface CollectContext { fieldLabel?: string; fieldKey?: string; fieldType?: string; } export function sanitizeUrlForLog(url: string): string { try { const parsed = new URL(url); if (parsed.search) { return `${parsed.origin}${parsed.pathname}?[MASKED]`; } return url; } catch { return url.replace(/\?.*$/, "?[MASKED]"); } } export function sanitizeFileName(name: string): string { const cleaned = name.replace(/[/\\?%*:|"<>]/g, "_").trim(); return cleaned || "attachment"; } function compactObject(object: Record) { return Object.fromEntries(Object.entries(object).filter(([, value]) => value !== undefined)); } function asRecord(value: unknown): Record | undefined { return value && typeof value === "object" && !Array.isArray(value) ? value as Record : undefined; } function stringFromUnknown(value: unknown): string | undefined { return typeof value === "string" && value.trim() ? value.trim() : undefined; } function numberFromUnknown(value: unknown): number | undefined { return typeof value === "number" && Number.isFinite(value) ? value : undefined; } function tryParseToken(token: unknown): Record | undefined { if (!token) return undefined; if (typeof token === "string") { try { const parsed = JSON.parse(token); if (parsed && typeof parsed === "object") return parsed as Record; } catch { return undefined; } } if (typeof token === "object" && !Array.isArray(token)) { return token as Record; } return undefined; } function looksLikeAttachment(object: Record, path: string, context?: CollectContext): boolean { // If parent field explicitly declares ATTACHMENT type, any item with file properties is an attachment if (context?.fieldType?.toUpperCase() === "ATTACHMENT") { const hasIdentifier = Boolean( object.fileName || object.filename || object.name || object.originalName || object.fileId || object.ossPath || object.url || object.ossSignedUrl || object.signedUrl || object.token ); if (hasIdentifier) return true; } // Explicit signed URL presence always indicates a download-ready attachment if (object.ossSignedUrl || object.signedUrl) { return true; } // Check common file identity properties const fileName = object.fileName ?? object.filename ?? object.name ?? object.originalName; const fileId = object.fileId ?? object.id ?? object.attachmentId; const ossPath = object.ossPath ?? object.ossKey; const url = object.url ?? object.downloadUrl ?? object.previewUrl; const mimeType = object.mimeType ?? object.mimetype ?? object.contentType; const ossFileSize = object.ossFileSize ?? object.fileSize ?? object.size; if (fileName && (url || ossPath || fileId || ossFileSize)) { return true; } if (fileId && (mimeType || ossFileSize || ossPath || url)) { return true; } // Legacy path and keyword based heuristics const keys = Object.keys(object).map((k) => k.toLowerCase()); const pathHint = /(attachment|attachments|invoice|receipt|file|files|附件|发票)/i.test(path) || Boolean(context?.fieldKey && /(attachment|attachments|invoice|receipt|file|files|附件|发票)/i.test(context.fieldKey)) || Boolean(context?.fieldLabel && /(attachment|attachments|invoice|receipt|file|files|附件|发票)/i.test(context.fieldLabel)); const fileHints = [ "filename", "filename", "mimetype", "contenttype", "fileid", "osspath", "signedurl", "downloadurl", "previewurl", "attachmentid", "ossfilesize", "osssignedurl" ]; return pathHint && fileHints.some((hint) => keys.includes(hint)); } function inferAttachmentKind(path: string, object: Record, context?: CollectContext): string { const normalized = `${path} ${context?.fieldLabel ?? ""} ${context?.fieldKey ?? ""} ${stringFromUnknown(object.type) ?? ""} ${stringFromUnknown(object.category) ?? ""}`.toLowerCase(); if (normalized.includes("invoice") || normalized.includes("发票")) return "invoice"; if (normalized.includes("receipt")) return "receipt"; const name = (stringFromUnknown(object.fileName) ?? stringFromUnknown(object.name) ?? "").toLowerCase(); if (name.includes("发票") || name.includes("invoice")) return "invoice"; return "attachment"; } function collectAttachments( value: unknown, path: string, output: Array>, seen: Set, context?: CollectContext ) { if (Array.isArray(value)) { value.forEach((item, index) => collectAttachments(item, `${path}.${index}`, output, seen, context)); return; } const object = asRecord(value); if (!object) return; // Determine if this object is a field container (e.g. in document.fields[]) const isFieldContainer = (object.type && typeof object.type === "string") || ("label" in object && "value" in object) || ("key" in object && "value" in object); let nextContext = context; if (isFieldContainer) { nextContext = { fieldLabel: stringFromUnknown(object.label) ?? context?.fieldLabel, fieldKey: stringFromUnknown(object.key) ?? context?.fieldKey, fieldType: stringFromUnknown(object.type) ?? context?.fieldType }; } // If this object itself qualifies as an attachment file // (containers that just have array value without url/fileId are not attachment files) const isContainerOnly = Array.isArray(object.value) && !object.url && !object.ossSignedUrl && !object.fileId; if (!isContainerOnly && looksLikeAttachment(object, path, context)) { const parsedToken = tryParseToken(object.token); const tokenKey = stringFromUnknown(parsedToken?.key); const tokenFileId = stringFromUnknown(parsedToken?.fileId); const attachment = compactObject({ path, fieldPath: path, kind: inferAttachmentKind(path, object, context), fileName: stringFromUnknown(object.fileName) ?? stringFromUnknown(object.filename) ?? stringFromUnknown(object.name) ?? stringFromUnknown(object.originalName), mimeType: stringFromUnknown(object.mimeType) ?? stringFromUnknown(object.mimetype) ?? stringFromUnknown(object.contentType), fileId: stringFromUnknown(object.fileId) ?? stringFromUnknown(object.id) ?? stringFromUnknown(object.attachmentId) ?? tokenFileId, ossPath: stringFromUnknown(object.ossPath) ?? stringFromUnknown(object.ossKey) ?? tokenKey, url: stringFromUnknown(object.url) ?? stringFromUnknown(object.signedUrl) ?? stringFromUnknown(object.downloadUrl) ?? stringFromUnknown(object.previewUrl), ossSignedUrl: stringFromUnknown(object.ossSignedUrl) ?? stringFromUnknown(object.signedUrl), token: object.token, tokenKey, category: stringFromUnknown(object.category), ossFileSize: numberFromUnknown(object.ossFileSize) ?? numberFromUnknown(object.fileSize) ?? numberFromUnknown(object.size), invoiceId: stringFromUnknown(object.invoiceId), sourceField: stringFromUnknown(object.fieldName) ?? stringFromUnknown(object.label) ?? context?.fieldLabel ?? context?.fieldKey }); const key = JSON.stringify(attachment); if (!seen.has(key)) { seen.add(key); output.push(attachment); } } for (const [key, child] of Object.entries(object)) { collectAttachments(child, `${path}.${key}`, output, seen, nextContext); } } export function extractApprovalRunAttachments( record: ApprovalRun, options: { summary?: boolean } = {} ): ApprovalRunAttachmentsResult { const roots: Array<[string, unknown]> = [ ["document", record.document], ["result", record.result], ["pipelineData", record.pipelineData], ["sourceExtendData", record.sourceExtendData] ]; const attachments: Array> = []; const seen = new Set(); for (const [path, value] of roots) { collectAttachments(value, path, attachments, seen); } return { recordId: record.id, sourceDocumentSN: record.sourceDocumentSN, sourceDocumentId: record.sourceDocumentId, count: attachments.length, attachments: options.summary ? attachments.map((attachment) => compactObject({ path: attachment.path, kind: attachment.kind, fileName: attachment.fileName, mimeType: attachment.mimeType, fileId: attachment.fileId, sourceField: attachment.sourceField, ossFileSize: attachment.ossFileSize, hasSignedUrl: Boolean(attachment.ossSignedUrl) })) : attachments }; } export async function downloadApprovalRunAttachments( options: DownloadAttachmentsOptions ): Promise { const { record, fetchFn = globalThis.fetch } = options; const extraction = extractApprovalRunAttachments(record, { summary: false }); const allAttachments = extraction.attachments as unknown as ApprovalRunAttachment[]; const resolvedOutDir = path.resolve(options.outDir ?? "./attachments"); if (allAttachments.length === 0) { return { recordId: record.id, outDir: resolvedOutDir, total: 0, downloaded: 0, failed: 0, files: [] }; } let selected: ApprovalRunAttachment[] = []; if (options.name) { const term = options.name.toLowerCase(); selected = allAttachments.filter((att) => { const fileName = att.fileName?.toLowerCase() ?? ""; const fileId = att.fileId?.toLowerCase() ?? ""; const tokenKey = att.tokenKey?.toLowerCase() ?? ""; return fileName.includes(term) || fileId === term || tokenKey.includes(term); }); if (selected.length === 0) { const available = allAttachments.map((a) => a.fileName ?? a.fileId).filter(Boolean).join(", "); throw new Error(`未找到匹配 "${options.name}" 的附件。可选附件: ${available || "无"}`); } } else if (!options.all) { if (allAttachments.length > 1) { const available = allAttachments.map((a) => a.fileName ?? a.fileId).filter(Boolean).join(", "); throw new Error( `共发现 ${allAttachments.length} 个附件。请使用 --all 下载全部附件,或使用 --name <名称|fileId> 指定下载项。可选附件: ${available}` ); } selected = allAttachments; } else { selected = allAttachments; } await fs.promises.mkdir(resolvedOutDir, { recursive: true }); const files: DownloadedAttachmentFile[] = []; const usedNames = new Set(); for (const attachment of selected) { const rawName = attachment.fileName ?? attachment.fileId ?? "attachment"; const safeBase = sanitizeFileName(rawName); let targetName = safeBase; const lastDot = safeBase.lastIndexOf("."); const stem = lastDot > 0 ? safeBase.slice(0, lastDot) : safeBase; const ext = lastDot > 0 ? safeBase.slice(lastDot) : ""; let counter = 1; while (usedNames.has(targetName.toLowerCase())) { targetName = `${stem}_${counter}${ext}`; counter++; } usedNames.add(targetName.toLowerCase()); const downloadUrl = attachment.ossSignedUrl ?? attachment.url; if (!downloadUrl) { console.error(`⚠️ [跳过] 附件 "${rawName}": 记录中无下载直链 (ossSignedUrl/url)`); files.push({ name: targetName, fileId: attachment.fileId, status: "failed", error: "缺少可用的下载直链 (ossSignedUrl/url)。", sourceField: attachment.sourceField, tokenKey: attachment.tokenKey }); continue; } const sanitizedUrl = sanitizeUrlForLog(downloadUrl); try { const response = await fetchFn(downloadUrl, { signal: AbortSignal.timeout(60000) }); if (!response.ok) { const errorMsg = response.status === 403 ? "HTTP 403 Forbidden: 签名直链可能已过期" : `HTTP ${response.status} ${response.statusText}`; throw new Error(errorMsg); } const arrayBuffer = await response.arrayBuffer(); const buffer = Buffer.from(arrayBuffer); if (attachment.ossFileSize !== undefined && buffer.length !== attachment.ossFileSize) { console.error(`⚠️ [校验] 附件 "${targetName}" 实际大小 (${buffer.length} 字节) 与 ossFileSize (${attachment.ossFileSize} 字节) 不一致`); } const filePath = path.join(resolvedOutDir, targetName); await fs.promises.writeFile(filePath, buffer); console.error(`✓ 已下载: ${targetName} (${buffer.length} 字节)`); files.push({ name: targetName, fileId: attachment.fileId, path: filePath, size: buffer.length, expectedSize: attachment.ossFileSize, status: "success", sourceField: attachment.sourceField, tokenKey: attachment.tokenKey }); } catch (err: any) { const msg = err.message ?? String(err); console.error(`⚠️ [失败] 附件 "${rawName}" 下载失败: ${msg} [${sanitizedUrl}]`); files.push({ name: targetName, fileId: attachment.fileId, status: "failed", error: msg, sourceField: attachment.sourceField, tokenKey: attachment.tokenKey }); } } const downloaded = files.filter((f) => f.status === "success").length; const failed = files.filter((f) => f.status === "failed").length; return { recordId: record.id, outDir: resolvedOutDir, total: selected.length, downloaded, failed, files }; }