bjchy-udg-sdk 1.8.7 → 1.8.9
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 +28 -2
- package/package.json +1 -1
- package/src/ai.js +6 -1
- package/src/documents.js +24 -0
- package/src/index.js +3 -1
- package/src/request.js +70 -7
package/README.md
CHANGED
|
@@ -6,6 +6,10 @@
|
|
|
6
6
|
|
|
7
7
|
## 安装 / 引入
|
|
8
8
|
|
|
9
|
+
[](https://www.npmjs.com/package/bjchy-udg-sdk) <!-- sdk-version -->
|
|
10
|
+
|
|
11
|
+
在项目目录运行 `npm ls bjchy-udg-sdk --depth=0` 查看已安装版本。可用 `npm view bjchy-udg-sdk version` 直接查询 npm 最新版本。
|
|
12
|
+
|
|
9
13
|
已发布到公开 npm:[`bjchy-udg-sdk`](https://www.npmjs.com/package/bjchy-udg-sdk)。三端做法一致:
|
|
10
14
|
|
|
11
15
|
```bash
|
|
@@ -577,7 +581,7 @@ if (client.now() < new Date(activity.bookEnd)) { /* 可以报名 */ }
|
|
|
577
581
|
|
|
578
582
|
- 日期与关系库类型兼容:SDK 与 Gateway 以 `{ $date: 毫秒 }` 传输 `Date`。关系库按实际列类型保存:日期列保持日期,数字/字符列保存毫秒值;布尔写数字/字符列转 `1/0`;带时区的完整 ISO 8601 或 13 位毫秒时间戳写日期列会转 `Date`。不猜 10 位秒时间戳,不自动 JSON 化对象/数组,不截断或舍入;不存在字段仍严格报错
|
|
579
583
|
- `db.serverDate()` V1 以客户端时间近似;需要可信的“当前时间”用 `client.now()`,需要不可伪造的“写入时间”用 Gateway 的 `beforeWrite.autoTimestamps` 钩子
|
|
580
|
-
- distinct /
|
|
584
|
+
- distinct:V1 不提供。DOCX/XLSX 的上传和转换见下节。
|
|
581
585
|
- 集合是首次写入时自动创建的(CloudBase 端也一样,Gateway 会代建并放开集合权限)
|
|
582
586
|
- **建/删索引、删集合**:SDK 不提供(属 DDL 运维动作)。用 Gateway 的 Admin 面接口 `POST /api/execute` + 请求头 `X-Admin-Key`,`action` = `createIndex` / `dropIndex` / `listIndexes` / `dropCollection` / `createCollection`,仅 mongodb / cloudbase 数据源可用。例:
|
|
583
587
|
|
|
@@ -588,6 +592,28 @@ curl -X POST https://udg.vule.cn/api/execute -H 'X-Admin-Key: <ADMIN_KEY>' -H 'C
|
|
|
588
592
|
|
|
589
593
|
`keys` 也可写成 `[{"name":"street","direction":1}]`;方向支持 `1/-1/2d/2dsphere/text/hashed`;不传 `name` 时按 MongoDB 惯例生成索引名;重复创建幂等。`dropCollection` 删非空集合必须显式带 `force:true`(否则报错并告知集合内文档数)。
|
|
590
594
|
|
|
595
|
+
## 文档上传、转换和 AI 解析
|
|
596
|
+
|
|
597
|
+
复用已登录的 `client`。Web 传 `File`,Node 传 `Buffer`、字节数组或 `Blob` 加 `filename`,微信小程序传 `filePath` 与选中文件的 `filename`。小程序须将 UDG 域名同时加入请求和上传合法域名。
|
|
598
|
+
|
|
599
|
+
```js
|
|
600
|
+
// 默认只返回解析结果,文件留存由调用方选择
|
|
601
|
+
const { json } = await client.ai.analyzeDocument({
|
|
602
|
+
file: selectedFile,
|
|
603
|
+
prompt: '提取事项、责任单位、截止日期和原文出处,返回 JSON 对象。',
|
|
604
|
+
json: true
|
|
605
|
+
})
|
|
606
|
+
const { markdown, convertedFiles } = await client.documents.toMarkdown({
|
|
607
|
+
file: selectedFile,
|
|
608
|
+
returnConvertedUrl: true
|
|
609
|
+
})
|
|
610
|
+
const { sheets, file } = await client.documents.toCsv({ file: selectedWorkbook, sheet: '明细', returnOriginalUrl: true })
|
|
611
|
+
```
|
|
612
|
+
|
|
613
|
+
`client.documents.upload({ file })` 单独上传原件,返回 `file.url`。转换和 AI 默认只返回处理结果。`returnOriginalUrl: true` 将原件上传到 syl 并返回 `file.url`。`returnConvertedUrl: true` 将 Markdown 或按工作表生成的 CSV 上传到 syl 并返回 `convertedFiles: [{ name, url }]`。这些是 syl 的公开 URL。AI 接口需租户开启 `aiEnabled`,用途白名单须允许 `document`。省略 `json` 返回 `text`。Excel 省略 `sheet` 时按可见工作表分别输出 CSV,缺少公式缓存时返回 `FORMULA_VALUE_MISSING` 提示。
|
|
614
|
+
|
|
615
|
+
HTTP 的 `POST /api/documents/upload`、`/api/documents/word-to-markdown`、`/api/documents/excel-to-csv`、`/api/ai/document` 使用 Bearer access token。上传采用 `multipart/form-data` 的 `file` 字段,原件为 `.docx` 或 `.xlsx`,上限 10 MiB。转换在网关本机执行,工作目录在转换进程退出后清理。转换输出最多 512 KiB,AI 单次接受最多 48,000 字符的转换数据和 8,000 字符的 `prompt`。每次可上传最多 20 个转换结果。SDK 文档调用默认等待 120 秒,可用 `timeout` 指定毫秒数。部分上传失败时,错误详情包含已经生成的公开路径。
|
|
616
|
+
|
|
591
617
|
## 已注册的网关服务(npm 1.8.5 起)
|
|
592
618
|
|
|
593
619
|
`await client.callService(service, operation, data, { db: 'mongo' })` 调用
|
|
@@ -596,7 +622,7 @@ curl -X POST https://udg.vule.cn/api/execute -H 'X-Admin-Key: <ADMIN_KEY>' -H 'C
|
|
|
596
622
|
`db` 缺省使用 `init.defaultDb`;网关仍须注册具体服务并执行租户授权。
|
|
597
623
|
|
|
598
624
|
本次内置可选 YKBG 扩展(租户 wx7c21e61ce2640cff),支持 capabilities、function、external。
|
|
599
|
-
普通 CRUD
|
|
625
|
+
普通 CRUD 使用 `client.database('mongo')`。YKBG 公开附件使用小程序 `wx.uploadFile` 直传 syl。
|
|
600
626
|
扩展需要配套网关代码和 `YKBG_ENABLED=true`,不是现有已部署接口的保证。
|
|
601
627
|
|
|
602
628
|
### 身份证实名认证公共服务
|
package/package.json
CHANGED
package/src/ai.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* client.ai.*(AI-4.1):租户级 AI 能力,走 Gateway /api/ai/*(JWT 鉴权 + 租户配额)。
|
|
3
3
|
* 需管理员在租户配置中开启 aiEnabled;purpose 仅限 Gateway 预注册模板(防 prompt 注入)。
|
|
4
4
|
*/
|
|
5
|
-
const { post } = require('./request')
|
|
5
|
+
const { post, postDocument } = require('./request')
|
|
6
6
|
|
|
7
7
|
class AiNamespace {
|
|
8
8
|
constructor(ctx) {
|
|
@@ -24,6 +24,11 @@ class AiNamespace {
|
|
|
24
24
|
})
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
/** 上传并解析 DOCX/XLSX,填写 prompt,可选 sheet、json 和返回 syl URL 的选项。 */
|
|
28
|
+
analyzeDocument(options) {
|
|
29
|
+
return postDocument(this._ctx, '/api/ai/document', options)
|
|
30
|
+
}
|
|
31
|
+
|
|
27
32
|
/**
|
|
28
33
|
* 自然语言问数(只读,自动执行)。
|
|
29
34
|
* @param {object} p { collection, question, db? }
|
package/src/documents.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
const { postDocument } = require('./request')
|
|
2
|
+
|
|
3
|
+
class DocumentsNamespace {
|
|
4
|
+
constructor(ctx) {
|
|
5
|
+
this._ctx = ctx
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** 单独上传 DOCX/XLSX 原件,返回 file.url(syl 公共附件 URL)。 */
|
|
9
|
+
upload(options) {
|
|
10
|
+
return postDocument(this._ctx, '/api/documents/upload', options)
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** 转换 DOCX,返回 { file, markdown, warnings }。可选 returnOriginalUrl / returnConvertedUrl。 */
|
|
14
|
+
toMarkdown(options) {
|
|
15
|
+
return postDocument(this._ctx, '/api/documents/word-to-markdown', options)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** 转换 XLSX,可传 sheet,返回 { file, sheets, warnings }。可选 returnOriginalUrl / returnConvertedUrl。 */
|
|
19
|
+
toCsv(options) {
|
|
20
|
+
return postDocument(this._ctx, '/api/documents/excel-to-csv', options)
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
module.exports = { DocumentsNamespace }
|
package/src/index.js
CHANGED
|
@@ -26,6 +26,7 @@ const { command, UdgRegExp } = require('./command')
|
|
|
26
26
|
const { post, rawPost, postAuthed, fetchServerTime, UdgRequestError } = require('./request')
|
|
27
27
|
const { AuthManager } = require('./auth')
|
|
28
28
|
const { AiNamespace } = require('./ai')
|
|
29
|
+
const { DocumentsNamespace } = require('./documents')
|
|
29
30
|
const { WxNamespace } = require('./wx')
|
|
30
31
|
const { MpNamespace } = require('./mp')
|
|
31
32
|
const storage = require('./storage')
|
|
@@ -144,7 +145,8 @@ class UdgClient {
|
|
|
144
145
|
// 外部 token 直入(与现有 JWT 体系互通)
|
|
145
146
|
this._ctx.auth.setExternalToken(o.token)
|
|
146
147
|
}
|
|
147
|
-
// AI
|
|
148
|
+
// 文档上传、转换与 AI 解析。AI 需开通租户 aiEnabled。
|
|
149
|
+
this.documents = new DocumentsNamespace(this._ctx)
|
|
148
150
|
this.ai = new AiNamespace(this._ctx)
|
|
149
151
|
// 微信小程序服务端 API:client.wx.*(需 login;见 docs/wechat-mini-integration.md)
|
|
150
152
|
this.wx = new WxNamespace(this._ctx)
|
package/src/request.js
CHANGED
|
@@ -43,7 +43,7 @@ function requestViaWx(url, body, headers, timeout) {
|
|
|
43
43
|
})
|
|
44
44
|
}
|
|
45
45
|
|
|
46
|
-
async function requestViaFetch(url, body, headers, timeout) {
|
|
46
|
+
async function requestViaFetch(url, body, headers, timeout, multipart = false) {
|
|
47
47
|
if (typeof fetch !== 'function') {
|
|
48
48
|
throw new UdgRequestError({
|
|
49
49
|
errorCode: 'ENV_NOT_SUPPORTED',
|
|
@@ -56,7 +56,7 @@ async function requestViaFetch(url, body, headers, timeout) {
|
|
|
56
56
|
const res = await fetch(url, {
|
|
57
57
|
method: 'POST',
|
|
58
58
|
headers,
|
|
59
|
-
body: JSON.stringify(body),
|
|
59
|
+
body: multipart ? body : JSON.stringify(body),
|
|
60
60
|
signal: controller ? controller.signal : undefined
|
|
61
61
|
})
|
|
62
62
|
let json = null
|
|
@@ -161,9 +161,13 @@ async function rawRequest(ctx, path, body, token) {
|
|
|
161
161
|
if (token) headers.Authorization = 'Bearer ' + token
|
|
162
162
|
const timeout = ctx.timeout || 15000
|
|
163
163
|
const t0 = Date.now()
|
|
164
|
-
const
|
|
164
|
+
const response = isMiniProgram()
|
|
165
165
|
? await requestViaWx(url, encode(body), headers, timeout)
|
|
166
166
|
: await requestViaFetch(url, encode(body), headers, timeout)
|
|
167
|
+
return decodeResponse(ctx, response, t0)
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function decodeResponse(ctx, { status, json }, t0) {
|
|
167
171
|
captureServerTime(ctx, json, t0, Date.now())
|
|
168
172
|
if (!json || json.success !== true) {
|
|
169
173
|
throw new UdgRequestError(
|
|
@@ -190,6 +194,10 @@ function isAuthFailure(err) {
|
|
|
190
194
|
*/
|
|
191
195
|
async function post(ctx, path, payload) {
|
|
192
196
|
const body = Object.assign({ appid: ctx.appid }, payload)
|
|
197
|
+
return withAuth(ctx, token => rawRequest(ctx, path, body, token))
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async function withAuth(ctx, send) {
|
|
193
201
|
const auth = ctx.auth
|
|
194
202
|
const token = auth ? auth.token : ''
|
|
195
203
|
if (!token) {
|
|
@@ -199,14 +207,14 @@ async function post(ctx, path, payload) {
|
|
|
199
207
|
})
|
|
200
208
|
}
|
|
201
209
|
try {
|
|
202
|
-
return await
|
|
210
|
+
return await send(token)
|
|
203
211
|
} catch (err) {
|
|
204
212
|
const authFailed = isAuthFailure(err)
|
|
205
213
|
if (!authFailed || !auth || auth.mode === 'external' || auth.mode === '') throw err
|
|
206
214
|
|
|
207
215
|
// ① 尝试续期
|
|
208
216
|
if (await auth.refresh()) {
|
|
209
|
-
return
|
|
217
|
+
return send(auth.token)
|
|
210
218
|
}
|
|
211
219
|
// ② 续期失败 → 自动重登(wechat / apikey 模式)
|
|
212
220
|
let reloggedIn = false
|
|
@@ -216,12 +224,67 @@ async function post(ctx, path, payload) {
|
|
|
216
224
|
reloggedIn = false
|
|
217
225
|
}
|
|
218
226
|
if (reloggedIn) {
|
|
219
|
-
return
|
|
227
|
+
return send(auth.token)
|
|
220
228
|
}
|
|
221
229
|
throw err
|
|
222
230
|
}
|
|
223
231
|
}
|
|
224
232
|
|
|
233
|
+
function uploadViaWx(url, filePath, fields, headers, timeout) {
|
|
234
|
+
return new Promise((resolve, reject) => {
|
|
235
|
+
wx.uploadFile({
|
|
236
|
+
url, filePath, name: 'file', header: headers, formData: fields, timeout,
|
|
237
|
+
success(res) {
|
|
238
|
+
let json = res.data
|
|
239
|
+
if (typeof json === 'string') {
|
|
240
|
+
try { json = JSON.parse(json) } catch { json = null }
|
|
241
|
+
}
|
|
242
|
+
resolve({ status: res.statusCode, json })
|
|
243
|
+
},
|
|
244
|
+
fail(err) {
|
|
245
|
+
reject(new UdgRequestError({ errorCode: 'NETWORK_ERROR', errorMessage: err.errMsg || '文件上传失败' }))
|
|
246
|
+
}
|
|
247
|
+
})
|
|
248
|
+
})
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** 文档接口仅对上传使用 multipart,复用同一份 SDK 鉴权、续期和响应解析。 */
|
|
252
|
+
async function postDocument(ctx, path, options = {}) {
|
|
253
|
+
const { file, filePath, filename, timeout = 120000, ...params } = options
|
|
254
|
+
if ([file, filePath].filter(value => value !== undefined && value !== null).length !== 1) {
|
|
255
|
+
throw new UdgRequestError({ errorCode: 'INVALID_PARAM', errorMessage: '请选择 file 或 filePath 中的一项' })
|
|
256
|
+
}
|
|
257
|
+
const fields = { ...params, appid: ctx.appid || undefined }
|
|
258
|
+
const url = ctx.endpoint.replace(/\/+$/, '') + path
|
|
259
|
+
const multipartFields = Object.fromEntries(Object.entries({ ...fields, filename })
|
|
260
|
+
.filter(([, value]) => value !== undefined && value !== null && value !== '')
|
|
261
|
+
.map(([key, value]) => [key, String(value)]))
|
|
262
|
+
let form
|
|
263
|
+
if (isMiniProgram()) {
|
|
264
|
+
if (typeof filePath !== 'string' || !filePath || typeof wx.uploadFile !== 'function') {
|
|
265
|
+
throw new UdgRequestError({ errorCode: 'INVALID_PARAM', errorMessage: '微信小程序上传需要 filePath' })
|
|
266
|
+
}
|
|
267
|
+
} else {
|
|
268
|
+
const isBlob = typeof Blob !== 'undefined' && file instanceof Blob
|
|
269
|
+
const isBytes = ArrayBuffer.isView(file) || file instanceof ArrayBuffer
|
|
270
|
+
const name = filename || (isBlob && file.name)
|
|
271
|
+
if (typeof FormData !== 'function' || !(isBlob || isBytes) || !name) {
|
|
272
|
+
throw new UdgRequestError({ errorCode: 'INVALID_PARAM', errorMessage: 'Web/Node 上传需要 File,或文件字节和 filename' })
|
|
273
|
+
}
|
|
274
|
+
form = new FormData()
|
|
275
|
+
for (const [key, value] of Object.entries(multipartFields)) form.append(key, value)
|
|
276
|
+
form.append('file', isBlob ? file : new Blob([file]), name)
|
|
277
|
+
}
|
|
278
|
+
return withAuth(ctx, async token => {
|
|
279
|
+
const headers = { Authorization: 'Bearer ' + token }
|
|
280
|
+
const started = Date.now()
|
|
281
|
+
const response = form
|
|
282
|
+
? await requestViaFetch(url, form, headers, timeout, true)
|
|
283
|
+
: await uploadViaWx(url, filePath, multipartFields, headers, timeout)
|
|
284
|
+
return decodeResponse(ctx, response, started)
|
|
285
|
+
})
|
|
286
|
+
}
|
|
287
|
+
|
|
225
288
|
/** 带鉴权的 auth 类请求(如 scan/approve,需要已登录),不注入 dataSource */
|
|
226
289
|
async function postAuthed(ctx, path, payload) {
|
|
227
290
|
const auth = ctx.auth
|
|
@@ -239,4 +302,4 @@ async function postAuthed(ctx, path, payload) {
|
|
|
239
302
|
}
|
|
240
303
|
}
|
|
241
304
|
|
|
242
|
-
module.exports = { post, postAuthed, rawGet, rawPost, rawRequest, fetchServerTime, UdgRequestError }
|
|
305
|
+
module.exports = { post, postAuthed, postDocument, rawGet, rawPost, rawRequest, fetchServerTime, UdgRequestError }
|