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.
Files changed (82) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +19 -25
  3. package/dist/client/169.6888909107c553c3.js +10 -0
  4. package/dist/client/379.e29f5ced467ce23d.js +10 -0
  5. package/dist/client/867.3ed3b814115181ca.js +10 -0
  6. package/dist/client/index.js +1 -1
  7. package/dist/client-v2/169.53bf1be2ec192f0c.js +10 -0
  8. package/dist/client-v2/379.e75c4829567cdb89.js +10 -0
  9. package/dist/client-v2/867.66d7291e95f1de78.js +10 -0
  10. package/dist/client-v2/index.js +1 -1
  11. package/dist/externalVersion.js +10 -8
  12. package/dist/locale/en-US.json +126 -0
  13. package/dist/locale/vi-VN.json +130 -2
  14. package/dist/locale/zh-CN.json +127 -1
  15. package/dist/node_modules/form-data/package.json +1 -1
  16. package/dist/node_modules/mime-types/package.json +1 -1
  17. package/dist/server/actions.js +211 -11
  18. package/dist/server/collections/api-keys.js +55 -0
  19. package/dist/server/collections/artifacts.js +59 -0
  20. package/dist/server/collections/config.js +9 -3
  21. package/dist/server/collections/endpoints.js +3 -0
  22. package/dist/server/collections/jobs.js +7 -4
  23. package/dist/server/collections/operations.js +76 -0
  24. package/dist/server/contracts/du-contracts.js +828 -0
  25. package/dist/server/dugate-seed.js +98 -340
  26. package/dist/server/plugin.js +49 -7
  27. package/dist/server/routes/du-gateway-router.js +443 -0
  28. package/dist/server/services/ArtifactStorageService.js +459 -0
  29. package/dist/server/services/AsyncJobManager.js +1 -1
  30. package/dist/server/services/BuiltinBusinessEngine.js +1223 -0
  31. package/dist/server/services/DocumentUnderstandingService.js +151 -25
  32. package/dist/server/services/ExternalDuReworkClient.js +210 -0
  33. package/dist/server/services/OperationOrchestrator.js +1087 -0
  34. package/dist/server/services/PipelineExecutor.js +164 -43
  35. package/dist/server/tools/document-understanding-tool.js +49 -24
  36. package/dist/server/workflow/DocumentUnderstandingInstruction.js +292 -0
  37. package/package.json +8 -4
  38. package/src/client/index.tsx +11 -0
  39. package/src/client-v2/components/ApiKeysTab.tsx +198 -0
  40. package/src/client-v2/components/EndpointsTab.tsx +39 -2
  41. package/src/client-v2/components/JobsTab.tsx +136 -21
  42. package/src/client-v2/components/OperationsTab.tsx +586 -0
  43. package/src/client-v2/components/PluginSettings.tsx +24 -8
  44. package/src/client-v2/components/ServiceConfigTab.tsx +225 -65
  45. package/src/client-v2/components/__tests__/PluginSettings.test.tsx +43 -0
  46. package/src/client-v2/locale.ts +1 -8
  47. package/src/client-v2/models/index.ts +1 -8
  48. package/src/client-v2/plugin.tsx +12 -8
  49. package/src/client-v2/types.ts +13 -1
  50. package/src/client-v2/workflow/DocumentUnderstandingFieldset.tsx +122 -0
  51. package/src/client-v2/workflow/DocumentUnderstandingInstruction.tsx +49 -0
  52. package/src/locale/en-US.json +126 -0
  53. package/src/locale/vi-VN.json +130 -2
  54. package/src/locale/zh-CN.json +127 -1
  55. package/src/server/__tests__/actions.test.ts +1 -8
  56. package/src/server/__tests__/du-rework-gateway.test.ts +462 -0
  57. package/src/server/__tests__/dugate-integration.test.ts +79 -42
  58. package/src/server/__tests__/smoke.test.ts +1 -8
  59. package/src/server/__tests__/upload-security.test.ts +1 -8
  60. package/src/server/actions.ts +252 -36
  61. package/src/server/collections/api-keys.ts +35 -0
  62. package/src/server/collections/artifacts.ts +39 -0
  63. package/src/server/collections/config.ts +18 -2
  64. package/src/server/collections/endpoints.ts +12 -0
  65. package/src/server/collections/jobs.ts +16 -4
  66. package/src/server/collections/operations.ts +56 -0
  67. package/src/server/contracts/du-contracts.ts +1026 -0
  68. package/src/server/dugate-seed.ts +126 -453
  69. package/src/server/plugin.ts +64 -14
  70. package/src/server/routes/du-gateway-router.ts +465 -0
  71. package/src/server/services/ArtifactStorageService.ts +596 -0
  72. package/src/server/services/AsyncJobManager.ts +10 -1
  73. package/src/server/services/BuiltinBusinessEngine.ts +1544 -0
  74. package/src/server/services/DocumentUnderstandingService.ts +186 -44
  75. package/src/server/services/ExternalDuReworkClient.ts +222 -0
  76. package/src/server/services/OperationOrchestrator.ts +1359 -0
  77. package/src/server/services/PipelineExecutor.ts +245 -108
  78. package/src/server/tools/document-understanding-tool.ts +63 -45
  79. package/src/server/types.ts +101 -16
  80. package/src/server/workflow/DocumentUnderstandingInstruction.ts +308 -0
  81. package/dist/client/345.e6e484fb1974c3d3.js +0 -10
  82. package/dist/client-v2/345.a8f28526ac21e02a.js +0 -10
@@ -0,0 +1,443 @@
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 du_gateway_router_exports = {};
38
+ __export(du_gateway_router_exports, {
39
+ createDuDisableBodyParserMiddleware: () => createDuDisableBodyParserMiddleware,
40
+ createDuGatewayRouter: () => createDuGatewayRouter,
41
+ matchDuGatewayPath: () => matchDuGatewayPath
42
+ });
43
+ module.exports = __toCommonJS(du_gateway_router_exports);
44
+ var crypto = __toESM(require("crypto"));
45
+ var import_utils = require("@nocobase/utils");
46
+ var import_du_contracts = require("../contracts/du-contracts");
47
+ var import_ArtifactStorageService = require("../services/ArtifactStorageService");
48
+ const DU_NAMESPACE_PREFIX = "/api/du/v1";
49
+ const CANONICAL_ROOT_PATTERN = /^\/api\/v1\/(health|uploads|businesses|operations|artifacts|usage|docs)(\/.*)?$/;
50
+ const legacyMultipartUpload = (0, import_utils.koaMulter)({
51
+ storage: import_utils.koaMulter.memoryStorage(),
52
+ limits: { files: 20, fileSize: 64 * 1024 * 1024, fields: 30, fieldSize: 2 * 1024 * 1024 }
53
+ }).any();
54
+ function isRecord(value) {
55
+ return typeof value === "object" && value !== null && !Array.isArray(value);
56
+ }
57
+ function matchDuGatewayPath(pathname) {
58
+ if (pathname === DU_NAMESPACE_PREFIX || pathname.startsWith(`${DU_NAMESPACE_PREFIX}/`)) {
59
+ return {
60
+ matched: true,
61
+ subPath: pathname.slice(DU_NAMESPACE_PREFIX.length) || "/",
62
+ urlPrefix: DU_NAMESPACE_PREFIX
63
+ };
64
+ }
65
+ if (CANONICAL_ROOT_PATTERN.test(pathname)) {
66
+ return {
67
+ matched: true,
68
+ subPath: pathname.slice("/api/v1".length) || "/",
69
+ urlPrefix: "/api/v1"
70
+ };
71
+ }
72
+ return { matched: false, subPath: "", urlPrefix: DU_NAMESPACE_PREFIX };
73
+ }
74
+ async function readStreamBuffer(ctx, maxBytes) {
75
+ const chunks = [];
76
+ let total = 0;
77
+ for await (const chunk of ctx.req) {
78
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
79
+ total += buf.length;
80
+ if (total > maxBytes) {
81
+ throw new import_ArtifactStorageService.DuHttpError((0, import_du_contracts.createProblem)(413, "PAYLOAD_TOO_LARGE", `Request body exceeds ${maxBytes} bytes`));
82
+ }
83
+ chunks.push(buf);
84
+ }
85
+ return Buffer.concat(chunks);
86
+ }
87
+ async function readJsonBody(ctx, maxBytes = 2 * 1024 * 1024) {
88
+ if (isRecord(ctx.request.body)) {
89
+ return ctx.request.body;
90
+ }
91
+ const raw = await readStreamBuffer(ctx, maxBytes);
92
+ if (raw.length === 0) return {};
93
+ try {
94
+ const parsed = JSON.parse(raw.toString("utf8"));
95
+ if (!isRecord(parsed)) {
96
+ throw new Error("Root JSON value must be an object");
97
+ }
98
+ return parsed;
99
+ } catch (err) {
100
+ throw new import_ArtifactStorageService.DuHttpError(
101
+ (0, import_du_contracts.createProblem)(400, "INVALID_JSON", err instanceof Error ? err.message : "Malformed JSON body")
102
+ );
103
+ }
104
+ }
105
+ async function resolveGatewayPrincipal(ctx, service) {
106
+ var _a, _b, _c, _d, _e;
107
+ const rawApiKey = ctx.get("x-api-key");
108
+ if (rawApiKey) {
109
+ return service.orchestrator.authenticateRawApiKey(rawApiKey);
110
+ }
111
+ if ((_b = (_a = ctx.state) == null ? void 0 : _a.currentUser) == null ? void 0 : _b.id) {
112
+ return {
113
+ kind: "nocobase_user",
114
+ tenantId: ((_c = ctx.get("x-tenant-id")) == null ? void 0 : _c.trim()) || "default",
115
+ userId: Number(ctx.state.currentUser.id),
116
+ allowedBusinesses: ["*"],
117
+ allowedActions: ["*"]
118
+ };
119
+ }
120
+ const authHeader = ctx.get("Authorization") || "";
121
+ if (authHeader.startsWith("Bearer ")) {
122
+ const token = authHeader.slice(7).trim();
123
+ if (token.startsWith("du_live_")) {
124
+ return service.orchestrator.authenticateRawApiKey(token);
125
+ }
126
+ const jwt = (_d = ctx.app.authManager) == null ? void 0 : _d.jwt;
127
+ if (jwt && token) {
128
+ try {
129
+ const decoded = await jwt.decode(token);
130
+ if (decoded == null ? void 0 : decoded.userId) {
131
+ const user = await ctx.db.getRepository("users").findOne({ filterByTk: decoded.userId });
132
+ if (user) {
133
+ return {
134
+ kind: "nocobase_user",
135
+ tenantId: ((_e = ctx.get("x-tenant-id")) == null ? void 0 : _e.trim()) || "default",
136
+ userId: Number(user.id),
137
+ allowedBusinesses: ["*"],
138
+ allowedActions: ["*"]
139
+ };
140
+ }
141
+ }
142
+ } catch {
143
+ }
144
+ }
145
+ }
146
+ throw new import_ArtifactStorageService.DuHttpError(
147
+ (0, import_du_contracts.createProblem)(401, "UNAUTHENTICATED", "Missing or invalid x-api-key or Authorization Bearer credentials")
148
+ );
149
+ }
150
+ function createDuDisableBodyParserMiddleware() {
151
+ return async (ctx, next) => {
152
+ const matched = matchDuGatewayPath(ctx.path);
153
+ if (matched.matched) {
154
+ if (ctx.method === "PUT" && /^\/uploads\/[^/]+\/content$/.test(matched.subPath) || ctx.method === "POST" && matched.subPath.startsWith("/docs/")) {
155
+ ctx.disableBodyParser = true;
156
+ }
157
+ }
158
+ await next();
159
+ };
160
+ }
161
+ function createDuGatewayRouter(getService) {
162
+ return async (ctx, next) => {
163
+ const routeMatch = matchDuGatewayPath(ctx.path);
164
+ if (!routeMatch.matched) {
165
+ return next();
166
+ }
167
+ ctx.withoutDataWrapping = true;
168
+ const { subPath, urlPrefix } = routeMatch;
169
+ const method = ctx.method.toUpperCase();
170
+ const correlationId = (ctx.get("x-correlation-id") || crypto.randomUUID()).trim();
171
+ ctx.set("x-correlation-id", correlationId);
172
+ const service = getService();
173
+ await service.ensureInitialized();
174
+ const config = await service.getConfig();
175
+ if (config.publicGatewayEnabled === false) {
176
+ ctx.status = 503;
177
+ ctx.type = "application/problem+json";
178
+ ctx.body = (0, import_du_contracts.createProblem)(503, "TEMPORARY_UNAVAILABLE", "Document Understanding Public Gateway is disabled", {
179
+ correlationId
180
+ });
181
+ return;
182
+ }
183
+ try {
184
+ if (method === "GET" && subPath === "/health") {
185
+ ctx.status = 200;
186
+ ctx.body = await service.getGatewayHealth();
187
+ return;
188
+ }
189
+ const principal = await resolveGatewayPrincipal(ctx, service);
190
+ if (method === "POST" && subPath === "/uploads") {
191
+ const body = await readJsonBody(ctx);
192
+ const res = await service.orchestrator.artifactStorage.initiateUpload({
193
+ tenantId: principal.tenantId,
194
+ fileName: String(body.fileName || ""),
195
+ mimeType: typeof body.mimeType === "string" ? body.mimeType : void 0,
196
+ sizeBytes: Number(body.sizeBytes ?? 0),
197
+ uploadToken: typeof body.uploadToken === "string" ? body.uploadToken : void 0,
198
+ idempotencyKey: ctx.get("Idempotency-Key") || void 0,
199
+ userId: principal.userId,
200
+ urlPrefix
201
+ });
202
+ ctx.status = res.httpStatus;
203
+ ctx.body = {
204
+ artifactId: res.artifactId,
205
+ state: res.state,
206
+ replayed: res.replayed,
207
+ uploadUrl: res.uploadUrl
208
+ };
209
+ return;
210
+ }
211
+ const uploadContentMatch = /^\/uploads\/([^/]+)\/content$/.exec(subPath);
212
+ if (method === "PUT" && uploadContentMatch) {
213
+ const artifactId = decodeURIComponent(uploadContentMatch[1]);
214
+ const rawBytes = Buffer.isBuffer(ctx.request.body) ? ctx.request.body : await readStreamBuffer(ctx, 64 * 1024 * 1024);
215
+ const res = await service.orchestrator.artifactStorage.writeUploadContent({
216
+ tenantId: principal.tenantId,
217
+ artifactId,
218
+ buffer: rawBytes,
219
+ expectedSha256: ctx.get("x-content-sha256") || void 0
220
+ });
221
+ ctx.status = res.httpStatus;
222
+ ctx.body = {
223
+ artifactId: res.artifactId,
224
+ state: res.state,
225
+ sizeBytes: res.sizeBytes,
226
+ replayed: res.replayed
227
+ };
228
+ return;
229
+ }
230
+ const uploadLifecycleMatch = /^\/uploads\/([^/]+)\/(complete|abort|part)$/.exec(subPath);
231
+ if (method === "POST" && uploadLifecycleMatch) {
232
+ const artifactId = decodeURIComponent(uploadLifecycleMatch[1]);
233
+ const subAction = uploadLifecycleMatch[2];
234
+ if (subAction === "part") {
235
+ throw new import_ArtifactStorageService.DuHttpError(
236
+ (0, import_du_contracts.createProblem)(
237
+ 501,
238
+ "NOT_IMPLEMENTED",
239
+ "Direct S3 multipart part URLs are disabled when gateway upload is active"
240
+ )
241
+ );
242
+ }
243
+ ctx.status = 200;
244
+ ctx.body = subAction === "complete" ? await service.orchestrator.artifactStorage.completeUpload(principal.tenantId, artifactId) : await service.orchestrator.artifactStorage.abortUpload(principal.tenantId, artifactId);
245
+ return;
246
+ }
247
+ const bizActionMatch = /^\/businesses\/([^/]+)\/actions\/([^/]+)$/.exec(subPath);
248
+ if (method === "POST" && bizActionMatch) {
249
+ const businessId = decodeURIComponent(bizActionMatch[1]);
250
+ const action = decodeURIComponent(bizActionMatch[2]);
251
+ const body = await readJsonBody(ctx);
252
+ const syncRequested = ctx.query.sync === "true";
253
+ const res = await service.orchestrator.submitOperation({
254
+ principal,
255
+ businessId,
256
+ action,
257
+ submission: body,
258
+ idempotencyKey: ctx.get("Idempotency-Key") || void 0,
259
+ correlationId,
260
+ urlPrefix,
261
+ waitCompletionMs: syncRequested ? Math.min(config.pollTimeout || 3e4, 3e4) : 0
262
+ });
263
+ ctx.status = res.httpStatus;
264
+ ctx.body = {
265
+ operationId: res.operationId,
266
+ state: res.state,
267
+ stateVersion: res.stateVersion,
268
+ replayed: res.replayed,
269
+ correlationId: res.correlationId,
270
+ links: res.links
271
+ };
272
+ return;
273
+ }
274
+ if (method === "GET" && subPath === "/operations") {
275
+ ctx.status = 200;
276
+ ctx.body = await service.orchestrator.listOperations({
277
+ tenantId: principal.tenantId,
278
+ state: typeof ctx.query.state === "string" ? ctx.query.state : void 0,
279
+ businessId: typeof ctx.query.business === "string" ? ctx.query.business : void 0,
280
+ action: typeof ctx.query.action === "string" ? ctx.query.action : void 0,
281
+ from: typeof ctx.query.from === "string" ? ctx.query.from : void 0,
282
+ to: typeof ctx.query.to === "string" ? ctx.query.to : void 0,
283
+ limit: typeof ctx.query.limit === "string" ? Number(ctx.query.limit) : void 0,
284
+ cursor: typeof ctx.query.cursor === "string" ? ctx.query.cursor : void 0,
285
+ urlPrefix
286
+ });
287
+ return;
288
+ }
289
+ const opDetailMatch = /^\/operations\/([^/]+)$/.exec(subPath);
290
+ if (method === "GET" && opDetailMatch) {
291
+ const operationId = decodeURIComponent(opDetailMatch[1]);
292
+ const waitSec = typeof ctx.query.wait === "string" ? Number(ctx.query.wait) : 0;
293
+ ctx.status = 200;
294
+ ctx.body = await service.orchestrator.waitForOperation(principal.tenantId, operationId, waitSec, urlPrefix);
295
+ return;
296
+ }
297
+ const opActionMatch = /^\/operations\/([^/]+)\/(cancel|resume|result)$/.exec(subPath);
298
+ if (opActionMatch) {
299
+ const operationId = decodeURIComponent(opActionMatch[1]);
300
+ const subAction = opActionMatch[2];
301
+ if (method === "POST" && subAction === "cancel") {
302
+ const res = await service.orchestrator.cancelOperation(principal.tenantId, operationId);
303
+ ctx.status = res.httpStatus;
304
+ ctx.body = {
305
+ operationId: res.operationId,
306
+ state: res.state,
307
+ stateVersion: res.stateVersion,
308
+ replayed: res.replayed
309
+ };
310
+ return;
311
+ }
312
+ if (method === "POST" && subAction === "resume") {
313
+ const body = await readJsonBody(ctx);
314
+ const resumeInput = isRecord(body.input) ? body.input : {};
315
+ const res = await service.orchestrator.resumeOperation({
316
+ tenantId: principal.tenantId,
317
+ operationId,
318
+ waitId: typeof body.waitId === "string" ? body.waitId : void 0,
319
+ expectedStateVersion: body.expectedStateVersion !== void 0 ? Number(body.expectedStateVersion) : void 0,
320
+ input: resumeInput,
321
+ urlPrefix
322
+ });
323
+ ctx.status = res.httpStatus;
324
+ ctx.body = res;
325
+ return;
326
+ }
327
+ if (method === "GET" && subAction === "result") {
328
+ ctx.status = 200;
329
+ ctx.body = await service.orchestrator.getOperationResult(principal.tenantId, operationId);
330
+ return;
331
+ }
332
+ }
333
+ const artifactDownloadMatch = /^\/artifacts\/([^/]+)\/download$/.exec(subPath);
334
+ if (method === "GET" && artifactDownloadMatch) {
335
+ const artifactId = decodeURIComponent(artifactDownloadMatch[1]);
336
+ const record = await service.orchestrator.artifactStorage.getArtifactOrThrow(principal.tenantId, artifactId);
337
+ const bytes = service.orchestrator.artifactStorage.readArtifactBuffer(record);
338
+ ctx.status = 200;
339
+ ctx.type = record.mimeType || "application/octet-stream";
340
+ ctx.set("Content-Length", String(bytes.length));
341
+ ctx.set("Content-Disposition", `inline; filename="${encodeURIComponent(record.fileName)}"`);
342
+ ctx.body = bytes;
343
+ return;
344
+ }
345
+ if (method === "GET" && subPath === "/usage/summary") {
346
+ ctx.status = 200;
347
+ ctx.body = await service.orchestrator.getUsageSummary({
348
+ tenantId: principal.tenantId,
349
+ from: String(ctx.query.from || ""),
350
+ to: String(ctx.query.to || "")
351
+ });
352
+ return;
353
+ }
354
+ if (method === "GET" && subPath === "/usage/events") {
355
+ ctx.status = 200;
356
+ ctx.body = await service.orchestrator.listUsageEvents({
357
+ tenantId: principal.tenantId,
358
+ operationId: typeof ctx.query.operationId === "string" ? ctx.query.operationId : void 0,
359
+ provider: typeof ctx.query.provider === "string" ? ctx.query.provider : void 0,
360
+ model: typeof ctx.query.model === "string" ? ctx.query.model : void 0,
361
+ action: typeof ctx.query.action === "string" ? ctx.query.action : void 0,
362
+ limit: typeof ctx.query.limit === "string" ? Number(ctx.query.limit) : void 0
363
+ });
364
+ return;
365
+ }
366
+ const legacyDocsMatch = /^\/docs\/([^/]+)$/.exec(subPath);
367
+ if (method === "POST" && legacyDocsMatch) {
368
+ const target = decodeURIComponent(legacyDocsMatch[1]);
369
+ await legacyMultipartUpload(ctx, async () => void 0);
370
+ const rawFields = isRecord(ctx.request.body) ? ctx.request.body : {};
371
+ const uploadedFiles = Array.isArray(ctx.request.files) ? ctx.request.files : [];
372
+ const artifactRefs = [];
373
+ for (const f of uploadedFiles) {
374
+ if (Buffer.isBuffer(f.buffer)) {
375
+ const created = await service.orchestrator.artifactStorage.createReadyArtifactFromBuffer({
376
+ tenantId: principal.tenantId,
377
+ fileName: String(f.originalname || "upload.bin"),
378
+ mimeType: String(f.mimetype || "application/octet-stream"),
379
+ buffer: f.buffer,
380
+ userId: principal.userId
381
+ });
382
+ artifactRefs.push({ artifactId: created.artifactId, role: "input" });
383
+ }
384
+ }
385
+ const parsedFields = {};
386
+ for (const [k, v] of Object.entries(rawFields)) {
387
+ if (typeof v === "string" && (v.startsWith("{") || v.startsWith("["))) {
388
+ try {
389
+ parsedFields[k] = JSON.parse(v);
390
+ continue;
391
+ } catch {
392
+ }
393
+ }
394
+ parsedFields[k] = v;
395
+ }
396
+ const isWorkflowFacade = target === "workflows";
397
+ const processName = String(parsedFields.process || "disbursement");
398
+ const businessId = isWorkflowFacade && processName === "lc-checker" ? "lc-checker" : "document-core";
399
+ const actionName = isWorkflowFacade ? processName : target;
400
+ const syncMode = ctx.query.sync === "true";
401
+ const submitted = await service.orchestrator.submitOperation({
402
+ principal,
403
+ businessId,
404
+ action: actionName,
405
+ submission: {
406
+ input: parsedFields,
407
+ artifacts: artifactRefs
408
+ },
409
+ idempotencyKey: ctx.get("Idempotency-Key") || void 0,
410
+ correlationId,
411
+ urlPrefix,
412
+ waitCompletionMs: syncMode ? 3e4 : 0
413
+ });
414
+ const latest = await service.orchestrator.getOperationRecordOrThrow(principal.tenantId, submitted.operationId);
415
+ const isDone = latest.state === "SUCCEEDED";
416
+ ctx.status = isDone ? 200 : 202;
417
+ ctx.body = {
418
+ name: `operations/${submitted.operationId}`,
419
+ done: isDone,
420
+ metadata: {
421
+ processor: actionName,
422
+ state: latest.state,
423
+ createdAt: latest.createdAt
424
+ },
425
+ ...isDone ? { result: latest.outputPayload } : {}
426
+ };
427
+ return;
428
+ }
429
+ throw new import_ArtifactStorageService.DuHttpError((0, import_du_contracts.createProblem)(404, "NOT_FOUND", `Gateway route ${method} ${subPath} not found`));
430
+ } catch (err) {
431
+ const problem = err instanceof import_ArtifactStorageService.DuHttpError ? { ...err.problem, correlationId: err.problem.correlationId || correlationId } : (0, import_du_contracts.createProblem)(500, "INTERNAL_ERROR", err instanceof Error ? err.message : String(err), { correlationId });
432
+ ctx.status = problem.status;
433
+ ctx.type = "application/problem+json";
434
+ ctx.body = problem;
435
+ }
436
+ };
437
+ }
438
+ // Annotate the CommonJS export names for ESM import in node:
439
+ 0 && (module.exports = {
440
+ createDuDisableBodyParserMiddleware,
441
+ createDuGatewayRouter,
442
+ matchDuGatewayPath
443
+ });