@cn-quickotp/k3cloud-webapi-sdk 0.0.0-stage → 1.0.1
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/CHANGELOG.md +168 -0
- package/LICENSE +102 -0
- package/README.md +104 -2
- package/dist/index.js +1751 -0
- package/package.json +66 -4
- package/types/index.d.ts +99 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1751 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
function getDefaultExportFromCjs (x) {
|
|
4
|
+
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
var version;
|
|
8
|
+
var hasRequiredVersion;
|
|
9
|
+
|
|
10
|
+
function requireVersion () {
|
|
11
|
+
if (hasRequiredVersion) return version;
|
|
12
|
+
hasRequiredVersion = 1;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* SDK 版本号,与 package.json 的 version 保持一致。
|
|
16
|
+
* @type {string}
|
|
17
|
+
*/
|
|
18
|
+
const SDK_VERSION = '1.0.1';
|
|
19
|
+
|
|
20
|
+
version = { SDK_VERSION };
|
|
21
|
+
return version;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
var errors;
|
|
25
|
+
var hasRequiredErrors;
|
|
26
|
+
|
|
27
|
+
function requireErrors () {
|
|
28
|
+
if (hasRequiredErrors) return errors;
|
|
29
|
+
hasRequiredErrors = 1;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* SDK 错误类型与错误码分类。
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
/** 错误码分类 */
|
|
36
|
+
const ERROR_CODES = Object.freeze({
|
|
37
|
+
NETWORK: 'NETWORK',
|
|
38
|
+
TIMEOUT: 'TIMEOUT',
|
|
39
|
+
HTTP: 'HTTP',
|
|
40
|
+
AUTH: 'AUTH',
|
|
41
|
+
SESSION: 'SESSION',
|
|
42
|
+
BUSINESS: 'BUSINESS',
|
|
43
|
+
PARSE: 'PARSE',
|
|
44
|
+
VALIDATION: 'VALIDATION',
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* SDK 统一错误类型。
|
|
49
|
+
*
|
|
50
|
+
* 除 `code`、`message`、`cause` 外,构造时可传入任意附加字段,
|
|
51
|
+
* 统一挂到 `details` 上,供上层保留原始响应等上下文。
|
|
52
|
+
*/
|
|
53
|
+
class K3CloudError extends Error {
|
|
54
|
+
/**
|
|
55
|
+
* @param {string} code 错误码,取自 {@link ERROR_CODES}
|
|
56
|
+
* @param {string} message 错误信息
|
|
57
|
+
* @param {object} [options] 附加选项;`cause` 为原始错误,其余字段进入 `details`
|
|
58
|
+
*/
|
|
59
|
+
constructor(code, message, options = {}) {
|
|
60
|
+
const opts = options && typeof options === 'object' ? options : {};
|
|
61
|
+
super(message, opts);
|
|
62
|
+
this.name = 'K3CloudError';
|
|
63
|
+
this.code = code;
|
|
64
|
+
this.cause = opts.cause;
|
|
65
|
+
this.details = Object.assign({}, opts);
|
|
66
|
+
delete this.details.cause;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
errors = { K3CloudError, ERROR_CODES };
|
|
71
|
+
return errors;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
var constants;
|
|
75
|
+
var hasRequiredConstants;
|
|
76
|
+
|
|
77
|
+
function requireConstants () {
|
|
78
|
+
if (hasRequiredConstants) return constants;
|
|
79
|
+
hasRequiredConstants = 1;
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* 协议常量、默认值与请求封装。
|
|
83
|
+
*
|
|
84
|
+
* 本文件是协议相关取值的单一事实来源:endpoint 拼装、服务/方法名、
|
|
85
|
+
* 默认配置与请求封装字段均在此定义,协议变更只需改动此处。
|
|
86
|
+
*/
|
|
87
|
+
|
|
88
|
+
/** endpoint 前缀:服务名之前的部分 */
|
|
89
|
+
const ENDPOINT_PREFIX = 'Kingdee.BOS.WebApi.ServicesStub.';
|
|
90
|
+
|
|
91
|
+
/** endpoint 后缀:方法名之后的部分 */
|
|
92
|
+
const ENDPOINT_SUFFIX = '.common.kdsvc';
|
|
93
|
+
|
|
94
|
+
/** 服务名 */
|
|
95
|
+
const SERVICES = Object.freeze({
|
|
96
|
+
AUTH: 'AuthService',
|
|
97
|
+
DYNAMIC_FORM: 'DynamicFormService',
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
/** 服务方法名 */
|
|
101
|
+
const METHODS = Object.freeze({
|
|
102
|
+
VALIDATE_USER: 'ValidateUser',
|
|
103
|
+
LOGIN_BY_APP_SECRET: 'LoginByAppSecret',
|
|
104
|
+
LOGOUT: 'Logout',
|
|
105
|
+
QUERY_BUSINESS_INFO: 'QueryBusinessInfo',
|
|
106
|
+
EXECUTE_BILL_QUERY: 'ExecuteBillQuery',
|
|
107
|
+
SAVE: 'Save',
|
|
108
|
+
VIEW: 'View',
|
|
109
|
+
SUBMIT: 'Submit',
|
|
110
|
+
AUDIT: 'Audit',
|
|
111
|
+
UN_AUDIT: 'UnAudit',
|
|
112
|
+
DELETE: 'Delete',
|
|
113
|
+
BATCH_SAVE: 'BatchSave',
|
|
114
|
+
PUSH: 'Push',
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
/** 默认配置值 */
|
|
118
|
+
const DEFAULTS = Object.freeze({
|
|
119
|
+
timeout: 30000,
|
|
120
|
+
retries: 3,
|
|
121
|
+
retryBaseDelay: 500,
|
|
122
|
+
format: 1,
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
/** 请求封装字段名 */
|
|
126
|
+
const ENVELOPE_FIELDS = Object.freeze({
|
|
127
|
+
FORMAT: 'format',
|
|
128
|
+
USER_AGENT: 'useragent',
|
|
129
|
+
REQUEST_ID: 'rid',
|
|
130
|
+
PARAMETERS: 'parameters',
|
|
131
|
+
TIMESTAMP: 'timestamp',
|
|
132
|
+
VERSION: 'v',
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
/** 请求封装固定值 */
|
|
136
|
+
const ENVELOPE_VALUES = Object.freeze({
|
|
137
|
+
USER_AGENT: 'ApiClient',
|
|
138
|
+
VERSION: '1.0',
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
/** 需要脱敏的敏感字段名 */
|
|
142
|
+
const SENSITIVE_FIELDS = Object.freeze(['appSec', 'password']);
|
|
143
|
+
|
|
144
|
+
/** 脱敏占位符 */
|
|
145
|
+
const REDACTED = '***';
|
|
146
|
+
|
|
147
|
+
/** 配置项对应的环境变量名 */
|
|
148
|
+
const ENV_KEYS = Object.freeze({
|
|
149
|
+
serverUrl: 'K3CLOUD_SERVER_URL',
|
|
150
|
+
acctId: 'K3CLOUD_ACCT_ID',
|
|
151
|
+
username: 'K3CLOUD_USERNAME',
|
|
152
|
+
password: 'K3CLOUD_PASSWORD',
|
|
153
|
+
appKey: 'K3CLOUD_APP_KEY',
|
|
154
|
+
appSec: 'K3CLOUD_APP_SEC',
|
|
155
|
+
lang: 'K3CLOUD_LANG',
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
/** 配置项在浏览器 localStorage 中的键名 */
|
|
159
|
+
const STORAGE_KEYS = Object.freeze({
|
|
160
|
+
serverUrl: 'k3cloud.serverUrl',
|
|
161
|
+
acctId: 'k3cloud.acctId',
|
|
162
|
+
username: 'k3cloud.username',
|
|
163
|
+
password: 'k3cloud.password',
|
|
164
|
+
appKey: 'k3cloud.appKey',
|
|
165
|
+
appSec: 'k3cloud.appSec',
|
|
166
|
+
lang: 'k3cloud.lang',
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* 拼装服务 endpoint。
|
|
171
|
+
* @param {string} service 服务名,如 `DynamicFormService`
|
|
172
|
+
* @param {string} method 方法名,如 `Save`
|
|
173
|
+
* @returns {string}
|
|
174
|
+
*/
|
|
175
|
+
function buildEndpoint(service, method) {
|
|
176
|
+
return `${ENDPOINT_PREFIX}${service}.${method}${ENDPOINT_SUFFIX}`;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* 构造请求封装。
|
|
181
|
+
* @param {*} parameters 业务参数(通常为参数数组)
|
|
182
|
+
* @returns {{ parameters: string }}
|
|
183
|
+
*/
|
|
184
|
+
function buildEnvelope(parameters) {
|
|
185
|
+
const args = parameters === undefined ? [] : parameters;
|
|
186
|
+
return { [ENVELOPE_FIELDS.PARAMETERS]: JSON.stringify(args) };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
constants = {
|
|
190
|
+
ENDPOINT_PREFIX,
|
|
191
|
+
ENDPOINT_SUFFIX,
|
|
192
|
+
SERVICES,
|
|
193
|
+
METHODS,
|
|
194
|
+
DEFAULTS,
|
|
195
|
+
ENVELOPE_FIELDS,
|
|
196
|
+
ENVELOPE_VALUES,
|
|
197
|
+
SENSITIVE_FIELDS,
|
|
198
|
+
REDACTED,
|
|
199
|
+
ENV_KEYS,
|
|
200
|
+
STORAGE_KEYS,
|
|
201
|
+
buildEndpoint,
|
|
202
|
+
buildEnvelope,
|
|
203
|
+
};
|
|
204
|
+
return constants;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
var config;
|
|
208
|
+
var hasRequiredConfig;
|
|
209
|
+
|
|
210
|
+
function requireConfig () {
|
|
211
|
+
if (hasRequiredConfig) return config;
|
|
212
|
+
hasRequiredConfig = 1;
|
|
213
|
+
|
|
214
|
+
const { DEFAULTS, ENV_KEYS } = requireConstants();
|
|
215
|
+
const { K3CloudError, ERROR_CODES } = requireErrors();
|
|
216
|
+
|
|
217
|
+
/** 默认配置 */
|
|
218
|
+
const DEFAULT_CONFIG = Object.freeze({
|
|
219
|
+
serverUrl: 'http://localhost/K3Cloud/',
|
|
220
|
+
acctId: '',
|
|
221
|
+
username: '',
|
|
222
|
+
password: '',
|
|
223
|
+
appKey: '',
|
|
224
|
+
appSec: '',
|
|
225
|
+
lang: 2052,
|
|
226
|
+
timeout: DEFAULTS.timeout,
|
|
227
|
+
retries: DEFAULTS.retries,
|
|
228
|
+
retryBaseDelay: DEFAULTS.retryBaseDelay,
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
/** 必填配置项 */
|
|
232
|
+
const REQUIRED_FIELDS = Object.freeze([
|
|
233
|
+
'serverUrl',
|
|
234
|
+
'acctId',
|
|
235
|
+
'username',
|
|
236
|
+
'password',
|
|
237
|
+
'appKey',
|
|
238
|
+
'appSec',
|
|
239
|
+
]);
|
|
240
|
+
|
|
241
|
+
/** 配置来源的优先级顺序(低 → 高) */
|
|
242
|
+
const SOURCE_ORDER = Object.freeze(['envFile', 'env', 'explicit']);
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* 补齐 `serverUrl` 结尾的 `/`。
|
|
246
|
+
* @param {string} serverUrl
|
|
247
|
+
* @returns {string}
|
|
248
|
+
*/
|
|
249
|
+
function normalizeServerUrl(serverUrl) {
|
|
250
|
+
if (typeof serverUrl !== 'string' || serverUrl === '') return serverUrl;
|
|
251
|
+
return serverUrl.endsWith('/') ? serverUrl : `${serverUrl}/`;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* 将数字字符串形式的 `lang` 归一化为数值。
|
|
256
|
+
* @param {*} lang
|
|
257
|
+
* @returns {*}
|
|
258
|
+
*/
|
|
259
|
+
function normalizeLang(lang) {
|
|
260
|
+
if (typeof lang === 'string' && lang.trim() !== '') {
|
|
261
|
+
const numeric = Number(lang);
|
|
262
|
+
if (Number.isFinite(numeric)) return numeric;
|
|
263
|
+
}
|
|
264
|
+
return lang;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* 按优先级合并配置来源(默认值 < `.env` < 环境变量 < 显式传入),不做必填校验。
|
|
269
|
+
* @param {{ envFile?: object, env?: object, explicit?: object }} sources
|
|
270
|
+
* @returns {object}
|
|
271
|
+
*/
|
|
272
|
+
function mergeConfig(sources = {}) {
|
|
273
|
+
const config = { ...DEFAULT_CONFIG };
|
|
274
|
+
for (const name of SOURCE_ORDER) {
|
|
275
|
+
const source = sources[name];
|
|
276
|
+
if (!source || typeof source !== 'object') continue;
|
|
277
|
+
for (const [key, value] of Object.entries(source)) {
|
|
278
|
+
if (value !== undefined) config[key] = value;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
config.serverUrl = normalizeServerUrl(config.serverUrl);
|
|
282
|
+
config.lang = normalizeLang(config.lang);
|
|
283
|
+
return config;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* 校验必填配置项,缺失时抛出 `VALIDATION` 错误并列出全部缺失字段。
|
|
288
|
+
* @param {object} config
|
|
289
|
+
*/
|
|
290
|
+
function validateConfig(config) {
|
|
291
|
+
const missing = REQUIRED_FIELDS.filter((field) => {
|
|
292
|
+
const value = config[field];
|
|
293
|
+
return value === undefined || value === null || value === '';
|
|
294
|
+
});
|
|
295
|
+
if (missing.length > 0) {
|
|
296
|
+
throw new K3CloudError(ERROR_CODES.VALIDATION, `缺少必填配置项: ${missing.join(', ')}`, {
|
|
297
|
+
missing,
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* 从环境变量记录中提取已知配置项(按 `ENV_KEYS` 映射)。
|
|
304
|
+
* @param {Object<string, string>} record
|
|
305
|
+
* @returns {object}
|
|
306
|
+
*/
|
|
307
|
+
function fromEnvVars(record) {
|
|
308
|
+
const config = {};
|
|
309
|
+
const source = record && typeof record === 'object' ? record : {};
|
|
310
|
+
for (const [field, envName] of Object.entries(ENV_KEYS)) {
|
|
311
|
+
const value = source[envName];
|
|
312
|
+
if (value !== undefined && value !== '') config[field] = value;
|
|
313
|
+
}
|
|
314
|
+
return config;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* 构建配置:合并来源 → 归一化 → 必填校验。
|
|
319
|
+
* @param {{ envFile?: object, env?: object, explicit?: object }} sources
|
|
320
|
+
* @param {{ validate?: boolean }} [options] 传 `{ validate: false }` 可跳过必填校验
|
|
321
|
+
* @returns {object}
|
|
322
|
+
*/
|
|
323
|
+
function buildConfig(sources = {}, options = {}) {
|
|
324
|
+
const config = mergeConfig(sources);
|
|
325
|
+
if (options.validate !== false) validateConfig(config);
|
|
326
|
+
return config;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
config = {
|
|
330
|
+
DEFAULT_CONFIG,
|
|
331
|
+
REQUIRED_FIELDS,
|
|
332
|
+
SOURCE_ORDER,
|
|
333
|
+
normalizeServerUrl,
|
|
334
|
+
normalizeLang,
|
|
335
|
+
mergeConfig,
|
|
336
|
+
validateConfig,
|
|
337
|
+
fromEnvVars,
|
|
338
|
+
buildConfig,
|
|
339
|
+
};
|
|
340
|
+
return config;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
var retry;
|
|
344
|
+
var hasRequiredRetry;
|
|
345
|
+
|
|
346
|
+
function requireRetry () {
|
|
347
|
+
if (hasRequiredRetry) return retry;
|
|
348
|
+
hasRequiredRetry = 1;
|
|
349
|
+
|
|
350
|
+
const { K3CloudError, ERROR_CODES } = requireErrors();
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* 计算第 n 次重试的退避延时(毫秒)。
|
|
354
|
+
*
|
|
355
|
+
* 间隔按 `retryBaseDelay * 2^n` 递增,n 从 0 开始。
|
|
356
|
+
*
|
|
357
|
+
* @param {number} attempt 重试序号,从 0 开始
|
|
358
|
+
* @param {number} baseDelay 基础延时(毫秒)
|
|
359
|
+
* @returns {number}
|
|
360
|
+
*/
|
|
361
|
+
function backoffDelay(attempt, baseDelay) {
|
|
362
|
+
const n = Number.isFinite(attempt) && attempt > 0 ? Math.floor(attempt) : 0;
|
|
363
|
+
const base = Number.isFinite(baseDelay) && baseDelay > 0 ? baseDelay : 0;
|
|
364
|
+
return base * 2 ** n;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/**
|
|
368
|
+
* 等待指定毫秒后 resolve。
|
|
369
|
+
* @param {number} ms 延时(毫秒)
|
|
370
|
+
* @returns {Promise<void>}
|
|
371
|
+
*/
|
|
372
|
+
function delay(ms) {
|
|
373
|
+
return new Promise((resolve) => {
|
|
374
|
+
setTimeout(resolve, ms);
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* 判断错误是否值得重试。
|
|
380
|
+
*
|
|
381
|
+
* 仅网络错误与 5xx 响应可重试;超时、4xx、解析失败与业务错误均不重试,
|
|
382
|
+
* 避免对非幂等接口造成重复写入。
|
|
383
|
+
*
|
|
384
|
+
* @param {K3CloudError} err
|
|
385
|
+
* @returns {boolean}
|
|
386
|
+
*/
|
|
387
|
+
function isRetryable(err) {
|
|
388
|
+
if (!(err instanceof K3CloudError)) return false;
|
|
389
|
+
if (err.code === ERROR_CODES.NETWORK) return true;
|
|
390
|
+
if (err.code === ERROR_CODES.HTTP) {
|
|
391
|
+
const status = Number(err.details && err.details.status);
|
|
392
|
+
return Number.isFinite(status) && status >= 500;
|
|
393
|
+
}
|
|
394
|
+
return false;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
retry = { backoffDelay, delay, isRetryable };
|
|
398
|
+
return retry;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
var logger;
|
|
402
|
+
var hasRequiredLogger;
|
|
403
|
+
|
|
404
|
+
function requireLogger () {
|
|
405
|
+
if (hasRequiredLogger) return logger;
|
|
406
|
+
hasRequiredLogger = 1;
|
|
407
|
+
|
|
408
|
+
const { SENSITIVE_FIELDS, REDACTED } = requireConstants();
|
|
409
|
+
|
|
410
|
+
/** 日志级别,即日志器接口约定 */
|
|
411
|
+
const LOG_LEVELS = Object.freeze(['debug', 'info', 'warn', 'error']);
|
|
412
|
+
|
|
413
|
+
/** 无操作函数 */
|
|
414
|
+
function noop() {}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* 空实现日志器:所有级别均为无操作,作为未注入日志器时的默认值。
|
|
418
|
+
*/
|
|
419
|
+
const nullLogger = Object.freeze({
|
|
420
|
+
debug: noop,
|
|
421
|
+
info: noop,
|
|
422
|
+
warn: noop,
|
|
423
|
+
error: noop,
|
|
424
|
+
});
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* 判断是否为普通对象(排除 `Error`、`Date` 等内置实例)。
|
|
428
|
+
* @param {*} value
|
|
429
|
+
* @returns {boolean}
|
|
430
|
+
*/
|
|
431
|
+
function isPlainObject(value) {
|
|
432
|
+
if (value === null || typeof value !== 'object') return false;
|
|
433
|
+
const proto = Object.getPrototypeOf(value);
|
|
434
|
+
return proto === Object.prototype || proto === null;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* 递归脱敏记录:敏感字段替换为占位符,返回新对象,不修改入参。
|
|
439
|
+
* @param {*} record
|
|
440
|
+
* @returns {*}
|
|
441
|
+
*/
|
|
442
|
+
function redactRecord(record) {
|
|
443
|
+
if (Array.isArray(record)) return record.map(redactRecord);
|
|
444
|
+
if (!isPlainObject(record)) return record;
|
|
445
|
+
const result = {};
|
|
446
|
+
for (const key of Object.keys(record)) {
|
|
447
|
+
const value = record[key];
|
|
448
|
+
result[key] = SENSITIVE_FIELDS.indexOf(key) !== -1 ? REDACTED : redactRecord(value);
|
|
449
|
+
}
|
|
450
|
+
return result;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* 写出一条日志记录:脱敏后交给日志器;日志器缺失该级别时静默跳过。
|
|
455
|
+
* @param {object|null|undefined} logger
|
|
456
|
+
* @param {'debug'|'info'|'warn'|'error'} level
|
|
457
|
+
* @param {object} record
|
|
458
|
+
*/
|
|
459
|
+
function logRecord(logger, level, record) {
|
|
460
|
+
if (logger && typeof logger[level] === 'function') logger[level](redactRecord(record));
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* 由输出目标创建日志器:级别缺失时为无操作;目标缺失时返回空实现。
|
|
465
|
+
* @param {object} [sink] 输出目标,可含 `debug` / `info` / `warn` / `error` 方法
|
|
466
|
+
* @returns {{debug: Function, info: Function, warn: Function, error: Function}}
|
|
467
|
+
*/
|
|
468
|
+
function createLogger(sink) {
|
|
469
|
+
const target = sink && typeof sink === 'object' ? sink : null;
|
|
470
|
+
if (target === null) return nullLogger;
|
|
471
|
+
const logger = {};
|
|
472
|
+
for (const level of LOG_LEVELS) {
|
|
473
|
+
logger[level] = (record) => logRecord(target, level, record);
|
|
474
|
+
}
|
|
475
|
+
return Object.freeze(logger);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* 创建请求日志埋点:在请求开始、成功、失败三个时机各写出一条记录。
|
|
480
|
+
* @param {object|null} logger
|
|
481
|
+
* @param {object} context
|
|
482
|
+
* @param {string} context.rid 请求标识
|
|
483
|
+
* @param {string} context.endpoint 服务 endpoint
|
|
484
|
+
* @param {number} context.startedAt 起始时间戳
|
|
485
|
+
* @returns {{start: Function, success: Function, failure: Function}}
|
|
486
|
+
*/
|
|
487
|
+
function createRequestLog(logger, context) {
|
|
488
|
+
const ctx = context && typeof context === 'object' ? context : {};
|
|
489
|
+
const rid = ctx.rid;
|
|
490
|
+
const endpoint = ctx.endpoint;
|
|
491
|
+
const startedAt = Number.isFinite(ctx.startedAt) ? ctx.startedAt : Date.now();
|
|
492
|
+
return {
|
|
493
|
+
start() {
|
|
494
|
+
logRecord(logger, 'debug', { rid, endpoint, elapsed: 0, phase: 'start' });
|
|
495
|
+
},
|
|
496
|
+
success() {
|
|
497
|
+
logRecord(logger, 'info', {
|
|
498
|
+
rid,
|
|
499
|
+
endpoint,
|
|
500
|
+
elapsed: Date.now() - startedAt,
|
|
501
|
+
phase: 'success',
|
|
502
|
+
});
|
|
503
|
+
},
|
|
504
|
+
failure(code) {
|
|
505
|
+
logRecord(logger, 'error', {
|
|
506
|
+
rid,
|
|
507
|
+
endpoint,
|
|
508
|
+
elapsed: Date.now() - startedAt,
|
|
509
|
+
phase: 'failure',
|
|
510
|
+
code,
|
|
511
|
+
});
|
|
512
|
+
},
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
logger = {
|
|
517
|
+
LOG_LEVELS,
|
|
518
|
+
nullLogger,
|
|
519
|
+
createLogger,
|
|
520
|
+
redactRecord,
|
|
521
|
+
logRecord,
|
|
522
|
+
createRequestLog,
|
|
523
|
+
};
|
|
524
|
+
return logger;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
var request_1;
|
|
528
|
+
var hasRequiredRequest;
|
|
529
|
+
|
|
530
|
+
function requireRequest () {
|
|
531
|
+
if (hasRequiredRequest) return request_1;
|
|
532
|
+
hasRequiredRequest = 1;
|
|
533
|
+
|
|
534
|
+
const { K3CloudError, ERROR_CODES } = requireErrors();
|
|
535
|
+
const { DEFAULTS, ENVELOPE_FIELDS, ENVELOPE_VALUES, buildEnvelope } = requireConstants();
|
|
536
|
+
const { backoffDelay, delay, isRetryable } = requireRetry();
|
|
537
|
+
const { createRequestLog, nullLogger } = requireLogger();
|
|
538
|
+
|
|
539
|
+
/** 解析失败时保留的原始文本最大长度 */
|
|
540
|
+
const RAW_TEXT_LIMIT = 200;
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* 生成 32 位十六进制请求标识。
|
|
544
|
+
* @returns {string}
|
|
545
|
+
*/
|
|
546
|
+
function generateRid() {
|
|
547
|
+
let rid = '';
|
|
548
|
+
for (let i = 0; i < 32; i += 1) {
|
|
549
|
+
rid += Math.floor(Math.random() * 16).toString(16);
|
|
550
|
+
}
|
|
551
|
+
return rid;
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/**
|
|
555
|
+
* 截断文本,保留前 limit 个字符。
|
|
556
|
+
* @param {*} text
|
|
557
|
+
* @param {number} [limit]
|
|
558
|
+
* @returns {string}
|
|
559
|
+
*/
|
|
560
|
+
function truncate(text, limit = RAW_TEXT_LIMIT) {
|
|
561
|
+
if (text === undefined || text === null) return '';
|
|
562
|
+
const value = typeof text === 'string' ? text : String(text);
|
|
563
|
+
return value.length > limit ? value.slice(0, limit) : value;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/**
|
|
567
|
+
* 构造完整请求封装,字段与采集报文保持一致。
|
|
568
|
+
* @param {*} parameters 业务参数
|
|
569
|
+
* @param {object} config 传输配置(取 `format`)
|
|
570
|
+
* @param {string} rid 请求标识
|
|
571
|
+
* @returns {object}
|
|
572
|
+
*/
|
|
573
|
+
function buildRequestBody(parameters, config, rid) {
|
|
574
|
+
const { parameters: serialized } = buildEnvelope(parameters);
|
|
575
|
+
return {
|
|
576
|
+
[ENVELOPE_FIELDS.FORMAT]: config.format,
|
|
577
|
+
[ENVELOPE_FIELDS.USER_AGENT]: ENVELOPE_VALUES.USER_AGENT,
|
|
578
|
+
[ENVELOPE_FIELDS.REQUEST_ID]: rid,
|
|
579
|
+
[ENVELOPE_FIELDS.PARAMETERS]: serialized,
|
|
580
|
+
[ENVELOPE_FIELDS.TIMESTAMP]: new Date().toISOString(),
|
|
581
|
+
[ENVELOPE_FIELDS.VERSION]: ENVELOPE_VALUES.VERSION,
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* 读取响应文本,兼容 `text()` 与 `body` 两种替身形态。
|
|
587
|
+
* @param {object} response
|
|
588
|
+
* @returns {Promise<string>}
|
|
589
|
+
*/
|
|
590
|
+
async function readText(response) {
|
|
591
|
+
if (typeof response.text === 'function') return response.text();
|
|
592
|
+
if (typeof response.body === 'string') return response.body;
|
|
593
|
+
return '';
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/**
|
|
597
|
+
* 把响应归一化为解析后的 JSON,并把状态码与解析失败映射为错误。
|
|
598
|
+
* @param {object} response
|
|
599
|
+
* @returns {Promise<*>}
|
|
600
|
+
*/
|
|
601
|
+
async function handleResponse(response) {
|
|
602
|
+
if (!response || typeof response !== 'object' || typeof response.status !== 'number') {
|
|
603
|
+
throw new K3CloudError(ERROR_CODES.NETWORK, '传输层返回了非法响应');
|
|
604
|
+
}
|
|
605
|
+
const status = response.status;
|
|
606
|
+
|
|
607
|
+
let text = '';
|
|
608
|
+
try {
|
|
609
|
+
text = await readText(response);
|
|
610
|
+
} catch (cause) {
|
|
611
|
+
throw new K3CloudError(ERROR_CODES.NETWORK, '响应体读取失败', { cause });
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
if (status < 200 || status >= 300) {
|
|
615
|
+
throw new K3CloudError(ERROR_CODES.HTTP, `HTTP ${status}`, {
|
|
616
|
+
status,
|
|
617
|
+
body: truncate(text),
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
try {
|
|
622
|
+
return JSON.parse(text);
|
|
623
|
+
} catch (cause) {
|
|
624
|
+
const raw = truncate(text);
|
|
625
|
+
throw new K3CloudError(ERROR_CODES.PARSE, `响应体不是合法 JSON: ${raw}`, { raw, cause });
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* 创建 `AbortController`,环境不支持时返回 `null`(超时仍由定时器兜底)。
|
|
631
|
+
* @returns {AbortController|null}
|
|
632
|
+
*/
|
|
633
|
+
function createAbortController() {
|
|
634
|
+
const Impl = globalThis.AbortController;
|
|
635
|
+
if (typeof Impl !== 'function') return null;
|
|
636
|
+
return new Impl();
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/**
|
|
640
|
+
* 执行一次请求:POST + 超时控制 + 响应归一化。
|
|
641
|
+
*
|
|
642
|
+
* 超时由定时器与 `AbortController` 双重保证:定时器置 `timedOut` 标志并中止
|
|
643
|
+
* 底层连接,响应慢于 `timeout` 时无论替身是否响应 abort,都会归入 `TIMEOUT`。
|
|
644
|
+
*
|
|
645
|
+
* @param {object} options
|
|
646
|
+
* @returns {Promise<*>}
|
|
647
|
+
*/
|
|
648
|
+
async function sendOnce({ url, body, config, fetchImpl }) {
|
|
649
|
+
const timeout = Number.isFinite(config.timeout) ? config.timeout : DEFAULTS.timeout;
|
|
650
|
+
const controller = createAbortController();
|
|
651
|
+
const init = {
|
|
652
|
+
method: 'POST',
|
|
653
|
+
headers: { 'Content-Type': 'application/json' },
|
|
654
|
+
body: JSON.stringify(body),
|
|
655
|
+
};
|
|
656
|
+
if (controller !== null) init.signal = controller.signal;
|
|
657
|
+
|
|
658
|
+
let timer = null;
|
|
659
|
+
let timedOut = false;
|
|
660
|
+
const timerPromise = new Promise((resolve, reject) => {
|
|
661
|
+
timer = setTimeout(() => {
|
|
662
|
+
timedOut = true;
|
|
663
|
+
if (controller !== null) controller.abort();
|
|
664
|
+
// 推迟到微任务,让 abort 事件先于超时拒绝传播
|
|
665
|
+
Promise.resolve().then(() => {
|
|
666
|
+
reject(new K3CloudError(ERROR_CODES.TIMEOUT, `请求超时(${timeout}ms)`));
|
|
667
|
+
});
|
|
668
|
+
}, timeout);
|
|
669
|
+
});
|
|
670
|
+
|
|
671
|
+
try {
|
|
672
|
+
// 延迟到微任务再调用,确保替身同步抛错也被归一化
|
|
673
|
+
const fetchPromise = Promise.resolve().then(() => fetchImpl(url, init));
|
|
674
|
+
const response = await Promise.race([fetchPromise, timerPromise]);
|
|
675
|
+
return await handleResponse(response);
|
|
676
|
+
} catch (cause) {
|
|
677
|
+
if (cause instanceof K3CloudError) throw cause;
|
|
678
|
+
throw new K3CloudError(
|
|
679
|
+
timedOut ? ERROR_CODES.TIMEOUT : ERROR_CODES.NETWORK,
|
|
680
|
+
timedOut ? `请求超时(${timeout}ms)` : '网络请求失败',
|
|
681
|
+
{ cause },
|
|
682
|
+
);
|
|
683
|
+
} finally {
|
|
684
|
+
clearTimeout(timer);
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
/**
|
|
689
|
+
* 发送请求:拼接 URL、构造封装、超时控制、退避重试与错误归一化。
|
|
690
|
+
*
|
|
691
|
+
* @param {object} options
|
|
692
|
+
* @param {string} options.serverUrl 服务根地址,如 `http://host/K3Cloud/`
|
|
693
|
+
* @param {string} options.endpoint 服务 endpoint
|
|
694
|
+
* @param {*} [options.parameters] 业务参数,通常为数组
|
|
695
|
+
* @param {object} [options.config] 传输配置,缺省项取 `DEFAULTS`
|
|
696
|
+
* @param {Function} [options.fetchImpl] fetch 替身;缺省使用 `globalThis.fetch`
|
|
697
|
+
* @param {object} [options.logger] 日志器,需含 `debug` / `info` / `error` 方法
|
|
698
|
+
* @param {string} [options.rid] 请求标识;缺省自动生成
|
|
699
|
+
* @returns {Promise<*>} 解析后的响应 JSON
|
|
700
|
+
*/
|
|
701
|
+
async function request(options) {
|
|
702
|
+
const opts = options && typeof options === 'object' ? options : {};
|
|
703
|
+
const config = Object.assign({}, DEFAULTS, opts.config);
|
|
704
|
+
const fetchImpl = typeof opts.fetchImpl === 'function' ? opts.fetchImpl : globalThis.fetch;
|
|
705
|
+
const logger = opts.logger && typeof opts.logger === 'object' ? opts.logger : nullLogger;
|
|
706
|
+
const url = `${opts.serverUrl}${opts.endpoint}`;
|
|
707
|
+
const rid = typeof opts.rid === 'string' && opts.rid !== '' ? opts.rid : generateRid();
|
|
708
|
+
const body = buildRequestBody(opts.parameters, config, rid);
|
|
709
|
+
const retries =
|
|
710
|
+
Number.isFinite(config.retries) && config.retries > 0 ? Math.floor(config.retries) : 0;
|
|
711
|
+
const startedAt = Date.now();
|
|
712
|
+
const log = createRequestLog(logger, { rid, endpoint: opts.endpoint, startedAt });
|
|
713
|
+
|
|
714
|
+
log.start();
|
|
715
|
+
|
|
716
|
+
let attempt = 0;
|
|
717
|
+
for (;;) {
|
|
718
|
+
try {
|
|
719
|
+
const result = await sendOnce({ url, body, config, fetchImpl });
|
|
720
|
+
log.success();
|
|
721
|
+
return result;
|
|
722
|
+
} catch (err) {
|
|
723
|
+
if (!isRetryable(err) || attempt >= retries) {
|
|
724
|
+
log.failure(err instanceof K3CloudError ? err.code : ERROR_CODES.NETWORK);
|
|
725
|
+
throw err;
|
|
726
|
+
}
|
|
727
|
+
await delay(backoffDelay(attempt, config.retryBaseDelay));
|
|
728
|
+
attempt += 1;
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
request_1 = {
|
|
734
|
+
request,
|
|
735
|
+
RAW_TEXT_LIMIT,
|
|
736
|
+
buildRequestBody,
|
|
737
|
+
truncate,
|
|
738
|
+
};
|
|
739
|
+
return request_1;
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
var browserConfig;
|
|
743
|
+
var hasRequiredBrowserConfig;
|
|
744
|
+
|
|
745
|
+
function requireBrowserConfig () {
|
|
746
|
+
if (hasRequiredBrowserConfig) return browserConfig;
|
|
747
|
+
hasRequiredBrowserConfig = 1;
|
|
748
|
+
|
|
749
|
+
const { STORAGE_KEYS } = requireConstants();
|
|
750
|
+
|
|
751
|
+
/**
|
|
752
|
+
* 判断当前运行环境是否为浏览器。
|
|
753
|
+
* @returns {boolean}
|
|
754
|
+
*/
|
|
755
|
+
function isBrowser() {
|
|
756
|
+
return typeof window !== 'undefined' && typeof window.localStorage !== 'undefined';
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/**
|
|
760
|
+
* 从浏览器 `localStorage` 的约定键名读取配置。
|
|
761
|
+
* @param {Object<string, string>} [storage] 默认取 `window.localStorage`
|
|
762
|
+
* @returns {object}
|
|
763
|
+
*/
|
|
764
|
+
function loadBrowserConfig(storage) {
|
|
765
|
+
const store = storage === undefined ? (isBrowser() ? window.localStorage : undefined) : storage;
|
|
766
|
+
const config = {};
|
|
767
|
+
if (!store || typeof store.getItem !== 'function') return config;
|
|
768
|
+
for (const [field, key] of Object.entries(STORAGE_KEYS)) {
|
|
769
|
+
const value = store.getItem(key);
|
|
770
|
+
if (value !== null && value !== '') config[field] = value;
|
|
771
|
+
}
|
|
772
|
+
return config;
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
browserConfig = { isBrowser, loadBrowserConfig };
|
|
776
|
+
return browserConfig;
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
var login_1;
|
|
780
|
+
var hasRequiredLogin;
|
|
781
|
+
|
|
782
|
+
function requireLogin () {
|
|
783
|
+
if (hasRequiredLogin) return login_1;
|
|
784
|
+
hasRequiredLogin = 1;
|
|
785
|
+
|
|
786
|
+
const { SERVICES, METHODS, buildEndpoint } = requireConstants();
|
|
787
|
+
const { K3CloudError, ERROR_CODES } = requireErrors();
|
|
788
|
+
|
|
789
|
+
/** 登录成功对应的 `LoginResultType` */
|
|
790
|
+
const LOGIN_RESULT_TYPE_SUCCESS = 1;
|
|
791
|
+
|
|
792
|
+
/** 未显式给出语言时使用的默认语言(zh-CN) */
|
|
793
|
+
const DEFAULT_LANG = 2052;
|
|
794
|
+
|
|
795
|
+
/** 会话 Cookie 所在的响应头 */
|
|
796
|
+
const COOKIE_HEADER = 'set-cookie';
|
|
797
|
+
|
|
798
|
+
/** 两种登录方式对应的 endpoint */
|
|
799
|
+
const LOGIN_ENDPOINTS = Object.freeze({
|
|
800
|
+
PASSWORD: buildEndpoint(SERVICES.AUTH, METHODS.VALIDATE_USER),
|
|
801
|
+
APP_SECRET: buildEndpoint(SERVICES.AUTH, METHODS.LOGIN_BY_APP_SECRET),
|
|
802
|
+
});
|
|
803
|
+
|
|
804
|
+
/**
|
|
805
|
+
* 传输层契约。
|
|
806
|
+
*
|
|
807
|
+
* 由客户端装配层实现,登录与会话模块只依赖该契约,便于测试注入替身。
|
|
808
|
+
*
|
|
809
|
+
* @callback Transport
|
|
810
|
+
* @param {object} message
|
|
811
|
+
* @param {string} message.endpoint 服务 endpoint
|
|
812
|
+
* @param {Array<*>} message.parameters 业务参数
|
|
813
|
+
* @param {string} [message.cookie] 会话 Cookie 串
|
|
814
|
+
* @returns {Promise<TransportResult>}
|
|
815
|
+
*/
|
|
816
|
+
|
|
817
|
+
/**
|
|
818
|
+
* @typedef {object} TransportResult
|
|
819
|
+
* @property {number} status HTTP 状态码
|
|
820
|
+
* @property {Object<string, string|string[]>} headers 响应头(键名小写)
|
|
821
|
+
* @property {*} body 解析后的响应体
|
|
822
|
+
*/
|
|
823
|
+
|
|
824
|
+
/**
|
|
825
|
+
* 返回第一个非 `undefined` / `null` 的取值。
|
|
826
|
+
* @param {...*} values
|
|
827
|
+
* @returns {*}
|
|
828
|
+
*/
|
|
829
|
+
function firstDefined(...values) {
|
|
830
|
+
for (const value of values) {
|
|
831
|
+
if (value !== undefined && value !== null) return value;
|
|
832
|
+
}
|
|
833
|
+
return undefined;
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/**
|
|
837
|
+
* 判定登录响应是否为成功。
|
|
838
|
+
*
|
|
839
|
+
* 以 `LoginResultType` 为主判据(采集报文中成功值为 1);响应未给出该字段时
|
|
840
|
+
* 退回 `IsSuccessByAPI`。
|
|
841
|
+
*
|
|
842
|
+
* @param {*} body 登录响应体
|
|
843
|
+
* @returns {boolean}
|
|
844
|
+
*/
|
|
845
|
+
function isLoginSuccess(body) {
|
|
846
|
+
if (!body || typeof body !== 'object') return false;
|
|
847
|
+
if (typeof body.LoginResultType === 'number') {
|
|
848
|
+
return body.LoginResultType === LOGIN_RESULT_TYPE_SUCCESS;
|
|
849
|
+
}
|
|
850
|
+
return body.IsSuccessByAPI === true;
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
/**
|
|
854
|
+
* 从响应头中提取会话 Cookie 串。
|
|
855
|
+
* @param {Object<string, string|string[]>} headers
|
|
856
|
+
* @returns {string}
|
|
857
|
+
*/
|
|
858
|
+
function extractCookie(headers) {
|
|
859
|
+
if (!headers || typeof headers !== 'object') return '';
|
|
860
|
+
const key = Object.keys(headers).find((name) => name.toLowerCase() === COOKIE_HEADER);
|
|
861
|
+
if (key === undefined) return '';
|
|
862
|
+
const raw = headers[key];
|
|
863
|
+
const value = Array.isArray(raw) ? raw[0] : raw;
|
|
864
|
+
return typeof value === 'string' ? value : '';
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
/**
|
|
868
|
+
* 由登录响应构造失败信息,只取服务端给出的提示,不含任何凭证。
|
|
869
|
+
* @param {*} body
|
|
870
|
+
* @returns {string}
|
|
871
|
+
*/
|
|
872
|
+
function buildLoginErrorMessage(body) {
|
|
873
|
+
const message = body && typeof body.Message === 'string' ? body.Message : '';
|
|
874
|
+
const messageCode = body && typeof body.MessageCode === 'string' ? body.MessageCode : '';
|
|
875
|
+
if (message !== '' && messageCode !== '') return `登录失败: ${message} (${messageCode})`;
|
|
876
|
+
if (message !== '') return `登录失败: ${message}`;
|
|
877
|
+
if (messageCode !== '') return `登录失败: ${messageCode}`;
|
|
878
|
+
return '登录失败';
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
/**
|
|
882
|
+
* 归一化登录凭证:显式凭证优先,其余字段回落到配置。
|
|
883
|
+
*
|
|
884
|
+
* `appId` 与 `appKey` 视为同一凭证的两种写法,配置侧以 `appKey` 为准。
|
|
885
|
+
*
|
|
886
|
+
* @param {object} credentials 显式凭证
|
|
887
|
+
* @param {object} config 配置
|
|
888
|
+
* @returns {{ acctId: *, username: *, password: *, appId: *, appSec: *, lang: * }}
|
|
889
|
+
*/
|
|
890
|
+
function resolveCredentials(credentials, config) {
|
|
891
|
+
const source = credentials && typeof credentials === 'object' ? credentials : {};
|
|
892
|
+
return {
|
|
893
|
+
acctId: firstDefined(source.acctId, config.acctId),
|
|
894
|
+
username: source.username,
|
|
895
|
+
password: source.password,
|
|
896
|
+
appId: firstDefined(source.appId, source.appKey, config.appId, config.appKey),
|
|
897
|
+
appSec: firstDefined(source.appSec, config.appSec),
|
|
898
|
+
lang: firstDefined(source.lang, config.lang, DEFAULT_LANG),
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
/**
|
|
903
|
+
* 执行一次登录:调用 endpoint、校验结果并提取会话 Cookie。
|
|
904
|
+
* @param {object} options
|
|
905
|
+
* @param {Transport} options.transport
|
|
906
|
+
* @param {string} options.endpoint
|
|
907
|
+
* @param {Array<*>} options.parameters
|
|
908
|
+
* @returns {Promise<{cookie: string, context: object|null, raw: object}>}
|
|
909
|
+
*/
|
|
910
|
+
async function performLogin({ transport, endpoint, parameters }) {
|
|
911
|
+
const response = await transport({ endpoint, parameters });
|
|
912
|
+
const body = response ? response.body : undefined;
|
|
913
|
+
|
|
914
|
+
if (!isLoginSuccess(body)) {
|
|
915
|
+
throw new K3CloudError(ERROR_CODES.AUTH, buildLoginErrorMessage(body), {
|
|
916
|
+
loginResultType: body ? body.LoginResultType : undefined,
|
|
917
|
+
messageCode: body ? body.MessageCode : undefined,
|
|
918
|
+
});
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
const cookie = extractCookie(response.headers);
|
|
922
|
+
if (cookie === '') {
|
|
923
|
+
throw new K3CloudError(ERROR_CODES.SESSION, '登录成功但未取得会话 Cookie');
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
const context = body.Context && typeof body.Context === 'object' ? body.Context : null;
|
|
927
|
+
return { cookie, context, raw: body };
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
/**
|
|
931
|
+
* 以用户名 / 密码登录。
|
|
932
|
+
* @param {object} options
|
|
933
|
+
* @param {Transport} options.transport
|
|
934
|
+
* @param {object} options.config
|
|
935
|
+
* @param {object} options.credentials
|
|
936
|
+
* @returns {Promise<{cookie: string, context: object|null, raw: object}>}
|
|
937
|
+
*/
|
|
938
|
+
async function loginByPassword({ transport, config, credentials }) {
|
|
939
|
+
const resolved = resolveCredentials(credentials, config);
|
|
940
|
+
return performLogin({
|
|
941
|
+
transport,
|
|
942
|
+
endpoint: LOGIN_ENDPOINTS.PASSWORD,
|
|
943
|
+
parameters: [resolved.acctId, resolved.username, resolved.password, resolved.lang],
|
|
944
|
+
});
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
/**
|
|
948
|
+
* 以 appId / appSec 组合登录。
|
|
949
|
+
* @param {object} options
|
|
950
|
+
* @param {Transport} options.transport
|
|
951
|
+
* @param {object} options.config
|
|
952
|
+
* @param {object} options.credentials
|
|
953
|
+
* @returns {Promise<{cookie: string, context: object|null, raw: object}>}
|
|
954
|
+
*/
|
|
955
|
+
async function loginByAppSecret({ transport, config, credentials }) {
|
|
956
|
+
const resolved = resolveCredentials(credentials, config);
|
|
957
|
+
return performLogin({
|
|
958
|
+
transport,
|
|
959
|
+
endpoint: LOGIN_ENDPOINTS.APP_SECRET,
|
|
960
|
+
parameters: [resolved.acctId, resolved.appId, resolved.appSec, resolved.lang],
|
|
961
|
+
});
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
/**
|
|
965
|
+
* 按凭证形态选择登录方式:具备用户名与密码时走账密登录,否则走应用凭证登录。
|
|
966
|
+
* @param {object} options
|
|
967
|
+
* @param {Transport} options.transport
|
|
968
|
+
* @param {object} options.config
|
|
969
|
+
* @param {object} options.credentials
|
|
970
|
+
* @returns {Promise<{cookie: string, context: object|null, raw: object}>}
|
|
971
|
+
*/
|
|
972
|
+
async function login(options) {
|
|
973
|
+
const credentials = options && options.credentials;
|
|
974
|
+
if (!credentials || typeof credentials !== 'object') {
|
|
975
|
+
throw new K3CloudError(ERROR_CODES.AUTH, '登录凭证缺失');
|
|
976
|
+
}
|
|
977
|
+
const hasPassword =
|
|
978
|
+
typeof credentials.username === 'string' && typeof credentials.password === 'string';
|
|
979
|
+
const hasAppSecret =
|
|
980
|
+
(typeof credentials.appId === 'string' || typeof credentials.appKey === 'string') &&
|
|
981
|
+
typeof credentials.appSec === 'string';
|
|
982
|
+
|
|
983
|
+
if (hasPassword) return loginByPassword(options);
|
|
984
|
+
if (hasAppSecret) return loginByAppSecret(options);
|
|
985
|
+
throw new K3CloudError(
|
|
986
|
+
ERROR_CODES.AUTH,
|
|
987
|
+
'登录凭证不完整:需提供用户名与密码,或 appId 与 appSec',
|
|
988
|
+
);
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
login_1 = {
|
|
992
|
+
login,
|
|
993
|
+
loginByPassword,
|
|
994
|
+
loginByAppSecret,
|
|
995
|
+
isLoginSuccess,
|
|
996
|
+
extractCookie,
|
|
997
|
+
resolveCredentials,
|
|
998
|
+
LOGIN_ENDPOINTS,
|
|
999
|
+
LOGIN_RESULT_TYPE_SUCCESS,
|
|
1000
|
+
};
|
|
1001
|
+
return login_1;
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
var session;
|
|
1005
|
+
var hasRequiredSession;
|
|
1006
|
+
|
|
1007
|
+
function requireSession () {
|
|
1008
|
+
if (hasRequiredSession) return session;
|
|
1009
|
+
hasRequiredSession = 1;
|
|
1010
|
+
|
|
1011
|
+
const { SERVICES, METHODS, buildEndpoint } = requireConstants();
|
|
1012
|
+
const { K3CloudError, ERROR_CODES } = requireErrors();
|
|
1013
|
+
const { login: loginWithTransport } = requireLogin();
|
|
1014
|
+
const { logRecord } = requireLogger();
|
|
1015
|
+
|
|
1016
|
+
/** 登出 endpoint */
|
|
1017
|
+
const LOGOUT_ENDPOINT = buildEndpoint(SERVICES.AUTH, METHODS.LOGOUT);
|
|
1018
|
+
|
|
1019
|
+
/** 默认会话失效判据:HTTP 401,或业务失败信息中的会话关键字 */
|
|
1020
|
+
const SESSION_EXPIRED_PATTERNS = Object.freeze([/会话/, /登录/, /session/i, /login/i, /unauthor/i]);
|
|
1021
|
+
|
|
1022
|
+
/**
|
|
1023
|
+
* 默认会话失效判定。
|
|
1024
|
+
*
|
|
1025
|
+
* 命中任一条件即视为失效:HTTP 状态码为 401;业务响应的
|
|
1026
|
+
* `Result.ResponseStatus.IsSuccess` 为 `false` 且错误信息含会话关键字。
|
|
1027
|
+
* 判据可由 `createSession` 的 `isSessionExpired` 替换。
|
|
1028
|
+
*
|
|
1029
|
+
* @param {*} subject 传输结果(含 `status` / `body`)或传输层错误
|
|
1030
|
+
* @returns {boolean}
|
|
1031
|
+
*/
|
|
1032
|
+
function defaultIsSessionExpired(subject) {
|
|
1033
|
+
if (!subject) return false;
|
|
1034
|
+
|
|
1035
|
+
if (subject.code === ERROR_CODES.HTTP) {
|
|
1036
|
+
return Boolean(subject.details) && subject.details.status === 401;
|
|
1037
|
+
}
|
|
1038
|
+
if (typeof subject.status === 'number' && subject.status === 401) return true;
|
|
1039
|
+
|
|
1040
|
+
// 兼容传输结果(含 body)与已解析的业务体两种形状
|
|
1041
|
+
const body = subject.body !== undefined ? subject.body : subject;
|
|
1042
|
+
if (!body || typeof body !== 'object') return false;
|
|
1043
|
+
|
|
1044
|
+
const responseStatus = body.Result && body.Result.ResponseStatus;
|
|
1045
|
+
if (!responseStatus || responseStatus.IsSuccess !== false) return false;
|
|
1046
|
+
|
|
1047
|
+
const errors = Array.isArray(responseStatus.Errors) ? responseStatus.Errors : [];
|
|
1048
|
+
const text = [
|
|
1049
|
+
typeof responseStatus.Message === 'string' ? responseStatus.Message : '',
|
|
1050
|
+
...errors.map((item) =>
|
|
1051
|
+
[item && item.ErrorCode, item && item.Name, item && item.Message]
|
|
1052
|
+
.filter((value) => typeof value === 'string' || typeof value === 'number')
|
|
1053
|
+
.join(' '),
|
|
1054
|
+
),
|
|
1055
|
+
].join(' ');
|
|
1056
|
+
|
|
1057
|
+
return SESSION_EXPIRED_PATTERNS.some((pattern) => pattern.test(text));
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
/**
|
|
1061
|
+
* 创建会话:持有登录态、自动续期与登出。
|
|
1062
|
+
*
|
|
1063
|
+
* 凭证只保留在闭包内,不进入会话状态,也不写入日志。
|
|
1064
|
+
*
|
|
1065
|
+
* @param {object} options
|
|
1066
|
+
* @param {import('./login.js').Transport} options.transport 传输层
|
|
1067
|
+
* @param {object} [options.config] 配置
|
|
1068
|
+
* @param {object} [options.logger] 日志器
|
|
1069
|
+
* @param {(subject: *) => boolean} [options.isSessionExpired] 会话失效判定
|
|
1070
|
+
* @returns {object}
|
|
1071
|
+
*/
|
|
1072
|
+
function createSession(options = {}) {
|
|
1073
|
+
const opts = options && typeof options === 'object' ? options : {};
|
|
1074
|
+
const { config, logger } = opts;
|
|
1075
|
+
const { transport } = opts;
|
|
1076
|
+
const isSessionExpired =
|
|
1077
|
+
typeof opts.isSessionExpired === 'function' ? opts.isSessionExpired : defaultIsSessionExpired;
|
|
1078
|
+
|
|
1079
|
+
if (typeof transport !== 'function') {
|
|
1080
|
+
throw new K3CloudError(ERROR_CODES.VALIDATION, '会话需要注入传输层');
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
let cookie = '';
|
|
1084
|
+
let context = null;
|
|
1085
|
+
let credentials = null;
|
|
1086
|
+
let renewPromise = null;
|
|
1087
|
+
|
|
1088
|
+
function isAuthenticated() {
|
|
1089
|
+
return cookie !== '';
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
function getState() {
|
|
1093
|
+
return { authenticated: isAuthenticated(), cookie, context };
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
function getCookie() {
|
|
1097
|
+
return cookie;
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
async function performLogin() {
|
|
1101
|
+
const result = await loginWithTransport({ transport, config, credentials });
|
|
1102
|
+
cookie = result.cookie;
|
|
1103
|
+
context = result.context;
|
|
1104
|
+
logRecord(logger, 'info', { phase: 'login', ok: true });
|
|
1105
|
+
return result;
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
/**
|
|
1109
|
+
* 重新登录:并发调用共享同一次登录,只触发一次。
|
|
1110
|
+
* @returns {Promise<object>}
|
|
1111
|
+
*/
|
|
1112
|
+
function renew() {
|
|
1113
|
+
if (renewPromise !== null) return renewPromise;
|
|
1114
|
+
renewPromise = (async () => {
|
|
1115
|
+
try {
|
|
1116
|
+
return await performLogin();
|
|
1117
|
+
} finally {
|
|
1118
|
+
renewPromise = null;
|
|
1119
|
+
}
|
|
1120
|
+
})();
|
|
1121
|
+
return renewPromise;
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
async function sendOnce(send) {
|
|
1125
|
+
try {
|
|
1126
|
+
return { ok: true, value: await send(cookie) };
|
|
1127
|
+
} catch (err) {
|
|
1128
|
+
return { ok: false, error: err };
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
function isExpiredOutcome(outcome) {
|
|
1133
|
+
return isSessionExpired(outcome.ok ? outcome.value : outcome.error);
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
function unwrap(outcome) {
|
|
1137
|
+
if (outcome.ok) return outcome.value;
|
|
1138
|
+
throw outcome.error;
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
function toSessionError(outcome) {
|
|
1142
|
+
const cause = outcome.ok ? undefined : outcome.error;
|
|
1143
|
+
return new K3CloudError(ERROR_CODES.SESSION, '会话已失效,重新登录后仍未通过', { cause });
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1146
|
+
/**
|
|
1147
|
+
* 执行一次带会话的请求:自动附带 Cookie,命中失效判定时重新登录并重试一次。
|
|
1148
|
+
* @param {(cookie: string) => Promise<*>} send 请求函数
|
|
1149
|
+
* @returns {Promise<*>}
|
|
1150
|
+
*/
|
|
1151
|
+
async function execute(send) {
|
|
1152
|
+
if (typeof send !== 'function') {
|
|
1153
|
+
throw new K3CloudError(ERROR_CODES.VALIDATION, 'execute 需要传入请求函数');
|
|
1154
|
+
}
|
|
1155
|
+
if (!isAuthenticated()) {
|
|
1156
|
+
if (credentials === null) {
|
|
1157
|
+
throw new K3CloudError(ERROR_CODES.AUTH, '尚未登录:请先调用 login() 完成登录');
|
|
1158
|
+
}
|
|
1159
|
+
await renew();
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
const first = await sendOnce(send);
|
|
1163
|
+
if (!isExpiredOutcome(first)) return unwrap(first);
|
|
1164
|
+
|
|
1165
|
+
logRecord(logger, 'warn', { phase: 'renew', reason: 'session-expired' });
|
|
1166
|
+
await renew();
|
|
1167
|
+
|
|
1168
|
+
const second = await sendOnce(send);
|
|
1169
|
+
if (isExpiredOutcome(second)) throw toSessionError(second);
|
|
1170
|
+
return unwrap(second);
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
/**
|
|
1174
|
+
* 登录并持有会话。
|
|
1175
|
+
* @param {object} credentialsInput 登录凭证
|
|
1176
|
+
* @returns {Promise<{authenticated: boolean, cookie: string, context: object|null}>}
|
|
1177
|
+
*/
|
|
1178
|
+
async function login(credentialsInput) {
|
|
1179
|
+
if (!credentialsInput || typeof credentialsInput !== 'object') {
|
|
1180
|
+
throw new K3CloudError(ERROR_CODES.AUTH, '登录凭证缺失');
|
|
1181
|
+
}
|
|
1182
|
+
credentials = credentialsInput;
|
|
1183
|
+
await renew();
|
|
1184
|
+
return getState();
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
/**
|
|
1188
|
+
* 登出:先清理本地会话,再尝试通知服务端;本地状态始终被清理。
|
|
1189
|
+
* @returns {Promise<{authenticated: boolean, cookie: string, context: object|null}>}
|
|
1190
|
+
*/
|
|
1191
|
+
async function logout() {
|
|
1192
|
+
const previousCookie = cookie;
|
|
1193
|
+
cookie = '';
|
|
1194
|
+
context = null;
|
|
1195
|
+
|
|
1196
|
+
if (previousCookie !== '') {
|
|
1197
|
+
try {
|
|
1198
|
+
await transport({ endpoint: LOGOUT_ENDPOINT, parameters: [], cookie: previousCookie });
|
|
1199
|
+
logRecord(logger, 'info', { phase: 'logout', ok: true });
|
|
1200
|
+
} catch (err) {
|
|
1201
|
+
logRecord(logger, 'warn', {
|
|
1202
|
+
phase: 'logout',
|
|
1203
|
+
ok: false,
|
|
1204
|
+
code: err && typeof err.code === 'string' ? err.code : undefined,
|
|
1205
|
+
});
|
|
1206
|
+
}
|
|
1207
|
+
}
|
|
1208
|
+
return getState();
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
return {
|
|
1212
|
+
isAuthenticated,
|
|
1213
|
+
getState,
|
|
1214
|
+
getCookie,
|
|
1215
|
+
execute,
|
|
1216
|
+
login,
|
|
1217
|
+
logout,
|
|
1218
|
+
};
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
session = {
|
|
1222
|
+
createSession,
|
|
1223
|
+
defaultIsSessionExpired,
|
|
1224
|
+
LOGOUT_ENDPOINT,
|
|
1225
|
+
SESSION_EXPIRED_PATTERNS,
|
|
1226
|
+
};
|
|
1227
|
+
return session;
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
var bill;
|
|
1231
|
+
var hasRequiredBill;
|
|
1232
|
+
|
|
1233
|
+
function requireBill () {
|
|
1234
|
+
if (hasRequiredBill) return bill;
|
|
1235
|
+
hasRequiredBill = 1;
|
|
1236
|
+
|
|
1237
|
+
const { SERVICES, METHODS, buildEndpoint } = requireConstants();
|
|
1238
|
+
const { K3CloudError, ERROR_CODES } = requireErrors();
|
|
1239
|
+
|
|
1240
|
+
/** 单据服务 endpoint */
|
|
1241
|
+
const BILL_ENDPOINTS = Object.freeze({
|
|
1242
|
+
SAVE: buildEndpoint(SERVICES.DYNAMIC_FORM, METHODS.SAVE),
|
|
1243
|
+
VIEW: buildEndpoint(SERVICES.DYNAMIC_FORM, METHODS.VIEW),
|
|
1244
|
+
SUBMIT: buildEndpoint(SERVICES.DYNAMIC_FORM, METHODS.SUBMIT),
|
|
1245
|
+
AUDIT: buildEndpoint(SERVICES.DYNAMIC_FORM, METHODS.AUDIT),
|
|
1246
|
+
UN_AUDIT: buildEndpoint(SERVICES.DYNAMIC_FORM, METHODS.UN_AUDIT),
|
|
1247
|
+
DELETE: buildEndpoint(SERVICES.DYNAMIC_FORM, METHODS.DELETE),
|
|
1248
|
+
EXECUTE_BILL_QUERY: buildEndpoint(SERVICES.DYNAMIC_FORM, METHODS.EXECUTE_BILL_QUERY),
|
|
1249
|
+
});
|
|
1250
|
+
|
|
1251
|
+
/**
|
|
1252
|
+
* 默认业务成功判定。
|
|
1253
|
+
*
|
|
1254
|
+
* 结果集(数组)视为成功;其余响应以 `Result.ResponseStatus.IsSuccess` 为准。
|
|
1255
|
+
*
|
|
1256
|
+
* @param {*} body 业务响应体
|
|
1257
|
+
* @returns {boolean}
|
|
1258
|
+
*/
|
|
1259
|
+
function defaultIsBusinessSuccess(body) {
|
|
1260
|
+
if (Array.isArray(body)) return true;
|
|
1261
|
+
const status = body && body.Result && body.Result.ResponseStatus;
|
|
1262
|
+
return Boolean(status) && status.IsSuccess === true;
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
/**
|
|
1266
|
+
* 默认响应解析:结果集原样返回,其余响应取 `Result` 负载。
|
|
1267
|
+
* @param {*} body 业务响应体
|
|
1268
|
+
* @returns {*}
|
|
1269
|
+
*/
|
|
1270
|
+
function defaultParseResponse(body) {
|
|
1271
|
+
if (Array.isArray(body)) return body;
|
|
1272
|
+
if (body && typeof body === 'object' && body.Result !== undefined) return body.Result;
|
|
1273
|
+
return body;
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
/**
|
|
1277
|
+
* 由业务失败响应构造错误,保留原始响应状态对象。
|
|
1278
|
+
* @param {*} body 业务响应体
|
|
1279
|
+
* @returns {K3CloudError}
|
|
1280
|
+
*/
|
|
1281
|
+
function toBusinessError(body) {
|
|
1282
|
+
const status = body && body.Result && body.Result.ResponseStatus;
|
|
1283
|
+
return new K3CloudError(ERROR_CODES.BUSINESS, buildBusinessMessage(status), {
|
|
1284
|
+
responseStatus: status || null,
|
|
1285
|
+
body,
|
|
1286
|
+
});
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
/**
|
|
1290
|
+
* 由响应状态对象提取服务端给出的失败提示。
|
|
1291
|
+
* @param {*} status 响应状态对象
|
|
1292
|
+
* @returns {string}
|
|
1293
|
+
*/
|
|
1294
|
+
function buildBusinessMessage(status) {
|
|
1295
|
+
const errors = status && Array.isArray(status.Errors) ? status.Errors : [];
|
|
1296
|
+
const text = errors
|
|
1297
|
+
.filter((item) => item && typeof item === 'object')
|
|
1298
|
+
.map((item) =>
|
|
1299
|
+
[item.ErrorCode, item.Name, item.Message]
|
|
1300
|
+
.filter((value) => typeof value === 'string' || typeof value === 'number')
|
|
1301
|
+
.join(' '),
|
|
1302
|
+
)
|
|
1303
|
+
.filter((value) => value !== '')
|
|
1304
|
+
.join('; ');
|
|
1305
|
+
return text === '' ? '业务处理失败' : `业务处理失败: ${text}`;
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
/**
|
|
1309
|
+
* Save 的第二个参数:业务字段集合。
|
|
1310
|
+
*
|
|
1311
|
+
* 已含 `Model` 键时按协议形状原样透传,否则包一层。
|
|
1312
|
+
*
|
|
1313
|
+
* @param {*} model 业务字段集合或已包装的对象
|
|
1314
|
+
* @returns {object}
|
|
1315
|
+
*/
|
|
1316
|
+
function toSaveParameter(model) {
|
|
1317
|
+
if (
|
|
1318
|
+
model &&
|
|
1319
|
+
typeof model === 'object' &&
|
|
1320
|
+
!Array.isArray(model) &&
|
|
1321
|
+
Object.prototype.hasOwnProperty.call(model, 'Model')
|
|
1322
|
+
) {
|
|
1323
|
+
return model;
|
|
1324
|
+
}
|
|
1325
|
+
return { Model: model };
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
/**
|
|
1329
|
+
* ExecuteBillQuery 的查询参数:对象序列化为 JSON 字符串,字符串按原样透传。
|
|
1330
|
+
* @param {object|string} query 查询条件
|
|
1331
|
+
* @returns {string}
|
|
1332
|
+
*/
|
|
1333
|
+
function serializeQuery(query) {
|
|
1334
|
+
return typeof query === 'string' ? query : JSON.stringify(query);
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
/**
|
|
1338
|
+
* 创建单据服务。
|
|
1339
|
+
*
|
|
1340
|
+
* 请求经会话执行以自动附带并在失效时刷新 Cookie;未注入会话时不附带 Cookie。
|
|
1341
|
+
*
|
|
1342
|
+
* @param {object} options
|
|
1343
|
+
* @param {(message: {endpoint: string, parameters: Array<*>, cookie: string}) => Promise<{status: number, headers: Object<string, string|string[]>, body: *}>} options.transport 传输层
|
|
1344
|
+
* @param {{execute: (send: (cookie: string) => Promise<*>) => Promise<*>}} [options.session] 会话
|
|
1345
|
+
* @param {(body: *) => boolean} [options.isBusinessSuccess] 业务成功判定
|
|
1346
|
+
* @param {(body: *) => *} [options.parseResponse] 响应解析
|
|
1347
|
+
* @returns {{save: Function, view: Function, submit: Function, audit: Function, unAudit: Function, delete: Function, executeBillQuery: Function}}
|
|
1348
|
+
*/
|
|
1349
|
+
function createBillService(options = {}) {
|
|
1350
|
+
const opts = options && typeof options === 'object' ? options : {};
|
|
1351
|
+
const { transport, session } = opts;
|
|
1352
|
+
const isBusinessSuccess =
|
|
1353
|
+
typeof opts.isBusinessSuccess === 'function'
|
|
1354
|
+
? opts.isBusinessSuccess
|
|
1355
|
+
: defaultIsBusinessSuccess;
|
|
1356
|
+
const parseResponse =
|
|
1357
|
+
typeof opts.parseResponse === 'function' ? opts.parseResponse : defaultParseResponse;
|
|
1358
|
+
|
|
1359
|
+
if (typeof transport !== 'function') {
|
|
1360
|
+
throw new K3CloudError(ERROR_CODES.VALIDATION, '单据服务需要注入传输层');
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
/**
|
|
1364
|
+
* 发起一次调用:附带 Cookie,校验业务结果,解析响应。
|
|
1365
|
+
* @param {string} endpoint 服务 endpoint
|
|
1366
|
+
* @param {Array<*>} parameters 业务参数
|
|
1367
|
+
* @returns {Promise<*>}
|
|
1368
|
+
*/
|
|
1369
|
+
async function call(endpoint, parameters) {
|
|
1370
|
+
const send = (cookie) =>
|
|
1371
|
+
transport({ endpoint, parameters, cookie }).then((result) =>
|
|
1372
|
+
result ? result.body : undefined,
|
|
1373
|
+
);
|
|
1374
|
+
const body =
|
|
1375
|
+
session && typeof session.execute === 'function'
|
|
1376
|
+
? await session.execute(send)
|
|
1377
|
+
: await send('');
|
|
1378
|
+
if (!isBusinessSuccess(body)) throw toBusinessError(body);
|
|
1379
|
+
return parseResponse(body);
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1382
|
+
/**
|
|
1383
|
+
* 保存单据。
|
|
1384
|
+
* @param {string} formId 单据标识
|
|
1385
|
+
* @param {object} model 业务字段集合
|
|
1386
|
+
* @returns {Promise<*>}
|
|
1387
|
+
*/
|
|
1388
|
+
function save(formId, model) {
|
|
1389
|
+
return call(BILL_ENDPOINTS.SAVE, [formId, toSaveParameter(model)]);
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
/**
|
|
1393
|
+
* 查看单据。
|
|
1394
|
+
* @param {string} formId 单据标识
|
|
1395
|
+
* @param {string} number 单据编号
|
|
1396
|
+
* @returns {Promise<*>}
|
|
1397
|
+
*/
|
|
1398
|
+
function view(formId, number) {
|
|
1399
|
+
return call(BILL_ENDPOINTS.VIEW, [formId, { Number: number }]);
|
|
1400
|
+
}
|
|
1401
|
+
|
|
1402
|
+
/**
|
|
1403
|
+
* 提交单据。
|
|
1404
|
+
* @param {string} formId 单据标识
|
|
1405
|
+
* @param {string[]} numbers 单据编号集合
|
|
1406
|
+
* @returns {Promise<*>}
|
|
1407
|
+
*/
|
|
1408
|
+
function submit(formId, numbers) {
|
|
1409
|
+
return call(BILL_ENDPOINTS.SUBMIT, [formId, { Numbers: numbers }]);
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
/**
|
|
1413
|
+
* 审核单据。
|
|
1414
|
+
* @param {string} formId 单据标识
|
|
1415
|
+
* @param {string[]} numbers 单据编号集合
|
|
1416
|
+
* @returns {Promise<*>}
|
|
1417
|
+
*/
|
|
1418
|
+
function audit(formId, numbers) {
|
|
1419
|
+
return call(BILL_ENDPOINTS.AUDIT, [formId, { Numbers: numbers }]);
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
/**
|
|
1423
|
+
* 反审核单据。
|
|
1424
|
+
* @param {string} formId 单据标识
|
|
1425
|
+
* @param {string[]} numbers 单据编号集合
|
|
1426
|
+
* @returns {Promise<*>}
|
|
1427
|
+
*/
|
|
1428
|
+
function unAudit(formId, numbers) {
|
|
1429
|
+
return call(BILL_ENDPOINTS.UN_AUDIT, [formId, { Numbers: numbers }]);
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
/**
|
|
1433
|
+
* 删除单据。
|
|
1434
|
+
* @param {string} formId 单据标识
|
|
1435
|
+
* @param {string[]} numbers 单据编号集合
|
|
1436
|
+
* @returns {Promise<*>}
|
|
1437
|
+
*/
|
|
1438
|
+
function remove(formId, numbers) {
|
|
1439
|
+
return call(BILL_ENDPOINTS.DELETE, [formId, { Numbers: numbers }]);
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
/**
|
|
1443
|
+
* 执行单据查询。
|
|
1444
|
+
* @param {object|string} query 查询条件对象或已序列化的 JSON 字符串
|
|
1445
|
+
* @returns {Promise<Array<*>>}
|
|
1446
|
+
*/
|
|
1447
|
+
async function executeBillQuery(query) {
|
|
1448
|
+
const rows = await call(BILL_ENDPOINTS.EXECUTE_BILL_QUERY, [serializeQuery(query)]);
|
|
1449
|
+
return rows === null || rows === undefined ? [] : rows;
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
return {
|
|
1453
|
+
save,
|
|
1454
|
+
view,
|
|
1455
|
+
submit,
|
|
1456
|
+
audit,
|
|
1457
|
+
unAudit,
|
|
1458
|
+
delete: remove,
|
|
1459
|
+
executeBillQuery,
|
|
1460
|
+
};
|
|
1461
|
+
}
|
|
1462
|
+
|
|
1463
|
+
bill = {
|
|
1464
|
+
createBillService,
|
|
1465
|
+
defaultIsBusinessSuccess,
|
|
1466
|
+
defaultParseResponse,
|
|
1467
|
+
BILL_ENDPOINTS,
|
|
1468
|
+
};
|
|
1469
|
+
return bill;
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
var metadata;
|
|
1473
|
+
var hasRequiredMetadata;
|
|
1474
|
+
|
|
1475
|
+
function requireMetadata () {
|
|
1476
|
+
if (hasRequiredMetadata) return metadata;
|
|
1477
|
+
hasRequiredMetadata = 1;
|
|
1478
|
+
|
|
1479
|
+
const { SERVICES, METHODS, buildEndpoint } = requireConstants();
|
|
1480
|
+
const { K3CloudError, ERROR_CODES } = requireErrors();
|
|
1481
|
+
|
|
1482
|
+
/** 元数据服务 endpoint */
|
|
1483
|
+
const METADATA_ENDPOINTS = Object.freeze({
|
|
1484
|
+
QUERY_BUSINESS_INFO: buildEndpoint(SERVICES.DYNAMIC_FORM, METHODS.QUERY_BUSINESS_INFO),
|
|
1485
|
+
});
|
|
1486
|
+
|
|
1487
|
+
/**
|
|
1488
|
+
* 从 `Result` 负载中取出 `NeedReturnData`。
|
|
1489
|
+
* @param {*} result `Result` 负载
|
|
1490
|
+
* @returns {object|null}
|
|
1491
|
+
*/
|
|
1492
|
+
function extractMetadata(result) {
|
|
1493
|
+
const data = result && typeof result === 'object' ? result.NeedReturnData : undefined;
|
|
1494
|
+
return data && typeof data === 'object' ? data : null;
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
/**
|
|
1498
|
+
* 反序列化字符串形态的 `Result` 负载。
|
|
1499
|
+
* @param {string} text `Result` 文本
|
|
1500
|
+
* @returns {object|null}
|
|
1501
|
+
*/
|
|
1502
|
+
function parseMetadataResult(text) {
|
|
1503
|
+
try {
|
|
1504
|
+
return extractMetadata(JSON.parse(text));
|
|
1505
|
+
} catch (err) {
|
|
1506
|
+
throw new K3CloudError(ERROR_CODES.PARSE, '元数据响应解析失败', { cause: err });
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
/**
|
|
1511
|
+
* 默认元数据解析:取 `Result.NeedReturnData`;`Result` 为字符串时先反序列化。
|
|
1512
|
+
* @param {*} body 业务响应体
|
|
1513
|
+
* @returns {object}
|
|
1514
|
+
*/
|
|
1515
|
+
function defaultParseMetadata(body) {
|
|
1516
|
+
const result = body && typeof body === 'object' ? body.Result : undefined;
|
|
1517
|
+
const data = typeof result === 'string' ? parseMetadataResult(result) : extractMetadata(result);
|
|
1518
|
+
if (!data) throw new K3CloudError(ERROR_CODES.PARSE, '元数据响应缺少 NeedReturnData');
|
|
1519
|
+
return data;
|
|
1520
|
+
}
|
|
1521
|
+
|
|
1522
|
+
/**
|
|
1523
|
+
* 创建元数据服务。
|
|
1524
|
+
*
|
|
1525
|
+
* 查询结果缓存在本实例闭包内,不写入全局或持久化存储;未注入会话时不附带 Cookie。
|
|
1526
|
+
*
|
|
1527
|
+
* @param {object} options
|
|
1528
|
+
* @param {(message: {endpoint: string, parameters: Array<*>, cookie: string}) => Promise<{status: number, headers: Object<string, string|string[]>, body: *}>} options.transport 传输层
|
|
1529
|
+
* @param {{execute: (send: (cookie: string) => Promise<*>) => Promise<*>}} [options.session] 会话
|
|
1530
|
+
* @param {(body: *) => object} [options.parseResponse] 响应解析
|
|
1531
|
+
* @param {boolean} [options.cache] 是否启用实例内缓存,缺省启用
|
|
1532
|
+
* @returns {{queryBusinessInfo: Function}}
|
|
1533
|
+
*/
|
|
1534
|
+
function createMetadataService(options = {}) {
|
|
1535
|
+
const opts = options && typeof options === 'object' ? options : {};
|
|
1536
|
+
const { transport, session } = opts;
|
|
1537
|
+
const parseResponse =
|
|
1538
|
+
typeof opts.parseResponse === 'function' ? opts.parseResponse : defaultParseMetadata;
|
|
1539
|
+
const cacheEnabled = opts.cache !== false;
|
|
1540
|
+
/** 实例内缓存:formId -> 查询 Promise */
|
|
1541
|
+
const cache = new Map();
|
|
1542
|
+
|
|
1543
|
+
if (typeof transport !== 'function') {
|
|
1544
|
+
throw new K3CloudError(ERROR_CODES.VALIDATION, '元数据服务需要注入传输层');
|
|
1545
|
+
}
|
|
1546
|
+
|
|
1547
|
+
/**
|
|
1548
|
+
* 发起一次元数据查询并解析响应。
|
|
1549
|
+
* @param {string} formId 单据标识
|
|
1550
|
+
* @returns {Promise<object>}
|
|
1551
|
+
*/
|
|
1552
|
+
async function request(formId) {
|
|
1553
|
+
const send = (cookie) =>
|
|
1554
|
+
transport({
|
|
1555
|
+
endpoint: METADATA_ENDPOINTS.QUERY_BUSINESS_INFO,
|
|
1556
|
+
parameters: [JSON.stringify({ FormId: formId })],
|
|
1557
|
+
cookie,
|
|
1558
|
+
}).then((result) => (result ? result.body : undefined));
|
|
1559
|
+
const body =
|
|
1560
|
+
session && typeof session.execute === 'function'
|
|
1561
|
+
? await session.execute(send)
|
|
1562
|
+
: await send('');
|
|
1563
|
+
return parseResponse(body);
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
/**
|
|
1567
|
+
* 查询单据元数据。
|
|
1568
|
+
* @param {string} formId 单据标识
|
|
1569
|
+
* @param {object} [options] 调用选项
|
|
1570
|
+
* @param {boolean} [options.cache] 为 `false` 时跳过实例内缓存
|
|
1571
|
+
* @returns {Promise<object>}
|
|
1572
|
+
*/
|
|
1573
|
+
function queryBusinessInfo(formId, options) {
|
|
1574
|
+
const useCache = cacheEnabled && !(options && options.cache === false);
|
|
1575
|
+
if (useCache && cache.has(formId)) return cache.get(formId);
|
|
1576
|
+
const pending = request(formId);
|
|
1577
|
+
if (!useCache) return pending;
|
|
1578
|
+
cache.set(formId, pending);
|
|
1579
|
+
pending.catch(() => cache.delete(formId));
|
|
1580
|
+
return pending;
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
return { queryBusinessInfo };
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1586
|
+
metadata = {
|
|
1587
|
+
createMetadataService,
|
|
1588
|
+
defaultParseMetadata,
|
|
1589
|
+
METADATA_ENDPOINTS,
|
|
1590
|
+
};
|
|
1591
|
+
return metadata;
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1594
|
+
var client;
|
|
1595
|
+
var hasRequiredClient;
|
|
1596
|
+
|
|
1597
|
+
function requireClient () {
|
|
1598
|
+
if (hasRequiredClient) return client;
|
|
1599
|
+
hasRequiredClient = 1;
|
|
1600
|
+
|
|
1601
|
+
const { buildConfig, fromEnvVars } = requireConfig();
|
|
1602
|
+
const { request } = requireRequest();
|
|
1603
|
+
const { isBrowser, loadBrowserConfig } = requireBrowserConfig();
|
|
1604
|
+
const { createSession } = requireSession();
|
|
1605
|
+
const { createBillService } = requireBill();
|
|
1606
|
+
const { createMetadataService } = requireMetadata();
|
|
1607
|
+
|
|
1608
|
+
/**
|
|
1609
|
+
* 读取当前运行环境的环境变量记录。
|
|
1610
|
+
* @returns {Object<string, string>}
|
|
1611
|
+
*/
|
|
1612
|
+
function currentEnvRecord() {
|
|
1613
|
+
return isBrowser() ? loadBrowserConfig() : process.env;
|
|
1614
|
+
}
|
|
1615
|
+
|
|
1616
|
+
/**
|
|
1617
|
+
* 从原始响应提取小写键名的响应头。
|
|
1618
|
+
* @param {object} raw 原始响应
|
|
1619
|
+
* @returns {Object<string, string>}
|
|
1620
|
+
*/
|
|
1621
|
+
function extractHeaders(raw) {
|
|
1622
|
+
if (!raw || !raw.headers) return {};
|
|
1623
|
+
const headers = raw.headers;
|
|
1624
|
+
if (typeof headers.forEach === 'function') {
|
|
1625
|
+
const result = {};
|
|
1626
|
+
headers.forEach((value, key) => {
|
|
1627
|
+
result[key] = typeof value === 'string' ? value : String(value);
|
|
1628
|
+
});
|
|
1629
|
+
return result;
|
|
1630
|
+
}
|
|
1631
|
+
return { ...headers };
|
|
1632
|
+
}
|
|
1633
|
+
|
|
1634
|
+
/**
|
|
1635
|
+
* 读取原始响应状态码。
|
|
1636
|
+
* @param {object} raw 原始响应
|
|
1637
|
+
* @returns {number}
|
|
1638
|
+
*/
|
|
1639
|
+
function extractStatus(raw) {
|
|
1640
|
+
return raw && Number.isFinite(raw.status) ? raw.status : 200;
|
|
1641
|
+
}
|
|
1642
|
+
|
|
1643
|
+
/**
|
|
1644
|
+
* 构造传输层:把内核请求适配为模块契约(`{endpoint, parameters, cookie}` → `{status, headers, body}`)。
|
|
1645
|
+
* 会话 Cookie 随请求头下发,响应头回传给登录流程以提取 Cookie。
|
|
1646
|
+
* @param {object} context
|
|
1647
|
+
* @param {object} context.config 生效配置
|
|
1648
|
+
* @param {object} [context.logger] 日志器
|
|
1649
|
+
* @param {Function} [context.fetchImpl] fetch 实现
|
|
1650
|
+
* @returns {Function} 传输函数
|
|
1651
|
+
*/
|
|
1652
|
+
function createTransport({ config, logger, fetchImpl }) {
|
|
1653
|
+
const baseFetch = typeof fetchImpl === 'function' ? fetchImpl : globalThis.fetch;
|
|
1654
|
+
return async ({ endpoint, parameters, cookie }) => {
|
|
1655
|
+
let raw = null;
|
|
1656
|
+
const fetchImpl = (url, init) => {
|
|
1657
|
+
const headers = cookie ? { ...init.headers, Cookie: cookie } : init.headers;
|
|
1658
|
+
return Promise.resolve()
|
|
1659
|
+
.then(() => baseFetch(url, { ...init, headers }))
|
|
1660
|
+
.then((response) => {
|
|
1661
|
+
raw = response;
|
|
1662
|
+
return response;
|
|
1663
|
+
});
|
|
1664
|
+
};
|
|
1665
|
+
const body = await request({
|
|
1666
|
+
serverUrl: config.serverUrl,
|
|
1667
|
+
endpoint,
|
|
1668
|
+
parameters,
|
|
1669
|
+
config,
|
|
1670
|
+
logger,
|
|
1671
|
+
fetchImpl,
|
|
1672
|
+
});
|
|
1673
|
+
return { status: extractStatus(raw), headers: extractHeaders(raw), body };
|
|
1674
|
+
};
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
/**
|
|
1678
|
+
* 合并登录凭证:配置中的账号密码作为缺省,显式凭证覆盖之。
|
|
1679
|
+
* @param {object} config 生效配置
|
|
1680
|
+
* @param {object} [credentials] 显式凭证
|
|
1681
|
+
* @returns {object}
|
|
1682
|
+
*/
|
|
1683
|
+
function mergeCredentials(config, credentials) {
|
|
1684
|
+
const merged = { username: config.username, password: config.password };
|
|
1685
|
+
const source = credentials && typeof credentials === 'object' ? credentials : {};
|
|
1686
|
+
for (const key of Object.keys(source)) {
|
|
1687
|
+
if (source[key] !== undefined) merged[key] = source[key];
|
|
1688
|
+
}
|
|
1689
|
+
return merged;
|
|
1690
|
+
}
|
|
1691
|
+
|
|
1692
|
+
/**
|
|
1693
|
+
* 装配客户端实例:构建传输层、会话与能力模块。
|
|
1694
|
+
* @param {object} config 生效配置
|
|
1695
|
+
* @returns {{login: Function, logout: Function, bill: object, metadata: object, session: object}}
|
|
1696
|
+
*/
|
|
1697
|
+
function assemble(config) {
|
|
1698
|
+
const logger = config.logger && typeof config.logger === 'object' ? config.logger : undefined;
|
|
1699
|
+
const transport = createTransport({ config, logger, fetchImpl: config.fetchImpl });
|
|
1700
|
+
const session = createSession({ transport, config, logger });
|
|
1701
|
+
return {
|
|
1702
|
+
login: (credentials) => session.login(mergeCredentials(config, credentials)),
|
|
1703
|
+
logout: () => session.logout(),
|
|
1704
|
+
bill: createBillService({ transport, session }),
|
|
1705
|
+
metadata: createMetadataService({ transport, session }),
|
|
1706
|
+
session,
|
|
1707
|
+
};
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
/**
|
|
1711
|
+
* 创建客户端:合并默认值、环境变量与显式配置,并做必填校验。
|
|
1712
|
+
* @param {object} [config]
|
|
1713
|
+
* @returns {object}
|
|
1714
|
+
*/
|
|
1715
|
+
function createClient(config) {
|
|
1716
|
+
return assemble(buildConfig({ env: fromEnvVars(currentEnvRecord()), explicit: config }));
|
|
1717
|
+
}
|
|
1718
|
+
|
|
1719
|
+
/**
|
|
1720
|
+
* 由环境变量创建客户端:仅合并默认值与环境变量,并做必填校验。
|
|
1721
|
+
* @param {object} [env] 显式环境变量记录,缺省取当前运行环境
|
|
1722
|
+
* @returns {object}
|
|
1723
|
+
*/
|
|
1724
|
+
function createClientFromEnv(env) {
|
|
1725
|
+
const record = env === undefined ? currentEnvRecord() : env;
|
|
1726
|
+
return assemble(buildConfig({ env: fromEnvVars(record) }));
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1729
|
+
client = { createClient, createClientFromEnv };
|
|
1730
|
+
return client;
|
|
1731
|
+
}
|
|
1732
|
+
|
|
1733
|
+
var src;
|
|
1734
|
+
var hasRequiredSrc;
|
|
1735
|
+
|
|
1736
|
+
function requireSrc () {
|
|
1737
|
+
if (hasRequiredSrc) return src;
|
|
1738
|
+
hasRequiredSrc = 1;
|
|
1739
|
+
|
|
1740
|
+
const { SDK_VERSION } = requireVersion();
|
|
1741
|
+
const { K3CloudError } = requireErrors();
|
|
1742
|
+
const { createClient, createClientFromEnv } = requireClient();
|
|
1743
|
+
|
|
1744
|
+
src = { SDK_VERSION, K3CloudError, createClient, createClientFromEnv };
|
|
1745
|
+
return src;
|
|
1746
|
+
}
|
|
1747
|
+
|
|
1748
|
+
var srcExports = requireSrc();
|
|
1749
|
+
var index = /*@__PURE__*/getDefaultExportFromCjs(srcExports);
|
|
1750
|
+
|
|
1751
|
+
module.exports = index;
|