plugin-document-understanding 1.1.0 → 1.1.2
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/README.md +16 -366
- package/dist/client/index.js +1 -1
- package/dist/client/plugin.d.ts +1 -0
- package/dist/externalVersion.js +6 -6
- package/dist/server/actions.js +48 -4
- package/dist/server/collections/endpoints.js +1 -0
- package/dist/server/services/AsyncJobManager.d.ts +4 -0
- package/dist/server/services/AsyncJobManager.js +21 -0
- package/dist/server/services/DocumentUnderstandingService.d.ts +3 -0
- package/dist/server/services/DocumentUnderstandingService.js +38 -5
- package/dist/server/services/ExternalApiClient.d.ts +2 -0
- package/dist/server/services/ExternalApiClient.js +20 -3
- package/dist/server/services/PipelineExecutor.d.ts +1 -0
- package/dist/server/services/PipelineExecutor.js +181 -2
- package/dist/server/tools/document-understanding-tool.js +37 -3
- package/dist/server/types.d.ts +1 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,366 +1,16 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
```bash
|
|
18
|
-
yarn nocobase pm add @nocobase/plugin-document-understanding
|
|
19
|
-
```
|
|
20
|
-
|
|
21
|
-
Sau do vao **Settings > Plugin Manager**, tim plugin **Document Understanding** va bat **Enable**.
|
|
22
|
-
|
|
23
|
-
---
|
|
24
|
-
|
|
25
|
-
## Huong dan su dung
|
|
26
|
-
|
|
27
|
-
Sau khi enable plugin, vao **Settings > Document Understanding** se thay giao dien voi 4 tab.
|
|
28
|
-
|
|
29
|
-
### Buoc 1: Cau hinh Service (Tab "Service Config")
|
|
30
|
-
|
|
31
|
-
Day la buoc bat buoc dau tien — plugin can biet external service cua ban o dau va xac thuc nhu the nao.
|
|
32
|
-
|
|
33
|
-
1. Mo tab **Service Config**
|
|
34
|
-
2. Dien cac truong:
|
|
35
|
-
|
|
36
|
-
| Truong | Mo ta | Vi du |
|
|
37
|
-
|--------|-------|-------|
|
|
38
|
-
| **Base URL** | URL goc cua external document processing service | `http://my-ocr-service:8000` |
|
|
39
|
-
| **Auth Type** | Phuong thuc xac thuc | `None`, `API Key`, `Bearer Token`, `Custom Header` |
|
|
40
|
-
| **API Key / Token** | Key hoac token (hien thi khi Auth Type khac None) | `sk-abc123...` |
|
|
41
|
-
| **Custom Header Name** | Ten header tuy chinh (khi chon Custom Header) | `X-Api-Key` |
|
|
42
|
-
| **Default Request Timeout** | Timeout mac dinh cho moi request (ms) | `30000` |
|
|
43
|
-
| **Default Retries** | So lan thu lai mac dinh khi loi | `2` |
|
|
44
|
-
| **Default Poll Interval** | Khoang thoi gian giua cac lan poll (ms) | `5000` |
|
|
45
|
-
| **Default Poll Timeout** | Thoi gian toi da cho poll (ms) | `300000` |
|
|
46
|
-
| **Webhook Secret** | Secret de verify webhook callback tu external service | (tuy chon) |
|
|
47
|
-
|
|
48
|
-
3. Nhan **Save Configuration**
|
|
49
|
-
|
|
50
|
-
### Buoc 2: Dang ky Endpoints (Tab "Endpoints")
|
|
51
|
-
|
|
52
|
-
Moi endpoint dai dien cho mot chuc nang cua external service (OCR, classify, extract, ...).
|
|
53
|
-
|
|
54
|
-
1. Mo tab **Endpoints**
|
|
55
|
-
2. Nhan **Add Endpoint**
|
|
56
|
-
3. Dien thong tin:
|
|
57
|
-
|
|
58
|
-
| Truong | Mo ta | Vi du |
|
|
59
|
-
|--------|-------|-------|
|
|
60
|
-
| **Unique Name** | Ten dinh danh (khong trung) | `ocr`, `classify`, `extract_table` |
|
|
61
|
-
| **Subpath** | Duong dan API tuong doi voi Base URL | `/api/v1/ocr` |
|
|
62
|
-
| **HTTP Method** | `GET` hoac `POST` | `POST` |
|
|
63
|
-
| **Execution Mode** | Cach thuc thi | Xem ben duoi |
|
|
64
|
-
| **File Input Mode** | Cach gui file | `None`, `Multipart`, `Base64` |
|
|
65
|
-
| **Enabled** | Bat/tat endpoint | `true` |
|
|
66
|
-
|
|
67
|
-
**Execution Mode giai thich:**
|
|
68
|
-
|
|
69
|
-
- **Synchronous**: Goi API, nhan ket qua ngay trong response. Phu hop cho cac task nhanh (< 30s).
|
|
70
|
-
- **Polling**: Goi API nhan `task_id`, sau do plugin tu dong poll ket qua theo interval. Dien them:
|
|
71
|
-
- `Poll Task ID Field`: truong trong response chua task_id (mac dinh: `task_id`)
|
|
72
|
-
- `Poll Result Field`: truong chua ket qua khi poll thanh cong
|
|
73
|
-
- `Poll Status Field` (tuy chon): truong chua trang thai, kiem tra xem task da xong chua
|
|
74
|
-
- `Poll Completed Value` (tuy chon): gia tri cua status field khi hoan thanh (mac dinh: `completed`)
|
|
75
|
-
- **Webhook**: Goi API nhan `task_id`, external service se goi lai webhook khi xong. Plugin tu dong xu ly callback.
|
|
76
|
-
|
|
77
|
-
**Vi du: Dang ky endpoint OCR dong bo**
|
|
78
|
-
|
|
79
|
-
```
|
|
80
|
-
Name: ocr
|
|
81
|
-
Subpath: /api/v1/ocr
|
|
82
|
-
Method: POST
|
|
83
|
-
Execution Mode: Synchronous
|
|
84
|
-
File Input: Multipart
|
|
85
|
-
Enabled: true
|
|
86
|
-
```
|
|
87
|
-
|
|
88
|
-
**Vi du: Dang ky endpoint classify bat dong bo (polling)**
|
|
89
|
-
|
|
90
|
-
```
|
|
91
|
-
Name: classify
|
|
92
|
-
Subpath: /api/v1/classify
|
|
93
|
-
Method: POST
|
|
94
|
-
Execution Mode: Polling
|
|
95
|
-
Poll Task ID: task_id
|
|
96
|
-
Poll Result Field: result
|
|
97
|
-
File Input: None
|
|
98
|
-
Enabled: true
|
|
99
|
-
```
|
|
100
|
-
|
|
101
|
-
### Buoc 3: Tao Pipeline (Tab "Pipelines")
|
|
102
|
-
|
|
103
|
-
Pipeline la mot chuoi cac buoc (steps) goi lan luot cac endpoints da dang ky.
|
|
104
|
-
|
|
105
|
-
1. Mo tab **Pipelines**
|
|
106
|
-
2. Nhan **Add Pipeline**
|
|
107
|
-
3. Dien:
|
|
108
|
-
- **Name**: ten pipeline (vi du: `full_document_processing`)
|
|
109
|
-
- **Description**: mo ta
|
|
110
|
-
- **Enabled**: bat
|
|
111
|
-
|
|
112
|
-
**Cau hinh Steps (thong qua API hoac JSON):**
|
|
113
|
-
|
|
114
|
-
Hien tai giao dien UI cua Pipelines Tab chi ho tro CRUD co ban (name, description, enabled).
|
|
115
|
-
De cau hinh steps chi tiet, su dung REST API:
|
|
116
|
-
|
|
117
|
-
```bash
|
|
118
|
-
# Tao pipeline voi steps
|
|
119
|
-
curl -X POST http://localhost:13000/api/docUnderstanding:createPipeline \
|
|
120
|
-
-H "Content-Type: application/json" \
|
|
121
|
-
-H "Authorization: Bearer <your-nocobase-token>" \
|
|
122
|
-
-d '{
|
|
123
|
-
"name": "full_document_processing",
|
|
124
|
-
"description": "OCR roi classify roi extract",
|
|
125
|
-
"enabled": true,
|
|
126
|
-
"steps": [
|
|
127
|
-
{
|
|
128
|
-
"stepOrder": 1,
|
|
129
|
-
"name": "OCR",
|
|
130
|
-
"endpointId": 1,
|
|
131
|
-
"inputMapping": {},
|
|
132
|
-
"outputAlias": "ocr_result",
|
|
133
|
-
"onError": "fail"
|
|
134
|
-
},
|
|
135
|
-
{
|
|
136
|
-
"stepOrder": 2,
|
|
137
|
-
"name": "Classify",
|
|
138
|
-
"endpointId": 2,
|
|
139
|
-
"inputMapping": {
|
|
140
|
-
"text": "$step[ocr_result].response.text"
|
|
141
|
-
},
|
|
142
|
-
"outputAlias": "classify_result",
|
|
143
|
-
"onError": "fail"
|
|
144
|
-
},
|
|
145
|
-
{
|
|
146
|
-
"stepOrder": 3,
|
|
147
|
-
"name": "Extract Table",
|
|
148
|
-
"endpointId": 3,
|
|
149
|
-
"inputMapping": {
|
|
150
|
-
"text": "$step[ocr_result].response.text",
|
|
151
|
-
"doc_type": "$step[classify_result].response.category"
|
|
152
|
-
},
|
|
153
|
-
"outputAlias": "extract_result",
|
|
154
|
-
"onError": "skip",
|
|
155
|
-
"condition": {
|
|
156
|
-
"field": "$step[classify_result].response.category",
|
|
157
|
-
"op": "eq",
|
|
158
|
-
"value": "invoice"
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
]
|
|
162
|
-
}'
|
|
163
|
-
```
|
|
164
|
-
|
|
165
|
-
**Input Mapping DSL:**
|
|
166
|
-
|
|
167
|
-
| Cu phap | Mo ta | Vi du |
|
|
168
|
-
|---------|-------|-------|
|
|
169
|
-
| `$input.fieldName` | Lay tu input goc cua pipeline | `$input.document_url` |
|
|
170
|
-
| `$step[alias].response.path` | Lay tu ket qua step truoc (theo alias) | `$step[ocr_result].response.text` |
|
|
171
|
-
| `$step[1].response.path` | Lay tu ket qua step truoc (theo so thu tu) | `$step[1].response.text` |
|
|
172
|
-
| `$files` | Toan bo files dau vao | `$files` |
|
|
173
|
-
| Gia tri co dinh | String literal | `"invoice"` |
|
|
174
|
-
|
|
175
|
-
**Condition operators ho tro:** `eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `in`, `contains`
|
|
176
|
-
|
|
177
|
-
**onError options:** `fail` (dung pipeline), `skip` (bo qua step), `retry` (thu lai theo retryCount)
|
|
178
|
-
|
|
179
|
-
### Buoc 4: Chay Pipeline
|
|
180
|
-
|
|
181
|
-
**Cach 1: Qua REST API**
|
|
182
|
-
|
|
183
|
-
```bash
|
|
184
|
-
# Chay pipeline (tham so la pipelineId)
|
|
185
|
-
curl -X POST http://localhost:13000/api/docUnderstanding:executePipeline \
|
|
186
|
-
-H "Content-Type: application/json" \
|
|
187
|
-
-H "Authorization: Bearer <your-nocobase-token>" \
|
|
188
|
-
-d '{
|
|
189
|
-
"pipelineId": 1,
|
|
190
|
-
"input": {
|
|
191
|
-
"document_url": "https://example.com/invoice.pdf"
|
|
192
|
-
}
|
|
193
|
-
}'
|
|
194
|
-
|
|
195
|
-
# Response:
|
|
196
|
-
# { "jobId": 42 }
|
|
197
|
-
```
|
|
198
|
-
|
|
199
|
-
```bash
|
|
200
|
-
# Kiem tra trang thai job
|
|
201
|
-
curl http://localhost:13000/api/docUnderstanding:getJobStatus?jobId=42 \
|
|
202
|
-
-H "Authorization: Bearer <your-nocobase-token>"
|
|
203
|
-
|
|
204
|
-
# Response:
|
|
205
|
-
# {
|
|
206
|
-
# "id": 42,
|
|
207
|
-
# "status": "completed",
|
|
208
|
-
# "stepResults": { "ocr_result": {...}, "classify_result": {...} },
|
|
209
|
-
# "finalResult": {...}
|
|
210
|
-
# }
|
|
211
|
-
```
|
|
212
|
-
|
|
213
|
-
**Cach 2: Qua AI Employee (neu da cai plugin-ai)**
|
|
214
|
-
|
|
215
|
-
Khi `@nocobase/plugin-ai` duoc bat, **moi pipeline enabled se tu dong tro thanh mot AI tool/skill rieng biet**.
|
|
216
|
-
AI employee co the chon va goi truc tiep pipeline phu hop ma khong can biet pipeline name.
|
|
217
|
-
|
|
218
|
-
**Cach hoat dong:**
|
|
219
|
-
|
|
220
|
-
- Plugin dang ky mot **dynamic tools provider** voi AI tools manager.
|
|
221
|
-
- Moi khi AI can danh sach tools, provider se query tat ca pipeline co `enabled = true` va tao 1 tool cho moi pipeline.
|
|
222
|
-
- Tool name duoc sinh tu pipeline name: `doc_understanding.<sanitized_pipeline_name>`
|
|
223
|
-
- Vi du: pipeline "Full Document Processing" → tool `doc_understanding.full_document_processing`
|
|
224
|
-
- Moi tool co:
|
|
225
|
-
- **Title**: `Document: <pipeline name>`
|
|
226
|
-
- **Description**: mo ta pipeline + danh sach steps (vi du: "OCR → Classify → Extract")
|
|
227
|
-
- **Schema**: lay tu `inputSchema` cua pipeline (neu co), hoac fallback la `{ input: object }`
|
|
228
|
-
|
|
229
|
-
**Vi du: Ban co 3 pipelines enabled:**
|
|
230
|
-
|
|
231
|
-
| Pipeline | Tool name | Mo ta AI nhin thay |
|
|
232
|
-
|----------|-----------|-------------------|
|
|
233
|
-
| OCR Only | `doc_understanding.ocr_only` | "Thuc hien OCR tren tai lieu. Steps: OCR" |
|
|
234
|
-
| Invoice Processing | `doc_understanding.invoice_processing` | "Xu ly hoa don. Steps: OCR → Classify → Extract Table" |
|
|
235
|
-
| Contract Analysis | `doc_understanding.contract_analysis` | "Phan tich hop dong. Steps: OCR → NER → Summarize" |
|
|
236
|
-
|
|
237
|
-
**Khi nguoi dung hoi AI employee:**
|
|
238
|
-
|
|
239
|
-
```
|
|
240
|
-
User: "Phan tich hoa don nay giup toi"
|
|
241
|
-
|
|
242
|
-
AI tu dong chon tool: doc_understanding.invoice_processing
|
|
243
|
-
- input: { document_url: "..." }
|
|
244
|
-
|
|
245
|
-
→ Tra ve ket qua JSON sau khi pipeline chay xong (poll toi da 30s)
|
|
246
|
-
→ Neu chua xong, tra ve jobId de theo doi
|
|
247
|
-
```
|
|
248
|
-
|
|
249
|
-
**Luu y:**
|
|
250
|
-
- Chi pipeline co `enabled = true` moi duoc dang ky lam tool
|
|
251
|
-
- Khi ban tao/sua/xoa/bat/tat pipeline, danh sach tools tu dong cap nhat (dynamic, khong can restart)
|
|
252
|
-
- Neu pipeline co `inputSchema` duoc dinh nghia, AI se biet chinh xac can truyen tham so gi
|
|
253
|
-
- Moi tool hoat dong doc lap — AI employee co the chon dung tool phu hop theo ngu canh
|
|
254
|
-
|
|
255
|
-
**Tip: Dinh nghia inputSchema cho pipeline de AI hieu ro input can thiet:**
|
|
256
|
-
|
|
257
|
-
```bash
|
|
258
|
-
curl -X POST http://localhost:13000/api/docUnderstanding:updatePipeline/1 \
|
|
259
|
-
-H "Content-Type: application/json" \
|
|
260
|
-
-H "Authorization: Bearer <your-nocobase-token>" \
|
|
261
|
-
-d '{
|
|
262
|
-
"inputSchema": {
|
|
263
|
-
"type": "object",
|
|
264
|
-
"properties": {
|
|
265
|
-
"document_url": {
|
|
266
|
-
"type": "string",
|
|
267
|
-
"description": "URL cua tai lieu can xu ly"
|
|
268
|
-
},
|
|
269
|
-
"language": {
|
|
270
|
-
"type": "string",
|
|
271
|
-
"enum": ["vi", "en", "ja"],
|
|
272
|
-
"description": "Ngon ngu cua tai lieu"
|
|
273
|
-
}
|
|
274
|
-
},
|
|
275
|
-
"required": ["document_url"]
|
|
276
|
-
}
|
|
277
|
-
}'
|
|
278
|
-
```
|
|
279
|
-
|
|
280
|
-
Khi do AI se biet chinh xac can `document_url` (bat buoc) va `language` (tuy chon) khi goi tool.
|
|
281
|
-
|
|
282
|
-
### Buoc 5: Theo doi Jobs (Tab "Jobs history")
|
|
283
|
-
|
|
284
|
-
1. Mo tab **Jobs history**
|
|
285
|
-
2. Xem danh sach jobs voi trang thai:
|
|
286
|
-
- **pending**: Dang cho
|
|
287
|
-
- **running**: Dang chay
|
|
288
|
-
- **polling**: Dang cho ket qua tu external service
|
|
289
|
-
- **completed**: Hoan thanh
|
|
290
|
-
- **failed**: That bai
|
|
291
|
-
- **timeout**: Het thoi gian cho
|
|
292
|
-
3. Nhan **View Details** de xem chi tiet:
|
|
293
|
-
- Input da gui
|
|
294
|
-
- Ket qua tung step
|
|
295
|
-
- Ket qua cuoi cung
|
|
296
|
-
- Loi (neu co)
|
|
297
|
-
|
|
298
|
-
Tab tu dong refresh moi 10 giay.
|
|
299
|
-
|
|
300
|
-
---
|
|
301
|
-
|
|
302
|
-
## Webhook Callback
|
|
303
|
-
|
|
304
|
-
Neu endpoint su dung execution mode **Webhook**, external service can goi callback ve:
|
|
305
|
-
|
|
306
|
-
```
|
|
307
|
-
POST http://localhost:13000/api/docUnderstanding:webhookCallback
|
|
308
|
-
Content-Type: application/json
|
|
309
|
-
X-Webhook-Signature: sha256=<hmac-hex> (neu co cau hinh Webhook Secret)
|
|
310
|
-
|
|
311
|
-
{
|
|
312
|
-
"task_id": "abc-123",
|
|
313
|
-
"result": { ... }
|
|
314
|
-
}
|
|
315
|
-
```
|
|
316
|
-
|
|
317
|
-
Plugin se tu dong match `task_id` voi job dang cho va tiep tuc pipeline.
|
|
318
|
-
|
|
319
|
-
---
|
|
320
|
-
|
|
321
|
-
## REST API Reference
|
|
322
|
-
|
|
323
|
-
| Action | Method | URL |
|
|
324
|
-
|--------|--------|-----|
|
|
325
|
-
| Lay config | GET | `/api/docUnderstanding:getConfig` |
|
|
326
|
-
| Cap nhat config | POST | `/api/docUnderstanding:updateConfig` |
|
|
327
|
-
| Danh sach endpoints | GET | `/api/docUnderstanding:listEndpoints` |
|
|
328
|
-
| Tao endpoint | POST | `/api/docUnderstanding:createEndpoint` |
|
|
329
|
-
| Sua endpoint | POST | `/api/docUnderstanding:updateEndpoint/{id}` |
|
|
330
|
-
| Xoa endpoint | DELETE | `/api/docUnderstanding:deleteEndpoint/{id}` |
|
|
331
|
-
| Danh sach pipelines | GET | `/api/docUnderstanding:listPipelines` |
|
|
332
|
-
| Tao pipeline | POST | `/api/docUnderstanding:createPipeline` |
|
|
333
|
-
| Sua pipeline | POST | `/api/docUnderstanding:updatePipeline/{id}` |
|
|
334
|
-
| Xoa pipeline | DELETE | `/api/docUnderstanding:deletePipeline/{id}` |
|
|
335
|
-
| Chay pipeline | POST | `/api/docUnderstanding:executePipeline` |
|
|
336
|
-
| Trang thai job | GET | `/api/docUnderstanding:getJobStatus?jobId={id}` |
|
|
337
|
-
| Danh sach jobs | GET | `/api/docUnderstanding:listJobs` |
|
|
338
|
-
| Webhook callback | POST | `/api/docUnderstanding:webhookCallback` |
|
|
339
|
-
|
|
340
|
-
---
|
|
341
|
-
|
|
342
|
-
## Vi du: Pipeline OCR + Extract hoan chinh
|
|
343
|
-
|
|
344
|
-
```
|
|
345
|
-
1. Cau hinh Service Config:
|
|
346
|
-
Base URL: http://docai-service:8000
|
|
347
|
-
Auth Type: API Key
|
|
348
|
-
API Key: sk-my-secret-key
|
|
349
|
-
|
|
350
|
-
2. Tao 2 endpoints:
|
|
351
|
-
- "ocr": POST /ocr, Sync, Multipart
|
|
352
|
-
- "extract": POST /extract, Sync, None
|
|
353
|
-
|
|
354
|
-
3. Tao pipeline "ocr_and_extract" voi 2 steps:
|
|
355
|
-
Step 1: endpoint=ocr, outputAlias=ocr_out, onError=fail
|
|
356
|
-
Step 2: endpoint=extract, inputMapping={ "text": "$step[ocr_out].response.text" },
|
|
357
|
-
outputAlias=extract_out, onError=fail
|
|
358
|
-
|
|
359
|
-
4. Chay:
|
|
360
|
-
POST /api/docUnderstanding:executePipeline
|
|
361
|
-
{ "pipelineId": 1, "input": {} }
|
|
362
|
-
(gui file qua multipart neu can)
|
|
363
|
-
|
|
364
|
-
5. Kiem tra ket qua:
|
|
365
|
-
GET /api/docUnderstanding:getJobStatus?jobId=1
|
|
366
|
-
```
|
|
1
|
+
# plugin-document-understanding
|
|
2
|
+
|
|
3
|
+
## Overview
|
|
4
|
+
Provides advanced document understanding and structured data extraction capabilities.
|
|
5
|
+
|
|
6
|
+
## Features
|
|
7
|
+
- **Schema-Based Extraction**: Define a NocoBase collection, and the AI will extract data from documents to fill the fields.
|
|
8
|
+
- **Batch Processing**: Process multiple documents in an automated workflow.
|
|
9
|
+
- **Human-in-the-loop**: UI to review and approve extracted fields before committing to the database.
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
1. Enable the plugin.
|
|
13
|
+
2. Create a collection (e.g., "Invoices" with fields: Total, Date, Vendor).
|
|
14
|
+
3. Set up a Document Understanding task linked to this collection.
|
|
15
|
+
4. Upload documents.
|
|
16
|
+
5. The system will extract the data. Review the pending records in the UI and click "Approve" to save them.
|
package/dist/client/index.js
CHANGED
|
@@ -7,4 +7,4 @@
|
|
|
7
7
|
* For more information, please refer to: https://www.nocobase.com/agreement.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
-
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("@nocobase/client"),require("@ant-design/icons"),require("antd")):"function"==typeof define&&define.amd?define("plugin-document-understanding",["react","@nocobase/client","@ant-design/icons","antd"],t):"object"==typeof exports?exports["plugin-document-understanding"]=t(require("react"),require("@nocobase/client"),require("@ant-design/icons"),require("antd")):e["plugin-document-understanding"]=t(e.react,e["@nocobase/client"],e["@ant-design/icons"],e.antd)}(self,function(e,t,n,r){return function(){"use strict";var l={482:function(e){e.exports=n},772:function(e){e.exports=t},721:function(e){e.exports=r},156:function(t){t.exports=e}},a={};function o(e){var t=a[e];if(void 0!==t)return t.exports;var n=a[e]={exports:{}};return l[e](n,n.exports,o),n.exports}o.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(t,{a:t}),t},o.d=function(e,t){for(var n in t)o.o(t,n)&&!o.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},o.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};return!function(){o.r(i),o.d(i,{default:function(){return X}});var e=o(772),t={},n=o(156),r=o.n(n),l=o(721),a=o(482);function u(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function c(e,t,n,r,l,a,o){try{var i=e[a](o),u=i.value}catch(e){n(e);return}i.done?t(u):Promise.resolve(u).then(r,l)}function s(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,l=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=l){var a=[],o=!0,i=!1;try{for(l=l.call(e);!(o=(n=l.next()).done)&&(a.push(n.value),!t||a.length!==t);o=!0);}catch(e){i=!0,r=e}finally{try{o||null==l.return||l.return()}finally{if(i)throw r}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return u(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if("Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return u(e,t)}}(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var p=function(){var t,o,i=s(l.Form.useForm(),1)[0],u=(0,e.useAPIClient)(),p=s((0,n.useState)(!0),2),d=p[0],m=p[1],f=s((0,n.useState)(!1),2),y=f[0],h=f[1];(0,n.useEffect)(function(){u.request({url:"docUnderstanding:getConfig"}).then(function(e){var t=e.data;i.setFieldsValue((null==t?void 0:t.data)||{}),m(!1)}).catch(function(){return m(!1)})},[]);var b=(t=function(e){return function(e,t){var n,r,l,a,o={label:0,sent:function(){if(1&l[0])throw l[1];return l[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(a){return function(i){var u=[a,i];if(n)throw TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(l=2&u[0]?r.return:u[0]?r.throw||((l=r.return)&&l.call(r),0):r.next)&&!(l=l.call(r,u[1])).done)return l;switch(r=0,l&&(u=[2&u[0],l.value]),u[0]){case 0:case 1:l=u;break;case 4:return o.label++,{value:u[1],done:!1};case 5:o.label++,r=u[1],u=[0];continue;case 7:u=o.ops.pop(),o.trys.pop();continue;default:if(!(l=(l=o.trys).length>0&&l[l.length-1])&&(6===u[0]||2===u[0])){o=0;continue}if(3===u[0]&&(!l||u[1]>l[0]&&u[1]<l[3])){o.label=u[1];break}if(6===u[0]&&o.label<l[1]){o.label=l[1],l=u;break}if(l&&o.label<l[2]){o.label=l[2],o.ops.push(u);break}l[2]&&o.ops.pop(),o.trys.pop();continue}u=t.call(e,o)}catch(e){u=[6,e],r=0}finally{n=l=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}}(this,function(t){switch(t.label){case 0:h(!0),t.label=1;case 1:return t.trys.push([1,3,4,5]),[4,u.request({url:"docUnderstanding:updateConfig",method:"POST",data:e})];case 2:return t.sent(),l.message.success("Configuration saved successfully"),[3,5];case 3:return t.sent(),l.message.error("Failed to save config"),[3,5];case 4:return h(!1),[7];case 5:return[2]}})},o=function(){var e=this,n=arguments;return new Promise(function(r,l){var a=t.apply(e,n);function o(e){c(a,r,l,o,i,"next",e)}function i(e){c(a,r,l,o,i,"throw",e)}o(void 0)})},function(e){return o.apply(this,arguments)});return d?r().createElement(l.Spin,{style:{marginTop:40}}):r().createElement(l.Form,{form:i,layout:"vertical",onFinish:b,style:{maxWidth:600}},r().createElement(l.Alert,{message:"Service Connection",description:"Configure the connection to your external document processing service. All endpoints will use this base URL and authentication.",type:"info",showIcon:!0,style:{marginBottom:24}}),r().createElement(l.Form.Item,{name:"baseUrl",label:"Base URL",rules:[{required:!0,message:"Base URL is required"}],help:"The root URL of your document processing API"},r().createElement(l.Input,{prefix:r().createElement(a.LinkOutlined,null),placeholder:"http://my-ocr-service:8000"})),r().createElement(l.Form.Item,{name:"authType",label:"Authentication Type",initialValue:"none"},r().createElement(l.Select,null,r().createElement(l.Select.Option,{value:"none"},"None"),r().createElement(l.Select.Option,{value:"api_key"},"API Key"),r().createElement(l.Select.Option,{value:"bearer"},"Bearer Token"),r().createElement(l.Select.Option,{value:"custom_header"},"Custom Header"))),r().createElement(l.Form.Item,{noStyle:!0,dependencies:["authType"]},function(){var e=i.getFieldValue("authType");return"none"===e?null:r().createElement(r().Fragment,null,"custom_header"===e&&r().createElement(l.Form.Item,{name:"authHeaderName",label:"Custom Header Name",rules:[{required:!0}]},r().createElement(l.Input,{placeholder:"X-Api-Key"})),r().createElement(l.Form.Item,{name:"authKey",label:"bearer"===e?"Bearer Token":"API Key",rules:[{required:!0}]},r().createElement(l.Input.Password,{placeholder:"Enter key or token"})))}),r().createElement("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"0 16px"}},r().createElement(l.Form.Item,{name:"defaultTimeout",label:"Request Timeout (ms)",initialValue:3e4},r().createElement(l.InputNumber,{style:{width:"100%"},min:1e3,step:1e3})),r().createElement(l.Form.Item,{name:"defaultRetries",label:"Default Retries",initialValue:2},r().createElement(l.InputNumber,{style:{width:"100%"},min:0,max:10})),r().createElement(l.Form.Item,{name:"pollInterval",label:"Poll Interval (ms)",initialValue:5e3},r().createElement(l.InputNumber,{style:{width:"100%"},min:1e3,step:1e3})),r().createElement(l.Form.Item,{name:"pollTimeout",label:"Poll Timeout (ms)",initialValue:3e5},r().createElement(l.InputNumber,{style:{width:"100%"},min:5e3,step:5e3}))),r().createElement(l.Form.Item,{name:"webhookSecret",label:"Webhook Secret",help:"Used to verify HMAC-SHA256 signatures on incoming webhook callbacks"},r().createElement(l.Input.Password,{placeholder:"Optional: secret for webhook signature verification"})),r().createElement(l.Form.Item,null,r().createElement(l.Button,{type:"primary",htmlType:"submit",icon:r().createElement(a.SaveOutlined,null),loading:y},"Save Configuration")))};function d(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function m(e,t,n,r,l,a,o){try{var i=e[a](o),u=i.value}catch(e){n(e);return}i.done?t(u):Promise.resolve(u).then(r,l)}function f(e){return function(){var t=this,n=arguments;return new Promise(function(r,l){var a=e.apply(t,n);function o(e){m(a,r,l,o,i,"next",e)}function i(e){m(a,r,l,o,i,"throw",e)}o(void 0)})}}function y(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,l=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=l){var a=[],o=!0,i=!1;try{for(l=l.call(e);!(o=(n=l.next()).done)&&(a.push(n.value),!t||a.length!==t);o=!0);}catch(e){i=!0,r=e}finally{try{o||null==l.return||l.return()}finally{if(i)throw r}}return a}}(e,t)||b(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function h(e){return function(e){if(Array.isArray(e))return d(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||b(e)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function b(e,t){if(e){if("string"==typeof e)return d(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if("Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return d(e,t)}}function g(e,t){var n,r,l,a,o={label:0,sent:function(){if(1&l[0])throw l[1];return l[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(a){return function(i){var u=[a,i];if(n)throw TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(l=2&u[0]?r.return:u[0]?r.throw||((l=r.return)&&l.call(r),0):r.next)&&!(l=l.call(r,u[1])).done)return l;switch(r=0,l&&(u=[2&u[0],l.value]),u[0]){case 0:case 1:l=u;break;case 4:return o.label++,{value:u[1],done:!1};case 5:o.label++,r=u[1],u=[0];continue;case 7:u=o.ops.pop(),o.trys.pop();continue;default:if(!(l=(l=o.trys).length>0&&l[l.length-1])&&(6===u[0]||2===u[0])){o=0;continue}if(3===u[0]&&(!l||u[1]>l[0]&&u[1]<l[3])){o.label=u[1];break}if(6===u[0]&&o.label<l[1]){o.label=l[1],l=u;break}if(l&&o.label<l[2]){o.label=l[2],o.ops.push(u);break}l[2]&&o.ops.pop(),o.trys.pop();continue}u=t.call(e,o)}catch(e){u=[6,e],r=0}finally{n=l=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}}var E=l.Input.TextArea,v=function(e){var t=e.value,n=void 0===t?{}:t,o=e.onChange,i=Object.entries(n),u=function(e,t,n){var r=h(i);r[e]=[t,n],null==o||o(Object.fromEntries(r))},c=function(e){var t=h(i);t.splice(e,1),null==o||o(Object.fromEntries(t))};return r().createElement("div",null,i.map(function(e,t){var n=y(e,2),o=n[0],i=n[1];return r().createElement(l.Space,{key:t,style:{display:"flex",marginBottom:4}},r().createElement(l.Input,{placeholder:"Header name",value:o,onChange:function(e){return u(t,e.target.value,i)},style:{width:180}}),r().createElement(l.Input,{placeholder:"Value",value:i,onChange:function(e){return u(t,o,e.target.value)},style:{width:220}}),r().createElement(l.Button,{size:"small",danger:!0,icon:r().createElement(a.DeleteOutlined,null),onClick:function(){return c(t)}}))}),r().createElement(l.Button,{size:"small",type:"dashed",icon:r().createElement(a.PlusOutlined,null),onClick:function(){var e,t;return null==o?void 0:o((e=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){var r;r=n[t],t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r})}return e}({},n),t=t={"":""},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):(function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);n.push.apply(n,r)}return n})(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e))}},"Add Header"))},S=function(e){var t=e.value,l=e.onChange,a=e.placeholder,o=y((0,n.useState)(""),2),i=o[0],u=o[1],c=y((0,n.useState)(""),2),s=c[0],p=c[1];return(0,n.useEffect)(function(){if(!t)return void u("");try{u("string"==typeof t?JSON.stringify(JSON.parse(t),null,2):JSON.stringify(t,null,2))}catch(e){u("string"==typeof t?t:"")}},[t]),r().createElement("div",null,r().createElement(E,{rows:6,value:i,onChange:function(e){return u(e.target.value)},onBlur:function(){if(!i.trim()){p(""),null==l||l(null);return}try{var e=JSON.parse(i);p(""),null==l||l(e)}catch(e){p("Invalid JSON")}},placeholder:a||"{}",style:{fontFamily:"monospace",fontSize:12}}),s&&r().createElement("div",{style:{color:"#ff4d4f",fontSize:12}},s))},w=function(){var t,o,i,u=(0,e.useAPIClient)(),c=y((0,n.useState)([]),2),s=c[0],p=c[1],d=y((0,n.useState)(!1),2),m=d[0],h=d[1],b=y((0,n.useState)(!1),2),w=b[0],O=b[1],I=y(l.Form.useForm(),1)[0],k=y((0,n.useState)(null),2),T=k[0],x=k[1],P=(t=f(function(){var e;return g(this,function(t){switch(t.label){case 0:h(!0),t.label=1;case 1:return t.trys.push([1,,3,4]),[4,u.request({url:"docUnderstanding:listEndpoints"})];case 2:return p((null==(e=t.sent().data)?void 0:e.data)||[]),[3,4];case 3:return h(!1),[7];case 4:return[2]}})}),function(){return t.apply(this,arguments)});(0,n.useEffect)(function(){P()},[]);var C=function(e){x(e.id),I.setFieldsValue(e),O(!0)},F=(o=f(function(e){return g(this,function(t){switch(t.label){case 0:return[4,u.request({url:"docUnderstanding:deleteEndpoint",method:"POST",params:{filterByTk:e}})];case 1:return t.sent(),l.message.success("Deleted"),P(),[2]}})}),function(e){return o.apply(this,arguments)}),A=(i=f(function(){var e;return g(this,function(t){switch(t.label){case 0:return t.trys.push([0,6,,7]),[4,I.validateFields()];case 1:if(e=t.sent(),!T)return[3,3];return[4,u.request({url:"docUnderstanding:updateEndpoint",method:"POST",params:{filterByTk:T},data:e})];case 2:return t.sent(),[3,5];case 3:return[4,u.request({url:"docUnderstanding:createEndpoint",method:"POST",data:e})];case 4:t.sent(),t.label=5;case 5:return l.message.success("Saved"),O(!1),P(),[3,7];case 6:return t.sent(),[3,7];case 7:return[2]}})}),function(){return i.apply(this,arguments)}),j=[{title:"Name",dataIndex:"name",width:150},{title:"Subpath",dataIndex:"subpath",width:200},{title:"Method",dataIndex:"method",width:80,render:function(e){return r().createElement(l.Tag,null,e)}},{title:"Execution",dataIndex:"executionMode",width:100,render:function(e){return r().createElement(l.Tag,{color:{sync:"green",polling:"blue",webhook:"purple"}[e]},e)}},{title:"File",dataIndex:"fileInputMode",width:90,render:function(e){return"none"===e?"-":e}},{title:"Enabled",dataIndex:"enabled",width:70,render:function(e){return e?r().createElement(l.Tag,{color:"success"},"Yes"):r().createElement(l.Tag,null,"No")}},{title:"Action",width:120,render:function(e,t){return r().createElement(l.Space,null,r().createElement(l.Button,{type:"link",size:"small",icon:r().createElement(a.EditOutlined,null),onClick:function(){return C(t)}},"Edit"),r().createElement(l.Popconfirm,{title:"Delete this endpoint?",onConfirm:function(){return F(t.id)}},r().createElement(l.Button,{type:"link",size:"small",danger:!0,icon:r().createElement(a.DeleteOutlined,null)},"Delete")))}}];return r().createElement("div",null,r().createElement("div",{style:{marginBottom:16}},r().createElement(l.Button,{type:"primary",icon:r().createElement(a.PlusOutlined,null),onClick:function(){x(null),I.resetFields(),O(!0)}},"Add Endpoint")),r().createElement(l.Table,{rowKey:"id",columns:j,dataSource:s,loading:m,size:"small"}),r().createElement(l.Modal,{title:T?"Edit Endpoint":"Add Endpoint",open:w,onOk:A,onCancel:function(){return O(!1)},width:680,destroyOnClose:!0},r().createElement(l.Form,{form:I,layout:"vertical",preserve:!1},r().createElement(l.Tabs,{size:"small",items:[{key:"basic",label:"Basic",children:r().createElement(r().Fragment,null,r().createElement(l.Form.Item,{name:"name",label:"Unique Name",rules:[{required:!0}]},r().createElement(l.Input,{placeholder:"ocr, classify, extract..."})),r().createElement(l.Form.Item,{name:"subpath",label:"Subpath",rules:[{required:!0}]},r().createElement(l.Input,{placeholder:"/api/v1/ocr"})),r().createElement(l.Form.Item,{name:"description",label:"Description"},r().createElement(E,{rows:2,placeholder:"What this endpoint does"})),r().createElement(l.Space,{size:"large"},r().createElement(l.Form.Item,{name:"method",label:"HTTP Method",initialValue:"POST"},r().createElement(l.Select,{style:{width:120}},r().createElement(l.Select.Option,{value:"GET"},"GET"),r().createElement(l.Select.Option,{value:"POST"},"POST"),r().createElement(l.Select.Option,{value:"PUT"},"PUT"))),r().createElement(l.Form.Item,{name:"enabled",label:"Enabled",valuePropName:"checked",initialValue:!0},r().createElement(l.Switch,null))))},{key:"file",label:"File Input",children:r().createElement(r().Fragment,null,r().createElement(l.Form.Item,{name:"fileInputMode",label:"File Input Mode",initialValue:"none"},r().createElement(l.Select,{style:{width:200}},r().createElement(l.Select.Option,{value:"none"},"None"),r().createElement(l.Select.Option,{value:"multipart"},"Multipart Upload"),r().createElement(l.Select.Option,{value:"base64"},"Base64 in JSON"))),r().createElement(l.Form.Item,{noStyle:!0,dependencies:["fileInputMode"]},function(){return"none"!==I.getFieldValue("fileInputMode")?r().createElement(l.Form.Item,{name:"maxFiles",label:"Max Files",initialValue:1},r().createElement(l.InputNumber,{min:1,max:20,style:{width:120}})):null}))},{key:"async",label:"Async Config",children:r().createElement(r().Fragment,null,r().createElement(l.Form.Item,{name:"executionMode",label:"Execution Mode",initialValue:"sync"},r().createElement(l.Select,{style:{width:200}},r().createElement(l.Select.Option,{value:"sync"},"Synchronous"),r().createElement(l.Select.Option,{value:"polling"},"Polling"),r().createElement(l.Select.Option,{value:"webhook"},"Webhook"))),r().createElement(l.Form.Item,{noStyle:!0,dependencies:["executionMode"]},function(){var e=I.getFieldValue("executionMode");return"sync"===e?null:r().createElement(r().Fragment,null,r().createElement(l.Form.Item,{name:"pollTaskIdField",label:"Task ID Field",help:"Field in response containing the async task ID",initialValue:"task_id"},r().createElement(l.Input,{placeholder:"task_id"})),"polling"===e&&r().createElement(r().Fragment,null,r().createElement(l.Form.Item,{name:"pollResultSubpath",label:"Poll Result Subpath",help:"URL to poll for result. Use {taskId} as placeholder.",rules:[{required:!0,message:"Required for polling mode"}]},r().createElement(l.Input,{placeholder:"/api/v1/tasks/{taskId}/result"})),r().createElement(l.Form.Item,{name:"pollResultField",label:"Result Field",help:"Field in poll response containing the actual result"},r().createElement(l.Input,{placeholder:"result"})),r().createElement(l.Form.Item,{name:"pollStatusField",label:"Status Field (optional)",help:"Field to check completion status. If empty, any non-null result = complete."},r().createElement(l.Input,{placeholder:"status"})),r().createElement(l.Form.Item,{name:"pollCompletedValue",label:"Completed Value",help:"Value of status field that means 'done'",initialValue:"completed"},r().createElement(l.Input,{placeholder:"completed"})),r().createElement(l.Space,{size:"large"},r().createElement(l.Form.Item,{name:"pollInterval",label:"Poll Interval (ms)",help:"Override default"},r().createElement(l.InputNumber,{min:1e3,step:1e3,placeholder:"5000",style:{width:150}})),r().createElement(l.Form.Item,{name:"pollTimeout",label:"Poll Timeout (ms)",help:"Override default"},r().createElement(l.InputNumber,{min:5e3,step:5e3,placeholder:"300000",style:{width:150}})))))}))},{key:"schema",label:"Schema",children:r().createElement(r().Fragment,null,r().createElement(l.Form.Item,{name:"requestBodySchema",label:"Request Body Schema (JSON Schema)"},r().createElement(S,{placeholder:'{ "type": "object", "properties": { ... } }'})),r().createElement(l.Form.Item,{name:"responseSchema",label:"Response Schema (JSON Schema)"},r().createElement(S,{placeholder:'{ "type": "object", "properties": { ... } }'})))},{key:"headers",label:"Custom Headers",children:r().createElement(l.Form.Item,{name:"customHeaders",label:"Additional Headers"},r().createElement(v,null))}]}))))};function O(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function I(e,t,n,r,l,a,o){try{var i=e[a](o),u=i.value}catch(e){n(e);return}i.done?t(u):Promise.resolve(u).then(r,l)}function k(e){return function(){var t=this,n=arguments;return new Promise(function(r,l){var a=e.apply(t,n);function o(e){I(a,r,l,o,i,"next",e)}function i(e){I(a,r,l,o,i,"throw",e)}o(void 0)})}}function T(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){var r;r=n[t],t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r})}return e}function x(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):(function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);n.push.apply(n,r)}return n})(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}function P(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,l=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=l){var a=[],o=!0,i=!1;try{for(l=l.call(e);!(o=(n=l.next()).done)&&(a.push(n.value),!t||a.length!==t);o=!0);}catch(e){i=!0,r=e}finally{try{o||null==l.return||l.return()}finally{if(i)throw r}}return a}}(e,t)||F(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function C(e){return function(e){if(Array.isArray(e))return O(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||F(e)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function F(e,t){if(e){if("string"==typeof e)return O(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if("Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return O(e,t)}}function A(e,t){var n,r,l,a,o={label:0,sent:function(){if(1&l[0])throw l[1];return l[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(a){return function(i){var u=[a,i];if(n)throw TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(l=2&u[0]?r.return:u[0]?r.throw||((l=r.return)&&l.call(r),0):r.next)&&!(l=l.call(r,u[1])).done)return l;switch(r=0,l&&(u=[2&u[0],l.value]),u[0]){case 0:case 1:l=u;break;case 4:return o.label++,{value:u[1],done:!1};case 5:o.label++,r=u[1],u=[0];continue;case 7:u=o.ops.pop(),o.trys.pop();continue;default:if(!(l=(l=o.trys).length>0&&l[l.length-1])&&(6===u[0]||2===u[0])){o=0;continue}if(3===u[0]&&(!l||u[1]>l[0]&&u[1]<l[3])){o.label=u[1];break}if(6===u[0]&&o.label<l[1]){o.label=l[1],l=u;break}if(l&&o.label<l[2]){o.label=l[2],o.ops.push(u);break}l[2]&&o.ops.pop(),o.trys.pop();continue}u=t.call(e,o)}catch(e){u=[6,e],r=0}finally{n=l=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}}var j=l.Input.TextArea,B=l.Collapse.Panel,M=function(e){var t=e.value,l=e.onChange,a=e.placeholder,o=e.rows,i=P((0,n.useState)(""),2),u=i[0],c=i[1],s=P((0,n.useState)(""),2),p=s[0],d=s[1];return(0,n.useEffect)(function(){if(!t)return void c("");try{c("string"==typeof t?JSON.stringify(JSON.parse(t),null,2):JSON.stringify(t,null,2))}catch(e){c("string"==typeof t?t:"")}},[t]),r().createElement("div",null,r().createElement(j,{rows:void 0===o?5:o,value:u,onChange:function(e){return c(e.target.value)},onBlur:function(){if(!u.trim()){d(""),null==l||l(null);return}try{var e=JSON.parse(u);d(""),null==l||l(e)}catch(e){d("Invalid JSON")}},placeholder:a||"{}",style:{fontFamily:"monospace",fontSize:12}}),p&&r().createElement("div",{style:{color:"#ff4d4f",fontSize:12}},p))},N=function(e){var t=e.steps,n=e.endpoints,o=e.onChange,i=function(e,n){var r,l=C(t),a=e+n;a<0||a>=l.length||(r=[l[a],l[e]],l[e]=r[0],l[a]=r[1],l.forEach(function(e,t){return e.stepOrder=t+1}),o(l))},u=function(e,n,r){var l=C(t);l[e][n]=r,o(l)},c=function(e){var n=t.filter(function(t,n){return n!==e});n.forEach(function(e,t){return e.stepOrder=t+1}),o(n)},s=function(){var e;o(C(t).concat([(e=t.length+1,{_key:"new_".concat(Date.now(),"_").concat(Math.random()),stepOrder:e,name:"",endpointId:null,inputMapping:null,outputAlias:"",condition:null,onError:"fail",retryCount:0})]))};return 0===t.length?r().createElement("div",{style:{textAlign:"center",padding:"20px 0"}},r().createElement(l.Empty,{description:"No steps yet",imageStyle:{height:40}}),r().createElement(l.Button,{type:"dashed",icon:r().createElement(a.PlusOutlined,null),onClick:s,style:{marginTop:8}},"Add First Step")):r().createElement("div",null,r().createElement(l.Collapse,{size:"small",defaultActiveKey:t.map(function(e){return e._key})},t.map(function(e,o){var s=n.find(function(t){return t.id===e.endpointId}),p=r().createElement(l.Space,{size:4,onClick:function(e){return e.stopPropagation()}},r().createElement(l.Button,{size:"small",disabled:0===o,icon:r().createElement(a.ArrowUpOutlined,null),onClick:function(){return i(o,-1)}}),r().createElement(l.Button,{size:"small",disabled:o===t.length-1,icon:r().createElement(a.ArrowDownOutlined,null),onClick:function(){return i(o,1)}}),r().createElement(l.Popconfirm,{title:"Remove step?",onConfirm:function(){return c(o)}},r().createElement(l.Button,{size:"small",danger:!0,icon:r().createElement(a.DeleteOutlined,null)}))),d=r().createElement(l.Space,null,r().createElement(l.Badge,{count:e.stepOrder,style:{backgroundColor:"#1677ff"}}),r().createElement("span",null,e.name||"(unnamed)"),s&&r().createElement(l.Tag,null,s.name),"skip"===e.onError&&r().createElement(l.Tooltip,{title:"Step can be skipped on error"},r().createElement(l.Tag,{color:"orange"},"skip on error")),e.condition&&r().createElement(l.Tooltip,{title:"Has condition"},r().createElement(l.Tag,{color:"purple"},"conditional")));return r().createElement(B,{key:e._key,header:d,extra:p},r().createElement("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"0 16px"}},r().createElement("div",null,r().createElement("label",{style:{fontWeight:500,display:"block",marginBottom:4}},"Step Name *"),r().createElement(l.Input,{value:e.name,onChange:function(e){return u(o,"name",e.target.value)},placeholder:"OCR, Classify, Extract..."})),r().createElement("div",null,r().createElement("label",{style:{fontWeight:500,display:"block",marginBottom:4}},"Endpoint *"),r().createElement(l.Select,{value:e.endpointId,onChange:function(e){return u(o,"endpointId",e)},placeholder:"Select endpoint",style:{width:"100%"},options:n.map(function(e){return{value:e.id,label:"".concat(e.name," (").concat(e.method," ").concat(e.subpath,")")}})})),r().createElement("div",null,r().createElement("label",{style:{fontWeight:500,display:"block",marginBottom:4,marginTop:12}},"Output Alias"),r().createElement(l.Input,{value:e.outputAlias,onChange:function(e){return u(o,"outputAlias",e.target.value)},placeholder:"ocr_result"}),r().createElement("div",{style:{color:"#888",fontSize:11}},"Other steps reference this as: $step[",e.outputAlias||e.stepOrder,"].response.field")),r().createElement("div",null,r().createElement("label",{style:{fontWeight:500,display:"block",marginBottom:4,marginTop:12}},"On Error"),r().createElement(l.Space,null,r().createElement(l.Select,{value:e.onError,onChange:function(e){return u(o,"onError",e)},style:{width:120}},r().createElement(l.Select.Option,{value:"fail"},"Fail"),r().createElement(l.Select.Option,{value:"skip"},"Skip"),r().createElement(l.Select.Option,{value:"retry"},"Retry")),"retry"===e.onError&&r().createElement(l.InputNumber,{value:e.retryCount,onChange:function(e){return u(o,"retryCount",e||0)},min:1,max:10,addonBefore:"x",style:{width:100}})))),r().createElement("div",{style:{marginTop:12}},r().createElement("label",{style:{fontWeight:500,display:"block",marginBottom:4}},"Input Mapping (JSON)",r().createElement(l.Tooltip,{title:"Map endpoint input fields. Use $input.field, $step[alias].response.field, $files, or literal values."},r().createElement("span",{style:{fontWeight:"normal",color:"#888",marginLeft:6,cursor:"help"}},"?"))),r().createElement(M,{value:e.inputMapping,onChange:function(e){return u(o,"inputMapping",e)},placeholder:'{ "text": "$step[ocr_result].response.text", "lang": "vi" }',rows:3})),r().createElement("div",{style:{marginTop:12}},r().createElement("label",{style:{fontWeight:500,display:"block",marginBottom:4}},"Condition (optional JSON)",r().createElement(l.Tooltip,{title:'Only run this step if condition matches. Format: { "field": "$step[x].response.y", "op": "eq", "value": "..." }'},r().createElement("span",{style:{fontWeight:"normal",color:"#888",marginLeft:6,cursor:"help"}},"?"))),r().createElement(M,{value:e.condition,onChange:function(e){return u(o,"condition",e)},placeholder:'{ "field": "$step[classify].response.type", "op": "eq", "value": "invoice" }',rows:2})))})),r().createElement(l.Button,{type:"dashed",icon:r().createElement(a.PlusOutlined,null),onClick:s,style:{marginTop:8,width:"100%"}},"Add Step"))},q=function(){var t,o,i=(0,e.useAPIClient)(),u=P((0,n.useState)([]),2),c=u[0],s=u[1],p=P((0,n.useState)([]),2),d=p[0],m=p[1],f=P((0,n.useState)(!1),2),y=f[0],h=f[1],b=P((0,n.useState)(!1),2),g=b[0],E=b[1],v=P(l.Form.useForm(),1)[0],S=P((0,n.useState)(null),2),w=S[0],O=S[1],I=P((0,n.useState)([]),2),F=I[0],q=I[1],R=(0,n.useCallback)(k(function(){var e,t,n,r,l;return A(this,function(a){switch(a.label){case 0:h(!0),a.label=1;case 1:return a.trys.push([1,,3,4]),[4,Promise.all([i.request({url:"docUnderstanding:listPipelines"}),i.request({url:"docUnderstanding:listEndpoints"})])];case 2:return r=(n=P.apply(void 0,[a.sent(),2]))[0],l=n[1],s((null==(e=r.data)?void 0:e.data)||[]),m((null==(t=l.data)?void 0:t.data)||[]),[3,4];case 3:return h(!1),[7];case 4:return[2]}})}),[i]);(0,n.useEffect)(function(){R()},[R]);var D=function(e){O(e.id),v.setFieldsValue({name:e.name,description:e.description,enabled:e.enabled,inputSchema:e.inputSchema,outputMapping:e.outputMapping}),q(C(e.steps||[]).sort(function(e,t){return e.stepOrder-t.stepOrder}).map(function(e){return{_key:"srv_".concat(e.id),id:e.id,stepOrder:e.stepOrder,name:e.name,endpointId:e.endpointId,inputMapping:e.inputMapping,outputAlias:e.outputAlias||"",condition:e.condition,onError:e.onError||"fail",retryCount:e.retryCount||0}})),E(!0)},U=(t=k(function(e){return A(this,function(t){switch(t.label){case 0:return[4,i.request({url:"docUnderstanding:deletePipeline",method:"POST",params:{filterByTk:e}})];case 1:return t.sent(),l.message.success("Deleted"),R(),[2]}})}),function(e){return t.apply(this,arguments)}),z=(o=k(function(){var e,t,n,r,a,o,u,c,s;return A(this,function(p){switch(p.label){case 0:return p.trys.push([0,6,,7]),[4,v.validateFields()];case 1:e=p.sent(),t=!0,n=!1,r=void 0;try{for(a=F[Symbol.iterator]();!(t=(o=a.next()).done);t=!0){if(!(u=o.value).name)return l.message.error("All steps must have a name"),[2];if(!u.endpointId)return l.message.error('Step "'.concat(u.name||u.stepOrder,'" must have an endpoint')),[2]}}catch(e){n=!0,r=e}finally{try{t||null==a.return||a.return()}finally{if(n)throw r}}if(new Set(c=F.map(function(e){return e.outputAlias}).filter(Boolean)).size!==c.length)return l.message.error("Step output aliases must be unique"),[2];if(s=x(T({},e),{steps:F.map(function(e){return x(T({},e.id?{id:e.id}:{}),{stepOrder:e.stepOrder,name:e.name,endpointId:e.endpointId,inputMapping:e.inputMapping,outputAlias:e.outputAlias||void 0,condition:e.condition,onError:e.onError,retryCount:"retry"===e.onError?e.retryCount:0})})}),!w)return[3,3];return[4,i.request({url:"docUnderstanding:updatePipeline",method:"POST",params:{filterByTk:w},data:s})];case 2:return p.sent(),[3,5];case 3:return[4,i.request({url:"docUnderstanding:createPipeline",method:"POST",data:s})];case 4:p.sent(),p.label=5;case 5:return l.message.success("Saved"),E(!1),R(),[3,7];case 6:return p.sent(),[3,7];case 7:return[2]}})}),function(){return o.apply(this,arguments)}),_=[{title:"Name",dataIndex:"name",width:200},{title:"Steps",dataIndex:"steps",width:300,render:function(e){if(!e||0===e.length)return r().createElement(l.Tag,null,"0 steps");var t=C(e).sort(function(e,t){return e.stepOrder-t.stepOrder});return r().createElement(l.Space,{size:2,wrap:!0},t.map(function(e,t){return r().createElement(r().Fragment,{key:e.id},t>0&&r().createElement("span",{style:{color:"#ccc"}},"→"),r().createElement(l.Tag,null,e.name||"Step ".concat(e.stepOrder)))}))}},{title:"Enabled",dataIndex:"enabled",width:80,render:function(e){return e?r().createElement(l.Tag,{color:"success"},"Yes"):r().createElement(l.Tag,null,"No")}},{title:"AI Tool",width:100,render:function(e,t){var n;return t.enabled?r().createElement(l.Tooltip,{title:"Registered as: doc_understanding.".concat(null==(n=t.name)?void 0:n.toLowerCase().replace(/[^a-z0-9_]/g,"_"))},r().createElement(l.Tag,{color:"blue",icon:r().createElement(a.ThunderboltOutlined,null)},"Active")):r().createElement(l.Tag,null,"Inactive")}},{title:"Action",width:120,render:function(e,t){return r().createElement(l.Space,null,r().createElement(l.Button,{type:"link",size:"small",icon:r().createElement(a.EditOutlined,null),onClick:function(){return D(t)}},"Edit"),r().createElement(l.Popconfirm,{title:"Delete this pipeline?",onConfirm:function(){return U(t.id)}},r().createElement(l.Button,{type:"link",size:"small",danger:!0,icon:r().createElement(a.DeleteOutlined,null)},"Delete")))}}];return r().createElement("div",null,r().createElement("div",{style:{marginBottom:16}},r().createElement(l.Button,{type:"primary",icon:r().createElement(a.PlusOutlined,null),onClick:function(){O(null),v.resetFields(),q([]),E(!0)}},"Add Pipeline")),r().createElement(l.Table,{rowKey:"id",columns:_,dataSource:c,loading:y,size:"small"}),r().createElement(l.Modal,{title:w?"Edit Pipeline":"New Pipeline",open:g,onOk:z,onCancel:function(){return E(!1)},width:800,destroyOnClose:!0},r().createElement(l.Form,{form:v,layout:"vertical",preserve:!1},r().createElement("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"0 16px"}},r().createElement(l.Form.Item,{name:"name",label:"Pipeline Name",rules:[{required:!0}]},r().createElement(l.Input,{placeholder:"full_document_processing"})),r().createElement(l.Form.Item,{name:"enabled",label:"Enabled",valuePropName:"checked",initialValue:!0},r().createElement(l.Switch,null))),r().createElement(l.Form.Item,{name:"description",label:"Description"},r().createElement(j,{rows:2,placeholder:"What this pipeline does"})),r().createElement(l.Card,{title:"Pipeline Steps",size:"small",style:{marginBottom:16},extra:r().createElement(l.Tag,{color:"blue"},F.length," step(s)")},r().createElement(N,{steps:F,endpoints:d,onChange:q})),r().createElement(l.Collapse,{size:"small",ghost:!0},r().createElement(B,{header:"Advanced: Input Schema & Output Mapping",key:"advanced"},r().createElement(l.Form.Item,{name:"inputSchema",label:"Input Schema (JSON Schema)",help:"Defines what input this pipeline accepts. Used by AI tool schema."},r().createElement(M,{placeholder:'{ "type": "object", "properties": { "document_url": { "type": "string" } }, "required": ["document_url"] }'})),r().createElement(l.Form.Item,{name:"outputMapping",label:"Output Mapping (JSON)",help:"Map final step results to pipeline output. If empty, all step results are returned."},r().createElement(M,{placeholder:'{ "text": "$step[ocr_result].response.text", "category": "$step[classify].response.category" }'})))))))};function R(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function D(e,t,n,r,l,a,o){try{var i=e[a](o),u=i.value}catch(e){n(e);return}i.done?t(u):Promise.resolve(u).then(r,l)}function U(e){return function(){var t=this,n=arguments;return new Promise(function(r,l){var a=e.apply(t,n);function o(e){D(a,r,l,o,i,"next",e)}function i(e){D(a,r,l,o,i,"throw",e)}o(void 0)})}}function z(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,l=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=l){var a=[],o=!0,i=!1;try{for(l=l.call(e);!(o=(n=l.next()).done)&&(a.push(n.value),!t||a.length!==t);o=!0);}catch(e){i=!0,r=e}finally{try{o||null==l.return||l.return()}finally{if(i)throw r}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return R(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if("Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return R(e,t)}}(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function _(e,t){var n,r,l,a,o={label:0,sent:function(){if(1&l[0])throw l[1];return l[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(a){return function(i){var u=[a,i];if(n)throw TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(l=2&u[0]?r.return:u[0]?r.throw||((l=r.return)&&l.call(r),0):r.next)&&!(l=l.call(r,u[1])).done)return l;switch(r=0,l&&(u=[2&u[0],l.value]),u[0]){case 0:case 1:l=u;break;case 4:return o.label++,{value:u[1],done:!1};case 5:o.label++,r=u[1],u=[0];continue;case 7:u=o.ops.pop(),o.trys.pop();continue;default:if(!(l=(l=o.trys).length>0&&l[l.length-1])&&(6===u[0]||2===u[0])){o=0;continue}if(3===u[0]&&(!l||u[1]>l[0]&&u[1]<l[3])){o.label=u[1];break}if(6===u[0]&&o.label<l[1]){o.label=l[1],l=u;break}if(l&&o.label<l[2]){o.label=l[2],o.ops.push(u);break}l[2]&&o.ops.pop(),o.trys.pop();continue}u=t.call(e,o)}catch(e){u=[6,e],r=0}finally{n=l=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}}var J={pending:{color:"default",label:"Pending"},running:{color:"processing",label:"Running"},polling:{color:"processing",label:"Polling"},completed:{color:"success",label:"Completed"},failed:{color:"error",label:"Failed"},timeout:{color:"error",label:"Timeout"}},V=function(){var t,o,i=(0,e.useAPIClient)(),u=z((0,n.useState)([]),2),c=u[0],s=u[1],p=z((0,n.useState)([]),2),d=p[0],m=p[1],f=z((0,n.useState)(!1),2),y=f[0],h=f[1],b=z((0,n.useState)(!1),2),g=b[0],E=b[1],v=z((0,n.useState)(null),2),S=v[0],w=v[1],O=z((0,n.useState)(void 0),2),I=O[0],k=O[1],T=z((0,n.useState)(void 0),2),x=T[0],P=T[1],C=(0,n.useCallback)(U(function(){var e,t;return _(this,function(n){switch(n.label){case 0:h(!0),n.label=1;case 1:return n.trys.push([1,,3,4]),t={},I&&(t.status=I),x&&(t.pipelineId=x),[4,i.request({url:"docUnderstanding:listJobs",params:{filter:Object.keys(t).length>0?t:void 0}})];case 2:return s((null==(e=n.sent().data)?void 0:e.data)||[]),[3,4];case 3:return h(!1),[7];case 4:return[2]}})}),[i,I,x]),F=(0,n.useCallback)(U(function(){var e;return _(this,function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,i.request({url:"docUnderstanding:listPipelines"})];case 1:return m((null==(e=t.sent().data)?void 0:e.data)||[]),[3,3];case 2:return t.sent(),[3,3];case 3:return[2]}})}),[i]);(0,n.useEffect)(function(){F()},[F]),(0,n.useEffect)(function(){C();var e=setInterval(C,1e4);return function(){return clearInterval(e)}},[C]);var A=new Map(d.map(function(e){return[e.id,e.name]})),j=(t=U(function(e){var t;return _(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,i.request({url:"docUnderstanding:getJobStatus",params:{filterByTk:e.id}})];case 1:return w((null==(t=n.sent().data)?void 0:t.data)||e),[3,3];case 2:return n.sent(),w(e),[3,3];case 3:return E(!0),[2]}})}),function(e){return t.apply(this,arguments)}),B=[{title:"ID",dataIndex:"id",width:60},{title:"Pipeline",dataIndex:"pipelineId",width:180,render:function(e){return A.get(e)||"#".concat(e)}},{title:"Status",dataIndex:"status",width:100,render:function(e){var t=J[e]||{color:"default",label:e};return r().createElement(l.Tag,{color:t.color},t.label)}},{title:"Current Step",dataIndex:"currentStep",width:90,render:function(e,t){return"completed"===t.status?r().createElement(l.Tag,{color:"success"},"Done"):"failed"===t.status?r().createElement(l.Tag,{color:"error"},"Step ",e):r().createElement(l.Badge,{status:"processing",text:"Step ".concat(e)})}},{title:"Started",dataIndex:"startedAt",width:160,render:function(e){return e?new Date(e).toLocaleString():"-"}},{title:"Completed",dataIndex:"completedAt",width:160,render:function(e){return e?new Date(e).toLocaleString():"-"}},{title:"Action",width:80,render:function(e,t){return r().createElement(l.Button,{size:"small",icon:r().createElement(a.EyeOutlined,null),onClick:function(){return j(t)}},"View")}}];return r().createElement("div",null,r().createElement(l.Space,{style:{marginBottom:16},wrap:!0},r().createElement(l.Select,{allowClear:!0,placeholder:"Filter by status",value:I,onChange:k,style:{width:160},options:Object.entries(J).map(function(e){var t=z(e,2);return{value:t[0],label:t[1].label}})}),r().createElement(l.Select,{allowClear:!0,placeholder:"Filter by pipeline",value:x,onChange:P,style:{width:200},options:d.map(function(e){return{value:e.id,label:e.name}})}),r().createElement(l.Button,{icon:r().createElement(a.ReloadOutlined,null),onClick:C},"Refresh")),r().createElement(l.Table,{rowKey:"id",columns:B,dataSource:c,loading:y,size:"small",pagination:{pageSize:20}}),r().createElement(l.Drawer,{title:S?"Job #".concat(S.id," — ").concat(A.get(S.pipelineId)||"Unknown"):"Job Details",width:640,open:g,onClose:function(){return E(!1)}},S&&r().createElement("div",null,r().createElement("div",{style:{marginBottom:16}},r().createElement(l.Space,null,r().createElement(l.Tag,{color:null==(o=J[S.status])?void 0:o.color},S.status),S.startedAt&&r().createElement("span",null,"Started: ",new Date(S.startedAt).toLocaleString()),S.completedAt&&r().createElement("span",null,"Completed: ",new Date(S.completedAt).toLocaleString()))),S.error&&r().createElement("div",{style:{background:"#fff2f0",border:"1px solid #ffccc7",borderRadius:6,padding:12,marginBottom:16}},r().createElement("strong",{style:{color:"#cf1322"}},"Error:"),r().createElement("pre",{style:{margin:"4px 0 0",whiteSpace:"pre-wrap",color:"#cf1322"}},S.error)),r().createElement("h4",null,"Input"),r().createElement("pre",{style:{background:"#f5f5f5",padding:12,borderRadius:6,fontSize:12,maxHeight:200,overflow:"auto"}},JSON.stringify(S.input,null,2)),r().createElement("h4",{style:{marginTop:16}},"Step Results"),S.stepResults&&Object.keys(S.stepResults).length>0?Object.entries(S.stepResults).map(function(e){var t=z(e,2),n=t[0],a=t[1];return r().createElement("div",{key:n,style:{marginBottom:8}},r().createElement(l.Tag,{color:"blue"},n),r().createElement("pre",{style:{background:"#f5f5f5",padding:8,borderRadius:4,fontSize:11,maxHeight:150,overflow:"auto",marginTop:4}},JSON.stringify(a,null,2)))}):r().createElement("div",{style:{color:"#999"}},"No step results yet"),r().createElement("h4",{style:{marginTop:16}},"Final Result"),r().createElement("pre",{style:{background:"#f0f5ff",padding:12,borderRadius:6,fontSize:12,maxHeight:300,overflow:"auto"}},S.finalResult?JSON.stringify(S.finalResult,null,2):"(not yet available)"),S.externalTaskIds&&Object.keys(S.externalTaskIds).length>0&&r().createElement(r().Fragment,null,r().createElement("h4",{style:{marginTop:16}},"External Task IDs"),r().createElement("pre",{style:{background:"#f5f5f5",padding:8,borderRadius:4,fontSize:11}},JSON.stringify(S.externalTaskIds,null,2))))))},H=function(){return r().createElement("div",{style:{backgroundColor:"var(--nb-box-bg)",minHeight:"100vh"}},r().createElement("div",{style:{padding:"16px 24px",backgroundColor:"#fff",borderBottom:"1px solid #f0f0f0"}},r().createElement("h2",{style:{margin:0,fontSize:20,fontWeight:500}},"Document Understanding - Pipeline Orchestrator")),r().createElement("div",{style:{padding:"0 24px 24px"}},r().createElement(l.Tabs,{defaultActiveKey:"config",items:[{key:"config",label:"Service Config",children:r().createElement(p,null)},{key:"endpoints",label:"Endpoints",children:r().createElement(w,null)},{key:"pipelines",label:"Pipelines",children:r().createElement(q,null)},{key:"jobs",label:"Jobs history",children:r().createElement(V,null)}]})))};function W(e,t,n,r,l,a,o){try{var i=e[a](o),u=i.value}catch(e){n(e);return}i.done?t(u):Promise.resolve(u).then(r,l)}function L(e,t,n){return(L=Y()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var l=new(Function.bind.apply(e,r));return n&&K(l,n.prototype),l}).apply(null,arguments)}function $(e){return($=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function K(e,t){return(K=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function G(e){var t="function"==typeof Map?new Map:void 0;return(G=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return L(e,arguments,$(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),K(n,e)})(e)}function Y(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(Y=function(){return!!e})()}var X=function(e){var n;if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function r(){var e,t;if(!(this instanceof r))throw TypeError("Cannot call a class as a function");return e=r,t=arguments,e=$(e),function(e,t){var n;if(t&&("object"==((n=t)&&"undefined"!=typeof Symbol&&n.constructor===Symbol?"symbol":typeof n)||"function"==typeof t))return t;if(void 0===e)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(this,Y()?Reflect.construct(e,t||[],$(this).constructor):e.apply(this,t))}return r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),e&&K(r,e),n=[{key:"load",value:function(){var e,n=this;return(e=function(){var e;return function(e,t){var n,r,l,a,o={label:0,sent:function(){if(1&l[0])throw l[1];return l[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(a){return function(i){var u=[a,i];if(n)throw TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(l=2&u[0]?r.return:u[0]?r.throw||((l=r.return)&&l.call(r),0):r.next)&&!(l=l.call(r,u[1])).done)return l;switch(r=0,l&&(u=[2&u[0],l.value]),u[0]){case 0:case 1:l=u;break;case 4:return o.label++,{value:u[1],done:!1};case 5:o.label++,r=u[1],u=[0];continue;case 7:u=o.ops.pop(),o.trys.pop();continue;default:if(!(l=(l=o.trys).length>0&&l[l.length-1])&&(6===u[0]||2===u[0])){o=0;continue}if(3===u[0]&&(!l||u[1]>l[0]&&u[1]<l[3])){o.label=u[1];break}if(6===u[0]&&o.label<l[1]){o.label=l[1],l=u;break}if(l&&o.label<l[2]){o.label=l[2],o.ops.push(u);break}l[2]&&o.ops.pop(),o.trys.pop();continue}u=t.call(e,o)}catch(e){u=[6,e],r=0}finally{n=l=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}}(this,function(r){return null==(e=n.flowEngine)||e.registerModels(t),n.app.pluginSettingsManager.add("document-understanding",{title:n.t("Document Understanding"),icon:"FileSearchOutlined",Component:H,aclSnippet:"pm.document-understanding"}),[2]})},function(){var t=this,n=arguments;return new Promise(function(r,l){var a=e.apply(t,n);function o(e){W(a,r,l,o,i,"next",e)}function i(e){W(a,r,l,o,i,"throw",e)}o(void 0)})})()}}],function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}(r.prototype,n),r}(G(e.Plugin))}(),i}()});
|
|
10
|
+
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("@nocobase/client"),require("@ant-design/icons"),require("antd")):"function"==typeof define&&define.amd?define("plugin-document-understanding",["react","@nocobase/client","@ant-design/icons","antd"],t):"object"==typeof exports?exports["plugin-document-understanding"]=t(require("react"),require("@nocobase/client"),require("@ant-design/icons"),require("antd")):e["plugin-document-understanding"]=t(e.react,e["@nocobase/client"],e["@ant-design/icons"],e.antd)}(self,function(e,t,n,r){return function(){"use strict";var l={482:function(e){e.exports=n},772:function(e){e.exports=t},721:function(e){e.exports=r},156:function(t){t.exports=e}},a={};function o(e){var t=a[e];if(void 0!==t)return t.exports;var n=a[e]={exports:{}};return l[e](n,n.exports,o),n.exports}o.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return o.d(t,{a:t}),t},o.d=function(e,t){for(var n in t)o.o(t,n)&&!o.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},o.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};return!function(){o.r(i),o.d(i,{default:function(){return el}});var e=o(772),t={},n=o(156),r=o.n(n),l=o(721),a=o(482);function u(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function c(e,t,n,r,l,a,o){try{var i=e[a](o),u=i.value}catch(e){n(e);return}i.done?t(u):Promise.resolve(u).then(r,l)}function s(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,l=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=l){var a=[],o=!0,i=!1;try{for(l=l.call(e);!(o=(n=l.next()).done)&&(a.push(n.value),!t||a.length!==t);o=!0);}catch(e){i=!0,r=e}finally{try{o||null==l.return||l.return()}finally{if(i)throw r}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return u(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if("Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return u(e,t)}}(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}var d=function(){var t,o,i=s(l.Form.useForm(),1)[0],u=(0,e.useAPIClient)(),d=s((0,n.useState)(!0),2),p=d[0],m=d[1],f=s((0,n.useState)(!1),2),y=f[0],h=f[1];(0,n.useEffect)(function(){u.request({url:"docUnderstanding:getConfig"}).then(function(e){var t=e.data;i.setFieldsValue((null==t?void 0:t.data)||{}),m(!1)}).catch(function(){return m(!1)})},[]);var b=(t=function(e){return function(e,t){var n,r,l,a,o={label:0,sent:function(){if(1&l[0])throw l[1];return l[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(a){return function(i){var u=[a,i];if(n)throw TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(l=2&u[0]?r.return:u[0]?r.throw||((l=r.return)&&l.call(r),0):r.next)&&!(l=l.call(r,u[1])).done)return l;switch(r=0,l&&(u=[2&u[0],l.value]),u[0]){case 0:case 1:l=u;break;case 4:return o.label++,{value:u[1],done:!1};case 5:o.label++,r=u[1],u=[0];continue;case 7:u=o.ops.pop(),o.trys.pop();continue;default:if(!(l=(l=o.trys).length>0&&l[l.length-1])&&(6===u[0]||2===u[0])){o=0;continue}if(3===u[0]&&(!l||u[1]>l[0]&&u[1]<l[3])){o.label=u[1];break}if(6===u[0]&&o.label<l[1]){o.label=l[1],l=u;break}if(l&&o.label<l[2]){o.label=l[2],o.ops.push(u);break}l[2]&&o.ops.pop(),o.trys.pop();continue}u=t.call(e,o)}catch(e){u=[6,e],r=0}finally{n=l=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}}(this,function(t){switch(t.label){case 0:h(!0),t.label=1;case 1:return t.trys.push([1,3,4,5]),[4,u.request({url:"docUnderstanding:updateConfig",method:"POST",data:e})];case 2:return t.sent(),l.message.success("Configuration saved successfully"),[3,5];case 3:return t.sent(),l.message.error("Failed to save config"),[3,5];case 4:return h(!1),[7];case 5:return[2]}})},o=function(){var e=this,n=arguments;return new Promise(function(r,l){var a=t.apply(e,n);function o(e){c(a,r,l,o,i,"next",e)}function i(e){c(a,r,l,o,i,"throw",e)}o(void 0)})},function(e){return o.apply(this,arguments)});return p?r().createElement(l.Spin,{style:{marginTop:40}}):r().createElement(l.Form,{form:i,layout:"vertical",onFinish:b,style:{maxWidth:600}},r().createElement(l.Alert,{message:"Service Connection",description:"Configure the connection to your external document processing service. All endpoints will use this base URL and authentication.",type:"info",showIcon:!0,style:{marginBottom:24}}),r().createElement(l.Form.Item,{name:"baseUrl",label:"Base URL",rules:[{required:!0,message:"Base URL is required"}],help:"The root URL of your document processing API"},r().createElement(l.Input,{prefix:r().createElement(a.LinkOutlined,null),placeholder:"http://my-ocr-service:8000"})),r().createElement(l.Form.Item,{name:"authType",label:"Authentication Type",initialValue:"none"},r().createElement(l.Select,null,r().createElement(l.Select.Option,{value:"none"},"None"),r().createElement(l.Select.Option,{value:"api_key"},"API Key"),r().createElement(l.Select.Option,{value:"bearer"},"Bearer Token"),r().createElement(l.Select.Option,{value:"custom_header"},"Custom Header"))),r().createElement(l.Form.Item,{noStyle:!0,dependencies:["authType"]},function(){var e=i.getFieldValue("authType");return"none"===e?null:r().createElement(r().Fragment,null,"custom_header"===e&&r().createElement(l.Form.Item,{name:"authHeaderName",label:"Custom Header Name",rules:[{required:!0}]},r().createElement(l.Input,{placeholder:"X-Api-Key"})),r().createElement(l.Form.Item,{name:"authKey",label:"bearer"===e?"Bearer Token":"API Key",rules:[{required:!0}]},r().createElement(l.Input.Password,{placeholder:"Enter key or token"})))}),r().createElement("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"0 16px"}},r().createElement(l.Form.Item,{name:"defaultTimeout",label:"Request Timeout (ms)",initialValue:3e4},r().createElement(l.InputNumber,{style:{width:"100%"},min:1e3,step:1e3})),r().createElement(l.Form.Item,{name:"defaultRetries",label:"Default Retries",initialValue:2},r().createElement(l.InputNumber,{style:{width:"100%"},min:0,max:10})),r().createElement(l.Form.Item,{name:"pollInterval",label:"Poll Interval (ms)",initialValue:5e3},r().createElement(l.InputNumber,{style:{width:"100%"},min:1e3,step:1e3})),r().createElement(l.Form.Item,{name:"pollTimeout",label:"Poll Timeout (ms)",initialValue:3e5},r().createElement(l.InputNumber,{style:{width:"100%"},min:5e3,step:5e3}))),r().createElement(l.Form.Item,{name:"webhookSecret",label:"Webhook Secret",help:"Used to verify HMAC-SHA256 signatures on incoming webhook callbacks"},r().createElement(l.Input.Password,{placeholder:"Optional: secret for webhook signature verification"})),r().createElement(l.Form.Item,null,r().createElement(l.Button,{type:"primary",htmlType:"submit",icon:r().createElement(a.SaveOutlined,null),loading:y},"Save Configuration")))};function p(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function m(e,t,n,r,l,a,o){try{var i=e[a](o),u=i.value}catch(e){n(e);return}i.done?t(u):Promise.resolve(u).then(r,l)}function f(e){return function(){var t=this,n=arguments;return new Promise(function(r,l){var a=e.apply(t,n);function o(e){m(a,r,l,o,i,"next",e)}function i(e){m(a,r,l,o,i,"throw",e)}o(void 0)})}}function y(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,l=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=l){var a=[],o=!0,i=!1;try{for(l=l.call(e);!(o=(n=l.next()).done)&&(a.push(n.value),!t||a.length!==t);o=!0);}catch(e){i=!0,r=e}finally{try{o||null==l.return||l.return()}finally{if(i)throw r}}return a}}(e,t)||b(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function h(e){return function(e){if(Array.isArray(e))return p(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||b(e)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function b(e,t){if(e){if("string"==typeof e)return p(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if("Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return p(e,t)}}function g(e,t){var n,r,l,a,o={label:0,sent:function(){if(1&l[0])throw l[1];return l[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(a){return function(i){var u=[a,i];if(n)throw TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(l=2&u[0]?r.return:u[0]?r.throw||((l=r.return)&&l.call(r),0):r.next)&&!(l=l.call(r,u[1])).done)return l;switch(r=0,l&&(u=[2&u[0],l.value]),u[0]){case 0:case 1:l=u;break;case 4:return o.label++,{value:u[1],done:!1};case 5:o.label++,r=u[1],u=[0];continue;case 7:u=o.ops.pop(),o.trys.pop();continue;default:if(!(l=(l=o.trys).length>0&&l[l.length-1])&&(6===u[0]||2===u[0])){o=0;continue}if(3===u[0]&&(!l||u[1]>l[0]&&u[1]<l[3])){o.label=u[1];break}if(6===u[0]&&o.label<l[1]){o.label=l[1],l=u;break}if(l&&o.label<l[2]){o.label=l[2],o.ops.push(u);break}l[2]&&o.ops.pop(),o.trys.pop();continue}u=t.call(e,o)}catch(e){u=[6,e],r=0}finally{n=l=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}}var v=l.Input.TextArea,E=function(e){var t=e.value,o=void 0===t?{}:t,i=e.onChange,u=y((0,n.useState)([]),2),c=u[0],s=u[1],d=(0,n.useRef)(!1);(0,n.useEffect)(function(){if(d.current){d.current=!1;return}s(Object.entries(o||{}).map(function(e,t){var n=y(e,2),r=n[0],l=n[1];return{id:"".concat(r,"_").concat(t),key:r,value:String(null!=l?l:"")}}))},[o]);var p=function(e){s(e);var t=e.reduce(function(e,t){var n=t.key.trim();return n&&(e[n]=t.value),e},{});d.current=!0,null==i||i(t)},m=function(e,t,n){var r,l,a=h(c);a[e]=(r=function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){var r;r=n[t],t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r})}return e}({},a[e]),l=l={key:t,value:n},Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(l)):(function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);n.push.apply(n,r)}return n})(Object(l)).forEach(function(e){Object.defineProperty(r,e,Object.getOwnPropertyDescriptor(l,e))}),r),p(a)},f=function(e){p(c.filter(function(t,n){return n!==e}))};return r().createElement("div",null,c.map(function(e,t){return r().createElement(l.Space,{key:e.id,style:{display:"flex",marginBottom:4}},r().createElement(l.Input,{placeholder:"Header name",value:e.key,onChange:function(n){return m(t,n.target.value,e.value)},style:{width:180}}),r().createElement(l.Input,{placeholder:"Value",value:e.value,onChange:function(n){return m(t,e.key,n.target.value)},style:{width:220}}),r().createElement(l.Button,{size:"small",danger:!0,icon:r().createElement(a.DeleteOutlined,null),onClick:function(){return f(t)}}))}),r().createElement(l.Button,{size:"small",type:"dashed",icon:r().createElement(a.PlusOutlined,null),onClick:function(){return s(h(c).concat([{id:"new_".concat(Date.now(),"_").concat(Math.random()),key:"",value:""}]))}},"Add Header"))},S=function(e){var t=e.value,l=e.onChange,a=e.placeholder,o=y((0,n.useState)(""),2),i=o[0],u=o[1],c=y((0,n.useState)(""),2),s=c[0],d=c[1];return(0,n.useEffect)(function(){if(!t)return void u("");try{u("string"==typeof t?JSON.stringify(JSON.parse(t),null,2):JSON.stringify(t,null,2))}catch(e){u("string"==typeof t?t:"")}},[t]),r().createElement("div",null,r().createElement(v,{rows:6,value:i,onChange:function(e){return u(e.target.value)},onBlur:function(){if(!i.trim()){d(""),null==l||l(null);return}try{var e=JSON.parse(i);d(""),null==l||l(e)}catch(e){d("Invalid JSON")}},placeholder:a||"{}",style:{fontFamily:"monospace",fontSize:12}}),s&&r().createElement("div",{style:{color:"#ff4d4f",fontSize:12}},s))},w=function(){var t,o,i=(0,e.useAPIClient)(),u=y((0,n.useState)([]),2),c=u[0],s=u[1],d=y((0,n.useState)(!1),2),p=d[0],m=d[1],h=y((0,n.useState)(!1),2),b=h[0],w=h[1],O=y(l.Form.useForm(),1)[0],I=y((0,n.useState)(null),2),k=I[0],T=I[1],x=(0,n.useCallback)(f(function(){var e;return g(this,function(t){switch(t.label){case 0:m(!0),t.label=1;case 1:return t.trys.push([1,,3,4]),[4,i.request({url:"docUnderstanding:listEndpoints"})];case 2:return s((null==(e=t.sent().data)?void 0:e.data)||[]),[3,4];case 3:return m(!1),[7];case 4:return[2]}})}),[i]);(0,n.useEffect)(function(){x()},[x]);var C=function(e){T(e.id),O.setFieldsValue(e),w(!0)},P=(t=f(function(e){return g(this,function(t){switch(t.label){case 0:return[4,i.request({url:"docUnderstanding:deleteEndpoint",method:"POST",params:{filterByTk:e}})];case 1:return t.sent(),l.message.success("Deleted"),x(),[2]}})}),function(e){return t.apply(this,arguments)}),F=(o=f(function(){var e;return g(this,function(t){switch(t.label){case 0:return t.trys.push([0,6,,7]),[4,O.validateFields()];case 1:if((e=t.sent()).customHeaders=A(e.customHeaders),!k)return[3,3];return[4,i.request({url:"docUnderstanding:updateEndpoint",method:"POST",params:{filterByTk:k},data:e})];case 2:return t.sent(),[3,5];case 3:return[4,i.request({url:"docUnderstanding:createEndpoint",method:"POST",data:e})];case 4:t.sent(),t.label=5;case 5:return l.message.success("Saved"),w(!1),x(),[3,7];case 6:return t.sent(),[3,7];case 7:return[2]}})}),function(){return o.apply(this,arguments)}),A=function(e){return Object.entries(e||{}).reduce(function(e,t){var n=y(t,2),r=n[0],l=n[1],a=r.trim();return a&&(e[a]=l),e},{})},j=[{title:"Name",dataIndex:"name",width:150},{title:"Subpath",dataIndex:"subpath",width:200},{title:"Method",dataIndex:"method",width:80,render:function(e){return r().createElement(l.Tag,null,e)}},{title:"Execution",dataIndex:"executionMode",width:100,render:function(e){return r().createElement(l.Tag,{color:{sync:"green",polling:"blue",webhook:"purple"}[e]},e)}},{title:"File",dataIndex:"fileInputMode",width:90,render:function(e){return"none"===e?"-":e}},{title:"Enabled",dataIndex:"enabled",width:70,render:function(e){return e?r().createElement(l.Tag,{color:"success"},"Yes"):r().createElement(l.Tag,null,"No")}},{title:"Action",width:120,render:function(e,t){return r().createElement(l.Space,null,r().createElement(l.Button,{type:"link",size:"small",icon:r().createElement(a.EditOutlined,null),onClick:function(){return C(t)}},"Edit"),r().createElement(l.Popconfirm,{title:"Delete this endpoint?",onConfirm:function(){return P(t.id)}},r().createElement(l.Button,{type:"link",size:"small",danger:!0,icon:r().createElement(a.DeleteOutlined,null)},"Delete")))}}];return r().createElement("div",null,r().createElement("div",{style:{marginBottom:16}},r().createElement(l.Button,{type:"primary",icon:r().createElement(a.PlusOutlined,null),onClick:function(){T(null),O.resetFields(),w(!0)}},"Add Endpoint")),r().createElement(l.Table,{rowKey:"id",columns:j,dataSource:c,loading:p,size:"small"}),r().createElement(l.Modal,{title:k?"Edit Endpoint":"Add Endpoint",open:b,onOk:F,onCancel:function(){return w(!1)},width:680,destroyOnClose:!0},r().createElement(l.Form,{form:O,layout:"vertical",preserve:!1},r().createElement(l.Tabs,{size:"small",items:[{key:"basic",label:"Basic",children:r().createElement(r().Fragment,null,r().createElement(l.Form.Item,{name:"name",label:"Unique Name",rules:[{required:!0}]},r().createElement(l.Input,{placeholder:"ocr, classify, extract..."})),r().createElement(l.Form.Item,{name:"subpath",label:"Subpath",rules:[{required:!0}]},r().createElement(l.Input,{placeholder:"/api/v1/ocr"})),r().createElement(l.Form.Item,{name:"description",label:"Description"},r().createElement(v,{rows:2,placeholder:"What this endpoint does"})),r().createElement(l.Space,{size:"large"},r().createElement(l.Form.Item,{name:"method",label:"HTTP Method",initialValue:"POST"},r().createElement(l.Select,{style:{width:120}},r().createElement(l.Select.Option,{value:"GET"},"GET"),r().createElement(l.Select.Option,{value:"POST"},"POST"),r().createElement(l.Select.Option,{value:"PUT"},"PUT"))),r().createElement(l.Form.Item,{name:"enabled",label:"Enabled",valuePropName:"checked",initialValue:!0},r().createElement(l.Switch,null))))},{key:"file",label:"File Input",children:r().createElement(r().Fragment,null,r().createElement(l.Form.Item,{name:"fileInputMode",label:"File Input Mode",initialValue:"none"},r().createElement(l.Select,{style:{width:200}},r().createElement(l.Select.Option,{value:"none"},"None"),r().createElement(l.Select.Option,{value:"multipart"},"Multipart Upload"),r().createElement(l.Select.Option,{value:"base64"},"Base64 in JSON"))),r().createElement(l.Form.Item,{noStyle:!0,dependencies:["fileInputMode"]},function(){return"none"!==O.getFieldValue("fileInputMode")?r().createElement(r().Fragment,null,r().createElement(l.Form.Item,{name:"fileFieldName",label:"File Field Name",initialValue:"file"},r().createElement(l.Input,{placeholder:"file",style:{width:200}})),r().createElement(l.Form.Item,{name:"maxFiles",label:"Max Files",initialValue:1},r().createElement(l.InputNumber,{min:1,max:20,style:{width:120}}))):null}))},{key:"async",label:"Async Config",children:r().createElement(r().Fragment,null,r().createElement(l.Form.Item,{name:"executionMode",label:"Execution Mode",initialValue:"sync"},r().createElement(l.Select,{style:{width:200}},r().createElement(l.Select.Option,{value:"sync"},"Synchronous"),r().createElement(l.Select.Option,{value:"polling"},"Polling"),r().createElement(l.Select.Option,{value:"webhook"},"Webhook"))),r().createElement(l.Form.Item,{noStyle:!0,dependencies:["executionMode"]},function(){var e=O.getFieldValue("executionMode");return"sync"===e?null:r().createElement(r().Fragment,null,r().createElement(l.Form.Item,{name:"pollTaskIdField",label:"Task ID Field",help:"Field in response containing the async task ID",initialValue:"task_id"},r().createElement(l.Input,{placeholder:"task_id"})),"polling"===e&&r().createElement(r().Fragment,null,r().createElement(l.Form.Item,{name:"pollResultSubpath",label:"Poll Result Subpath",help:"URL to poll for result. Use {taskId} as placeholder.",rules:[{required:!0,message:"Required for polling mode"}]},r().createElement(l.Input,{placeholder:"/api/v1/tasks/{taskId}/result"})),r().createElement(l.Form.Item,{name:"pollResultField",label:"Result Field",help:"Field in poll response containing the actual result"},r().createElement(l.Input,{placeholder:"result"})),r().createElement(l.Form.Item,{name:"pollStatusField",label:"Status Field (optional)",help:"Field to check completion status. If empty, any non-null result = complete."},r().createElement(l.Input,{placeholder:"status"})),r().createElement(l.Form.Item,{name:"pollCompletedValue",label:"Completed Value",help:"Value of status field that means 'done'",initialValue:"completed"},r().createElement(l.Input,{placeholder:"completed"})),r().createElement(l.Space,{size:"large"},r().createElement(l.Form.Item,{name:"pollInterval",label:"Poll Interval (ms)",help:"Override default"},r().createElement(l.InputNumber,{min:1e3,step:1e3,placeholder:"5000",style:{width:150}})),r().createElement(l.Form.Item,{name:"pollTimeout",label:"Poll Timeout (ms)",help:"Override default"},r().createElement(l.InputNumber,{min:5e3,step:5e3,placeholder:"300000",style:{width:150}})))))}))},{key:"schema",label:"Schema",children:r().createElement(r().Fragment,null,r().createElement(l.Form.Item,{name:"requestBodySchema",label:"Request Body Schema (JSON Schema)"},r().createElement(S,{placeholder:'{ "type": "object", "properties": { ... } }'})),r().createElement(l.Form.Item,{name:"responseSchema",label:"Response Schema (JSON Schema)"},r().createElement(S,{placeholder:'{ "type": "object", "properties": { ... } }'})))},{key:"headers",label:"Custom Headers",children:r().createElement(l.Form.Item,{name:"customHeaders",label:"Additional Headers"},r().createElement(E,null))}]}))))};function O(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function I(e,t,n,r,l,a,o){try{var i=e[a](o),u=i.value}catch(e){n(e);return}i.done?t(u):Promise.resolve(u).then(r,l)}function k(e){return function(){var t=this,n=arguments;return new Promise(function(r,l){var a=e.apply(t,n);function o(e){I(a,r,l,o,i,"next",e)}function i(e){I(a,r,l,o,i,"throw",e)}o(void 0)})}}function T(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function x(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),r.forEach(function(t){T(e,t,n[t])})}return e}function C(e,t){return t=null!=t?t:{},Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):(function(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);n.push.apply(n,r)}return n})(Object(t)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}function P(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,l=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=l){var a=[],o=!0,i=!1;try{for(l=l.call(e);!(o=(n=l.next()).done)&&(a.push(n.value),!t||a.length!==t);o=!0);}catch(e){i=!0,r=e}finally{try{o||null==l.return||l.return()}finally{if(i)throw r}}return a}}(e,t)||j(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function F(e){return function(e){if(Array.isArray(e))return O(e)}(e)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(e)||j(e)||function(){throw TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function A(e){return e&&"undefined"!=typeof Symbol&&e.constructor===Symbol?"symbol":typeof e}function j(e,t){if(e){if("string"==typeof e)return O(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if("Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return O(e,t)}}function B(e,t){var n,r,l,a,o={label:0,sent:function(){if(1&l[0])throw l[1];return l[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(a){return function(i){var u=[a,i];if(n)throw TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(l=2&u[0]?r.return:u[0]?r.throw||((l=r.return)&&l.call(r),0):r.next)&&!(l=l.call(r,u[1])).done)return l;switch(r=0,l&&(u=[2&u[0],l.value]),u[0]){case 0:case 1:l=u;break;case 4:return o.label++,{value:u[1],done:!1};case 5:o.label++,r=u[1],u=[0];continue;case 7:u=o.ops.pop(),o.trys.pop();continue;default:if(!(l=(l=o.trys).length>0&&l[l.length-1])&&(6===u[0]||2===u[0])){o=0;continue}if(3===u[0]&&(!l||u[1]>l[0]&&u[1]<l[3])){o.label=u[1];break}if(6===u[0]&&o.label<l[1]){o.label=l[1],l=u;break}if(l&&o.label<l[2]){o.label=l[2],o.ops.push(u);break}l[2]&&o.ops.pop(),o.trys.pop();continue}u=t.call(e,o)}catch(e){u=[6,e],r=0}finally{n=l=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}}var R=l.Input.TextArea,N=l.Collapse.Panel,M={pending:{color:"default",label:"Pending"},running:{color:"processing",label:"Running"},polling:{color:"processing",label:"Polling"},completed:{color:"success",label:"Completed"},failed:{color:"error",label:"Failed"},timeout:{color:"error",label:"Timeout"}},q=function(e){var t,n,r;return null!=(r=null!=(n=null==e||null==(t=e.data)?void 0:t.data)?n:null==e?void 0:e.data)?r:e},z=function(e){return JSON.stringify(null!=e?e:{},null,2)},D=function(e){return e&&(void 0===e?"undefined":A(e))==="object"?Object.prototype.hasOwnProperty.call(e,"default")?e.default:"object"===e.type||e.properties?Object.entries(e.properties||{}).reduce(function(e,t){var n=P(t,2),r=n[0],l=D(n[1]);return void 0!==l&&(e[r]=l),e},{}):"array"===e.type?[]:void 0:{}},U=function(e,t){return e&&t&&(void 0===e?"undefined":A(e))==="object"&&(void 0===t?"undefined":A(t))==="object"&&!Array.isArray(e)&&!Array.isArray(t)?Object.entries(e).reduce(function(e,t){var n=P(t,2),r=n[0],l=n[1];return C(x({},e),T({},r,U(l,e[r])))},x({},t)):void 0===t?e:t},_=function(e){var t=e.value,l=e.onChange,a=e.placeholder,o=e.rows,i=P((0,n.useState)(""),2),u=i[0],c=i[1],s=P((0,n.useState)(""),2),d=s[0],p=s[1];return(0,n.useEffect)(function(){if(!t)return void c("");try{c("string"==typeof t?JSON.stringify(JSON.parse(t),null,2):JSON.stringify(t,null,2))}catch(e){c("string"==typeof t?t:"")}},[t]),r().createElement("div",null,r().createElement(R,{rows:void 0===o?5:o,value:u,onChange:function(e){return c(e.target.value)},onBlur:function(){if(!u.trim()){p(""),null==l||l(null);return}try{var e=JSON.parse(u);p(""),null==l||l(e)}catch(e){p("Invalid JSON")}},placeholder:a||"{}",style:{fontFamily:"monospace",fontSize:12}}),d&&r().createElement("div",{style:{color:"#ff4d4f",fontSize:12}},d))},J=function(e){var t=e.steps,n=e.endpoints,o=e.onChange,i=function(e,n){var r,l=F(t),a=e+n;a<0||a>=l.length||(r=[l[a],l[e]],l[e]=r[0],l[a]=r[1],l.forEach(function(e,t){return e.stepOrder=t+1}),o(l))},u=function(e,n,r){var l=F(t);l[e][n]=r,o(l)},c=function(e){var n=t.filter(function(t,n){return n!==e});n.forEach(function(e,t){return e.stepOrder=t+1}),o(n)},s=function(){var e;o(F(t).concat([(e=t.length+1,{_key:"new_".concat(Date.now(),"_").concat(Math.random()),stepOrder:e,name:"",endpointId:null,inputMapping:null,outputAlias:"",condition:null,onError:"fail",retryCount:0})]))};return 0===t.length?r().createElement("div",{style:{textAlign:"center",padding:"20px 0"}},r().createElement(l.Empty,{description:"No steps yet",imageStyle:{height:40}}),r().createElement(l.Button,{type:"dashed",icon:r().createElement(a.PlusOutlined,null),onClick:s,style:{marginTop:8}},"Add First Step")):r().createElement("div",null,r().createElement(l.Collapse,{size:"small",defaultActiveKey:t.map(function(e){return e._key})},t.map(function(e,o){var s=n.find(function(t){return t.id===e.endpointId}),d=r().createElement(l.Space,{size:4,onClick:function(e){return e.stopPropagation()}},r().createElement(l.Button,{size:"small",disabled:0===o,icon:r().createElement(a.ArrowUpOutlined,null),onClick:function(){return i(o,-1)}}),r().createElement(l.Button,{size:"small",disabled:o===t.length-1,icon:r().createElement(a.ArrowDownOutlined,null),onClick:function(){return i(o,1)}}),r().createElement(l.Popconfirm,{title:"Remove step?",onConfirm:function(){return c(o)}},r().createElement(l.Button,{size:"small",danger:!0,icon:r().createElement(a.DeleteOutlined,null)}))),p=r().createElement(l.Space,null,r().createElement(l.Badge,{count:e.stepOrder,style:{backgroundColor:"#1677ff"}}),r().createElement("span",null,e.name||"(unnamed)"),s&&r().createElement(l.Tag,null,s.name),"skip"===e.onError&&r().createElement(l.Tooltip,{title:"Step can be skipped on error"},r().createElement(l.Tag,{color:"orange"},"skip on error")),e.condition&&r().createElement(l.Tooltip,{title:"Has condition"},r().createElement(l.Tag,{color:"purple"},"conditional")));return r().createElement(N,{key:e._key,header:p,extra:d},r().createElement("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"0 16px"}},r().createElement("div",null,r().createElement("label",{style:{fontWeight:500,display:"block",marginBottom:4}},"Step Name *"),r().createElement(l.Input,{value:e.name,onChange:function(e){return u(o,"name",e.target.value)},placeholder:"OCR, Classify, Extract..."})),r().createElement("div",null,r().createElement("label",{style:{fontWeight:500,display:"block",marginBottom:4}},"Endpoint *"),r().createElement(l.Select,{value:e.endpointId,onChange:function(e){return u(o,"endpointId",e)},placeholder:"Select endpoint",style:{width:"100%"},options:n.map(function(e){return{value:e.id,label:"".concat(e.name," (").concat(e.method," ").concat(e.subpath,")")}})})),r().createElement("div",null,r().createElement("label",{style:{fontWeight:500,display:"block",marginBottom:4,marginTop:12}},"Output Alias"),r().createElement(l.Input,{value:e.outputAlias,onChange:function(e){return u(o,"outputAlias",e.target.value)},placeholder:"ocr_result"}),r().createElement("div",{style:{color:"#888",fontSize:11}},"Other steps reference this as: $step[",e.outputAlias||e.stepOrder,"].response.field")),r().createElement("div",null,r().createElement("label",{style:{fontWeight:500,display:"block",marginBottom:4,marginTop:12}},"On Error"),r().createElement(l.Space,null,r().createElement(l.Select,{value:e.onError,onChange:function(e){return u(o,"onError",e)},style:{width:120}},r().createElement(l.Select.Option,{value:"fail"},"Fail"),r().createElement(l.Select.Option,{value:"skip"},"Skip"),r().createElement(l.Select.Option,{value:"retry"},"Retry")),"retry"===e.onError&&r().createElement(l.InputNumber,{value:e.retryCount,onChange:function(e){return u(o,"retryCount",e||0)},min:1,max:10,addonBefore:"x",style:{width:100}})))),r().createElement("div",{style:{marginTop:12}},r().createElement("label",{style:{fontWeight:500,display:"block",marginBottom:4}},"Input Mapping (JSON)",r().createElement(l.Tooltip,{title:"Map endpoint input fields. Use $input.field, $step[alias].response.field, $files, or literal values."},r().createElement("span",{style:{fontWeight:"normal",color:"#888",marginLeft:6,cursor:"help"}},"?"))),r().createElement(_,{value:e.inputMapping,onChange:function(e){return u(o,"inputMapping",e)},placeholder:'{ "text": "$step[ocr_result].response.text", "lang": "vi" }',rows:3})),r().createElement("div",{style:{marginTop:12}},r().createElement("label",{style:{fontWeight:500,display:"block",marginBottom:4}},"Condition (optional JSON)",r().createElement(l.Tooltip,{title:'Only run this step if condition matches. Format: { "field": "$step[x].response.y", "op": "eq", "value": "..." }'},r().createElement("span",{style:{fontWeight:"normal",color:"#888",marginLeft:6,cursor:"help"}},"?"))),r().createElement(_,{value:e.condition,onChange:function(e){return u(o,"condition",e)},placeholder:'{ "field": "$step[classify].response.type", "op": "eq", "value": "invoice" }',rows:2})))})),r().createElement(l.Button,{type:"dashed",icon:r().createElement(a.PlusOutlined,null),onClick:s,style:{marginTop:8,width:"100%"}},"Add Step"))},V=function(){var t,o,i,u,c,s,d=(0,e.useAPIClient)(),p=P((0,n.useState)([]),2),m=p[0],f=p[1],y=P((0,n.useState)([]),2),h=y[0],b=y[1],g=P((0,n.useState)(!1),2),v=g[0],E=g[1],S=P((0,n.useState)(!1),2),w=S[0],O=S[1],I=P(l.Form.useForm(),1)[0],T=P((0,n.useState)(null),2),A=T[0],j=T[1],V=P((0,n.useState)([]),2),H=V[0],W=V[1],L=P((0,n.useState)(!1),2),$=L[0],K=L[1],G=P((0,n.useState)(null),2),Y=G[0],X=G[1],Q=P((0,n.useState)("{}"),2),Z=Q[0],ee=Q[1],et=P((0,n.useState)(""),2),en=et[0],er=et[1],el=P((0,n.useState)(null),2),ea=el[0],eo=el[1],ei=P((0,n.useState)(!1),2),eu=ei[0],ec=ei[1],es=(0,n.useRef)(null),ed=(0,n.useCallback)(k(function(){var e,t,n,r,l;return B(this,function(a){switch(a.label){case 0:E(!0),a.label=1;case 1:return a.trys.push([1,,3,4]),[4,Promise.all([d.request({url:"docUnderstanding:listPipelines"}),d.request({url:"docUnderstanding:listEndpoints"})])];case 2:return r=(n=P.apply(void 0,[a.sent(),2]))[0],l=n[1],f((null==(e=r.data)?void 0:e.data)||[]),b((null==(t=l.data)?void 0:t.data)||[]),[3,4];case 3:return E(!1),[7];case 4:return[2]}})}),[d]);(0,n.useEffect)(function(){ed()},[ed]),(0,n.useEffect)(function(){return function(){es.current&&clearInterval(es.current)}},[]);var ep=function(e){j(e.id),I.setFieldsValue({name:e.name,description:e.description,enabled:e.enabled,inputSchema:e.inputSchema,outputMapping:e.outputMapping}),W(F(e.steps||[]).sort(function(e,t){return e.stepOrder-t.stepOrder}).map(function(e){return{_key:"srv_".concat(e.id),id:e.id,stepOrder:e.stepOrder,name:e.name,endpointId:e.endpointId,inputMapping:e.inputMapping,outputAlias:e.outputAlias||"",condition:e.condition,onError:e.onError||"fail",retryCount:e.retryCount||0}})),O(!0)},em=(t=k(function(e){return B(this,function(t){switch(t.label){case 0:return[4,d.request({url:"docUnderstanding:deletePipeline",method:"POST",params:{filterByTk:e}})];case 1:return t.sent(),l.message.success("Deleted"),ed(),[2]}})}),function(e){return t.apply(this,arguments)}),ef=(0,n.useCallback)(function(){es.current&&(clearInterval(es.current),es.current=null)},[]),ey=(0,n.useCallback)((o=k(function(e){var t;return B(this,function(n){switch(n.label){case 0:return[4,d.request({url:"docUnderstanding:getJobStatus",params:{filterByTk:e}})];case 1:return eo(t=q(n.sent())),["completed","failed","timeout"].includes(null==t?void 0:t.status)&&(ef(),ec(!1)),[2,t]}})}),function(e){return o.apply(this,arguments)}),[d,ef]),eh=(0,n.useCallback)(function(e){ef(),es.current=setInterval(function(){ey(e).catch(function(e){ef(),ec(!1),l.message.error((null==e?void 0:e.message)||"Failed to refresh test job")})},1500)},[ey,ef]),eb=function(e){ef(),X(e),eo(null),ec(!1),er(""),ee(z(D(e.inputSchema))),K(!0)},eg=function(){ef(),K(!1),X(null),eo(null),ec(!1)},ev=(i=k(function(){var e,t,n,r,a,o;return B(this,function(i){switch(i.label){case 0:if(!Y)return[2];try{t=Z.trim()?JSON.parse(Z):{},e=U(D(Y.inputSchema),t),er("")}catch(e){return er("Invalid JSON input"),[2]}ef(),ec(!0),eo(null),i.label=1;case 1:return i.trys.push([1,4,,5]),[4,d.request({url:"docUnderstanding:executePipeline",method:"POST",data:{pipelineId:Y.id,input:e}})];case 2:if(!(r=null==(n=q(i.sent()))?void 0:n.jobId))throw Error("Pipeline did not return a job ID");return[4,ey(r)];case 3:return["completed","failed","timeout"].includes(null==(a=i.sent())?void 0:a.status)||eh(r),l.message.success("Test job #".concat(r," started")),[3,5];case 4:return o=i.sent(),ec(!1),l.message.error((null==o?void 0:o.message)||"Failed to run pipeline test"),[3,5];case 5:return[2]}})}),function(){return i.apply(this,arguments)}),eE=(u=k(function(){var e,t,n,r,a,o,i,u,c;return B(this,function(s){switch(s.label){case 0:return s.trys.push([0,6,,7]),[4,I.validateFields()];case 1:e=s.sent(),t=!0,n=!1,r=void 0;try{for(a=H[Symbol.iterator]();!(t=(o=a.next()).done);t=!0){if(!(i=o.value).name)return l.message.error("All steps must have a name"),[2];if(!i.endpointId)return l.message.error('Step "'.concat(i.name||i.stepOrder,'" must have an endpoint')),[2]}}catch(e){n=!0,r=e}finally{try{t||null==a.return||a.return()}finally{if(n)throw r}}if(new Set(u=H.map(function(e){return e.outputAlias}).filter(Boolean)).size!==u.length)return l.message.error("Step output aliases must be unique"),[2];if(c=C(x({},e),{steps:H.map(function(e){return C(x({},e.id?{id:e.id}:{}),{stepOrder:e.stepOrder,name:e.name,endpointId:e.endpointId,inputMapping:e.inputMapping,outputAlias:e.outputAlias||void 0,condition:e.condition,onError:e.onError,retryCount:"retry"===e.onError?e.retryCount:0})})}),!A)return[3,3];return[4,d.request({url:"docUnderstanding:updatePipeline",method:"POST",params:{filterByTk:A},data:c})];case 2:return s.sent(),[3,5];case 3:return[4,d.request({url:"docUnderstanding:createPipeline",method:"POST",data:c})];case 4:s.sent(),s.label=5;case 5:return l.message.success("Saved"),O(!1),ed(),[3,7];case 6:return s.sent(),[3,7];case 7:return[2]}})}),function(){return u.apply(this,arguments)}),eS=[{title:"Name",dataIndex:"name",width:200},{title:"Steps",dataIndex:"steps",width:300,render:function(e){if(!e||0===e.length)return r().createElement(l.Tag,null,"0 steps");var t=F(e).sort(function(e,t){return e.stepOrder-t.stepOrder});return r().createElement(l.Space,{size:2,wrap:!0},t.map(function(e,t){return r().createElement(r().Fragment,{key:e.id},t>0&&r().createElement("span",{style:{color:"#ccc"}},"→"),r().createElement(l.Tag,null,e.name||"Step ".concat(e.stepOrder)))}))}},{title:"Enabled",dataIndex:"enabled",width:80,render:function(e){return e?r().createElement(l.Tag,{color:"success"},"Yes"):r().createElement(l.Tag,null,"No")}},{title:"AI Tool",width:100,render:function(e,t){var n;return t.enabled?r().createElement(l.Tooltip,{title:"Registered as: doc_understanding.".concat(null==(n=t.name)?void 0:n.toLowerCase().replace(/[^a-z0-9_]/g,"_"))},r().createElement(l.Tag,{color:"blue",icon:r().createElement(a.ThunderboltOutlined,null)},"Active")):r().createElement(l.Tag,null,"Inactive")}},{title:"Action",width:190,render:function(e,t){return r().createElement(l.Space,null,r().createElement(l.Button,{type:"link",size:"small",icon:r().createElement(a.PlayCircleOutlined,null),disabled:!t.enabled,onClick:function(){return eb(t)}},"Test"),r().createElement(l.Button,{type:"link",size:"small",icon:r().createElement(a.EditOutlined,null),onClick:function(){return ep(t)}},"Edit"),r().createElement(l.Popconfirm,{title:"Delete this pipeline?",onConfirm:function(){return em(t.id)}},r().createElement(l.Button,{type:"link",size:"small",danger:!0,icon:r().createElement(a.DeleteOutlined,null)},"Delete")))}}];return r().createElement("div",null,r().createElement("div",{style:{marginBottom:16}},r().createElement(l.Button,{type:"primary",icon:r().createElement(a.PlusOutlined,null),onClick:function(){j(null),I.resetFields(),W([]),O(!0)}},"Add Pipeline")),r().createElement(l.Table,{rowKey:"id",columns:eS,dataSource:m,loading:v,size:"small"}),r().createElement(l.Modal,{title:A?"Edit Pipeline":"New Pipeline",open:w,onOk:eE,onCancel:function(){return O(!1)},width:800,destroyOnClose:!0},r().createElement(l.Form,{form:I,layout:"vertical",preserve:!1},r().createElement("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"0 16px"}},r().createElement(l.Form.Item,{name:"name",label:"Pipeline Name",rules:[{required:!0}]},r().createElement(l.Input,{placeholder:"full_document_processing"})),r().createElement(l.Form.Item,{name:"enabled",label:"Enabled",valuePropName:"checked",initialValue:!0},r().createElement(l.Switch,null))),r().createElement(l.Form.Item,{name:"description",label:"Description"},r().createElement(R,{rows:2,placeholder:"What this pipeline does"})),r().createElement(l.Card,{title:"Pipeline Steps",size:"small",style:{marginBottom:16},extra:r().createElement(l.Tag,{color:"blue"},H.length," step(s)")},r().createElement(J,{steps:H,endpoints:h,onChange:W})),r().createElement(l.Collapse,{size:"small",ghost:!0},r().createElement(N,{header:"Advanced: Input Schema & Output Mapping",key:"advanced"},r().createElement(l.Form.Item,{name:"inputSchema",label:"Input Schema (JSON Schema)",help:"Defines what input this pipeline accepts. Used by AI tool schema."},r().createElement(_,{placeholder:'{ "type": "object", "properties": { "document_url": { "type": "string" } }, "required": ["document_url"] }'})),r().createElement(l.Form.Item,{name:"outputMapping",label:"Output Mapping (JSON)",help:"Map final step results to pipeline output. If empty, all step results are returned."},r().createElement(_,{placeholder:'{ "text": "$step[ocr_result].response.text", "category": "$step[classify].response.category" }'})))))),r().createElement(l.Modal,{title:Y?"Test Playground: ".concat(Y.name):"Test Playground",open:$,onCancel:eg,width:860,destroyOnClose:!0,footer:[r().createElement(l.Button,{key:"close",onClick:eg},"Close"),(null==ea?void 0:ea.id)&&r().createElement(l.Button,{key:"refresh",icon:r().createElement(a.ReloadOutlined,null),disabled:eu,onClick:function(){return ey(ea.id)}},"Refresh"),r().createElement(l.Button,{key:"run",type:"primary",icon:r().createElement(a.PlayCircleOutlined,null),loading:eu,onClick:ev},"Run test")].filter(Boolean)},r().createElement("div",{style:{display:"grid",gridTemplateColumns:"minmax(0, 1fr) minmax(0, 1fr)",gap:16}},r().createElement("div",null,r().createElement("div",{style:{fontWeight:500,marginBottom:6}},"Input JSON"),r().createElement(R,{rows:16,value:Z,onChange:function(e){ee(e.target.value),en&&er("")},placeholder:'{ "document_url": "https://..." }',style:{fontFamily:"monospace",fontSize:12}}),en&&r().createElement(l.Alert,{type:"error",showIcon:!0,message:en,style:{marginTop:8}}),r().createElement(l.Collapse,{size:"small",ghost:!0,style:{marginTop:12}},r().createElement(N,{header:"Input Schema",key:"schema"},r().createElement("pre",{style:{background:"#f5f5f5",padding:12,borderRadius:6,fontSize:12,maxHeight:220,overflow:"auto"}},z(null==Y?void 0:Y.inputSchema))))),r().createElement("div",null,r().createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:6}},r().createElement("span",{style:{fontWeight:500}},"Result"),(null==ea?void 0:ea.status)&&r().createElement(l.Tag,{color:(null==(c=M[ea.status])?void 0:c.color)||"default"},(null==(s=M[ea.status])?void 0:s.label)||ea.status)),ea?r().createElement("div",null,r().createElement(l.Space,{style:{marginBottom:8},wrap:!0},r().createElement(l.Tag,null,"Job #",ea.id),ea.currentStep&&r().createElement(l.Tag,null,"Step ",ea.currentStep)),ea.error&&r().createElement(l.Alert,{type:"error",showIcon:!0,message:"Pipeline error",description:r().createElement("pre",{style:{margin:0,whiteSpace:"pre-wrap"}},ea.error),style:{marginBottom:12}}),r().createElement("div",{style:{fontWeight:500,marginBottom:4}},"Final Result"),r().createElement("pre",{style:{background:"#f0f5ff",padding:12,borderRadius:6,fontSize:12,maxHeight:220,overflow:"auto"}},void 0!==ea.finalResult&&null!==ea.finalResult?z(ea.finalResult):"(not yet available)"),r().createElement("div",{style:{fontWeight:500,margin:"12px 0 4px"}},"Step Results"),r().createElement("pre",{style:{background:"#f5f5f5",padding:12,borderRadius:6,fontSize:12,maxHeight:260,overflow:"auto"}},ea.stepResults?z(ea.stepResults):"{}")):r().createElement(l.Empty,{description:"Run a test to see job output",imageStyle:{height:48}})))))};function H(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function W(e,t,n,r,l,a,o){try{var i=e[a](o),u=i.value}catch(e){n(e);return}i.done?t(u):Promise.resolve(u).then(r,l)}function L(e){return function(){var t=this,n=arguments;return new Promise(function(r,l){var a=e.apply(t,n);function o(e){W(a,r,l,o,i,"next",e)}function i(e){W(a,r,l,o,i,"throw",e)}o(void 0)})}}function $(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n,r,l=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=l){var a=[],o=!0,i=!1;try{for(l=l.call(e);!(o=(n=l.next()).done)&&(a.push(n.value),!t||a.length!==t);o=!0);}catch(e){i=!0,r=e}finally{try{o||null==l.return||l.return()}finally{if(i)throw r}}return a}}(e,t)||function(e,t){if(e){if("string"==typeof e)return H(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);if("Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n)return Array.from(n);if("Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return H(e,t)}}(e,t)||function(){throw TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function K(e,t){var n,r,l,a,o={label:0,sent:function(){if(1&l[0])throw l[1];return l[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(a){return function(i){var u=[a,i];if(n)throw TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(l=2&u[0]?r.return:u[0]?r.throw||((l=r.return)&&l.call(r),0):r.next)&&!(l=l.call(r,u[1])).done)return l;switch(r=0,l&&(u=[2&u[0],l.value]),u[0]){case 0:case 1:l=u;break;case 4:return o.label++,{value:u[1],done:!1};case 5:o.label++,r=u[1],u=[0];continue;case 7:u=o.ops.pop(),o.trys.pop();continue;default:if(!(l=(l=o.trys).length>0&&l[l.length-1])&&(6===u[0]||2===u[0])){o=0;continue}if(3===u[0]&&(!l||u[1]>l[0]&&u[1]<l[3])){o.label=u[1];break}if(6===u[0]&&o.label<l[1]){o.label=l[1],l=u;break}if(l&&o.label<l[2]){o.label=l[2],o.ops.push(u);break}l[2]&&o.ops.pop(),o.trys.pop();continue}u=t.call(e,o)}catch(e){u=[6,e],r=0}finally{n=l=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}}var G={pending:{color:"default",label:"Pending"},running:{color:"processing",label:"Running"},polling:{color:"processing",label:"Polling"},completed:{color:"success",label:"Completed"},failed:{color:"error",label:"Failed"},timeout:{color:"error",label:"Timeout"}},Y=function(){var t,o,i=(0,e.useAPIClient)(),u=$((0,n.useState)([]),2),c=u[0],s=u[1],d=$((0,n.useState)([]),2),p=d[0],m=d[1],f=$((0,n.useState)(!1),2),y=f[0],h=f[1],b=$((0,n.useState)(!1),2),g=b[0],v=b[1],E=$((0,n.useState)(null),2),S=E[0],w=E[1],O=$((0,n.useState)(void 0),2),I=O[0],k=O[1],T=$((0,n.useState)(void 0),2),x=T[0],C=T[1],P=(0,n.useCallback)(L(function(){var e,t;return K(this,function(n){switch(n.label){case 0:h(!0),n.label=1;case 1:return n.trys.push([1,,3,4]),t={},I&&(t.status=I),x&&(t.pipelineId=x),[4,i.request({url:"docUnderstanding:listJobs",params:{filter:Object.keys(t).length>0?t:void 0}})];case 2:return s((null==(e=n.sent().data)?void 0:e.data)||[]),[3,4];case 3:return h(!1),[7];case 4:return[2]}})}),[i,I,x]),F=(0,n.useCallback)(L(function(){var e;return K(this,function(t){switch(t.label){case 0:return t.trys.push([0,2,,3]),[4,i.request({url:"docUnderstanding:listPipelines"})];case 1:return m((null==(e=t.sent().data)?void 0:e.data)||[]),[3,3];case 2:return t.sent(),[3,3];case 3:return[2]}})}),[i]);(0,n.useEffect)(function(){F()},[F]),(0,n.useEffect)(function(){P();var e=setInterval(P,1e4);return function(){return clearInterval(e)}},[P]);var A=new Map(p.map(function(e){return[e.id,e.name]})),j=(t=L(function(e){var t;return K(this,function(n){switch(n.label){case 0:return n.trys.push([0,2,,3]),[4,i.request({url:"docUnderstanding:getJobStatus",params:{filterByTk:e.id}})];case 1:return w((null==(t=n.sent().data)?void 0:t.data)||e),[3,3];case 2:return n.sent(),w(e),[3,3];case 3:return v(!0),[2]}})}),function(e){return t.apply(this,arguments)}),B=[{title:"ID",dataIndex:"id",width:60},{title:"Pipeline",dataIndex:"pipelineId",width:180,render:function(e){return A.get(e)||"#".concat(e)}},{title:"Status",dataIndex:"status",width:100,render:function(e){var t=G[e]||{color:"default",label:e};return r().createElement(l.Tag,{color:t.color},t.label)}},{title:"Current Step",dataIndex:"currentStep",width:90,render:function(e,t){return"completed"===t.status?r().createElement(l.Tag,{color:"success"},"Done"):"failed"===t.status?r().createElement(l.Tag,{color:"error"},"Step ",e):r().createElement(l.Badge,{status:"processing",text:"Step ".concat(e)})}},{title:"Started",dataIndex:"startedAt",width:160,render:function(e){return e?new Date(e).toLocaleString():"-"}},{title:"Completed",dataIndex:"completedAt",width:160,render:function(e){return e?new Date(e).toLocaleString():"-"}},{title:"Action",width:80,render:function(e,t){return r().createElement(l.Button,{size:"small",icon:r().createElement(a.EyeOutlined,null),onClick:function(){return j(t)}},"View")}}];return r().createElement("div",null,r().createElement(l.Space,{style:{marginBottom:16},wrap:!0},r().createElement(l.Select,{allowClear:!0,placeholder:"Filter by status",value:I,onChange:k,style:{width:160},options:Object.entries(G).map(function(e){var t=$(e,2);return{value:t[0],label:t[1].label}})}),r().createElement(l.Select,{allowClear:!0,placeholder:"Filter by pipeline",value:x,onChange:C,style:{width:200},options:p.map(function(e){return{value:e.id,label:e.name}})}),r().createElement(l.Button,{icon:r().createElement(a.ReloadOutlined,null),onClick:P},"Refresh")),r().createElement(l.Table,{rowKey:"id",columns:B,dataSource:c,loading:y,size:"small",pagination:{pageSize:20}}),r().createElement(l.Drawer,{title:S?"Job #".concat(S.id," — ").concat(A.get(S.pipelineId)||"Unknown"):"Job Details",width:640,open:g,onClose:function(){return v(!1)}},S&&r().createElement("div",null,r().createElement("div",{style:{marginBottom:16}},r().createElement(l.Space,null,r().createElement(l.Tag,{color:null==(o=G[S.status])?void 0:o.color},S.status),S.startedAt&&r().createElement("span",null,"Started: ",new Date(S.startedAt).toLocaleString()),S.completedAt&&r().createElement("span",null,"Completed: ",new Date(S.completedAt).toLocaleString()))),S.error&&r().createElement("div",{style:{background:"#fff2f0",border:"1px solid #ffccc7",borderRadius:6,padding:12,marginBottom:16}},r().createElement("strong",{style:{color:"#cf1322"}},"Error:"),r().createElement("pre",{style:{margin:"4px 0 0",whiteSpace:"pre-wrap",color:"#cf1322"}},S.error)),r().createElement("h4",null,"Input"),r().createElement("pre",{style:{background:"#f5f5f5",padding:12,borderRadius:6,fontSize:12,maxHeight:200,overflow:"auto"}},JSON.stringify(S.input,null,2)),r().createElement("h4",{style:{marginTop:16}},"Step Results"),S.stepResults&&Object.keys(S.stepResults).length>0?Object.entries(S.stepResults).map(function(e){var t=$(e,2),n=t[0],a=t[1];return r().createElement("div",{key:n,style:{marginBottom:8}},r().createElement(l.Tag,{color:"blue"},n),r().createElement("pre",{style:{background:"#f5f5f5",padding:8,borderRadius:4,fontSize:11,maxHeight:150,overflow:"auto",marginTop:4}},JSON.stringify(a,null,2)))}):r().createElement("div",{style:{color:"#999"}},"No step results yet"),r().createElement("h4",{style:{marginTop:16}},"Final Result"),r().createElement("pre",{style:{background:"#f0f5ff",padding:12,borderRadius:6,fontSize:12,maxHeight:300,overflow:"auto"}},S.finalResult?JSON.stringify(S.finalResult,null,2):"(not yet available)"),S.externalTaskIds&&Object.keys(S.externalTaskIds).length>0&&r().createElement(r().Fragment,null,r().createElement("h4",{style:{marginTop:16}},"External Task IDs"),r().createElement("pre",{style:{background:"#f5f5f5",padding:8,borderRadius:4,fontSize:11}},JSON.stringify(S.externalTaskIds,null,2))))))},X=function(){return r().createElement("div",{style:{backgroundColor:"var(--nb-box-bg)",minHeight:"100vh"}},r().createElement("div",{style:{padding:"16px 24px",backgroundColor:"#fff",borderBottom:"1px solid #f0f0f0"}},r().createElement("h2",{style:{margin:0,fontSize:20,fontWeight:500}},"Document Understanding - Pipeline Orchestrator")),r().createElement("div",{style:{padding:"0 24px 24px"}},r().createElement(l.Tabs,{defaultActiveKey:"config",items:[{key:"config",label:"Service Config",children:r().createElement(d,null)},{key:"endpoints",label:"Endpoints",children:r().createElement(w,null)},{key:"pipelines",label:"Pipelines",children:r().createElement(V,null)},{key:"jobs",label:"Jobs history",children:r().createElement(Y,null)}]})))};function Q(e,t,n,r,l,a,o){try{var i=e[a](o),u=i.value}catch(e){n(e);return}i.done?t(u):Promise.resolve(u).then(r,l)}function Z(e,t,n){return(Z=er()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var l=new(Function.bind.apply(e,r));return n&&et(l,n.prototype),l}).apply(null,arguments)}function ee(e){return(ee=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function et(e,t){return(et=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function en(e){var t="function"==typeof Map?new Map:void 0;return(en=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return Z(e,arguments,ee(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),et(n,e)})(e)}function er(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(er=function(){return!!e})()}var el=function(e){var n;if("function"!=typeof e&&null!==e)throw TypeError("Super expression must either be null or a function");function r(){var e,t;if(!(this instanceof r))throw TypeError("Cannot call a class as a function");return e=r,t=arguments,e=ee(e),function(e,t){var n;if(t&&("object"==((n=t)&&"undefined"!=typeof Symbol&&n.constructor===Symbol?"symbol":typeof n)||"function"==typeof t))return t;if(void 0===e)throw ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(this,er()?Reflect.construct(e,t||[],ee(this).constructor):e.apply(this,t))}return r.prototype=Object.create(e&&e.prototype,{constructor:{value:r,writable:!0,configurable:!0}}),e&&et(r,e),n=[{key:"load",value:function(){var e,n=this;return(e=function(){var e;return function(e,t){var n,r,l,a,o={label:0,sent:function(){if(1&l[0])throw l[1];return l[1]},trys:[],ops:[]};return a={next:i(0),throw:i(1),return:i(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function i(a){return function(i){var u=[a,i];if(n)throw TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(l=2&u[0]?r.return:u[0]?r.throw||((l=r.return)&&l.call(r),0):r.next)&&!(l=l.call(r,u[1])).done)return l;switch(r=0,l&&(u=[2&u[0],l.value]),u[0]){case 0:case 1:l=u;break;case 4:return o.label++,{value:u[1],done:!1};case 5:o.label++,r=u[1],u=[0];continue;case 7:u=o.ops.pop(),o.trys.pop();continue;default:if(!(l=(l=o.trys).length>0&&l[l.length-1])&&(6===u[0]||2===u[0])){o=0;continue}if(3===u[0]&&(!l||u[1]>l[0]&&u[1]<l[3])){o.label=u[1];break}if(6===u[0]&&o.label<l[1]){o.label=l[1],l=u;break}if(l&&o.label<l[2]){o.label=l[2],o.ops.push(u);break}l[2]&&o.ops.pop(),o.trys.pop();continue}u=t.call(e,o)}catch(e){u=[6,e],r=0}finally{n=l=0}if(5&u[0])throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}}(this,function(r){return null==(e=n.flowEngine)||e.registerModels(t),n.app.pluginSettingsManager.add("document-understanding",{title:n.t("Document Understanding"),icon:"FileSearchOutlined",Component:X,aclSnippet:"pm.document-understanding"}),[2]})},function(){var t=this,n=arguments;return new Promise(function(r,l){var a=e.apply(t,n);function o(e){Q(a,r,l,o,i,"next",e)}function i(e){Q(a,r,l,o,i,"throw",e)}o(void 0)})})()}}],function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}(r.prototype,n),r}(en(e.Plugin))}(),i}()});
|
package/dist/client/plugin.d.ts
CHANGED
package/dist/externalVersion.js
CHANGED
|
@@ -8,13 +8,13 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
module.exports = {
|
|
11
|
-
"@nocobase/flow-engine": "2.0.
|
|
12
|
-
"@nocobase/client": "2.0.
|
|
13
|
-
"@nocobase/actions": "2.0.
|
|
14
|
-
"@nocobase/server": "2.0.
|
|
11
|
+
"@nocobase/flow-engine": "2.0.55",
|
|
12
|
+
"@nocobase/client": "2.0.55",
|
|
13
|
+
"@nocobase/actions": "2.0.55",
|
|
14
|
+
"@nocobase/server": "2.0.55",
|
|
15
15
|
"react": "18.2.0",
|
|
16
16
|
"antd": "5.24.2",
|
|
17
17
|
"@ant-design/icons": "5.6.1",
|
|
18
|
-
"@nocobase/database": "2.0.
|
|
19
|
-
"axios": "1.
|
|
18
|
+
"@nocobase/database": "2.0.55",
|
|
19
|
+
"axios": "1.16.1"
|
|
20
20
|
};
|
package/dist/server/actions.js
CHANGED
|
@@ -85,12 +85,45 @@ const defineActions = (plugin) => {
|
|
|
85
85
|
await next();
|
|
86
86
|
},
|
|
87
87
|
async executePipeline(ctx, next) {
|
|
88
|
-
var _a, _b;
|
|
88
|
+
var _a, _b, _c;
|
|
89
89
|
const { values } = ctx.action.params;
|
|
90
90
|
const pipelineId = values == null ? void 0 : values.pipelineId;
|
|
91
91
|
const input = (values == null ? void 0 : values.input) || {};
|
|
92
92
|
const userId = (_b = (_a = ctx.state) == null ? void 0 : _a.currentUser) == null ? void 0 : _b.id;
|
|
93
|
-
|
|
93
|
+
const multipartFiles = [];
|
|
94
|
+
const filesObj = ctx.request.files || ((_c = ctx.request.body) == null ? void 0 : _c.files);
|
|
95
|
+
if (filesObj) {
|
|
96
|
+
const addFile = (key, file) => {
|
|
97
|
+
const filePath = file.path || file.filepath;
|
|
98
|
+
const fileName = file.name || file.originalFilename || "file";
|
|
99
|
+
const mimeType = file.type || file.mimetype || "application/octet-stream";
|
|
100
|
+
if (filePath) {
|
|
101
|
+
try {
|
|
102
|
+
const buffer = require("fs").readFileSync(filePath);
|
|
103
|
+
multipartFiles.push({
|
|
104
|
+
fieldName: key,
|
|
105
|
+
buffer,
|
|
106
|
+
filename: fileName,
|
|
107
|
+
mimeType
|
|
108
|
+
});
|
|
109
|
+
} catch (err) {
|
|
110
|
+
console.error("Failed to read uploaded multipart file:", err);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
if (typeof filesObj === "object") {
|
|
115
|
+
for (const [key, value] of Object.entries(filesObj)) {
|
|
116
|
+
if (Array.isArray(value)) {
|
|
117
|
+
for (const f of value) {
|
|
118
|
+
addFile(key, f);
|
|
119
|
+
}
|
|
120
|
+
} else {
|
|
121
|
+
addFile(key, value);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
ctx.body = await service.executePipeline(pipelineId, input, multipartFiles, userId);
|
|
94
127
|
await next();
|
|
95
128
|
},
|
|
96
129
|
async getJobStatus(ctx, next) {
|
|
@@ -106,8 +139,19 @@ const defineActions = (plugin) => {
|
|
|
106
139
|
async webhookCallback(ctx, next) {
|
|
107
140
|
const signature = ctx.request.headers["x-webhook-signature"];
|
|
108
141
|
const { values } = ctx.action.params;
|
|
109
|
-
|
|
110
|
-
|
|
142
|
+
try {
|
|
143
|
+
await service.handleWebhook(values || ctx.request.body, signature);
|
|
144
|
+
ctx.body = { received: true };
|
|
145
|
+
} catch (err) {
|
|
146
|
+
console.error("Webhook callback error:", err.message);
|
|
147
|
+
if (err.message.includes("signature")) {
|
|
148
|
+
ctx.status = 401;
|
|
149
|
+
ctx.body = { error: err.message };
|
|
150
|
+
} else {
|
|
151
|
+
ctx.status = 400;
|
|
152
|
+
ctx.body = { error: err.message };
|
|
153
|
+
}
|
|
154
|
+
}
|
|
111
155
|
await next();
|
|
112
156
|
}
|
|
113
157
|
};
|
|
@@ -40,6 +40,7 @@ var endpoints_default = {
|
|
|
40
40
|
{ type: "json", name: "requestBodySchema" },
|
|
41
41
|
{ type: "json", name: "responseSchema" },
|
|
42
42
|
{ type: "string", name: "fileInputMode", length: 20 },
|
|
43
|
+
{ type: "string", name: "fileFieldName", length: 100, defaultValue: "file" },
|
|
43
44
|
{ type: "integer", name: "maxFiles", defaultValue: 1 },
|
|
44
45
|
{ type: "string", name: "executionMode", length: 20 },
|
|
45
46
|
{ type: "string", name: "pollResultSubpath", length: 500 },
|
|
@@ -12,6 +12,10 @@ export declare class AsyncJobManager {
|
|
|
12
12
|
onJobError: (jobId: number, error: string) => Promise<void>;
|
|
13
13
|
});
|
|
14
14
|
startPolling(jobId: number, endpoint: EndpointDef, taskId: string, customInterval?: number, customTimeout?: number): Promise<void>;
|
|
15
|
+
/**
|
|
16
|
+
* Transition pending and running jobs to failed state during startup.
|
|
17
|
+
*/
|
|
18
|
+
cleanupStuckJobs(): Promise<void>;
|
|
15
19
|
/**
|
|
16
20
|
* Recover polling jobs that were in-flight when server restarted.
|
|
17
21
|
* Call this during service initialization.
|
|
@@ -79,6 +79,27 @@ class AsyncJobManager {
|
|
|
79
79
|
}, interval);
|
|
80
80
|
this.intervals.set(jobId, timer);
|
|
81
81
|
}
|
|
82
|
+
/**
|
|
83
|
+
* Transition pending and running jobs to failed state during startup.
|
|
84
|
+
*/
|
|
85
|
+
async cleanupStuckJobs() {
|
|
86
|
+
const jobsRepo = this.db.getRepository("doc_understanding_jobs");
|
|
87
|
+
const stuckJobs = await jobsRepo.find({
|
|
88
|
+
filter: {
|
|
89
|
+
status: ["pending", "running"]
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
for (const job of stuckJobs) {
|
|
93
|
+
await jobsRepo.update({
|
|
94
|
+
filterByTk: job.id,
|
|
95
|
+
values: {
|
|
96
|
+
status: "failed",
|
|
97
|
+
error: "Server restarted during execution",
|
|
98
|
+
completedAt: /* @__PURE__ */ new Date()
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
}
|
|
82
103
|
/**
|
|
83
104
|
* Recover polling jobs that were in-flight when server restarted.
|
|
84
105
|
* Call this during service initialization.
|
|
@@ -9,6 +9,7 @@ export declare class DocumentUnderstandingService {
|
|
|
9
9
|
private pipelineExecutor;
|
|
10
10
|
private jobManager;
|
|
11
11
|
private initialized;
|
|
12
|
+
private static readonly HEADER_NAME_RE;
|
|
12
13
|
constructor(app: Application, db: Database);
|
|
13
14
|
initialize(): Promise<void>;
|
|
14
15
|
isReady(): boolean;
|
|
@@ -17,6 +18,8 @@ export declare class DocumentUnderstandingService {
|
|
|
17
18
|
listEndpoints(): Promise<EndpointDef[]>;
|
|
18
19
|
createEndpoint(data: Partial<EndpointDef>): Promise<EndpointDef>;
|
|
19
20
|
updateEndpoint(id: number, data: Partial<EndpointDef>): Promise<void>;
|
|
21
|
+
private normalizeEndpoint;
|
|
22
|
+
private normalizeHeaders;
|
|
20
23
|
deleteEndpoint(id: number): Promise<void>;
|
|
21
24
|
listPipelines(): Promise<PipelineDef[]>;
|
|
22
25
|
createPipeline(data: Partial<PipelineDef>): Promise<PipelineDef>;
|
|
@@ -50,6 +50,7 @@ class DocumentUnderstandingService {
|
|
|
50
50
|
pipelineExecutor;
|
|
51
51
|
jobManager;
|
|
52
52
|
initialized = false;
|
|
53
|
+
static HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
53
54
|
constructor(app, db) {
|
|
54
55
|
this.app = app;
|
|
55
56
|
this.db = db;
|
|
@@ -83,6 +84,7 @@ class DocumentUnderstandingService {
|
|
|
83
84
|
}
|
|
84
85
|
});
|
|
85
86
|
this.pipelineExecutor = new import_PipelineExecutor.PipelineExecutor(this.db, this.apiClient, this.jobManager);
|
|
87
|
+
await this.jobManager.cleanupStuckJobs();
|
|
86
88
|
await this.jobManager.recoverPollingJobs();
|
|
87
89
|
this.initialized = true;
|
|
88
90
|
}
|
|
@@ -107,10 +109,38 @@ class DocumentUnderstandingService {
|
|
|
107
109
|
return this.db.getRepository("doc_understanding_endpoints").find({ sort: "sortOrder" });
|
|
108
110
|
}
|
|
109
111
|
async createEndpoint(data) {
|
|
110
|
-
return this.db.getRepository("doc_understanding_endpoints").create({ values: data });
|
|
112
|
+
return this.db.getRepository("doc_understanding_endpoints").create({ values: this.normalizeEndpoint(data) });
|
|
111
113
|
}
|
|
112
114
|
async updateEndpoint(id, data) {
|
|
113
|
-
await this.db.getRepository("doc_understanding_endpoints").update({
|
|
115
|
+
await this.db.getRepository("doc_understanding_endpoints").update({
|
|
116
|
+
filterByTk: id,
|
|
117
|
+
values: this.normalizeEndpoint(data)
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
normalizeEndpoint(data = {}) {
|
|
121
|
+
if (!Object.prototype.hasOwnProperty.call(data, "customHeaders")) {
|
|
122
|
+
return data;
|
|
123
|
+
}
|
|
124
|
+
return {
|
|
125
|
+
...data,
|
|
126
|
+
customHeaders: this.normalizeHeaders(data.customHeaders)
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
normalizeHeaders(headers) {
|
|
130
|
+
const normalized = {};
|
|
131
|
+
if (!headers || typeof headers !== "object" || Array.isArray(headers)) {
|
|
132
|
+
return normalized;
|
|
133
|
+
}
|
|
134
|
+
for (const [rawName, rawValue] of Object.entries(headers)) {
|
|
135
|
+
const name = rawName.trim();
|
|
136
|
+
if (!name) continue;
|
|
137
|
+
if (!DocumentUnderstandingService.HEADER_NAME_RE.test(name)) {
|
|
138
|
+
throw new Error(`Invalid HTTP header name: ${rawName}`);
|
|
139
|
+
}
|
|
140
|
+
if (rawValue === void 0 || rawValue === null) continue;
|
|
141
|
+
normalized[name] = String(rawValue);
|
|
142
|
+
}
|
|
143
|
+
return normalized;
|
|
114
144
|
}
|
|
115
145
|
async deleteEndpoint(id) {
|
|
116
146
|
await this.db.getRepository("doc_understanding_endpoints").destroy({ filterByTk: id });
|
|
@@ -173,7 +203,8 @@ class DocumentUnderstandingService {
|
|
|
173
203
|
const jobsRepo = this.db.getRepository("doc_understanding_jobs");
|
|
174
204
|
const PAGE_SIZE = 100;
|
|
175
205
|
let offset = 0;
|
|
176
|
-
|
|
206
|
+
let hasMoreJobs = true;
|
|
207
|
+
while (hasMoreJobs) {
|
|
177
208
|
const jobs = await jobsRepo.find({
|
|
178
209
|
filter: { status: "polling" },
|
|
179
210
|
limit: PAGE_SIZE,
|
|
@@ -186,8 +217,10 @@ class DocumentUnderstandingService {
|
|
|
186
217
|
return;
|
|
187
218
|
}
|
|
188
219
|
}
|
|
189
|
-
|
|
190
|
-
|
|
220
|
+
hasMoreJobs = jobs.length >= PAGE_SIZE;
|
|
221
|
+
if (hasMoreJobs) {
|
|
222
|
+
offset += PAGE_SIZE;
|
|
223
|
+
}
|
|
191
224
|
}
|
|
192
225
|
throw new Error(`Job not found for webhook task ${taskId}`);
|
|
193
226
|
}
|
|
@@ -15,8 +15,10 @@ export interface ApiCallOptions {
|
|
|
15
15
|
export declare class ExternalApiClient {
|
|
16
16
|
private config;
|
|
17
17
|
private client;
|
|
18
|
+
private static readonly HEADER_NAME_RE;
|
|
18
19
|
constructor(config: ServiceConfig);
|
|
19
20
|
private buildAuthHeaders;
|
|
21
|
+
private sanitizeHeaders;
|
|
20
22
|
call(options: ApiCallOptions): Promise<{
|
|
21
23
|
status: number;
|
|
22
24
|
data: any;
|
|
@@ -44,6 +44,7 @@ var import_form_data = __toESM(require("form-data"));
|
|
|
44
44
|
class ExternalApiClient {
|
|
45
45
|
config;
|
|
46
46
|
client;
|
|
47
|
+
static HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
47
48
|
constructor(config) {
|
|
48
49
|
this.config = config;
|
|
49
50
|
this.client = import_axios.default.create({
|
|
@@ -66,15 +67,31 @@ class ExternalApiClient {
|
|
|
66
67
|
}
|
|
67
68
|
return headers;
|
|
68
69
|
}
|
|
70
|
+
sanitizeHeaders(headers) {
|
|
71
|
+
const normalized = {};
|
|
72
|
+
if (!headers || typeof headers !== "object" || Array.isArray(headers)) {
|
|
73
|
+
return normalized;
|
|
74
|
+
}
|
|
75
|
+
for (const [rawName, rawValue] of Object.entries(headers)) {
|
|
76
|
+
const name = rawName.trim();
|
|
77
|
+
if (!name) continue;
|
|
78
|
+
if (!ExternalApiClient.HEADER_NAME_RE.test(name)) {
|
|
79
|
+
throw new Error(`Invalid HTTP header name: ${rawName}`);
|
|
80
|
+
}
|
|
81
|
+
if (rawValue === void 0 || rawValue === null) continue;
|
|
82
|
+
normalized[name] = String(rawValue);
|
|
83
|
+
}
|
|
84
|
+
return normalized;
|
|
85
|
+
}
|
|
69
86
|
async call(options) {
|
|
70
87
|
const { endpoint, body, files, overrideHeaders } = options;
|
|
71
88
|
const url = endpoint.subpath;
|
|
72
89
|
const method = endpoint.method.toLowerCase();
|
|
73
90
|
let requestData = body;
|
|
74
91
|
let headers = {
|
|
75
|
-
...this.buildAuthHeaders(),
|
|
76
|
-
...endpoint.customHeaders
|
|
77
|
-
...overrideHeaders
|
|
92
|
+
...this.sanitizeHeaders(this.buildAuthHeaders()),
|
|
93
|
+
...this.sanitizeHeaders(endpoint.customHeaders),
|
|
94
|
+
...this.sanitizeHeaders(overrideHeaders)
|
|
78
95
|
};
|
|
79
96
|
if (endpoint.fileInputMode === "multipart" && files && files.length > 0) {
|
|
80
97
|
const formData = new import_form_data.default();
|
|
@@ -13,6 +13,7 @@ export declare class PipelineExecutor {
|
|
|
13
13
|
private apiClient;
|
|
14
14
|
private jobManager;
|
|
15
15
|
constructor(db: Database, apiClient: ExternalApiClient, jobManager: AsyncJobManager);
|
|
16
|
+
private resolveFile;
|
|
16
17
|
execute(pipelineId: number, input: Record<string, any>, files?: FileInput[], userId?: number): Promise<JobState>;
|
|
17
18
|
private runSteps;
|
|
18
19
|
resumeFromStep(jobId: number, asyncResult: any): Promise<void>;
|
|
@@ -38,6 +38,126 @@ class PipelineExecutor {
|
|
|
38
38
|
this.apiClient = apiClient;
|
|
39
39
|
this.jobManager = jobManager;
|
|
40
40
|
}
|
|
41
|
+
async resolveFile(urlOrPath, fieldName = "file") {
|
|
42
|
+
if (!urlOrPath || typeof urlOrPath !== "string") return null;
|
|
43
|
+
try {
|
|
44
|
+
let isLocal = false;
|
|
45
|
+
let absolutePath = "";
|
|
46
|
+
if (urlOrPath.startsWith("/") || urlOrPath.startsWith("storage/") || urlOrPath.includes("/uploads/")) {
|
|
47
|
+
let cleanedPath = urlOrPath;
|
|
48
|
+
if (urlOrPath.startsWith("/")) {
|
|
49
|
+
cleanedPath = urlOrPath.slice(1);
|
|
50
|
+
}
|
|
51
|
+
const pathOptions = [
|
|
52
|
+
require("path").resolve(process.cwd(), cleanedPath),
|
|
53
|
+
require("path").resolve(process.cwd(), "storage", cleanedPath),
|
|
54
|
+
require("path").resolve(process.cwd(), "storage/uploads", cleanedPath.replace(/^uploads\//, ""))
|
|
55
|
+
];
|
|
56
|
+
for (const p of pathOptions) {
|
|
57
|
+
if (require("fs").existsSync(p) && require("fs").statSync(p).isFile()) {
|
|
58
|
+
isLocal = true;
|
|
59
|
+
absolutePath = p;
|
|
60
|
+
break;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (isLocal) {
|
|
65
|
+
const fs = require("fs");
|
|
66
|
+
const path = require("path");
|
|
67
|
+
const buffer = fs.readFileSync(absolutePath);
|
|
68
|
+
const filename = path.basename(absolutePath);
|
|
69
|
+
let mimeLookup = (filePath) => "application/octet-stream";
|
|
70
|
+
try {
|
|
71
|
+
const mime = require("mime-types");
|
|
72
|
+
mimeLookup = (filePath) => mime.lookup(filePath) || "application/octet-stream";
|
|
73
|
+
} catch (e) {
|
|
74
|
+
mimeLookup = (filePath) => {
|
|
75
|
+
const ext = path.extname(filePath).toLowerCase();
|
|
76
|
+
const map = {
|
|
77
|
+
".pdf": "application/pdf",
|
|
78
|
+
".doc": "application/msword",
|
|
79
|
+
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
80
|
+
".xls": "application/vnd.ms-excel",
|
|
81
|
+
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
82
|
+
".png": "image/png",
|
|
83
|
+
".jpg": "image/jpeg",
|
|
84
|
+
".jpeg": "image/jpeg",
|
|
85
|
+
".txt": "text/plain",
|
|
86
|
+
".json": "application/json"
|
|
87
|
+
};
|
|
88
|
+
return map[ext] || "application/octet-stream";
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
const mimeType = mimeLookup(absolutePath);
|
|
92
|
+
return {
|
|
93
|
+
fieldName,
|
|
94
|
+
buffer,
|
|
95
|
+
filename,
|
|
96
|
+
mimeType
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
if (urlOrPath.startsWith("http://") || urlOrPath.startsWith("https://")) {
|
|
100
|
+
const axios = require("axios");
|
|
101
|
+
const path = require("path");
|
|
102
|
+
const response = await axios.get(urlOrPath, { responseType: "arraybuffer" });
|
|
103
|
+
const buffer = Buffer.from(response.data);
|
|
104
|
+
let filename = "file";
|
|
105
|
+
const disposition = response.headers["content-disposition"];
|
|
106
|
+
if (disposition && disposition.includes("filename=")) {
|
|
107
|
+
const match = disposition.match(/filename="?([^";]+)"?/);
|
|
108
|
+
if (match && match[1]) {
|
|
109
|
+
filename = match[1];
|
|
110
|
+
}
|
|
111
|
+
} else {
|
|
112
|
+
try {
|
|
113
|
+
const urlObj = new URL(urlOrPath);
|
|
114
|
+
const base = path.basename(urlObj.pathname);
|
|
115
|
+
if (base && base.includes(".")) {
|
|
116
|
+
filename = base;
|
|
117
|
+
}
|
|
118
|
+
} catch (e) {
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const contentType = response.headers["content-type"] || "application/octet-stream";
|
|
122
|
+
const mimeType = contentType.split(";")[0].trim();
|
|
123
|
+
if (!filename.includes(".")) {
|
|
124
|
+
let mimeExtension = (mime) => "";
|
|
125
|
+
try {
|
|
126
|
+
const mimeLib = require("mime-types");
|
|
127
|
+
mimeExtension = (mime) => mimeLib.extension(mime) || "";
|
|
128
|
+
} catch (e) {
|
|
129
|
+
mimeExtension = (mime) => {
|
|
130
|
+
const map = {
|
|
131
|
+
"application/pdf": "pdf",
|
|
132
|
+
"application/msword": "doc",
|
|
133
|
+
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
|
|
134
|
+
"application/vnd.ms-excel": "xls",
|
|
135
|
+
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
|
|
136
|
+
"image/png": "png",
|
|
137
|
+
"image/jpeg": "jpg",
|
|
138
|
+
"text/plain": "txt",
|
|
139
|
+
"application/json": "json"
|
|
140
|
+
};
|
|
141
|
+
return map[mime] || "";
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
const ext = mimeExtension(mimeType);
|
|
145
|
+
if (ext) {
|
|
146
|
+
filename = `${filename}.${ext}`;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return {
|
|
150
|
+
fieldName,
|
|
151
|
+
buffer,
|
|
152
|
+
filename,
|
|
153
|
+
mimeType
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
} catch (err) {
|
|
157
|
+
console.error(`Failed to resolve file URL/path "${urlOrPath}":`, err.message);
|
|
158
|
+
}
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
41
161
|
async execute(pipelineId, input, files = [], userId) {
|
|
42
162
|
const pipelineRepo = this.db.getRepository("doc_understanding_pipelines");
|
|
43
163
|
const jobsRepo = this.db.getRepository("doc_understanding_jobs");
|
|
@@ -59,9 +179,63 @@ class PipelineExecutor {
|
|
|
59
179
|
createdById: userId
|
|
60
180
|
}
|
|
61
181
|
});
|
|
182
|
+
const resolvedFiles = [];
|
|
183
|
+
const tryAddFile = async (urlOrPath, fieldName = "file") => {
|
|
184
|
+
const resolved = await this.resolveFile(urlOrPath, fieldName);
|
|
185
|
+
if (resolved) {
|
|
186
|
+
resolvedFiles.push(resolved);
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
if (Array.isArray(files)) {
|
|
190
|
+
for (const f of files) {
|
|
191
|
+
if (f && typeof f === "object") {
|
|
192
|
+
if (f.buffer) {
|
|
193
|
+
resolvedFiles.push(f);
|
|
194
|
+
} else if (f.url) {
|
|
195
|
+
await tryAddFile(f.url, f.fieldName || "file");
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
const urlFields = ["file_url", "file_urls", "file", "files"];
|
|
201
|
+
for (const key of urlFields) {
|
|
202
|
+
const val = input[key];
|
|
203
|
+
if (!val) continue;
|
|
204
|
+
if (typeof val === "string") {
|
|
205
|
+
if (val.startsWith("http://") || val.startsWith("https://") || val.startsWith("/") || val.startsWith("storage/")) {
|
|
206
|
+
await tryAddFile(val, "file");
|
|
207
|
+
} else if (val.includes(",")) {
|
|
208
|
+
const urls = val.split(",").map((s) => s.trim());
|
|
209
|
+
for (const u of urls) {
|
|
210
|
+
if (u.startsWith("http://") || u.startsWith("https://") || u.startsWith("/") || u.startsWith("storage/")) {
|
|
211
|
+
await tryAddFile(u, "file");
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
} else if (Array.isArray(val)) {
|
|
216
|
+
for (const item of val) {
|
|
217
|
+
if (typeof item === "string") {
|
|
218
|
+
if (item.startsWith("http://") || item.startsWith("https://") || item.startsWith("/") || item.startsWith("storage/")) {
|
|
219
|
+
await tryAddFile(item, "file");
|
|
220
|
+
}
|
|
221
|
+
} else if (item && typeof item === "object" && item.url) {
|
|
222
|
+
await tryAddFile(item.url, "file");
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
} else if (val && typeof val === "object" && val.url) {
|
|
226
|
+
await tryAddFile(val.url, "file");
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
if (resolvedFiles.length === 0 && files && files.length > 0) {
|
|
230
|
+
for (const f of files) {
|
|
231
|
+
if (f.buffer) {
|
|
232
|
+
resolvedFiles.push(f);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
62
236
|
const context = {
|
|
63
237
|
input,
|
|
64
|
-
files,
|
|
238
|
+
files: resolvedFiles,
|
|
65
239
|
stepResults: {},
|
|
66
240
|
jobId: job.id
|
|
67
241
|
};
|
|
@@ -90,10 +264,15 @@ class PipelineExecutor {
|
|
|
90
264
|
let lastError = null;
|
|
91
265
|
while (retries >= 0 && !success) {
|
|
92
266
|
try {
|
|
267
|
+
const fileFieldName = step.endpoint.fileFieldName || "file";
|
|
268
|
+
const mappedFiles = context.files ? context.files.map((f) => ({
|
|
269
|
+
...f,
|
|
270
|
+
fieldName: fileFieldName
|
|
271
|
+
})) : [];
|
|
93
272
|
const result = await this.apiClient.call({
|
|
94
273
|
endpoint: step.endpoint,
|
|
95
274
|
body: mappedBody,
|
|
96
|
-
files:
|
|
275
|
+
files: mappedFiles
|
|
97
276
|
});
|
|
98
277
|
if (step.endpoint.executionMode === "sync") {
|
|
99
278
|
context.stepResults[step.outputAlias || step.stepOrder.toString()] = result.data;
|
|
@@ -29,12 +29,18 @@ __export(document_understanding_tool_exports, {
|
|
|
29
29
|
createDynamicPipelineToolsProvider: () => createDynamicPipelineToolsProvider
|
|
30
30
|
});
|
|
31
31
|
module.exports = __toCommonJS(document_understanding_tool_exports);
|
|
32
|
+
function cloneJson(value) {
|
|
33
|
+
if (value === void 0 || value === null) {
|
|
34
|
+
return value;
|
|
35
|
+
}
|
|
36
|
+
return JSON.parse(JSON.stringify(value));
|
|
37
|
+
}
|
|
32
38
|
function buildToolName(pipelineName) {
|
|
33
39
|
const sanitized = pipelineName.toLowerCase().replace(/[^a-z0-9_]/g, "_").replace(/_+/g, "_").replace(/^_|_$/g, "");
|
|
34
40
|
return `doc_understanding.${sanitized}`;
|
|
35
41
|
}
|
|
36
42
|
function buildSchema(pipeline) {
|
|
37
|
-
const baseSchema = pipeline.inputSchema && Object.keys(pipeline.inputSchema).length > 0 ? pipeline.inputSchema : {
|
|
43
|
+
const baseSchema = pipeline.inputSchema && Object.keys(pipeline.inputSchema).length > 0 ? cloneJson(pipeline.inputSchema) : {
|
|
38
44
|
type: "object",
|
|
39
45
|
properties: {
|
|
40
46
|
input: {
|
|
@@ -52,6 +58,30 @@ function buildSchema(pipeline) {
|
|
|
52
58
|
}
|
|
53
59
|
return baseSchema;
|
|
54
60
|
}
|
|
61
|
+
function applySchemaDefaults(value, schema) {
|
|
62
|
+
if (!schema || typeof schema !== "object") {
|
|
63
|
+
return value;
|
|
64
|
+
}
|
|
65
|
+
if (value === void 0 && Object.prototype.hasOwnProperty.call(schema, "default")) {
|
|
66
|
+
return cloneJson(schema.default);
|
|
67
|
+
}
|
|
68
|
+
const isObjectSchema = schema.type === "object" || schema.properties;
|
|
69
|
+
if (isObjectSchema) {
|
|
70
|
+
const source = value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
|
|
71
|
+
for (const [key, propertySchema] of Object.entries(schema.properties || {})) {
|
|
72
|
+
const currentValue = source[key];
|
|
73
|
+
const nextValue = applySchemaDefaults(currentValue, propertySchema);
|
|
74
|
+
if (nextValue !== void 0) {
|
|
75
|
+
source[key] = nextValue;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return source;
|
|
79
|
+
}
|
|
80
|
+
if (Array.isArray(value) && schema.items) {
|
|
81
|
+
return value.map((item) => applySchemaDefaults(item, schema.items));
|
|
82
|
+
}
|
|
83
|
+
return value;
|
|
84
|
+
}
|
|
55
85
|
function createToolForPipeline(service, pipeline) {
|
|
56
86
|
const stepNames = (pipeline.steps || []).sort((a, b) => a.stepOrder - b.stepOrder).map((s) => s.name).join(" \u2192 ");
|
|
57
87
|
const description = [
|
|
@@ -81,11 +111,15 @@ function createToolForPipeline(service, pipeline) {
|
|
|
81
111
|
if (args.file_urls && Array.isArray(args.file_urls)) {
|
|
82
112
|
files = args.file_urls.map((url) => ({ url }));
|
|
83
113
|
}
|
|
84
|
-
|
|
114
|
+
const hasInputSchema = pipeline.inputSchema && Object.keys(pipeline.inputSchema).length > 0;
|
|
115
|
+
let input = hasInputSchema ? args : args.input || args;
|
|
85
116
|
if (input === args) {
|
|
86
117
|
input = { ...args };
|
|
87
118
|
delete input.file_urls;
|
|
88
119
|
}
|
|
120
|
+
if (hasInputSchema) {
|
|
121
|
+
input = applySchemaDefaults(input, pipeline.inputSchema);
|
|
122
|
+
}
|
|
89
123
|
const { jobId } = await service.executePipeline(pipeline.id, input, files);
|
|
90
124
|
const start = Date.now();
|
|
91
125
|
while (Date.now() - start < maxWait) {
|
|
@@ -95,7 +129,7 @@ function createToolForPipeline(service, pipeline) {
|
|
|
95
129
|
} else if (job.status === "failed" || job.status === "timeout") {
|
|
96
130
|
return { status: job.status, error: job.error };
|
|
97
131
|
}
|
|
98
|
-
await new Promise((
|
|
132
|
+
await new Promise((resolve) => setTimeout(resolve, pollInterval));
|
|
99
133
|
}
|
|
100
134
|
return {
|
|
101
135
|
status: "polling",
|
package/dist/server/types.d.ts
CHANGED
|
@@ -19,6 +19,7 @@ export interface EndpointDef {
|
|
|
19
19
|
requestBodySchema?: any;
|
|
20
20
|
responseSchema?: any;
|
|
21
21
|
fileInputMode: 'none' | 'multipart' | 'base64';
|
|
22
|
+
fileFieldName?: string;
|
|
22
23
|
maxFiles: number;
|
|
23
24
|
executionMode: 'sync' | 'polling' | 'webhook';
|
|
24
25
|
pollResultSubpath?: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "plugin-document-understanding",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.2",
|
|
4
4
|
"main": "dist/server/index.js",
|
|
5
5
|
"dependencies": {
|
|
6
6
|
"axios": "^1.6.0"
|
|
@@ -13,4 +13,4 @@
|
|
|
13
13
|
"@nocobase/plugin-ai": "2.x",
|
|
14
14
|
"@langchain/core": "^0.3.0"
|
|
15
15
|
}
|
|
16
|
-
}
|
|
16
|
+
}
|