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
@@ -43,18 +43,26 @@ var crypto = __toESM(require("crypto"));
43
43
  var import_ExternalApiClient = require("./ExternalApiClient");
44
44
  var import_AsyncJobManager = require("./AsyncJobManager");
45
45
  var import_PipelineExecutor = require("./PipelineExecutor");
46
+ var import_ArtifactStorageService = require("./ArtifactStorageService");
47
+ var import_BuiltinBusinessEngine = require("./BuiltinBusinessEngine");
48
+ var import_ExternalDuReworkClient = require("./ExternalDuReworkClient");
49
+ var import_OperationOrchestrator = require("./OperationOrchestrator");
50
+ var import_dugate_seed = require("../dugate-seed");
51
+ function isRecord(value) {
52
+ return typeof value === "object" && value !== null && !Array.isArray(value);
53
+ }
46
54
  class DocumentUnderstandingService {
47
55
  app;
48
56
  db;
49
57
  apiClient;
50
58
  pipelineExecutor;
51
59
  jobManager;
60
+ orchestrator;
52
61
  initialized = false;
53
62
  startupRecoveryCompleted = false;
54
63
  initializationPromise;
55
64
  maintenanceTimer;
56
- // Unique per process; used as the job owner so other nodes can tell orphaned
57
- // jobs apart from jobs that are still being processed.
65
+ processedWebhookDeliveries = /* @__PURE__ */ new Set();
58
66
  nodeId;
59
67
  static HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
60
68
  static MAINTENANCE_INTERVAL_MS = 3e4;
@@ -82,6 +90,35 @@ class DocumentUnderstandingService {
82
90
  const config = await this.ensureConfig();
83
91
  (_a = this.jobManager) == null ? void 0 : _a.destroy();
84
92
  this.stopMaintenance();
93
+ const artifactStorage = new import_ArtifactStorageService.ArtifactStorageService(this.db);
94
+ const builtinEngine = new import_BuiltinBusinessEngine.BuiltinBusinessEngine(this.app, artifactStorage, async (pipelineRef, input, userId) => {
95
+ const pipelines = await this.listPipelines();
96
+ const target = pipelineRef.pipelineId ? pipelines.find((p) => p.id === pipelineRef.pipelineId) : pipelines.find((p) => p.name === pipelineRef.pipelineName);
97
+ if (!target) {
98
+ throw new Error(`Referenced pipeline ${pipelineRef.pipelineName || pipelineRef.pipelineId} not found`);
99
+ }
100
+ const { jobId } = await this.executePipeline(target.id, input, [], userId);
101
+ const deadline = Date.now() + (config.pollTimeout || 12e4);
102
+ while (Date.now() < deadline) {
103
+ const j = await this.getJobStatus(jobId);
104
+ if (j.status === "completed") {
105
+ return isRecord(j.finalResult) ? j.finalResult : { result: j.finalResult };
106
+ }
107
+ if (["failed", "cancelled", "timeout"].includes(j.status)) {
108
+ throw new Error(j.error || `Pipeline job #${jobId} ended with ${j.status}`);
109
+ }
110
+ await new Promise((resolve) => setTimeout(resolve, 300));
111
+ }
112
+ throw new Error(`Schema workflow pipeline #${target.id} timed out`);
113
+ });
114
+ this.orchestrator = new import_OperationOrchestrator.OperationOrchestrator({
115
+ app: this.app,
116
+ db: this.db,
117
+ artifactStorage,
118
+ builtinEngine,
119
+ getConfig: () => this.getConfig(),
120
+ nodeId: this.nodeId
121
+ });
85
122
  this.apiClient = new import_ExternalApiClient.ExternalApiClient(config);
86
123
  this.jobManager = new import_AsyncJobManager.AsyncJobManager(
87
124
  this.db,
@@ -106,7 +143,8 @@ class DocumentUnderstandingService {
106
143
  this.apiClient,
107
144
  this.jobManager,
108
145
  this.app.logger,
109
- this.nodeId
146
+ this.nodeId,
147
+ this.orchestrator
110
148
  );
111
149
  if (recoverJobs && !this.startupRecoveryCompleted) {
112
150
  await this.maintainJobs();
@@ -115,11 +153,6 @@ class DocumentUnderstandingService {
115
153
  this.startMaintenance();
116
154
  this.initialized = true;
117
155
  }
118
- /**
119
- * Cluster maintenance sweep: fails active jobs whose owner is gone and
120
- * re-adopts orphaned polling jobs. Safe to run on every node — all state
121
- * transitions are guarded by ownership checks and row-level claims.
122
- */
123
156
  async maintainJobs() {
124
157
  if (!this.jobManager) return;
125
158
  try {
@@ -154,7 +187,11 @@ class DocumentUnderstandingService {
154
187
  defaultTimeout: 3e4,
155
188
  defaultRetries: 2,
156
189
  pollInterval: 5e3,
157
- pollTimeout: 3e5
190
+ pollTimeout: 3e5,
191
+ engineMode: "builtin",
192
+ maxFileSizeBytes: 10485760,
193
+ maxFilesPerRequest: 20,
194
+ publicGatewayEnabled: true
158
195
  }
159
196
  });
160
197
  }
@@ -185,6 +222,32 @@ class DocumentUnderstandingService {
185
222
  }
186
223
  await this.initialize();
187
224
  }
225
+ async getGatewayHealth() {
226
+ await this.ensureInitialized();
227
+ const config = await this.getConfig();
228
+ const llmServices = await this.orchestrator.builtinEngine.listAvailableLlmServices();
229
+ let externalStatus;
230
+ if (config.engineMode === "du_rework" || config.engineMode === "hybrid") {
231
+ const extClient = new import_ExternalDuReworkClient.ExternalDuReworkClient(config);
232
+ externalStatus = await extClient.checkHealth();
233
+ }
234
+ return {
235
+ status: "ok",
236
+ engineMode: config.engineMode || "builtin",
237
+ publicGatewayEnabled: config.publicGatewayEnabled !== false,
238
+ builtinAiAvailable: llmServices.length > 0 || Boolean(this.orchestrator.builtinEngine.resolveAiManager()),
239
+ llmServiceCount: llmServices.length,
240
+ ...externalStatus ? { externalGateway: externalStatus } : {},
241
+ businesses: [
242
+ { businessId: "document-core", version: "2.0.0", state: "ACTIVE" },
243
+ { businessId: "lc-checker", version: "1.2.0", state: "ACTIVE" },
244
+ { businessId: "example-review", version: "1.0.0", state: "ACTIVE" }
245
+ ]
246
+ };
247
+ }
248
+ async syncCatalog() {
249
+ return (0, import_dugate_seed.seedDugateEndpoints)(this.db);
250
+ }
188
251
  destroy() {
189
252
  var _a;
190
253
  this.stopMaintenance();
@@ -194,10 +257,12 @@ class DocumentUnderstandingService {
194
257
  }
195
258
  async listEndpoints() {
196
259
  await this.ensureInitialized();
197
- return this.db.getRepository("doc_understanding_endpoints").find({ sort: "sortOrder" });
260
+ const rows = await this.db.getRepository("doc_understanding_endpoints").find({ sort: "sortOrder" });
261
+ return rows;
198
262
  }
199
263
  async createEndpoint(data) {
200
- return this.db.getRepository("doc_understanding_endpoints").create({ values: this.normalizeEndpoint(data) });
264
+ const created = await this.db.getRepository("doc_understanding_endpoints").create({ values: this.normalizeEndpoint(data) });
265
+ return created;
201
266
  }
202
267
  async updateEndpoint(id, data) {
203
268
  await this.db.getRepository("doc_understanding_endpoints").update({
@@ -235,13 +300,15 @@ class DocumentUnderstandingService {
235
300
  }
236
301
  async listPipelines() {
237
302
  await this.ensureInitialized();
238
- return this.db.getRepository("doc_understanding_pipelines").find({
303
+ const rows = await this.db.getRepository("doc_understanding_pipelines").find({
239
304
  appends: ["steps", "steps.endpoint"]
240
305
  });
306
+ return rows;
241
307
  }
242
308
  async createPipeline(data) {
243
309
  this.validateStepAliases(data.steps);
244
- return this.db.getRepository("doc_understanding_pipelines").create({ values: data });
310
+ const created = await this.db.getRepository("doc_understanding_pipelines").create({ values: data });
311
+ return created;
245
312
  }
246
313
  async updatePipeline(id, data) {
247
314
  this.validateStepAliases(data.steps);
@@ -271,41 +338,100 @@ class DocumentUnderstandingService {
271
338
  }
272
339
  async listJobs(filters, userId) {
273
340
  const filter = userId ? { ...filters || {}, createdById: userId } : filters;
274
- return this.db.getRepository("doc_understanding_jobs").find({
341
+ const rows = await this.db.getRepository("doc_understanding_jobs").find({
275
342
  filter,
276
343
  sort: ["-createdAt"]
277
344
  });
345
+ return rows;
278
346
  }
279
- async handleWebhook(payload, signature) {
347
+ async cancelJob(jobId) {
348
+ await this.ensureInitialized();
349
+ const job = await this.getJobStatus(jobId);
350
+ this.jobManager.stopPolling(jobId);
351
+ if (job.operationId) {
352
+ await this.orchestrator.cancelOperation("*", job.operationId).catch(() => void 0);
353
+ }
354
+ await this.db.getRepository("doc_understanding_jobs").update({
355
+ filterByTk: jobId,
356
+ values: {
357
+ status: "cancelled",
358
+ completedAt: /* @__PURE__ */ new Date(),
359
+ leaseExpiresAt: null
360
+ }
361
+ });
362
+ return this.getJobStatus(jobId);
363
+ }
364
+ async resumeJob(jobId, input, resumedBy) {
365
+ await this.ensureInitialized();
366
+ const job = await this.getJobStatus(jobId);
367
+ if (job.status !== "waiting_input" || !job.operationId) {
368
+ throw new Error(`Job #${jobId} is not waiting for human input`);
369
+ }
370
+ await this.orchestrator.resumeOperation({
371
+ tenantId: "*",
372
+ operationId: job.operationId,
373
+ input,
374
+ resumedBy
375
+ });
376
+ const opView = await this.orchestrator.waitForOperation("*", job.operationId, 30);
377
+ if (opView.state === "SUCCEEDED") {
378
+ const opRecord = await this.orchestrator.getOperationRecordOrThrow("*", job.operationId);
379
+ await this.pipelineExecutor.resumeFromStep(jobId, {
380
+ ...opRecord.outputPayload || {},
381
+ usage: opRecord.usage,
382
+ operationId: opRecord.operationId
383
+ });
384
+ }
385
+ return this.getJobStatus(jobId);
386
+ }
387
+ async handleWebhook(payload, signature, duHeaders) {
280
388
  await this.ensureInitialized();
281
389
  const config = await this.getConfig();
390
+ if ((duHeaders == null ? void 0 : duHeaders.deliveryId) && this.processedWebhookDeliveries.has(duHeaders.deliveryId)) {
391
+ return;
392
+ }
282
393
  if (config.webhookSecret) {
283
- if (!signature) {
394
+ const effectiveSig = (duHeaders == null ? void 0 : duHeaders.signature) || signature;
395
+ if (!effectiveSig) {
284
396
  throw new Error("Webhook signature missing");
285
397
  }
286
- const expected = crypto.createHmac("sha256", config.webhookSecret).update(JSON.stringify(payload)).digest("hex");
287
- const signatureHash = signature.startsWith("sha256=") ? signature.slice(7) : signature;
288
- if (!crypto.timingSafeEqual(Buffer.from(signatureHash, "hex"), Buffer.from(expected, "hex"))) {
398
+ const rawJson = JSON.stringify(payload);
399
+ const signedInput = (duHeaders == null ? void 0 : duHeaders.timestamp) ? `${duHeaders.timestamp}.${rawJson}` : rawJson;
400
+ const expected = crypto.createHmac("sha256", config.webhookSecret).update(signedInput).digest("hex");
401
+ const signatureHash = effectiveSig.startsWith("sha256=") ? effectiveSig.slice(7) : effectiveSig;
402
+ const sigBuf = Buffer.from(signatureHash, "hex");
403
+ const expBuf = Buffer.from(expected, "hex");
404
+ if (sigBuf.length !== expBuf.length || !crypto.timingSafeEqual(sigBuf, expBuf)) {
289
405
  throw new Error("Webhook signature verification failed");
290
406
  }
291
407
  }
292
- const taskId = payload.task_id ?? payload.operation_id;
293
- const result = payload.result;
294
- if (!taskId) throw new Error("Webhook missing task_id");
408
+ const taskId = String(payload.operationId ?? payload.task_id ?? payload.operation_id ?? "");
409
+ if (!taskId) throw new Error("Webhook missing task_id / operationId");
410
+ if (duHeaders == null ? void 0 : duHeaders.deliveryId) {
411
+ this.processedWebhookDeliveries.add(duHeaders.deliveryId);
412
+ }
295
413
  const jobsRepo = this.db.getRepository("doc_understanding_jobs");
296
414
  const PAGE_SIZE = 100;
297
415
  let offset = 0;
298
416
  let hasMoreJobs = true;
299
417
  while (hasMoreJobs) {
300
418
  const jobs = await jobsRepo.find({
301
- filter: { status: "polling" },
419
+ filter: { status: { $in: ["polling", "waiting_input"] } },
302
420
  limit: PAGE_SIZE,
303
421
  offset
304
422
  });
305
423
  if (jobs.length === 0) break;
306
424
  for (const job of jobs) {
307
- if (Object.values(job.externalTaskIds || {}).includes(taskId)) {
308
- await this.pipelineExecutor.resumeFromStep(job.id, result || payload);
425
+ const extIds = Object.values(job.externalTaskIds || {});
426
+ if (extIds.includes(taskId) || job.operationId === taskId) {
427
+ if (payload.state === "WAITING_INPUT" && isRecord(payload.wait)) {
428
+ await jobsRepo.update({
429
+ filterByTk: job.id,
430
+ values: { status: "waiting_input", waitState: payload.wait, leaseExpiresAt: null }
431
+ });
432
+ return;
433
+ }
434
+ await this.pipelineExecutor.resumeFromStep(job.id, payload.result || payload);
309
435
  return;
310
436
  }
311
437
  }
@@ -0,0 +1,210 @@
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 ExternalDuReworkClient_exports = {};
38
+ __export(ExternalDuReworkClient_exports, {
39
+ ExternalDuReworkClient: () => ExternalDuReworkClient
40
+ });
41
+ module.exports = __toCommonJS(ExternalDuReworkClient_exports);
42
+ var crypto = __toESM(require("crypto"));
43
+ var import_axios = __toESM(require("axios"));
44
+ var import_ArtifactStorageService = require("./ArtifactStorageService");
45
+ function isRecord(value) {
46
+ return typeof value === "object" && value !== null && !Array.isArray(value);
47
+ }
48
+ function sleep(ms) {
49
+ return new Promise((resolve) => setTimeout(resolve, ms));
50
+ }
51
+ class ExternalDuReworkClient {
52
+ config;
53
+ http;
54
+ constructor(config) {
55
+ this.config = config;
56
+ this.http = import_axios.default.create({
57
+ baseURL: config.baseUrl.replace(/\/+$/, ""),
58
+ timeout: config.defaultTimeout || 3e4
59
+ });
60
+ }
61
+ buildAuthHeaders() {
62
+ const headers = {};
63
+ if (!this.config.authType || this.config.authType === "none" || !this.config.authKey) {
64
+ return headers;
65
+ }
66
+ if (this.config.authType === "bearer") {
67
+ headers["Authorization"] = `Bearer ${this.config.authKey}`;
68
+ } else if (this.config.authType === "api_key") {
69
+ headers[this.config.authHeaderName || "x-api-key"] = this.config.authKey;
70
+ } else if (this.config.authType === "custom_header" && this.config.authHeaderName) {
71
+ headers[this.config.authHeaderName] = this.config.authKey;
72
+ }
73
+ return headers;
74
+ }
75
+ async requestWithRetry(reqConfig, maxRetries = this.config.defaultRetries ?? 2) {
76
+ var _a, _b, _c;
77
+ for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
78
+ try {
79
+ const res = await this.http.request({
80
+ ...reqConfig,
81
+ headers: {
82
+ ...this.buildAuthHeaders(),
83
+ ...reqConfig.headers || {}
84
+ }
85
+ });
86
+ return res.data;
87
+ } catch (err) {
88
+ const axiosErr = err;
89
+ const status = (_a = axiosErr.response) == null ? void 0 : _a.status;
90
+ if ((status === 429 || status === 503) && attempt < maxRetries) {
91
+ const retryAfterHeader = Number((_c = (_b = axiosErr.response) == null ? void 0 : _b.headers) == null ? void 0 : _c["retry-after"]);
92
+ const delayMs = Number.isFinite(retryAfterHeader) && retryAfterHeader > 0 ? retryAfterHeader * 1e3 : Math.min(1e3 * 2 ** attempt, 1e4);
93
+ await sleep(delayMs);
94
+ continue;
95
+ }
96
+ if (axiosErr.response && isRecord(axiosErr.response.data) && typeof axiosErr.response.data.code === "string") {
97
+ throw new import_ArtifactStorageService.DuHttpError(axiosErr.response.data);
98
+ }
99
+ throw err;
100
+ }
101
+ }
102
+ throw new Error("Retry loop exhausted");
103
+ }
104
+ async uploadArtifact(artifact, buffer) {
105
+ const sha256 = crypto.createHash("sha256").update(buffer).digest("hex");
106
+ const uploadToken = crypto.randomUUID();
107
+ const initRes = await this.requestWithRetry({
108
+ method: "POST",
109
+ url: "/api/v1/uploads",
110
+ headers: {
111
+ "Idempotency-Key": `upload-${artifact.artifactId}`,
112
+ "Content-Type": "application/json"
113
+ },
114
+ data: {
115
+ fileName: artifact.fileName,
116
+ mimeType: artifact.mimeType,
117
+ sizeBytes: buffer.length,
118
+ uploadToken
119
+ }
120
+ });
121
+ const remoteArtifactId = initRes.artifactId;
122
+ const uploadUrl = initRes.uploadUrl || `/api/v1/uploads/${remoteArtifactId}/content`;
123
+ await this.requestWithRetry({
124
+ method: "PUT",
125
+ url: uploadUrl,
126
+ headers: {
127
+ "Content-Type": artifact.mimeType,
128
+ "Content-Length": String(buffer.length),
129
+ "x-content-sha256": sha256
130
+ },
131
+ data: buffer
132
+ });
133
+ return remoteArtifactId;
134
+ }
135
+ async submitAction(params) {
136
+ return this.requestWithRetry({
137
+ method: "POST",
138
+ url: `/api/v1/businesses/${encodeURIComponent(params.businessId)}/actions/${encodeURIComponent(params.action)}`,
139
+ headers: {
140
+ "Idempotency-Key": params.idempotencyKey,
141
+ ...params.correlationId ? { "x-correlation-id": params.correlationId } : {},
142
+ "Content-Type": "application/json"
143
+ },
144
+ data: {
145
+ input: params.input,
146
+ ...params.artifacts.length > 0 ? { artifacts: params.artifacts } : {},
147
+ ...params.documentSelection ? { documentSelection: params.documentSelection } : {},
148
+ ...params.sourceUrl ? { sourceUrl: params.sourceUrl } : {},
149
+ ...params.clientReference ? { clientReference: params.clientReference } : {}
150
+ }
151
+ });
152
+ }
153
+ async getOperation(remoteOperationId, waitSeconds) {
154
+ return this.requestWithRetry({
155
+ method: "GET",
156
+ url: `/api/v1/operations/${encodeURIComponent(remoteOperationId)}`,
157
+ params: waitSeconds ? { wait: waitSeconds } : void 0
158
+ });
159
+ }
160
+ async cancelOperation(remoteOperationId) {
161
+ return this.requestWithRetry({
162
+ method: "POST",
163
+ url: `/api/v1/operations/${encodeURIComponent(remoteOperationId)}/cancel`,
164
+ headers: { "Idempotency-Key": `cancel-${remoteOperationId}` }
165
+ });
166
+ }
167
+ async resumeOperation(remoteOperationId, body) {
168
+ return this.requestWithRetry({
169
+ method: "POST",
170
+ url: `/api/v1/operations/${encodeURIComponent(remoteOperationId)}/resume`,
171
+ headers: {
172
+ "Idempotency-Key": `resume-${remoteOperationId}-${body.expectedStateVersion}`,
173
+ "Content-Type": "application/json"
174
+ },
175
+ data: body
176
+ });
177
+ }
178
+ async fetchResultAndPayload(remoteOperationId) {
179
+ var _a;
180
+ const envelope = await this.requestWithRetry({
181
+ method: "GET",
182
+ url: `/api/v1/operations/${encodeURIComponent(remoteOperationId)}/result`
183
+ });
184
+ let outputPayload = envelope.data || {};
185
+ const resultRef = typeof ((_a = envelope.data) == null ? void 0 : _a.resultRef) === "string" ? envelope.data.resultRef : void 0;
186
+ if (resultRef && resultRef.startsWith("artifact://")) {
187
+ const outputArtifactId = resultRef.slice("artifact://".length);
188
+ const downloaded = await this.requestWithRetry({
189
+ method: "GET",
190
+ url: `/api/v1/artifacts/${encodeURIComponent(outputArtifactId)}/download`
191
+ });
192
+ if (isRecord(downloaded)) {
193
+ outputPayload = downloaded;
194
+ }
195
+ }
196
+ return { envelope, outputPayload };
197
+ }
198
+ async checkHealth() {
199
+ try {
200
+ const data = await this.requestWithRetry({ method: "GET", url: "/api/v1/health" }, 0);
201
+ return { ok: true, status: String(data.status || "healthy"), detail: data };
202
+ } catch (err) {
203
+ return { ok: false, status: "unreachable", detail: err instanceof Error ? err.message : String(err) };
204
+ }
205
+ }
206
+ }
207
+ // Annotate the CommonJS export names for ESM import in node:
208
+ 0 && (module.exports = {
209
+ ExternalDuReworkClient
210
+ });