plugin-document-understanding 1.1.15 → 2.0.0
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/LICENSE +201 -0
- package/README.md +19 -25
- package/dist/client/169.6888909107c553c3.js +10 -0
- package/dist/client/379.e29f5ced467ce23d.js +10 -0
- package/dist/client/867.3ed3b814115181ca.js +10 -0
- package/dist/client/index.js +1 -1
- package/dist/client-v2/169.53bf1be2ec192f0c.js +10 -0
- package/dist/client-v2/379.e75c4829567cdb89.js +10 -0
- package/dist/client-v2/867.66d7291e95f1de78.js +10 -0
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +10 -8
- package/dist/locale/en-US.json +126 -0
- package/dist/locale/vi-VN.json +130 -2
- package/dist/locale/zh-CN.json +127 -1
- package/dist/node_modules/form-data/package.json +1 -1
- package/dist/node_modules/mime-types/package.json +1 -1
- package/dist/server/actions.js +211 -11
- package/dist/server/collections/api-keys.js +55 -0
- package/dist/server/collections/artifacts.js +59 -0
- package/dist/server/collections/config.js +9 -3
- package/dist/server/collections/endpoints.js +3 -0
- package/dist/server/collections/jobs.js +7 -4
- package/dist/server/collections/operations.js +76 -0
- package/dist/server/contracts/du-contracts.js +828 -0
- package/dist/server/dugate-seed.js +98 -340
- package/dist/server/plugin.js +49 -7
- package/dist/server/routes/du-gateway-router.js +443 -0
- package/dist/server/services/ArtifactStorageService.js +459 -0
- package/dist/server/services/AsyncJobManager.js +1 -1
- package/dist/server/services/BuiltinBusinessEngine.js +1223 -0
- package/dist/server/services/DocumentUnderstandingService.js +151 -25
- package/dist/server/services/ExternalDuReworkClient.js +210 -0
- package/dist/server/services/OperationOrchestrator.js +1087 -0
- package/dist/server/services/PipelineExecutor.js +164 -43
- package/dist/server/tools/document-understanding-tool.js +49 -24
- package/dist/server/workflow/DocumentUnderstandingInstruction.js +292 -0
- package/package.json +8 -4
- package/src/client/index.tsx +11 -0
- package/src/client-v2/components/ApiKeysTab.tsx +198 -0
- package/src/client-v2/components/EndpointsTab.tsx +39 -2
- package/src/client-v2/components/JobsTab.tsx +136 -21
- package/src/client-v2/components/OperationsTab.tsx +586 -0
- package/src/client-v2/components/PluginSettings.tsx +24 -8
- package/src/client-v2/components/ServiceConfigTab.tsx +225 -65
- package/src/client-v2/components/__tests__/PluginSettings.test.tsx +43 -0
- package/src/client-v2/locale.ts +1 -8
- package/src/client-v2/models/index.ts +1 -8
- package/src/client-v2/plugin.tsx +12 -8
- package/src/client-v2/types.ts +13 -1
- package/src/client-v2/workflow/DocumentUnderstandingFieldset.tsx +122 -0
- package/src/client-v2/workflow/DocumentUnderstandingInstruction.tsx +49 -0
- package/src/locale/en-US.json +126 -0
- package/src/locale/vi-VN.json +130 -2
- package/src/locale/zh-CN.json +127 -1
- package/src/server/__tests__/actions.test.ts +1 -8
- package/src/server/__tests__/du-rework-gateway.test.ts +462 -0
- package/src/server/__tests__/dugate-integration.test.ts +79 -42
- package/src/server/__tests__/smoke.test.ts +1 -8
- package/src/server/__tests__/upload-security.test.ts +1 -8
- package/src/server/actions.ts +252 -36
- package/src/server/collections/api-keys.ts +35 -0
- package/src/server/collections/artifacts.ts +39 -0
- package/src/server/collections/config.ts +18 -2
- package/src/server/collections/endpoints.ts +12 -0
- package/src/server/collections/jobs.ts +16 -4
- package/src/server/collections/operations.ts +56 -0
- package/src/server/contracts/du-contracts.ts +1026 -0
- package/src/server/dugate-seed.ts +126 -453
- package/src/server/plugin.ts +64 -14
- package/src/server/routes/du-gateway-router.ts +465 -0
- package/src/server/services/ArtifactStorageService.ts +596 -0
- package/src/server/services/AsyncJobManager.ts +10 -1
- package/src/server/services/BuiltinBusinessEngine.ts +1544 -0
- package/src/server/services/DocumentUnderstandingService.ts +186 -44
- package/src/server/services/ExternalDuReworkClient.ts +222 -0
- package/src/server/services/OperationOrchestrator.ts +1359 -0
- package/src/server/services/PipelineExecutor.ts +245 -108
- package/src/server/tools/document-understanding-tool.ts +63 -45
- package/src/server/types.ts +101 -16
- package/src/server/workflow/DocumentUnderstandingInstruction.ts +308 -0
- package/dist/client/345.e6e484fb1974c3d3.js +0 -10
- package/dist/client-v2/345.a8f28526ac21e02a.js +0 -10
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This file is part of the NocoBase (R) project.
|
|
3
|
+
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
|
|
4
|
+
* Authors: NocoBase Team.
|
|
5
|
+
*
|
|
6
|
+
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
|
|
7
|
+
* For more information, please refer to: https://www.nocobase.com/agreement.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
var __create = Object.create;
|
|
11
|
+
var __defProp = Object.defineProperty;
|
|
12
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
13
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
14
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
15
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
16
|
+
var __export = (target, all) => {
|
|
17
|
+
for (var name in all)
|
|
18
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
19
|
+
};
|
|
20
|
+
var __copyProps = (to, from, except, desc) => {
|
|
21
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
22
|
+
for (let key of __getOwnPropNames(from))
|
|
23
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
24
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
25
|
+
}
|
|
26
|
+
return to;
|
|
27
|
+
};
|
|
28
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
29
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
30
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
31
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
32
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
33
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
34
|
+
mod
|
|
35
|
+
));
|
|
36
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
37
|
+
var ArtifactStorageService_exports = {};
|
|
38
|
+
__export(ArtifactStorageService_exports, {
|
|
39
|
+
ArtifactStorageService: () => ArtifactStorageService,
|
|
40
|
+
DuHttpError: () => DuHttpError
|
|
41
|
+
});
|
|
42
|
+
module.exports = __toCommonJS(ArtifactStorageService_exports);
|
|
43
|
+
var crypto = __toESM(require("crypto"));
|
|
44
|
+
var import_fs = require("fs");
|
|
45
|
+
var import_path = require("path");
|
|
46
|
+
var import_mime_types = __toESM(require("mime-types"));
|
|
47
|
+
var import_du_contracts = require("../contracts/du-contracts");
|
|
48
|
+
class DuHttpError extends Error {
|
|
49
|
+
problem;
|
|
50
|
+
constructor(problem) {
|
|
51
|
+
super(problem.detail || problem.title);
|
|
52
|
+
this.name = "DuHttpError";
|
|
53
|
+
this.problem = problem;
|
|
54
|
+
}
|
|
55
|
+
get status() {
|
|
56
|
+
return this.problem.status;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const ARTIFACTS_COLLECTION = "doc_understanding_artifacts";
|
|
60
|
+
const DEFAULT_GATEWAY_UPLOAD_MAX_BYTES = 64 * 1024 * 1024;
|
|
61
|
+
function sanitizeSegment(raw, fallback) {
|
|
62
|
+
const cleaned = (0, import_path.basename)(raw || fallback).replace(/[^a-zA-Z0-9._-]/g, "_").replace(/_{2,}/g, "_").slice(0, 120);
|
|
63
|
+
return cleaned || fallback;
|
|
64
|
+
}
|
|
65
|
+
function sha256Hex(buffer) {
|
|
66
|
+
return crypto.createHash("sha256").update(buffer).digest("hex");
|
|
67
|
+
}
|
|
68
|
+
function htmlToMarkdown(html) {
|
|
69
|
+
return html.replace(/<script[\s\S]*?<\/script>/gi, "").replace(/<style[\s\S]*?<\/style>/gi, "").replace(/<h1[^>]*>([\s\S]*?)<\/h1>/gi, "\n# $1\n").replace(/<h2[^>]*>([\s\S]*?)<\/h2>/gi, "\n## $1\n").replace(/<h3[^>]*>([\s\S]*?)<\/h3>/gi, "\n### $1\n").replace(/<li[^>]*>([\s\S]*?)<\/li>/gi, "\n- $1").replace(/<br\s*\/?>/gi, "\n").replace(/<\/p>/gi, "\n\n").replace(/<\/tr>/gi, "\n").replace(/<t[dh][^>]*>([\s\S]*?)<\/t[dh]>/gi, " | $1").replace(/<[^>]+>/g, "").replace(/ /gi, " ").replace(/&/gi, "&").replace(/</gi, "<").replace(/>/gi, ">").replace(/"/gi, '"').replace(/\n{3,}/g, "\n\n").trim();
|
|
70
|
+
}
|
|
71
|
+
function toPlainRecord(row) {
|
|
72
|
+
if (row && typeof row === "object" && typeof row.toJSON === "function") {
|
|
73
|
+
return row.toJSON();
|
|
74
|
+
}
|
|
75
|
+
return row;
|
|
76
|
+
}
|
|
77
|
+
function resolveAiWorkerLoader() {
|
|
78
|
+
try {
|
|
79
|
+
const aiModule = require("@nocobase/ai");
|
|
80
|
+
return typeof aiModule.loadByWorker === "function" ? aiModule.loadByWorker : null;
|
|
81
|
+
} catch {
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
class ArtifactStorageService {
|
|
86
|
+
db;
|
|
87
|
+
storageRoot;
|
|
88
|
+
constructor(db, customStorageRoot) {
|
|
89
|
+
this.db = db;
|
|
90
|
+
this.storageRoot = customStorageRoot || (0, import_path.resolve)(process.cwd(), "storage", "uploads", "doc-understanding", "artifacts");
|
|
91
|
+
(0, import_fs.mkdirSync)(this.storageRoot, { recursive: true });
|
|
92
|
+
}
|
|
93
|
+
assertSafeStoragePath(targetPath) {
|
|
94
|
+
const resolvedRoot = (0, import_fs.existsSync)(this.storageRoot) ? (0, import_fs.realpathSync)(this.storageRoot) : (0, import_path.resolve)(this.storageRoot);
|
|
95
|
+
const resolvedTarget = (0, import_path.resolve)(targetPath);
|
|
96
|
+
if (resolvedTarget !== resolvedRoot && !resolvedTarget.startsWith(`${resolvedRoot}${import_path.sep}`)) {
|
|
97
|
+
throw new DuHttpError((0, import_du_contracts.createProblem)(403, "PERMISSION_DENIED", "Artifact storage path is outside allowed root"));
|
|
98
|
+
}
|
|
99
|
+
return resolvedTarget;
|
|
100
|
+
}
|
|
101
|
+
buildArtifactPath(tenantId, artifactId, fileName) {
|
|
102
|
+
const safeTenant = sanitizeSegment(tenantId, "default");
|
|
103
|
+
const tenantDir = (0, import_path.resolve)(this.storageRoot, safeTenant);
|
|
104
|
+
(0, import_fs.mkdirSync)(tenantDir, { recursive: true });
|
|
105
|
+
const safeName = sanitizeSegment(fileName, "document.bin");
|
|
106
|
+
return this.assertSafeStoragePath((0, import_path.resolve)(tenantDir, `${artifactId}__${safeName}`));
|
|
107
|
+
}
|
|
108
|
+
async initiateUpload(params) {
|
|
109
|
+
const {
|
|
110
|
+
tenantId,
|
|
111
|
+
fileName,
|
|
112
|
+
sizeBytes,
|
|
113
|
+
uploadToken,
|
|
114
|
+
idempotencyKey,
|
|
115
|
+
maxFileSizeBytes = DEFAULT_GATEWAY_UPLOAD_MAX_BYTES,
|
|
116
|
+
userId,
|
|
117
|
+
urlPrefix = "/api/du/v1"
|
|
118
|
+
} = params;
|
|
119
|
+
if (!fileName || typeof fileName !== "string" || !fileName.trim()) {
|
|
120
|
+
throw new DuHttpError(
|
|
121
|
+
(0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", "fileName is required", {
|
|
122
|
+
errors: [{ pointer: "/fileName", message: "Expected non-empty string" }]
|
|
123
|
+
})
|
|
124
|
+
);
|
|
125
|
+
}
|
|
126
|
+
if (!Number.isFinite(sizeBytes) || sizeBytes < 0) {
|
|
127
|
+
throw new DuHttpError(
|
|
128
|
+
(0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", "sizeBytes must be a non-negative integer", {
|
|
129
|
+
errors: [{ pointer: "/sizeBytes", message: "Expected integer >= 0" }]
|
|
130
|
+
})
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
if (sizeBytes > maxFileSizeBytes) {
|
|
134
|
+
throw new DuHttpError(
|
|
135
|
+
(0, import_du_contracts.createProblem)(413, "PAYLOAD_TOO_LARGE", `Upload size ${sizeBytes} exceeds limit ${maxFileSizeBytes} bytes`)
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
const resolvedMime = (params.mimeType || import_mime_types.default.lookup(fileName) || "application/octet-stream").toString();
|
|
139
|
+
const repo = this.db.getRepository(ARTIFACTS_COLLECTION);
|
|
140
|
+
const dedupKey = (idempotencyKey == null ? void 0 : idempotencyKey.trim()) || (uploadToken == null ? void 0 : uploadToken.trim());
|
|
141
|
+
if (dedupKey) {
|
|
142
|
+
const existingRow = await repo.findOne({
|
|
143
|
+
filter: uploadToken ? { tenantId, $or: [{ artifactId: uploadToken }, { idempotencyKey: dedupKey }] } : { tenantId, idempotencyKey: dedupKey }
|
|
144
|
+
});
|
|
145
|
+
if (existingRow) {
|
|
146
|
+
const existing = toPlainRecord(existingRow);
|
|
147
|
+
if (existing.fileName !== fileName || existing.mimeType !== resolvedMime) {
|
|
148
|
+
throw new DuHttpError(
|
|
149
|
+
(0, import_du_contracts.createProblem)(
|
|
150
|
+
409,
|
|
151
|
+
"IDEMPOTENCY_CONFLICT",
|
|
152
|
+
"Idempotency-Key / uploadToken reused with different file metadata"
|
|
153
|
+
)
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
return {
|
|
157
|
+
httpStatus: 200,
|
|
158
|
+
artifactId: existing.artifactId,
|
|
159
|
+
state: existing.state,
|
|
160
|
+
replayed: true,
|
|
161
|
+
uploadUrl: `${urlPrefix}/uploads/${existing.artifactId}/content`
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
const artifactId = uploadToken && /^[0-9a-fA-F-]{8,64}$/.test(uploadToken.trim()) ? uploadToken.trim() : crypto.randomUUID();
|
|
166
|
+
const storagePath = this.buildArtifactPath(tenantId, artifactId, fileName);
|
|
167
|
+
await repo.create({
|
|
168
|
+
values: {
|
|
169
|
+
artifactId,
|
|
170
|
+
tenantId,
|
|
171
|
+
role: "input",
|
|
172
|
+
state: "UPLOADING",
|
|
173
|
+
fileName: fileName.trim(),
|
|
174
|
+
mimeType: resolvedMime,
|
|
175
|
+
sizeBytes,
|
|
176
|
+
storagePath,
|
|
177
|
+
idempotencyKey: dedupKey || null,
|
|
178
|
+
createdById: userId ?? null
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
return {
|
|
182
|
+
httpStatus: 201,
|
|
183
|
+
artifactId,
|
|
184
|
+
state: "UPLOADING",
|
|
185
|
+
replayed: false,
|
|
186
|
+
uploadUrl: `${urlPrefix}/uploads/${artifactId}/content`
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
async writeUploadContent(params) {
|
|
190
|
+
const {
|
|
191
|
+
tenantId,
|
|
192
|
+
artifactId,
|
|
193
|
+
buffer,
|
|
194
|
+
expectedSha256,
|
|
195
|
+
maxFileSizeBytes = DEFAULT_GATEWAY_UPLOAD_MAX_BYTES
|
|
196
|
+
} = params;
|
|
197
|
+
if (buffer.length > maxFileSizeBytes) {
|
|
198
|
+
throw new DuHttpError(
|
|
199
|
+
(0, import_du_contracts.createProblem)(
|
|
200
|
+
413,
|
|
201
|
+
"PAYLOAD_TOO_LARGE",
|
|
202
|
+
`Payload size ${buffer.length} exceeds limit ${maxFileSizeBytes} bytes`
|
|
203
|
+
)
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
const repo = this.db.getRepository(ARTIFACTS_COLLECTION);
|
|
207
|
+
const row = await repo.findOne({ filter: { tenantId, artifactId } });
|
|
208
|
+
if (!row) {
|
|
209
|
+
throw new DuHttpError((0, import_du_contracts.createProblem)(404, "NOT_FOUND", `Upload session ${artifactId} not found`));
|
|
210
|
+
}
|
|
211
|
+
const record = toPlainRecord(row);
|
|
212
|
+
if (record.state === "ABORTED") {
|
|
213
|
+
throw new DuHttpError((0, import_du_contracts.createProblem)(409, "STATE_CONFLICT", "Upload session has already been aborted"));
|
|
214
|
+
}
|
|
215
|
+
const actualSha256 = sha256Hex(buffer);
|
|
216
|
+
if (expectedSha256 && expectedSha256.trim().toLowerCase() !== actualSha256) {
|
|
217
|
+
throw new DuHttpError((0, import_du_contracts.createProblem)(422, "CHECKSUM_MISMATCH", "x-content-sha256 does not match uploaded bytes"));
|
|
218
|
+
}
|
|
219
|
+
if (record.state === "READY") {
|
|
220
|
+
if (record.hashSha256 && record.hashSha256 !== actualSha256) {
|
|
221
|
+
throw new DuHttpError(
|
|
222
|
+
(0, import_du_contracts.createProblem)(409, "IDEMPOTENCY_CONFLICT", "Artifact content already finalized with a different digest")
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
return {
|
|
226
|
+
httpStatus: 200,
|
|
227
|
+
artifactId,
|
|
228
|
+
state: "READY",
|
|
229
|
+
sizeBytes: record.sizeBytes,
|
|
230
|
+
hashSha256: actualSha256,
|
|
231
|
+
replayed: true
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
const safePath = this.assertSafeStoragePath(record.storagePath);
|
|
235
|
+
(0, import_fs.mkdirSync)((0, import_path.resolve)(safePath, ".."), { recursive: true });
|
|
236
|
+
(0, import_fs.writeFileSync)(safePath, buffer);
|
|
237
|
+
await repo.update({
|
|
238
|
+
filter: { tenantId, artifactId },
|
|
239
|
+
values: {
|
|
240
|
+
state: "READY",
|
|
241
|
+
sizeBytes: buffer.length,
|
|
242
|
+
hashSha256: actualSha256
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
return {
|
|
246
|
+
httpStatus: 201,
|
|
247
|
+
artifactId,
|
|
248
|
+
state: "READY",
|
|
249
|
+
sizeBytes: buffer.length,
|
|
250
|
+
hashSha256: actualSha256,
|
|
251
|
+
replayed: false
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
async completeUpload(tenantId, artifactId) {
|
|
255
|
+
const record = await this.getArtifactOrThrow(tenantId, artifactId);
|
|
256
|
+
if (record.state !== "READY") {
|
|
257
|
+
throw new DuHttpError(
|
|
258
|
+
(0, import_du_contracts.createProblem)(409, "STATE_CONFLICT", `Artifact ${artifactId} cannot complete from state ${record.state}`)
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
return { artifactId, state: "READY", replayed: true };
|
|
262
|
+
}
|
|
263
|
+
async abortUpload(tenantId, artifactId) {
|
|
264
|
+
const repo = this.db.getRepository(ARTIFACTS_COLLECTION);
|
|
265
|
+
const record = await this.getArtifactOrThrow(tenantId, artifactId);
|
|
266
|
+
if (record.state === "READY") {
|
|
267
|
+
throw new DuHttpError((0, import_du_contracts.createProblem)(409, "STATE_CONFLICT", "Cannot abort an already READY artifact"));
|
|
268
|
+
}
|
|
269
|
+
try {
|
|
270
|
+
const safePath = this.assertSafeStoragePath(record.storagePath);
|
|
271
|
+
if ((0, import_fs.existsSync)(safePath)) {
|
|
272
|
+
(0, import_fs.rmSync)(safePath, { force: true });
|
|
273
|
+
}
|
|
274
|
+
} catch {
|
|
275
|
+
}
|
|
276
|
+
await repo.update({
|
|
277
|
+
filter: { tenantId, artifactId },
|
|
278
|
+
values: { state: "ABORTED" }
|
|
279
|
+
});
|
|
280
|
+
return { artifactId, state: "ABORTED" };
|
|
281
|
+
}
|
|
282
|
+
async createReadyArtifactFromBuffer(params) {
|
|
283
|
+
const artifactId = crypto.randomUUID();
|
|
284
|
+
const resolvedMime = (params.mimeType || import_mime_types.default.lookup(params.fileName) || "application/octet-stream").toString();
|
|
285
|
+
const storagePath = this.buildArtifactPath(params.tenantId, artifactId, params.fileName);
|
|
286
|
+
const hashSha256 = sha256Hex(params.buffer);
|
|
287
|
+
(0, import_fs.writeFileSync)(storagePath, params.buffer);
|
|
288
|
+
const values = {
|
|
289
|
+
artifactId,
|
|
290
|
+
tenantId: params.tenantId,
|
|
291
|
+
operationId: params.operationId ?? null,
|
|
292
|
+
role: params.role || "input",
|
|
293
|
+
state: "READY",
|
|
294
|
+
fileName: params.fileName,
|
|
295
|
+
mimeType: resolvedMime,
|
|
296
|
+
sizeBytes: params.buffer.length,
|
|
297
|
+
hashSha256,
|
|
298
|
+
storagePath,
|
|
299
|
+
createdById: params.userId ?? null
|
|
300
|
+
};
|
|
301
|
+
const created = await this.db.getRepository(ARTIFACTS_COLLECTION).create({ values });
|
|
302
|
+
return toPlainRecord(created);
|
|
303
|
+
}
|
|
304
|
+
async createJsonOutputArtifact(params) {
|
|
305
|
+
const serialized = Buffer.from(JSON.stringify(params.payload, null, 2), "utf8");
|
|
306
|
+
return this.createReadyArtifactFromBuffer({
|
|
307
|
+
tenantId: params.tenantId,
|
|
308
|
+
operationId: params.operationId,
|
|
309
|
+
role: "output",
|
|
310
|
+
fileName: params.fileName || `${params.operationId}.result.json`,
|
|
311
|
+
mimeType: "application/json",
|
|
312
|
+
buffer: serialized,
|
|
313
|
+
userId: params.userId
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
async getArtifactOrThrow(tenantId, artifactId) {
|
|
317
|
+
const row = await this.db.getRepository(ARTIFACTS_COLLECTION).findOne({
|
|
318
|
+
filter: { tenantId, artifactId }
|
|
319
|
+
});
|
|
320
|
+
if (!row) {
|
|
321
|
+
throw new DuHttpError((0, import_du_contracts.createProblem)(404, "NOT_FOUND", `Artifact ${artifactId} not found`));
|
|
322
|
+
}
|
|
323
|
+
return toPlainRecord(row);
|
|
324
|
+
}
|
|
325
|
+
readArtifactBuffer(record) {
|
|
326
|
+
if (record.state !== "READY") {
|
|
327
|
+
throw new DuHttpError(
|
|
328
|
+
(0, import_du_contracts.createProblem)(
|
|
329
|
+
409,
|
|
330
|
+
"STATE_CONFLICT",
|
|
331
|
+
`Artifact ${record.artifactId} is in state ${record.state}, expected READY`
|
|
332
|
+
)
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
const safePath = this.assertSafeStoragePath(record.storagePath);
|
|
336
|
+
if (!(0, import_fs.existsSync)(safePath)) {
|
|
337
|
+
throw new DuHttpError((0, import_du_contracts.createProblem)(404, "NOT_FOUND", `Artifact ${record.artifactId} blob missing from storage`));
|
|
338
|
+
}
|
|
339
|
+
return (0, import_fs.readFileSync)(safePath);
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Local Document Kit: parses digital documents (PDF, DOCX, XLSX, PPTX, CSV, TXT, MD, JSON, HTML)
|
|
343
|
+
* into per-page text/Markdown and applies DI-06 page selection when requested.
|
|
344
|
+
*/
|
|
345
|
+
async parseArtifactPages(record, selection = { kind: "all" }) {
|
|
346
|
+
const buffer = this.readArtifactBuffer(record);
|
|
347
|
+
const ext = ((0, import_path.extname)(record.fileName) || `.${import_mime_types.default.extension(record.mimeType) || "txt"}`).toLowerCase();
|
|
348
|
+
const isImage = record.mimeType.startsWith("image/") || [".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tiff"].includes(ext);
|
|
349
|
+
if (isImage) {
|
|
350
|
+
const pages2 = [{ pageNumber: 1, text: "" }];
|
|
351
|
+
const selectedNums2 = (0, import_du_contracts.expandPageRanges)(selection, 1);
|
|
352
|
+
return {
|
|
353
|
+
artifactId: record.artifactId,
|
|
354
|
+
fileName: record.fileName,
|
|
355
|
+
mimeType: record.mimeType,
|
|
356
|
+
detectedFormat: ext.replace(/^\./, "") || "image",
|
|
357
|
+
totalPageCount: 1,
|
|
358
|
+
selectedPages: pages2.filter((p) => selectedNums2.includes(p.pageNumber)),
|
|
359
|
+
markdown: "",
|
|
360
|
+
text: "",
|
|
361
|
+
requiresVision: true,
|
|
362
|
+
parser: "image-vision-candidate"
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
let pages = [];
|
|
366
|
+
let parserName = "local-text";
|
|
367
|
+
let requiresVision = false;
|
|
368
|
+
if (ext === ".html" || ext === ".htm" || record.mimeType === "text/html") {
|
|
369
|
+
const md = htmlToMarkdown(buffer.toString("utf8"));
|
|
370
|
+
pages = [{ pageNumber: 1, text: md }];
|
|
371
|
+
parserName = "local-html";
|
|
372
|
+
} else if (ext === ".json" || record.mimeType === "application/json") {
|
|
373
|
+
const raw = buffer.toString("utf8");
|
|
374
|
+
let formatted = raw;
|
|
375
|
+
try {
|
|
376
|
+
formatted = JSON.stringify(JSON.parse(raw), null, 2);
|
|
377
|
+
} catch {
|
|
378
|
+
}
|
|
379
|
+
pages = [{ pageNumber: 1, text: formatted }];
|
|
380
|
+
parserName = "local-json";
|
|
381
|
+
} else if ([".txt", ".md"].includes(ext) || record.mimeType.startsWith("text/plain") || record.mimeType === "text/markdown") {
|
|
382
|
+
const raw = buffer.toString("utf8");
|
|
383
|
+
const formFeedPages = raw.split("\f");
|
|
384
|
+
pages = formFeedPages.map((content, idx) => ({ pageNumber: idx + 1, text: content.trim() }));
|
|
385
|
+
if (pages.length === 0) pages = [{ pageNumber: 1, text: "" }];
|
|
386
|
+
parserName = "local-text";
|
|
387
|
+
} else {
|
|
388
|
+
const workerLoader = resolveAiWorkerLoader();
|
|
389
|
+
const safePath = this.assertSafeStoragePath(record.storagePath);
|
|
390
|
+
if (workerLoader && [".pdf", ".docx", ".doc", ".pptx", ".xlsx", ".xls", ".xlsm", ".csv"].includes(ext)) {
|
|
391
|
+
try {
|
|
392
|
+
const docs = await workerLoader(ext, {
|
|
393
|
+
filePath: safePath,
|
|
394
|
+
mimeType: record.mimeType,
|
|
395
|
+
timeout: 6e4
|
|
396
|
+
});
|
|
397
|
+
if (docs.length > 0) {
|
|
398
|
+
pages = docs.map((doc, idx) => {
|
|
399
|
+
var _a;
|
|
400
|
+
const loc = (_a = doc.metadata) == null ? void 0 : _a.loc;
|
|
401
|
+
const pageNumber = typeof (loc == null ? void 0 : loc.pageNumber) === "number" ? loc.pageNumber : idx + 1;
|
|
402
|
+
return { pageNumber, text: (doc.pageContent || "").trim() };
|
|
403
|
+
});
|
|
404
|
+
parserName = "nocobase-ai-worker";
|
|
405
|
+
}
|
|
406
|
+
} catch {
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
if (pages.length === 0) {
|
|
410
|
+
if (ext === ".csv" || record.mimeType === "text/csv") {
|
|
411
|
+
pages = [{ pageNumber: 1, text: buffer.toString("utf8").trim() }];
|
|
412
|
+
parserName = "local-csv";
|
|
413
|
+
} else if (ext === ".pdf" || record.mimeType === "application/pdf") {
|
|
414
|
+
pages = [{ pageNumber: 1, text: "" }];
|
|
415
|
+
requiresVision = true;
|
|
416
|
+
parserName = "pdf-ocr-candidate";
|
|
417
|
+
} else {
|
|
418
|
+
pages = [{ pageNumber: 1, text: buffer.toString("utf8").trim() }];
|
|
419
|
+
parserName = "utf8-fallback";
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
if (pages.every((p) => !p.text.trim()) && (ext === ".pdf" || record.mimeType === "application/pdf")) {
|
|
424
|
+
requiresVision = true;
|
|
425
|
+
}
|
|
426
|
+
const totalPageCount = Math.max(pages.length, 1);
|
|
427
|
+
let selectedNums;
|
|
428
|
+
try {
|
|
429
|
+
selectedNums = (0, import_du_contracts.expandPageRanges)(selection, totalPageCount);
|
|
430
|
+
} catch (err) {
|
|
431
|
+
throw new DuHttpError(
|
|
432
|
+
(0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", err instanceof Error ? err.message : String(err), {
|
|
433
|
+
errors: [{ pointer: "/documentSelection", message: err instanceof Error ? err.message : String(err) }]
|
|
434
|
+
})
|
|
435
|
+
);
|
|
436
|
+
}
|
|
437
|
+
const selectedPages = pages.filter((p) => selectedNums.includes(p.pageNumber));
|
|
438
|
+
const joinedMarkdown = selectedPages.map((p) => totalPageCount > 1 ? `<!-- page ${p.pageNumber} -->
|
|
439
|
+
${p.text}` : p.text).join("\n\n").trim();
|
|
440
|
+
const joinedText = selectedPages.map((p) => p.text).join("\n\n").trim();
|
|
441
|
+
return {
|
|
442
|
+
artifactId: record.artifactId,
|
|
443
|
+
fileName: record.fileName,
|
|
444
|
+
mimeType: record.mimeType,
|
|
445
|
+
detectedFormat: ext.replace(/^\./, "") || "bin",
|
|
446
|
+
totalPageCount,
|
|
447
|
+
selectedPages,
|
|
448
|
+
markdown: joinedMarkdown,
|
|
449
|
+
text: joinedText,
|
|
450
|
+
requiresVision,
|
|
451
|
+
parser: parserName
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
456
|
+
0 && (module.exports = {
|
|
457
|
+
ArtifactStorageService,
|
|
458
|
+
DuHttpError
|
|
459
|
+
});
|
|
@@ -84,7 +84,7 @@ class AsyncJobManager {
|
|
|
84
84
|
const resultValue = endpoint.pollResultField ? this.getNestedValue(response, endpoint.pollResultField) : response;
|
|
85
85
|
this.stopPolling(jobId);
|
|
86
86
|
await this.onJobComplete(jobId, resultValue);
|
|
87
|
-
} else if (
|
|
87
|
+
} else if (["failed", "error", "cancelled", "timed_out"].includes(String(statusValue).toLowerCase())) {
|
|
88
88
|
this.stopPolling(jobId);
|
|
89
89
|
await this.onJobError(jobId, `External task failed with status: ${statusValue}`);
|
|
90
90
|
}
|