tigeropen 0.3.0 → 0.5.5
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 +55 -2
- package/dist/cjs/client/api-response.js +28 -7
- package/dist/cjs/client/case-convert.js +4 -3
- package/dist/cjs/client/http-client.js +124 -8
- package/dist/cjs/client/token-methods.js +42 -0
- package/dist/cjs/config/client-config.js +115 -16
- package/dist/cjs/config/config-parser.js +19 -9
- package/dist/cjs/config/index.js +4 -1
- package/dist/cjs/config/token-manager.js +54 -4
- package/dist/cjs/index.js +53 -2
- package/dist/cjs/model/enums.js +106 -7
- package/dist/cjs/model/order-helpers.js +149 -0
- package/dist/cjs/model/order-status.js +46 -0
- package/dist/cjs/model/quote-requests.js +11 -0
- package/dist/cjs/model/trade-requests.js +13 -0
- package/dist/cjs/push/index.js +1 -0
- package/dist/cjs/push/pb/OrderStatusData.js +24 -0
- package/dist/cjs/push/proto-message.js +6 -0
- package/dist/cjs/push/push-client.js +117 -19
- package/dist/cjs/push/push-message.js +4 -0
- package/dist/cjs/push/tick-util.js +172 -0
- package/dist/cjs/quote/quote-client.js +584 -42
- package/dist/cjs/trade/trade-client.js +334 -32
- package/dist/cjs/version.js +4 -0
- package/dist/esm/client/api-request.js +1 -1
- package/dist/esm/client/api-response.js +29 -8
- package/dist/esm/client/case-convert.js +4 -3
- package/dist/esm/client/http-client.js +128 -12
- package/dist/esm/client/index.js +6 -6
- package/dist/esm/client/token-methods.js +37 -0
- package/dist/esm/config/client-config.js +118 -20
- package/dist/esm/config/config-parser.js +19 -9
- package/dist/esm/config/index.js +4 -3
- package/dist/esm/config/token-manager.js +55 -5
- package/dist/esm/index.js +15 -1
- package/dist/esm/logger/index.js +1 -1
- package/dist/esm/model/contract-helpers.js +1 -1
- package/dist/esm/model/enums.js +104 -6
- package/dist/esm/model/order-helpers.js +142 -1
- package/dist/esm/model/order-status.js +43 -0
- package/dist/esm/model/quote-requests.js +10 -0
- package/dist/esm/model/trade-requests.js +12 -0
- package/dist/esm/push/index.js +6 -5
- package/dist/esm/push/pb/OrderStatusData.js +24 -0
- package/dist/esm/push/pb/PushData.js +11 -11
- package/dist/esm/push/pb/QuoteBasicData.js +1 -1
- package/dist/esm/push/pb/Response.js +1 -1
- package/dist/esm/push/pb/index.js +17 -17
- package/dist/esm/push/proto-message.js +9 -3
- package/dist/esm/push/push-client.js +124 -26
- package/dist/esm/push/push-message.js +4 -0
- package/dist/esm/push/tick-util.js +165 -0
- package/dist/esm/quote/index.js +1 -1
- package/dist/esm/quote/quote-client.js +553 -44
- package/dist/esm/signer/index.js +2 -2
- package/dist/esm/trade/index.js +1 -1
- package/dist/esm/trade/trade-client.js +303 -34
- package/dist/esm/version.js +1 -0
- package/dist/types/client/api-response.d.ts +6 -4
- package/dist/types/client/case-convert.d.ts +3 -1
- package/dist/types/client/http-client.d.ts +32 -1
- package/dist/types/client/token-methods.d.ts +34 -0
- package/dist/types/config/client-config.d.ts +22 -1
- package/dist/types/config/index.d.ts +3 -1
- package/dist/types/config/token-manager.d.ts +27 -3
- package/dist/types/index.d.ts +22 -1
- package/dist/types/model/enums.d.ts +77 -7
- package/dist/types/model/order-helpers.d.ts +52 -1
- package/dist/types/model/order-status.d.ts +14 -0
- package/dist/types/model/order.d.ts +127 -10
- package/dist/types/model/quote-requests.d.ts +356 -0
- package/dist/types/model/quote.d.ts +391 -4
- package/dist/types/model/trade-requests.d.ts +309 -0
- package/dist/types/model/trade.d.ts +231 -5
- package/dist/types/push/callbacks.d.ts +3 -7
- package/dist/types/push/index.d.ts +1 -0
- package/dist/types/push/pb/OrderStatusData.d.ts +4 -0
- package/dist/types/push/push-client.d.ts +36 -3
- package/dist/types/push/push-message.d.ts +4 -0
- package/dist/types/push/tick-util.d.ts +30 -0
- package/dist/types/quote/quote-client.d.ts +193 -15
- package/dist/types/trade/trade-client.d.ts +136 -18
- package/dist/types/version.d.ts +1 -0
- package/package.json +5 -2
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
|
|
1
|
+
import { TokenManager } from '../config/token-manager.js';
|
|
2
|
+
import { getSignContent } from '../signer/sign-content.js';
|
|
3
|
+
import { signWithRSA, verifyWithRSA } from '../signer/signer.js';
|
|
4
|
+
import { TigerError } from './errors.js';
|
|
5
|
+
import { defaultRetryPolicy } from './retry.js';
|
|
6
|
+
import { parseApiResponse, unmarshalData } from './api-response.js';
|
|
7
|
+
import { SDK_VERSION } from '../version.js';
|
|
8
8
|
/** User-Agent 字符串 */
|
|
9
9
|
const USER_AGENT = `openapi-typescript-sdk-${SDK_VERSION}`;
|
|
10
10
|
/** 默认字符集 */
|
|
@@ -13,14 +13,45 @@ const DEFAULT_CHARSET = 'UTF-8';
|
|
|
13
13
|
const DEFAULT_SIGN_TYPE = 'RSA';
|
|
14
14
|
/** 默认 API 版本 */
|
|
15
15
|
const DEFAULT_VERSION = '2.0';
|
|
16
|
+
/** Token 刷新 API 方法名 */
|
|
17
|
+
const METHOD_TOKEN_REFRESH = 'user_token_refresh';
|
|
18
|
+
/** 默认后台 token 检查间隔(毫秒):5 分钟 */
|
|
19
|
+
const DEFAULT_TOKEN_CHECK_INTERVAL = 5 * 60 * 1000;
|
|
16
20
|
/**
|
|
17
21
|
* HttpClient handles HTTP requests, signing, retry, and timeout
|
|
18
22
|
*/
|
|
19
23
|
export class HttpClient {
|
|
20
24
|
constructor(config, retryPolicy, options) {
|
|
25
|
+
/** non-null when auto-refresh is active */
|
|
26
|
+
this.tokenManager = null;
|
|
21
27
|
this.config = config;
|
|
22
28
|
this.retryPolicy = retryPolicy ?? defaultRetryPolicy();
|
|
23
29
|
this.targetUrl = options?.useQuoteServerUrl ? config.quoteServerUrl : config.serverUrl;
|
|
30
|
+
// Auto-start token refresh when tokenRefreshDuration is configured (mirrors Go SDK behaviour)
|
|
31
|
+
if (config.tokenRefreshDuration && config.tokenRefreshDuration > 0) {
|
|
32
|
+
const interval = config.tokenCheckInterval ?? DEFAULT_TOKEN_CHECK_INTERVAL;
|
|
33
|
+
const opts = {
|
|
34
|
+
refreshDuration: config.tokenRefreshDuration,
|
|
35
|
+
refreshInterval: interval,
|
|
36
|
+
};
|
|
37
|
+
if (config.tokenWriter) {
|
|
38
|
+
opts.tokenWriter = config.tokenWriter;
|
|
39
|
+
}
|
|
40
|
+
if (config.tokenLoader) {
|
|
41
|
+
opts.tokenLoader = config.tokenLoader;
|
|
42
|
+
}
|
|
43
|
+
this.tokenManager = this.startTokenAutoRefresh(null, opts);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Stop the background token auto-refresh timer.
|
|
48
|
+
* Call this when the HttpClient is no longer needed to avoid timer leaks.
|
|
49
|
+
*/
|
|
50
|
+
close() {
|
|
51
|
+
if (this.tokenManager) {
|
|
52
|
+
this.tokenManager.stopAutoRefresh();
|
|
53
|
+
this.tokenManager = null;
|
|
54
|
+
}
|
|
24
55
|
}
|
|
25
56
|
/**
|
|
26
57
|
* Build common request parameters
|
|
@@ -31,7 +62,11 @@ export class HttpClient {
|
|
|
31
62
|
method: apiMethod,
|
|
32
63
|
charset: DEFAULT_CHARSET,
|
|
33
64
|
sign_type: DEFAULT_SIGN_TYPE,
|
|
34
|
-
timestamp:
|
|
65
|
+
timestamp: (() => {
|
|
66
|
+
const d = new Date();
|
|
67
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
68
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
|
69
|
+
})(),
|
|
35
70
|
version: version || DEFAULT_VERSION,
|
|
36
71
|
biz_content: bizContent,
|
|
37
72
|
};
|
|
@@ -58,6 +93,7 @@ export class HttpClient {
|
|
|
58
93
|
const headers = {
|
|
59
94
|
'Content-Type': 'application/json;charset=UTF-8',
|
|
60
95
|
'User-Agent': USER_AGENT,
|
|
96
|
+
'Connection': 'close',
|
|
61
97
|
};
|
|
62
98
|
if (this.config.token) {
|
|
63
99
|
headers['Authorization'] = this.config.token;
|
|
@@ -68,7 +104,8 @@ export class HttpClient {
|
|
|
68
104
|
body,
|
|
69
105
|
signal: AbortSignal.timeout(this.config.timeout * 1000),
|
|
70
106
|
});
|
|
71
|
-
|
|
107
|
+
const text = await response.text();
|
|
108
|
+
return text;
|
|
72
109
|
}
|
|
73
110
|
/**
|
|
74
111
|
* Execute a structured API request, returning a parsed ApiResponse.
|
|
@@ -95,6 +132,10 @@ export class HttpClient {
|
|
|
95
132
|
}
|
|
96
133
|
catch (err) {
|
|
97
134
|
lastErr = err;
|
|
135
|
+
// Only retry on network errors, not API business errors (TigerError with code)
|
|
136
|
+
if (err.code !== undefined && err.code !== -1) {
|
|
137
|
+
throw err; // API returned a business error code, don't retry
|
|
138
|
+
}
|
|
98
139
|
if (!this.retryPolicy.shouldRetry(request.method)) {
|
|
99
140
|
throw err;
|
|
100
141
|
}
|
|
@@ -107,9 +148,10 @@ export class HttpClient {
|
|
|
107
148
|
*
|
|
108
149
|
* @param apiMethod - API method name (e.g. "market_state", "place_order")
|
|
109
150
|
* @param requestJson - Raw biz_content JSON string
|
|
151
|
+
* @param version - Optional API version override (default: "2.0")
|
|
110
152
|
* @returns Raw response JSON string, unparsed
|
|
111
153
|
*/
|
|
112
|
-
async execute(apiMethod, requestJson) {
|
|
154
|
+
async execute(apiMethod, requestJson, version) {
|
|
113
155
|
// Parameter validation
|
|
114
156
|
if (!apiMethod) {
|
|
115
157
|
throw new TigerError(-1, 'api_method must not be empty');
|
|
@@ -120,7 +162,7 @@ export class HttpClient {
|
|
|
120
162
|
catch {
|
|
121
163
|
throw new TigerError(-1, 'request_json is not valid JSON');
|
|
122
164
|
}
|
|
123
|
-
const params = this.buildCommonParams(apiMethod, requestJson);
|
|
165
|
+
const params = this.buildCommonParams(apiMethod, requestJson, version);
|
|
124
166
|
const sign = this.signParams(params);
|
|
125
167
|
params['sign'] = sign;
|
|
126
168
|
let lastErr;
|
|
@@ -141,6 +183,10 @@ export class HttpClient {
|
|
|
141
183
|
}
|
|
142
184
|
catch (err) {
|
|
143
185
|
lastErr = err;
|
|
186
|
+
// Don't retry API business errors
|
|
187
|
+
if (err.code !== undefined && err.code !== -1) {
|
|
188
|
+
throw err;
|
|
189
|
+
}
|
|
144
190
|
if (!this.retryPolicy.shouldRetry(apiMethod)) {
|
|
145
191
|
throw err;
|
|
146
192
|
}
|
|
@@ -148,6 +194,75 @@ export class HttpClient {
|
|
|
148
194
|
}
|
|
149
195
|
throw lastErr;
|
|
150
196
|
}
|
|
197
|
+
/**
|
|
198
|
+
* 调用 user_token_refresh 接口获取新 token,返回新 token 字符串。
|
|
199
|
+
* 此方法仅查询,不修改 config 中的 token。
|
|
200
|
+
*/
|
|
201
|
+
async queryToken() {
|
|
202
|
+
const params = this.buildCommonParams(METHOD_TOKEN_REFRESH, '{}');
|
|
203
|
+
const sign = this.signParams(params);
|
|
204
|
+
params['sign'] = sign;
|
|
205
|
+
const body = await this.doHttpPost(params);
|
|
206
|
+
const response = parseApiResponse(body);
|
|
207
|
+
this.verifyResponseSign(params['timestamp'], response.sign);
|
|
208
|
+
const data = unmarshalData(response.data);
|
|
209
|
+
const newToken = data?.token;
|
|
210
|
+
if (!newToken) {
|
|
211
|
+
throw new TigerError(-1, '服务端返回空 token');
|
|
212
|
+
}
|
|
213
|
+
return newToken;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* 刷新 token:调用接口获取新 token 后更新 config.token。
|
|
217
|
+
*
|
|
218
|
+
* @param tokenManager - 可选外部 TokenManager;若提供则调用 setToken() 写文件并触发回调。
|
|
219
|
+
* 若 NewHttpClient 已自动启动内部 TokenManager,其内存 token 也会同步更新。
|
|
220
|
+
*/
|
|
221
|
+
async refreshToken(tokenManager) {
|
|
222
|
+
const newToken = await this.queryToken();
|
|
223
|
+
this.config.token = newToken;
|
|
224
|
+
// Keep internal tokenManager in sync so shouldTokenRefresh stays accurate.
|
|
225
|
+
if (this.tokenManager && tokenManager !== this.tokenManager) {
|
|
226
|
+
this.tokenManager.syncToken(newToken);
|
|
227
|
+
}
|
|
228
|
+
if (tokenManager) {
|
|
229
|
+
tokenManager.setToken(newToken);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* 启动后台 token 自动刷新。
|
|
234
|
+
*
|
|
235
|
+
* @param tokenManager - 可为 null:SDK 内部自动创建一个仅内存的 TokenManager,
|
|
236
|
+
* 适合直接通过 token 在代码里设置、不使用文件的场景。
|
|
237
|
+
* @param options - 仅在 tokenManager 为 null 时生效,用于配置内部 TokenManager
|
|
238
|
+
* (refreshDuration / refreshInterval / tokenWriter / tokenLoader)。
|
|
239
|
+
* @returns 使用或创建的 TokenManager 实例
|
|
240
|
+
*/
|
|
241
|
+
startTokenAutoRefresh(tokenManager, options) {
|
|
242
|
+
if (!tokenManager) {
|
|
243
|
+
tokenManager = new TokenManager(options);
|
|
244
|
+
// 从 config.token 同步当前 token,使 shouldTokenRefresh 能正确判断。
|
|
245
|
+
// 若 config.token 暂时为空(异步 tokenLoader 尚未 resolve),则先异步加载。
|
|
246
|
+
if (this.config.token) {
|
|
247
|
+
tokenManager.syncToken(this.config.token);
|
|
248
|
+
}
|
|
249
|
+
else if (options?.tokenLoader) {
|
|
250
|
+
// tokenLoader 可能是异步的;在后台 resolve 后同步到 config.token 和 TokenManager。
|
|
251
|
+
Promise.resolve(options.tokenLoader()).then((t) => {
|
|
252
|
+
if (t) {
|
|
253
|
+
this.config.token = t;
|
|
254
|
+
tokenManager.syncToken(t);
|
|
255
|
+
}
|
|
256
|
+
}).catch(() => { });
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
tokenManager.startAutoRefresh(async () => {
|
|
260
|
+
const newToken = await this.queryToken();
|
|
261
|
+
this.config.token = newToken;
|
|
262
|
+
return newToken;
|
|
263
|
+
});
|
|
264
|
+
return tokenManager;
|
|
265
|
+
}
|
|
151
266
|
/** Delay for the specified milliseconds */
|
|
152
267
|
sleep(ms) {
|
|
153
268
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
@@ -161,7 +276,8 @@ export class HttpClient {
|
|
|
161
276
|
*/
|
|
162
277
|
verifyResponseSign(timestamp, signBase64) {
|
|
163
278
|
if (!signBase64) {
|
|
164
|
-
|
|
279
|
+
// Some endpoints don't return a signature; skip verification silently.
|
|
280
|
+
return;
|
|
165
281
|
}
|
|
166
282
|
const valid = verifyWithRSA(this.config.tigerPublicKey, timestamp, signBase64);
|
|
167
283
|
if (!valid) {
|
package/dist/esm/client/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Transport layer exports.
|
|
3
3
|
*/
|
|
4
|
-
export { HttpClient } from './http-client';
|
|
5
|
-
export { TigerError, classifyErrorCode } from './errors';
|
|
6
|
-
export { RetryPolicy, defaultRetryPolicy, isTradeOperation } from './retry';
|
|
7
|
-
export { createApiRequest } from './api-request';
|
|
8
|
-
export { parseApiResponse, unmarshalData } from './api-response';
|
|
9
|
-
export { camelToSnake, keysToSnakeCase } from './case-convert';
|
|
4
|
+
export { HttpClient } from './http-client.js';
|
|
5
|
+
export { TigerError, classifyErrorCode } from './errors.js';
|
|
6
|
+
export { RetryPolicy, defaultRetryPolicy, isTradeOperation } from './retry.js';
|
|
7
|
+
export { createApiRequest } from './api-request.js';
|
|
8
|
+
export { parseApiResponse, unmarshalData } from './api-response.js';
|
|
9
|
+
export { camelToSnake, keysToSnakeCase } from './case-convert.js';
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Call the `user_token_refresh` API and return the new token string.
|
|
3
|
+
* Read-only: does NOT update the stored token.
|
|
4
|
+
* Use `refreshToken()` to also update the in-memory config and optionally persist.
|
|
5
|
+
*/
|
|
6
|
+
export async function queryToken(httpClient) {
|
|
7
|
+
return httpClient.queryToken();
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Refresh the token: call the API, update the in-memory config token, and
|
|
11
|
+
* optionally persist via the provided TokenManager (file + writer callback).
|
|
12
|
+
*
|
|
13
|
+
* @param httpClient - The underlying HTTP client
|
|
14
|
+
* @param tokenManager - optional TokenManager for file persistence and writer callback
|
|
15
|
+
*/
|
|
16
|
+
export async function refreshToken(httpClient, tokenManager) {
|
|
17
|
+
return httpClient.refreshToken(tokenManager);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Start background token auto-refresh. Returns a TokenManager that can be
|
|
21
|
+
* used to stop the background task via `tm.stopAutoRefresh()`.
|
|
22
|
+
*
|
|
23
|
+
* @param httpClient - The underlying HTTP client
|
|
24
|
+
* @param refreshDurationSecs - Refresh threshold in seconds (minimum 30).
|
|
25
|
+
* When the token age exceeds this value the refresh is triggered.
|
|
26
|
+
* @param checkIntervalMs - How often to check whether a refresh is needed,
|
|
27
|
+
* in milliseconds. Defaults to 300 000 ms (5 minutes).
|
|
28
|
+
* @param tokenWriter - Optional callback invoked with the new token string
|
|
29
|
+
* after each successful refresh.
|
|
30
|
+
*/
|
|
31
|
+
export function startTokenAutoRefresh(httpClient, refreshDurationSecs, checkIntervalMs, tokenWriter) {
|
|
32
|
+
return httpClient.startTokenAutoRefresh(null, {
|
|
33
|
+
refreshDuration: refreshDurationSecs,
|
|
34
|
+
refreshInterval: checkIntervalMs,
|
|
35
|
+
tokenWriter,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
@@ -8,11 +8,12 @@
|
|
|
8
8
|
*
|
|
9
9
|
* Priority: environment variables > code options (incl. config file) > defaults
|
|
10
10
|
*/
|
|
11
|
-
import { readFileSync, existsSync } from 'fs';
|
|
12
|
-
import { join } from 'path';
|
|
11
|
+
import { readFileSync, existsSync, statSync } from 'fs';
|
|
12
|
+
import { join, dirname } from 'path';
|
|
13
13
|
import { homedir, networkInterfaces } from 'os';
|
|
14
|
-
import { parsePropertiesString } from './config-parser';
|
|
15
|
-
import { queryDomains, resolveDynamicServerUrl, resolveDynamicQuoteServerUrl } from './domain';
|
|
14
|
+
import { parsePropertiesString } from './config-parser.js';
|
|
15
|
+
import { queryDomains, resolveDynamicServerUrl, resolveDynamicQuoteServerUrl } from './domain.js';
|
|
16
|
+
import { TokenManager } from './token-manager.js';
|
|
16
17
|
/** Default config file name */
|
|
17
18
|
const CONFIG_FILE_NAME = 'tiger_openapi_config.properties';
|
|
18
19
|
/** Defaults */
|
|
@@ -21,11 +22,20 @@ const DEFAULT_TIMEOUT = 15;
|
|
|
21
22
|
const DEFAULT_SERVER_URL = 'https://openapi.tigerfintech.com/gateway';
|
|
22
23
|
/** Tiger public key for response signature verification (Base64-encoded) */
|
|
23
24
|
const TIGER_PUBLIC_KEY = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDNF3G8SoEcCZh2rshUbayDgLLrj6rKgzNMxDL2HSnKcB0+GPOsndqSv+a4IBu9+I3fyBp5hkyMMG2+AXugd9pMpy6VxJxlNjhX1MYbNTZJUT4nudki4uh+LMOkIBHOceGNXjgB+cXqmlUnjlqha/HgboeHSnSgpM3dKSJQlIOsDwIDAQAB';
|
|
25
|
+
/** Sandbox / QA tiger public key for response signature verification */
|
|
26
|
+
export const SANDBOX_TIGER_PUBLIC_KEY = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCbm21i11hgAENGd3/f280PSe4g9YGkS3TEXBYMidihTvHHf' +
|
|
27
|
+
'+tJ0PYD0o3PruI0hl3qhEjHTAxb75T5YD3SGK4IBhHn/Rk6mhqlGgI+bBrBVYaXixmHfRo75RpUUuWACyeqQk' +
|
|
28
|
+
'ZckgR0McxuW9xRMIa2cXZOoL1E4SL4lXKGhKoWbwIDAQAB';
|
|
24
29
|
/** Environment variable names */
|
|
25
30
|
const ENV_TIGER_ID = 'TIGEROPEN_TIGER_ID';
|
|
26
31
|
const ENV_PRIVATE_KEY = 'TIGEROPEN_PRIVATE_KEY';
|
|
27
32
|
const ENV_ACCOUNT = 'TIGEROPEN_ACCOUNT';
|
|
33
|
+
const ENV_SECRET_KEY = 'TIGEROPEN_SECRET_KEY';
|
|
28
34
|
const ENV_TOKEN = 'TIGEROPEN_TOKEN';
|
|
35
|
+
const ENV_TOKEN_FILE = 'TIGEROPEN_TOKEN_FILE';
|
|
36
|
+
const ENV_TIGER_PUBLIC_KEY = 'TIGEROPEN_TIGER_PUBLIC_KEY';
|
|
37
|
+
const ENV_SERVER_URL = 'TIGEROPEN_SERVER_URL';
|
|
38
|
+
const ENV_QUOTE_SERVER_URL = 'TIGEROPEN_QUOTE_SERVER_URL';
|
|
29
39
|
/**
|
|
30
40
|
* Load and parse a Java-style properties file.
|
|
31
41
|
*
|
|
@@ -98,12 +108,32 @@ export function createClientConfig(options) {
|
|
|
98
108
|
const opts = options ?? {};
|
|
99
109
|
// Load properties: explicit path > auto-discovery
|
|
100
110
|
let fileProps = {};
|
|
111
|
+
let configFileDir;
|
|
101
112
|
if (opts.propertiesFilePath) {
|
|
102
|
-
|
|
113
|
+
// Support both directory path and full file path
|
|
114
|
+
let filePath = opts.propertiesFilePath;
|
|
115
|
+
if (existsSync(filePath) && statSync(filePath).isDirectory()) {
|
|
116
|
+
configFileDir = filePath;
|
|
117
|
+
filePath = join(filePath, CONFIG_FILE_NAME);
|
|
118
|
+
}
|
|
119
|
+
else if (!existsSync(filePath) && !filePath.endsWith('.properties')) {
|
|
120
|
+
// Path doesn't exist as-is; try treating it as a directory
|
|
121
|
+
const asDir = join(filePath, CONFIG_FILE_NAME);
|
|
122
|
+
if (existsSync(asDir)) {
|
|
123
|
+
configFileDir = filePath;
|
|
124
|
+
filePath = asDir;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
// It's a file path: derive directory from it
|
|
129
|
+
configFileDir = dirname(filePath);
|
|
130
|
+
}
|
|
131
|
+
fileProps = loadPropertiesFile(filePath);
|
|
103
132
|
}
|
|
104
133
|
else {
|
|
105
134
|
const discovered = discoverConfigFile();
|
|
106
135
|
if (discovered) {
|
|
136
|
+
configFileDir = dirname(discovered);
|
|
107
137
|
fileProps = loadPropertiesFile(discovered);
|
|
108
138
|
}
|
|
109
139
|
}
|
|
@@ -111,15 +141,20 @@ export function createClientConfig(options) {
|
|
|
111
141
|
let tigerId = opts.tigerId || fileProps['tiger_id'] || '';
|
|
112
142
|
let privateKey = opts.privateKey || resolvePrivateKey(fileProps) || '';
|
|
113
143
|
let account = opts.account || fileProps['account'] || '';
|
|
144
|
+
let secretKey = opts.secretKey || fileProps['secret_key'] || undefined;
|
|
114
145
|
let token = opts.token || fileProps['token'];
|
|
115
146
|
const license = opts.license || fileProps['license'];
|
|
116
147
|
const language = opts.language || fileProps['language'] || DEFAULT_LANGUAGE;
|
|
117
148
|
const timezone = opts.timezone || fileProps['timezone'];
|
|
149
|
+
// tiger_public_key from properties file (e.g. for QA/sandbox environments)
|
|
150
|
+
let tigerPublicKey = opts.tigerPublicKey || fileProps['tiger_public_key'] || TIGER_PUBLIC_KEY;
|
|
118
151
|
// Environment variables override everything
|
|
119
152
|
const envTigerId = process.env[ENV_TIGER_ID];
|
|
120
153
|
const envPrivateKey = process.env[ENV_PRIVATE_KEY];
|
|
121
154
|
const envAccount = process.env[ENV_ACCOUNT];
|
|
155
|
+
const envSecretKey = process.env[ENV_SECRET_KEY];
|
|
122
156
|
const envToken = process.env[ENV_TOKEN];
|
|
157
|
+
const envTigerPublicKey = process.env[ENV_TIGER_PUBLIC_KEY];
|
|
123
158
|
if (envTigerId) {
|
|
124
159
|
tigerId = envTigerId;
|
|
125
160
|
}
|
|
@@ -129,9 +164,47 @@ export function createClientConfig(options) {
|
|
|
129
164
|
if (envAccount) {
|
|
130
165
|
account = envAccount;
|
|
131
166
|
}
|
|
167
|
+
if (envSecretKey) {
|
|
168
|
+
secretKey = envSecretKey;
|
|
169
|
+
}
|
|
132
170
|
if (envToken) {
|
|
133
171
|
token = envToken;
|
|
134
172
|
}
|
|
173
|
+
if (envTigerPublicKey) {
|
|
174
|
+
tigerPublicKey = envTigerPublicKey;
|
|
175
|
+
}
|
|
176
|
+
// Token loading priority: env TIGEROPEN_TOKEN > tokenLoader > token file (TIGEROPEN_TOKEN_FILE or default)
|
|
177
|
+
if (!token) {
|
|
178
|
+
if (opts.tokenLoader) {
|
|
179
|
+
// tokenLoader is async-capable; we do a best-effort synchronous call here.
|
|
180
|
+
// If the loader returns a Promise, the token will be set later via HttpClient.
|
|
181
|
+
try {
|
|
182
|
+
const result = opts.tokenLoader();
|
|
183
|
+
if (result instanceof Promise) {
|
|
184
|
+
// Cannot await in sync constructor; HttpClient.startTokenAutoRefresh() will
|
|
185
|
+
// resolve this Promise and sync the token after construction.
|
|
186
|
+
}
|
|
187
|
+
else if (result) {
|
|
188
|
+
token = result;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
// loader failed; leave token undefined
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
else {
|
|
196
|
+
// Load from token file: TIGEROPEN_TOKEN_FILE env var > config dir > default
|
|
197
|
+
const tokenFilePath = process.env[ENV_TOKEN_FILE]
|
|
198
|
+
|| (configFileDir ? join(configFileDir, 'tiger_openapi_token.properties') : 'tiger_openapi_token.properties');
|
|
199
|
+
const tm = new TokenManager({ filePath: tokenFilePath });
|
|
200
|
+
try {
|
|
201
|
+
token = tm.loadTokenSync();
|
|
202
|
+
}
|
|
203
|
+
catch {
|
|
204
|
+
// file not found or no token field; leave token undefined
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
135
208
|
// Validate required fields
|
|
136
209
|
if (!tigerId) {
|
|
137
210
|
throw new Error(`tigerId is required. Set it via options.tigerId, a config file, or the ${ENV_TIGER_ID} environment variable.`);
|
|
@@ -139,47 +212,72 @@ export function createClientConfig(options) {
|
|
|
139
212
|
if (!privateKey) {
|
|
140
213
|
throw new Error(`privateKey is required. Set it via options.privateKey, a config file, or the ${ENV_PRIVATE_KEY} environment variable.`);
|
|
141
214
|
}
|
|
142
|
-
// Resolve server URL: explicit > dynamic domain > default
|
|
215
|
+
// Resolve server URL: env var > explicit opts > file > dynamic domain > default
|
|
143
216
|
const enableDynamicDomain = opts.enableDynamicDomain ?? true;
|
|
144
217
|
let serverUrl;
|
|
145
218
|
let quoteServerUrl;
|
|
146
|
-
|
|
219
|
+
// Query dynamic domains once (may spawn a child process); reuse for both URLs.
|
|
220
|
+
let domainConf = {};
|
|
221
|
+
const envServerUrl = process.env[ENV_SERVER_URL];
|
|
222
|
+
const envQuoteServerUrl = process.env[ENV_QUOTE_SERVER_URL];
|
|
223
|
+
const needServerUrl = !envServerUrl && !opts.serverUrl && !fileProps['server_url'];
|
|
224
|
+
const needQuoteServerUrl = !envQuoteServerUrl && !opts.quoteServerUrl && !fileProps['quote_server_url'];
|
|
225
|
+
if (enableDynamicDomain && (needServerUrl || needQuoteServerUrl)) {
|
|
226
|
+
domainConf = queryDomains(license);
|
|
227
|
+
}
|
|
228
|
+
if (envServerUrl) {
|
|
229
|
+
serverUrl = envServerUrl;
|
|
230
|
+
}
|
|
231
|
+
else if (opts.serverUrl) {
|
|
147
232
|
serverUrl = opts.serverUrl;
|
|
148
233
|
}
|
|
234
|
+
else if (fileProps['server_url']) {
|
|
235
|
+
serverUrl = fileProps['server_url'];
|
|
236
|
+
}
|
|
149
237
|
else {
|
|
150
|
-
|
|
151
|
-
if (enableDynamicDomain) {
|
|
152
|
-
const domainConf = queryDomains(license);
|
|
153
|
-
dynamicUrl = resolveDynamicServerUrl(domainConf, license);
|
|
154
|
-
}
|
|
238
|
+
const dynamicUrl = resolveDynamicServerUrl(domainConf, license);
|
|
155
239
|
serverUrl = dynamicUrl || DEFAULT_SERVER_URL;
|
|
156
240
|
}
|
|
157
|
-
// Resolve quote server URL: explicit > dynamic domain > serverUrl fallback
|
|
158
|
-
if (
|
|
241
|
+
// Resolve quote server URL: env var > explicit opts > file > dynamic domain > serverUrl fallback
|
|
242
|
+
if (envQuoteServerUrl) {
|
|
243
|
+
quoteServerUrl = envQuoteServerUrl;
|
|
244
|
+
}
|
|
245
|
+
else if (opts.quoteServerUrl) {
|
|
159
246
|
quoteServerUrl = opts.quoteServerUrl;
|
|
160
247
|
}
|
|
248
|
+
else if (fileProps['quote_server_url']) {
|
|
249
|
+
quoteServerUrl = fileProps['quote_server_url'];
|
|
250
|
+
}
|
|
161
251
|
else {
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
252
|
+
// Only use dynamic domain if serverUrl itself came from dynamic resolution (not pinned by env/opts/file).
|
|
253
|
+
// When serverUrl is pinned, prefer it as the quote fallback to avoid mixing environments.
|
|
254
|
+
const serverUrlPinned = !!(envServerUrl || opts.serverUrl || fileProps['server_url']);
|
|
255
|
+
if (!serverUrlPinned) {
|
|
256
|
+
const dynamicQuoteUrl = resolveDynamicQuoteServerUrl(domainConf, license);
|
|
257
|
+
quoteServerUrl = dynamicQuoteUrl || serverUrl;
|
|
258
|
+
}
|
|
259
|
+
else {
|
|
260
|
+
quoteServerUrl = serverUrl;
|
|
166
261
|
}
|
|
167
|
-
quoteServerUrl = dynamicQuoteUrl || serverUrl;
|
|
168
262
|
}
|
|
169
263
|
return {
|
|
170
264
|
tigerId,
|
|
171
265
|
privateKey,
|
|
172
266
|
account,
|
|
267
|
+
secretKey: secretKey || undefined,
|
|
173
268
|
license,
|
|
174
269
|
language,
|
|
175
270
|
timezone,
|
|
176
271
|
timeout: opts.timeout ?? DEFAULT_TIMEOUT,
|
|
177
272
|
token,
|
|
178
273
|
tokenRefreshDuration: opts.tokenRefreshDuration,
|
|
274
|
+
tokenCheckInterval: opts.tokenCheckInterval,
|
|
275
|
+
tokenLoader: opts.tokenLoader,
|
|
276
|
+
tokenWriter: opts.tokenWriter,
|
|
179
277
|
serverUrl,
|
|
180
278
|
quoteServerUrl,
|
|
181
279
|
deviceId: detectDeviceId(),
|
|
182
|
-
tigerPublicKey
|
|
280
|
+
tigerPublicKey,
|
|
183
281
|
};
|
|
184
282
|
}
|
|
185
283
|
/**
|
|
@@ -33,34 +33,34 @@ export function parsePropertiesString(content) {
|
|
|
33
33
|
let continuation = false;
|
|
34
34
|
for (const rawLine of lines) {
|
|
35
35
|
if (continuation) {
|
|
36
|
-
// 续行:去除前导空格后拼接
|
|
37
36
|
const trimmedLeft = rawLine.replace(/^[ \t]+/, '');
|
|
38
|
-
if (trimmedLeft.
|
|
37
|
+
if (trimmedLeft === '' || trimmedLeft.startsWith('#') || trimmedLeft.startsWith('!')) {
|
|
38
|
+
continuation = false;
|
|
39
|
+
}
|
|
40
|
+
else if (endsWithContinuation(trimmedLeft)) {
|
|
39
41
|
currentLine += trimmedLeft.slice(0, -1);
|
|
40
42
|
continue;
|
|
41
43
|
}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
+
else {
|
|
45
|
+
currentLine += trimmedLeft;
|
|
46
|
+
continuation = false;
|
|
47
|
+
}
|
|
44
48
|
}
|
|
45
49
|
else {
|
|
46
50
|
const trimmed = rawLine.trim();
|
|
47
|
-
// 跳过空行
|
|
48
51
|
if (trimmed === '') {
|
|
49
52
|
continue;
|
|
50
53
|
}
|
|
51
|
-
// 跳过注释行
|
|
52
54
|
if (trimmed.startsWith('#') || trimmed.startsWith('!')) {
|
|
53
55
|
continue;
|
|
54
56
|
}
|
|
55
|
-
|
|
56
|
-
if (trimmed.endsWith('\\')) {
|
|
57
|
+
if (endsWithContinuation(trimmed)) {
|
|
57
58
|
currentLine = trimmed.slice(0, -1);
|
|
58
59
|
continuation = true;
|
|
59
60
|
continue;
|
|
60
61
|
}
|
|
61
62
|
currentLine = trimmed;
|
|
62
63
|
}
|
|
63
|
-
// 解析键值对
|
|
64
64
|
const result = parseKeyValue(currentLine);
|
|
65
65
|
if (result) {
|
|
66
66
|
props[result[0]] = result[1];
|
|
@@ -76,6 +76,16 @@ export function parsePropertiesString(content) {
|
|
|
76
76
|
}
|
|
77
77
|
return props;
|
|
78
78
|
}
|
|
79
|
+
/**
|
|
80
|
+
* 判断一行是否以续行标记结尾(奇数个末尾反斜杠)。
|
|
81
|
+
*/
|
|
82
|
+
function endsWithContinuation(line) {
|
|
83
|
+
let count = 0;
|
|
84
|
+
for (let i = line.length - 1; i >= 0 && line[i] === '\\'; i--) {
|
|
85
|
+
count++;
|
|
86
|
+
}
|
|
87
|
+
return count % 2 === 1;
|
|
88
|
+
}
|
|
79
89
|
/**
|
|
80
90
|
* 解析单行键值对,支持 = 和 : 分隔符。
|
|
81
91
|
* 值中可以包含 = 或 :,只按第一个分隔符拆分。
|
package/dist/esm/config/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* 配置层导出
|
|
3
3
|
*/
|
|
4
|
-
export { parsePropertiesFile, parsePropertiesString } from './config-parser';
|
|
5
|
-
export { createClientConfig, loadPropertiesFile } from './client-config';
|
|
6
|
-
export {
|
|
4
|
+
export { parsePropertiesFile, parsePropertiesString } from './config-parser.js';
|
|
5
|
+
export { createClientConfig, loadPropertiesFile, SANDBOX_TIGER_PUBLIC_KEY } from './client-config.js';
|
|
6
|
+
export { TokenManager } from './token-manager.js';
|
|
7
|
+
export { queryDomains, resolveDynamicServerUrl, resolveDynamicQuoteServerUrl } from './domain.js';
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { readFileSync, writeFileSync, mkdirSync } from 'fs';
|
|
8
8
|
import { dirname } from 'path';
|
|
9
|
-
import { parsePropertiesString } from './config-parser';
|
|
9
|
+
import { parsePropertiesString } from './config-parser.js';
|
|
10
10
|
/** 默认 Token 文件名 */
|
|
11
11
|
const DEFAULT_TOKEN_FILE = 'tiger_openapi_token.properties';
|
|
12
12
|
/** 默认刷新间隔(毫秒):24 小时 */
|
|
@@ -18,6 +18,7 @@ export class TokenManager {
|
|
|
18
18
|
constructor(options) {
|
|
19
19
|
this.token = '';
|
|
20
20
|
this.timer = null;
|
|
21
|
+
this.fileEnabled = options?.filePath !== undefined;
|
|
21
22
|
this.filePath = options?.filePath ?? DEFAULT_TOKEN_FILE;
|
|
22
23
|
this.refreshInterval = options?.refreshInterval ?? DEFAULT_REFRESH_INTERVAL;
|
|
23
24
|
let dur = options?.refreshDuration ?? 0;
|
|
@@ -25,9 +26,39 @@ export class TokenManager {
|
|
|
25
26
|
dur = 30;
|
|
26
27
|
}
|
|
27
28
|
this.refreshDuration = dur;
|
|
29
|
+
this.tokenLoader = options?.tokenLoader;
|
|
30
|
+
this.tokenWriter = options?.tokenWriter;
|
|
28
31
|
}
|
|
29
|
-
/**
|
|
30
|
-
|
|
32
|
+
/**
|
|
33
|
+
* 从 properties 文件(或自定义 tokenLoader)加载 Token。
|
|
34
|
+
* 若设置了 tokenLoader,优先调用;否则从 properties 文件读取。
|
|
35
|
+
*/
|
|
36
|
+
async loadToken() {
|
|
37
|
+
if (this.tokenLoader) {
|
|
38
|
+
const token = await this.tokenLoader();
|
|
39
|
+
if (!token) {
|
|
40
|
+
throw new Error('自定义 tokenLoader 返回空值');
|
|
41
|
+
}
|
|
42
|
+
this.token = token;
|
|
43
|
+
return token;
|
|
44
|
+
}
|
|
45
|
+
const content = readFileSync(this.filePath, 'utf-8');
|
|
46
|
+
const props = parsePropertiesString(content);
|
|
47
|
+
const token = props['token'];
|
|
48
|
+
if (!token) {
|
|
49
|
+
throw new Error('Token 文件中未找到 token 字段');
|
|
50
|
+
}
|
|
51
|
+
this.token = token;
|
|
52
|
+
return token;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* 同步版文件加载(仅用于无 tokenLoader 时的兼容入口)。
|
|
56
|
+
* 建议优先使用 loadToken()(异步)。
|
|
57
|
+
*/
|
|
58
|
+
loadTokenSync() {
|
|
59
|
+
if (this.tokenLoader) {
|
|
60
|
+
throw new Error('tokenLoader 是异步函数,请使用 loadToken()');
|
|
61
|
+
}
|
|
31
62
|
const content = readFileSync(this.filePath, 'utf-8');
|
|
32
63
|
const props = parsePropertiesString(content);
|
|
33
64
|
const token = props['token'];
|
|
@@ -41,10 +72,25 @@ export class TokenManager {
|
|
|
41
72
|
getToken() {
|
|
42
73
|
return this.token;
|
|
43
74
|
}
|
|
44
|
-
/**
|
|
75
|
+
/**
|
|
76
|
+
* 设置 Token;若启用了文件持久化(显式传入 filePath),则同步写文件。
|
|
77
|
+
* 成功后触发 tokenWriter 回调(如有)。
|
|
78
|
+
*/
|
|
45
79
|
setToken(token) {
|
|
46
80
|
this.token = token;
|
|
47
|
-
this.
|
|
81
|
+
if (this.fileEnabled) {
|
|
82
|
+
this.saveTokenToFile(token);
|
|
83
|
+
}
|
|
84
|
+
if (this.tokenWriter) {
|
|
85
|
+
this.tokenWriter(token);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* 仅更新内存中的 token,不写文件,不触发 tokenWriter 回调。
|
|
90
|
+
* 用于多个组件共享 token 时的内部同步。
|
|
91
|
+
*/
|
|
92
|
+
syncToken(token) {
|
|
93
|
+
this.token = token;
|
|
48
94
|
}
|
|
49
95
|
/** 将 Token 保存到 properties 文件 */
|
|
50
96
|
saveTokenToFile(token) {
|
|
@@ -101,6 +147,10 @@ export class TokenManager {
|
|
|
101
147
|
// 刷新失败时静默跳过
|
|
102
148
|
}
|
|
103
149
|
}, this.refreshInterval);
|
|
150
|
+
// 防止 timer 阻止 Node.js 进程退出
|
|
151
|
+
if (this.timer.unref) {
|
|
152
|
+
this.timer.unref();
|
|
153
|
+
}
|
|
104
154
|
}
|
|
105
155
|
/** 停止后台刷新 */
|
|
106
156
|
stopAutoRefresh() {
|