tigeropen 0.4.0 → 0.5.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +82 -2
  2. package/dist/cjs/auth/authentication.js +74 -0
  3. package/dist/cjs/auth/index.js +24 -0
  4. package/dist/cjs/auth/oauth2/client-registration.js +44 -0
  5. package/dist/cjs/auth/oauth2/device-authorization.js +40 -0
  6. package/dist/cjs/auth/oauth2/errors.js +64 -0
  7. package/dist/cjs/auth/oauth2/http-utils.js +112 -0
  8. package/dist/cjs/auth/oauth2/index.js +42 -0
  9. package/dist/cjs/auth/oauth2/loopback-receiver.js +215 -0
  10. package/dist/cjs/auth/oauth2/metadata.js +34 -0
  11. package/dist/cjs/auth/oauth2/oauth2-authentication.js +74 -0
  12. package/dist/cjs/auth/oauth2/session-manager.js +762 -0
  13. package/dist/cjs/auth/oauth2/token-store.js +252 -0
  14. package/dist/cjs/auth/oauth2/token.js +76 -0
  15. package/dist/cjs/client/api-response.js +28 -7
  16. package/dist/cjs/client/case-convert.js +4 -3
  17. package/dist/cjs/client/http-client.js +124 -8
  18. package/dist/cjs/client/token-methods.js +42 -0
  19. package/dist/cjs/config/client-config.js +115 -16
  20. package/dist/cjs/config/config-parser.js +19 -9
  21. package/dist/cjs/config/index.js +4 -1
  22. package/dist/cjs/config/token-manager.js +54 -4
  23. package/dist/cjs/index.js +53 -2
  24. package/dist/cjs/model/enums.js +18 -1
  25. package/dist/cjs/model/order-helpers.js +149 -0
  26. package/dist/cjs/push/index.js +1 -0
  27. package/dist/cjs/push/pb/Request.js +12 -1
  28. package/dist/cjs/push/proto-message.js +5 -1
  29. package/dist/cjs/push/push-client.js +69 -25
  30. package/dist/cjs/push/tick-util.js +172 -0
  31. package/dist/cjs/quote/quote-client.js +300 -70
  32. package/dist/cjs/trade/trade-client.js +186 -16
  33. package/dist/cjs/version.js +4 -0
  34. package/dist/esm/auth/authentication.js +68 -0
  35. package/dist/esm/auth/index.js +3 -0
  36. package/dist/esm/auth/oauth2/client-registration.js +40 -0
  37. package/dist/esm/auth/oauth2/device-authorization.js +36 -0
  38. package/dist/esm/auth/oauth2/errors.js +59 -0
  39. package/dist/esm/auth/oauth2/http-utils.js +105 -0
  40. package/dist/esm/auth/oauth2/index.js +11 -0
  41. package/dist/esm/auth/oauth2/loopback-receiver.js +178 -0
  42. package/dist/esm/auth/oauth2/metadata.js +30 -0
  43. package/dist/esm/auth/oauth2/oauth2-authentication.js +70 -0
  44. package/dist/esm/auth/oauth2/session-manager.js +725 -0
  45. package/dist/esm/auth/oauth2/token-store.js +214 -0
  46. package/dist/esm/auth/oauth2/token.js +71 -0
  47. package/dist/esm/client/api-request.js +1 -1
  48. package/dist/esm/client/api-response.js +29 -8
  49. package/dist/esm/client/case-convert.js +4 -3
  50. package/dist/esm/client/http-client.js +128 -12
  51. package/dist/esm/client/index.js +6 -6
  52. package/dist/esm/client/token-methods.js +37 -0
  53. package/dist/esm/config/client-config.js +118 -20
  54. package/dist/esm/config/config-parser.js +19 -9
  55. package/dist/esm/config/index.js +4 -3
  56. package/dist/esm/config/token-manager.js +55 -5
  57. package/dist/esm/index.js +15 -1
  58. package/dist/esm/logger/index.js +1 -1
  59. package/dist/esm/model/contract-helpers.js +1 -1
  60. package/dist/esm/model/enums.js +17 -0
  61. package/dist/esm/model/order-helpers.js +142 -1
  62. package/dist/esm/model/order-status.js +1 -1
  63. package/dist/esm/package.json +3 -0
  64. package/dist/esm/push/index.js +6 -5
  65. package/dist/esm/push/pb/PushData.js +11 -11
  66. package/dist/esm/push/pb/QuoteBasicData.js +1 -1
  67. package/dist/esm/push/pb/Request.js +12 -1
  68. package/dist/esm/push/pb/Response.js +1 -1
  69. package/dist/esm/push/pb/index.js +17 -17
  70. package/dist/esm/push/proto-message.js +8 -4
  71. package/dist/esm/push/push-client.js +76 -32
  72. package/dist/esm/push/tick-util.js +165 -0
  73. package/dist/esm/quote/index.js +1 -1
  74. package/dist/esm/quote/quote-client.js +269 -72
  75. package/dist/esm/signer/index.js +2 -2
  76. package/dist/esm/trade/index.js +1 -1
  77. package/dist/esm/trade/trade-client.js +156 -19
  78. package/dist/esm/version.js +1 -0
  79. package/dist/types/auth/authentication.d.ts +98 -0
  80. package/dist/types/auth/index.d.ts +4 -0
  81. package/dist/types/auth/oauth2/client-registration.d.ts +32 -0
  82. package/dist/types/auth/oauth2/device-authorization.d.ts +40 -0
  83. package/dist/types/auth/oauth2/errors.d.ts +46 -0
  84. package/dist/types/auth/oauth2/http-utils.d.ts +21 -0
  85. package/dist/types/auth/oauth2/index.d.ts +16 -0
  86. package/dist/types/auth/oauth2/loopback-receiver.d.ts +29 -0
  87. package/dist/types/auth/oauth2/metadata.d.ts +32 -0
  88. package/dist/types/auth/oauth2/oauth2-authentication.d.ts +31 -0
  89. package/dist/types/auth/oauth2/session-manager.d.ts +241 -0
  90. package/dist/types/auth/oauth2/token-store.d.ts +49 -0
  91. package/dist/types/auth/oauth2/token.d.ts +56 -0
  92. package/dist/types/client/api-response.d.ts +6 -4
  93. package/dist/types/client/case-convert.d.ts +3 -1
  94. package/dist/types/client/http-client.d.ts +32 -1
  95. package/dist/types/client/token-methods.d.ts +34 -0
  96. package/dist/types/config/client-config.d.ts +22 -1
  97. package/dist/types/config/index.d.ts +3 -1
  98. package/dist/types/config/token-manager.d.ts +27 -3
  99. package/dist/types/index.d.ts +22 -1
  100. package/dist/types/model/enums.d.ts +18 -2
  101. package/dist/types/model/order-helpers.d.ts +52 -1
  102. package/dist/types/model/order.d.ts +127 -10
  103. package/dist/types/model/quote-requests.d.ts +27 -15
  104. package/dist/types/model/quote.d.ts +151 -24
  105. package/dist/types/model/trade-requests.d.ts +123 -4
  106. package/dist/types/model/trade.d.ts +121 -17
  107. package/dist/types/push/callbacks.d.ts +3 -7
  108. package/dist/types/push/index.d.ts +2 -1
  109. package/dist/types/push/pb/Request.d.ts +1 -0
  110. package/dist/types/push/proto-message.d.ts +4 -1
  111. package/dist/types/push/push-client.d.ts +38 -3
  112. package/dist/types/push/tick-util.d.ts +30 -0
  113. package/dist/types/quote/quote-client.d.ts +101 -36
  114. package/dist/types/trade/trade-client.d.ts +69 -14
  115. package/dist/types/version.d.ts +1 -0
  116. package/package.json +9 -4
@@ -0,0 +1,252 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.OAuth2TokenStore = exports.DEFAULT_SURFACE = exports.ENV_HOME = void 0;
37
+ exports.hashIssuer = hashIssuer;
38
+ /**
39
+ * File-backed OAuth 2.0 authorization state.
40
+ *
41
+ * Storage layout:
42
+ *
43
+ * ~/.tiger/openapi/
44
+ * tokens/{clientId}.json authorization state, mode 0600, removed on logout
45
+ * clients/{issuerHash}-{surface}.json dynamic registration, retained across logout
46
+ *
47
+ * Registration files are keyed by issuer because the client ID is not yet available
48
+ * during lookup, and by surface so that each entry point registers its own client.
49
+ * Without the surface, whichever entry point ran first would own the registration and
50
+ * every other one would silently inherit its identity: one name on the user's
51
+ * authorization page, one revocation switch for all of them, and one shared token file
52
+ * whose refresh-token rotation they would race over.
53
+ *
54
+ * Token files need no surface: each surface registers a distinct client ID, so their
55
+ * token files are already distinct. A manually configured client ID is shared on
56
+ * purpose -- one client ID means one application.
57
+ *
58
+ * Storage root precedence is: explicit argument, `TIGEROPEN_HOME`, then
59
+ * `~/.tiger/openapi`. The format is shared with the Java and Python SDKs.
60
+ */
61
+ const crypto_1 = require("crypto");
62
+ const fs = __importStar(require("fs"));
63
+ const os_1 = require("os");
64
+ const path = __importStar(require("path"));
65
+ const client_registration_1 = require("./client-registration");
66
+ const errors_1 = require("./errors");
67
+ const token_1 = require("./token");
68
+ exports.ENV_HOME = 'TIGEROPEN_HOME';
69
+ /**
70
+ * Entry point owning a registration. Tools built on this SDK must pass their own value,
71
+ * otherwise they would be filed as the TypeScript SDK and share its client. Keep in
72
+ * step with the Java SDK's `sdk-java` and the Python SDK's `sdk-python`.
73
+ */
74
+ exports.DEFAULT_SURFACE = 'sdk-typescript';
75
+ const SAFE_CHARS = /[^a-zA-Z0-9\-_.]/g;
76
+ /**
77
+ * Surfaces become part of a file name, so they are restricted rather than sanitised: a
78
+ * silently rewritten surface would file two entry points under one name.
79
+ */
80
+ const SURFACE_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
81
+ class OAuth2TokenStore {
82
+ /**
83
+ * @param home storage root; defaults to `TIGEROPEN_HOME` then `~/.tiger/openapi`
84
+ * @param surface entry point owning the registration, e.g. `sdk-typescript`, `cli`.
85
+ * Lowercase alphanumerics and hyphens only
86
+ */
87
+ constructor(home, surface = exports.DEFAULT_SURFACE) {
88
+ const base = home || process.env[exports.ENV_HOME] || path.join((0, os_1.homedir)(), '.tiger', 'openapi');
89
+ this.home = path.resolve(expandHome(base));
90
+ this.surface = validateSurface(surface);
91
+ }
92
+ /** Load a token, treating a missing file or issuer mismatch as a cache miss. */
93
+ loadToken(clientId, expectedIssuer) {
94
+ const file = this.tokenFile(clientId);
95
+ if (!fs.existsSync(file))
96
+ return null;
97
+ let token;
98
+ try {
99
+ token = token_1.OAuth2Token.fromJSON(JSON.parse(fs.readFileSync(file, 'utf-8')));
100
+ }
101
+ catch (e) {
102
+ // A corrupt file tells us nothing; treat it as no authorization rather than crash.
103
+ console.error(`[TigerOpen] read token file fail: ${file}`, e);
104
+ return null;
105
+ }
106
+ if (!token)
107
+ return null;
108
+ if (token.schemaVersion !== token_1.TOKEN_SCHEMA_VERSION) {
109
+ // Unknown schema versions are not interpreted.
110
+ throw new errors_1.OAuth2Error(errors_1.OAuth2Category.StorageFailed, `unsupported token schema_version: ${token.schemaVersion}`);
111
+ }
112
+ if (expectedIssuer !== undefined && expectedIssuer !== token.issuer) {
113
+ return null;
114
+ }
115
+ return token;
116
+ }
117
+ saveToken(token) {
118
+ if (!token || !token.clientId) {
119
+ throw new errors_1.OAuth2Error(errors_1.OAuth2Category.StorageFailed, 'token or clientId is empty, cannot save');
120
+ }
121
+ writeAtomic(this.tokenFile(token.clientId), JSON.stringify(token.toJSON(), null, 2));
122
+ }
123
+ /**
124
+ * Delete authorization state while retaining client registration.
125
+ *
126
+ * @returns the path removed, or null when there was nothing to remove. A clientId is
127
+ * not its own file name, so a caller reporting what it deleted has to be told rather
128
+ * than build the path itself
129
+ */
130
+ deleteToken(clientId) {
131
+ if (!clientId)
132
+ return null;
133
+ const file = this.tokenFile(clientId);
134
+ return deleteFile(file) ? file : null;
135
+ }
136
+ loadClientId(issuer) {
137
+ return this.loadClientRegistration(issuer)?.clientId ?? null;
138
+ }
139
+ loadClientRegistration(issuer) {
140
+ const file = this.clientFile(issuer);
141
+ if (!fs.existsSync(file))
142
+ return null;
143
+ try {
144
+ return client_registration_1.OAuth2ClientRegistration.fromJSON(JSON.parse(fs.readFileSync(file, 'utf-8')));
145
+ }
146
+ catch (e) {
147
+ console.error(`[TigerOpen] read client registration file fail: ${file}`, e);
148
+ return null;
149
+ }
150
+ }
151
+ saveClientRegistration(registration) {
152
+ if (!registration || !registration.issuer) {
153
+ throw new errors_1.OAuth2Error(errors_1.OAuth2Category.StorageFailed, 'registration or issuer is empty, cannot save');
154
+ }
155
+ writeAtomic(this.clientFile(registration.issuer), JSON.stringify(registration.toJSON(), null, 2));
156
+ }
157
+ /** Delete registration state after an `invalid_client` response. */
158
+ deleteClientRegistration(issuer) {
159
+ if (!issuer)
160
+ return;
161
+ deleteFile(this.clientFile(issuer));
162
+ }
163
+ tokenFile(clientId) {
164
+ return path.join(this.home, 'tokens', `${safeFileName(clientId)}.json`);
165
+ }
166
+ clientFile(issuer) {
167
+ return path.join(this.home, 'clients', `${hashIssuer(issuer)}-${this.surface}.json`);
168
+ }
169
+ }
170
+ exports.OAuth2TokenStore = OAuth2TokenStore;
171
+ /** Return the Java-compatible 32-character SHA-256 issuer file key. */
172
+ function hashIssuer(issuer) {
173
+ return (0, crypto_1.createHash)('sha256').update(issuer || '', 'utf-8').digest('hex').slice(0, 32);
174
+ }
175
+ /** Sanitize an untrusted client ID for use as a file name. */
176
+ function safeFileName(raw) {
177
+ let name = (raw || '').replace(SAFE_CHARS, '_');
178
+ while (name.includes('..')) {
179
+ name = name.replace(/\.\./g, '__');
180
+ }
181
+ return name || '_';
182
+ }
183
+ /** Reject a surface that cannot be used verbatim as part of a file name. */
184
+ function validateSurface(surface) {
185
+ if (typeof surface !== 'string' || !SURFACE_PATTERN.test(surface)) {
186
+ throw new errors_1.OAuth2Error(errors_1.OAuth2Category.StorageFailed, `invalid surface '${surface}': expected lowercase alphanumerics and hyphens, e.g. 'cli'`);
187
+ }
188
+ return surface;
189
+ }
190
+ function expandHome(value) {
191
+ if (value === '~')
192
+ return (0, os_1.homedir)();
193
+ if (value.startsWith('~/') || value.startsWith(`~${path.sep}`)) {
194
+ return path.join((0, os_1.homedir)(), value.slice(2));
195
+ }
196
+ return value;
197
+ }
198
+ /** @returns true when the file was there and is now gone */
199
+ function deleteFile(file) {
200
+ try {
201
+ if (fs.existsSync(file)) {
202
+ fs.unlinkSync(file);
203
+ return true;
204
+ }
205
+ }
206
+ catch (e) {
207
+ console.error(`[TigerOpen] delete file fail: ${file}`, e);
208
+ }
209
+ return false;
210
+ }
211
+ /**
212
+ * Atomically replace a file through a same-directory temporary file.
213
+ *
214
+ * Same-filesystem replacement prevents partial JSON writes. Directories and files are
215
+ * restricted to modes 0700 and 0600 where supported.
216
+ */
217
+ function writeAtomic(file, content) {
218
+ const dir = path.dirname(file);
219
+ try {
220
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
221
+ restrict(dir, 0o700);
222
+ // Same directory, so the rename below stays on one filesystem and is atomic.
223
+ const tmp = path.join(dir, `.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);
224
+ try {
225
+ fs.writeFileSync(tmp, content, { encoding: 'utf-8', mode: 0o600 });
226
+ restrict(tmp, 0o600);
227
+ fs.renameSync(tmp, file);
228
+ }
229
+ catch (e) {
230
+ try {
231
+ fs.unlinkSync(tmp);
232
+ }
233
+ catch {
234
+ // The temporary file was never created; nothing to clean up.
235
+ }
236
+ throw e;
237
+ }
238
+ restrict(file, 0o600);
239
+ }
240
+ catch (e) {
241
+ throw new errors_1.OAuth2Error(errors_1.OAuth2Category.StorageFailed, `write file fail: ${file}`, e);
242
+ }
243
+ }
244
+ /** Restrict a credential file or directory where the platform supports it. */
245
+ function restrict(target, mode) {
246
+ try {
247
+ fs.chmodSync(target, mode);
248
+ }
249
+ catch {
250
+ // Windows and some network filesystems have no POSIX modes; the write still stands.
251
+ }
252
+ }
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ /**
3
+ * Persisted OAuth 2.0 authorization state.
4
+ *
5
+ * The `issuer` and `clientId` bind credentials to an authorization server and client,
6
+ * preventing credential reuse across environments. The on-disk field names are
7
+ * snake_case and shared with the Java and Python SDKs.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.OAuth2Token = exports.TOKEN_SCHEMA_VERSION = void 0;
11
+ exports.currentMillis = currentMillis;
12
+ /** On-disk format version. An unrecognised version is an error, not a guess. */
13
+ exports.TOKEN_SCHEMA_VERSION = 1;
14
+ function currentMillis() {
15
+ return Date.now();
16
+ }
17
+ /** An access token and its metadata. */
18
+ class OAuth2Token {
19
+ constructor(init = {}) {
20
+ this.schemaVersion = init.schemaVersion ?? exports.TOKEN_SCHEMA_VERSION;
21
+ this.issuer = init.issuer;
22
+ this.clientId = init.clientId;
23
+ this.accessToken = init.accessToken;
24
+ this.refreshToken = init.refreshToken;
25
+ this.tokenType = init.tokenType || 'Bearer';
26
+ this.scope = init.scope;
27
+ this.expiresAt = init.expiresAt ?? 0;
28
+ }
29
+ /** Time until expiry; negative once already expired. */
30
+ remainingMillis() {
31
+ return this.expiresAt - currentMillis();
32
+ }
33
+ /**
34
+ * @param aheadMillis how early to refresh. The window exists because time passes
35
+ * between sending a request and the server validating it, so using a token right up
36
+ * to its expiry produces intermittent 401s
37
+ */
38
+ needsRefresh(aheadMillis) {
39
+ return this.remainingMillis() <= aheadMillis;
40
+ }
41
+ hasRefreshToken() {
42
+ return !!this.refreshToken;
43
+ }
44
+ toJSON() {
45
+ return {
46
+ schema_version: this.schemaVersion,
47
+ issuer: this.issuer,
48
+ client_id: this.clientId,
49
+ access_token: this.accessToken,
50
+ refresh_token: this.refreshToken,
51
+ token_type: this.tokenType,
52
+ scope: this.scope,
53
+ expires_at: this.expiresAt,
54
+ };
55
+ }
56
+ static fromJSON(data) {
57
+ if (!data)
58
+ return null;
59
+ return new OAuth2Token({
60
+ schemaVersion: data.schema_version ?? exports.TOKEN_SCHEMA_VERSION,
61
+ issuer: data.issuer,
62
+ clientId: data.client_id,
63
+ accessToken: data.access_token,
64
+ refreshToken: data.refresh_token,
65
+ tokenType: data.token_type || 'Bearer',
66
+ scope: data.scope,
67
+ expiresAt: data.expires_at ?? 0,
68
+ });
69
+ }
70
+ /** Prints no token values. */
71
+ toString() {
72
+ return `OAuth2Token{clientId=${this.clientId}, issuer=${this.issuer}, scope=${this.scope}, `
73
+ + `expiresAt=${this.expiresAt}, hasRefreshToken=${this.hasRefreshToken()}}`;
74
+ }
75
+ }
76
+ exports.OAuth2Token = OAuth2Token;
@@ -7,11 +7,33 @@ exports.unmarshalData = unmarshalData;
7
7
  */
8
8
  const errors_1 = require("./errors");
9
9
  /**
10
- * Parse the raw HTTP response body.
11
- * Throws TigerError when code != 0.
10
+ * Replaces bare int64 values (≥17 digits, not part of a float) with quoted
11
+ * strings so they survive JSON.parse without precision loss.
12
+ * 17+ digits are guaranteed to exceed Number.MAX_SAFE_INTEGER (≈9.007e15),
13
+ * so 16-digit microsecond timestamps remain as numbers.
14
+ */
15
+ function patchLargeIntegers(text) {
16
+ const strings = [];
17
+ const masked = text.replace(/"(?:[^"\\]|\\.)*"/g, (match) => {
18
+ strings.push(match);
19
+ return '\x01' + (strings.length - 1) + '\x01';
20
+ });
21
+ // Match bare integers preceded by a JSON structural character or line start,
22
+ // not followed by decimal point or exponent (avoids matching float components).
23
+ // The `m` flag makes `^` match line-start for multi-line JSON.
24
+ const patched = masked.replace(/([:,\[{]|^)\s*(-?\d{17,})(?![.\deE])/gm, (full, prefix, num) => {
25
+ return prefix + '"' + num + '"';
26
+ });
27
+ return patched.replace(/\x01(\d+)\x01/g, (_, i) => strings[parseInt(i, 10)]);
28
+ }
29
+ /**
30
+ * Parse the raw HTTP response body. Throws TigerError when code != 0.
31
+ *
32
+ * patchLargeIntegers is applied before JSON.parse to preserve int64 order IDs
33
+ * (e.g. 28868646234578944) as strings rather than losing precision.
12
34
  */
13
35
  function parseApiResponse(body) {
14
- const resp = JSON.parse(body);
36
+ const resp = JSON.parse(patchLargeIntegers(body));
15
37
  if (resp.code !== 0) {
16
38
  throw new errors_1.TigerError(resp.code, resp.message);
17
39
  }
@@ -19,16 +41,15 @@ function parseApiResponse(body) {
19
41
  }
20
42
  /**
21
43
  * Decode an ApiResponse.data payload into a typed value.
22
- * Handles the server's occasional double-encoded JSON (where `data` is a
23
- * JSON string that itself wraps JSON), seen on some trade endpoints.
44
+ * Handles double-encoded JSON (where `data` is a JSON string wrapping JSON),
45
+ * seen on some trade endpoints.
24
46
  */
25
47
  function unmarshalData(data) {
26
48
  if (data == null)
27
49
  return undefined;
28
50
  if (typeof data === 'string') {
29
- // Attempt to parse JSON string (double-encoded case)
30
51
  try {
31
- return JSON.parse(data);
52
+ return JSON.parse(patchLargeIntegers(data));
32
53
  }
33
54
  catch {
34
55
  return data;
@@ -17,7 +17,9 @@ function camelToSnake(key) {
17
17
  /**
18
18
  * Recursively convert all object keys from camelCase to snake_case.
19
19
  * Preserves arrays, primitives, and Date/null/undefined.
20
- * Keys already containing an underscore are kept as-is (already snake_case).
20
+ *
21
+ * Note: camelToSnake is idempotent for pure snake_case keys (no uppercase
22
+ * letters → no replacements), so no pre-check is needed.
21
23
  */
22
24
  function keysToSnakeCase(value) {
23
25
  if (Array.isArray(value)) {
@@ -26,8 +28,7 @@ function keysToSnakeCase(value) {
26
28
  if (value && typeof value === 'object' && value.constructor === Object) {
27
29
  const out = {};
28
30
  for (const [k, v] of Object.entries(value)) {
29
- const newKey = k.includes('_') ? k : camelToSnake(k);
30
- out[newKey] = keysToSnakeCase(v);
31
+ out[camelToSnake(k)] = keysToSnakeCase(v);
31
32
  }
32
33
  return out;
33
34
  }
@@ -1,29 +1,60 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.HttpClient = void 0;
4
+ const token_manager_1 = require("../config/token-manager");
4
5
  const sign_content_1 = require("../signer/sign-content");
5
6
  const signer_1 = require("../signer/signer");
6
7
  const errors_1 = require("./errors");
7
8
  const retry_1 = require("./retry");
8
9
  const api_response_1 = require("./api-response");
9
- /** SDK 版本号 */
10
- const SDK_VERSION = '0.4.0';
10
+ const version_1 = require("../version");
11
11
  /** User-Agent 字符串 */
12
- const USER_AGENT = `openapi-typescript-sdk-${SDK_VERSION}`;
12
+ const USER_AGENT = `openapi-typescript-sdk-${version_1.SDK_VERSION}`;
13
13
  /** 默认字符集 */
14
14
  const DEFAULT_CHARSET = 'UTF-8';
15
15
  /** 默认签名类型 */
16
16
  const DEFAULT_SIGN_TYPE = 'RSA';
17
17
  /** 默认 API 版本 */
18
18
  const DEFAULT_VERSION = '2.0';
19
+ /** Token 刷新 API 方法名 */
20
+ const METHOD_TOKEN_REFRESH = 'user_token_refresh';
21
+ /** 默认后台 token 检查间隔(毫秒):5 分钟 */
22
+ const DEFAULT_TOKEN_CHECK_INTERVAL = 5 * 60 * 1000;
19
23
  /**
20
24
  * HttpClient handles HTTP requests, signing, retry, and timeout
21
25
  */
22
26
  class HttpClient {
23
27
  constructor(config, retryPolicy, options) {
28
+ /** non-null when auto-refresh is active */
29
+ this.tokenManager = null;
24
30
  this.config = config;
25
31
  this.retryPolicy = retryPolicy ?? (0, retry_1.defaultRetryPolicy)();
26
32
  this.targetUrl = options?.useQuoteServerUrl ? config.quoteServerUrl : config.serverUrl;
33
+ // Auto-start token refresh when tokenRefreshDuration is configured (mirrors Go SDK behaviour)
34
+ if (config.tokenRefreshDuration && config.tokenRefreshDuration > 0) {
35
+ const interval = config.tokenCheckInterval ?? DEFAULT_TOKEN_CHECK_INTERVAL;
36
+ const opts = {
37
+ refreshDuration: config.tokenRefreshDuration,
38
+ refreshInterval: interval,
39
+ };
40
+ if (config.tokenWriter) {
41
+ opts.tokenWriter = config.tokenWriter;
42
+ }
43
+ if (config.tokenLoader) {
44
+ opts.tokenLoader = config.tokenLoader;
45
+ }
46
+ this.tokenManager = this.startTokenAutoRefresh(null, opts);
47
+ }
48
+ }
49
+ /**
50
+ * Stop the background token auto-refresh timer.
51
+ * Call this when the HttpClient is no longer needed to avoid timer leaks.
52
+ */
53
+ close() {
54
+ if (this.tokenManager) {
55
+ this.tokenManager.stopAutoRefresh();
56
+ this.tokenManager = null;
57
+ }
27
58
  }
28
59
  /**
29
60
  * Build common request parameters
@@ -34,7 +65,11 @@ class HttpClient {
34
65
  method: apiMethod,
35
66
  charset: DEFAULT_CHARSET,
36
67
  sign_type: DEFAULT_SIGN_TYPE,
37
- timestamp: new Date().toISOString().replace('T', ' ').substring(0, 19),
68
+ timestamp: (() => {
69
+ const d = new Date();
70
+ const pad = (n) => String(n).padStart(2, '0');
71
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
72
+ })(),
38
73
  version: version || DEFAULT_VERSION,
39
74
  biz_content: bizContent,
40
75
  };
@@ -61,6 +96,7 @@ class HttpClient {
61
96
  const headers = {
62
97
  'Content-Type': 'application/json;charset=UTF-8',
63
98
  'User-Agent': USER_AGENT,
99
+ 'Connection': 'close',
64
100
  };
65
101
  if (this.config.token) {
66
102
  headers['Authorization'] = this.config.token;
@@ -71,7 +107,8 @@ class HttpClient {
71
107
  body,
72
108
  signal: AbortSignal.timeout(this.config.timeout * 1000),
73
109
  });
74
- return response.text();
110
+ const text = await response.text();
111
+ return text;
75
112
  }
76
113
  /**
77
114
  * Execute a structured API request, returning a parsed ApiResponse.
@@ -98,6 +135,10 @@ class HttpClient {
98
135
  }
99
136
  catch (err) {
100
137
  lastErr = err;
138
+ // Only retry on network errors, not API business errors (TigerError with code)
139
+ if (err.code !== undefined && err.code !== -1) {
140
+ throw err; // API returned a business error code, don't retry
141
+ }
101
142
  if (!this.retryPolicy.shouldRetry(request.method)) {
102
143
  throw err;
103
144
  }
@@ -110,9 +151,10 @@ class HttpClient {
110
151
  *
111
152
  * @param apiMethod - API method name (e.g. "market_state", "place_order")
112
153
  * @param requestJson - Raw biz_content JSON string
154
+ * @param version - Optional API version override (default: "2.0")
113
155
  * @returns Raw response JSON string, unparsed
114
156
  */
115
- async execute(apiMethod, requestJson) {
157
+ async execute(apiMethod, requestJson, version) {
116
158
  // Parameter validation
117
159
  if (!apiMethod) {
118
160
  throw new errors_1.TigerError(-1, 'api_method must not be empty');
@@ -123,7 +165,7 @@ class HttpClient {
123
165
  catch {
124
166
  throw new errors_1.TigerError(-1, 'request_json is not valid JSON');
125
167
  }
126
- const params = this.buildCommonParams(apiMethod, requestJson);
168
+ const params = this.buildCommonParams(apiMethod, requestJson, version);
127
169
  const sign = this.signParams(params);
128
170
  params['sign'] = sign;
129
171
  let lastErr;
@@ -144,6 +186,10 @@ class HttpClient {
144
186
  }
145
187
  catch (err) {
146
188
  lastErr = err;
189
+ // Don't retry API business errors
190
+ if (err.code !== undefined && err.code !== -1) {
191
+ throw err;
192
+ }
147
193
  if (!this.retryPolicy.shouldRetry(apiMethod)) {
148
194
  throw err;
149
195
  }
@@ -151,6 +197,75 @@ class HttpClient {
151
197
  }
152
198
  throw lastErr;
153
199
  }
200
+ /**
201
+ * 调用 user_token_refresh 接口获取新 token,返回新 token 字符串。
202
+ * 此方法仅查询,不修改 config 中的 token。
203
+ */
204
+ async queryToken() {
205
+ const params = this.buildCommonParams(METHOD_TOKEN_REFRESH, '{}');
206
+ const sign = this.signParams(params);
207
+ params['sign'] = sign;
208
+ const body = await this.doHttpPost(params);
209
+ const response = (0, api_response_1.parseApiResponse)(body);
210
+ this.verifyResponseSign(params['timestamp'], response.sign);
211
+ const data = (0, api_response_1.unmarshalData)(response.data);
212
+ const newToken = data?.token;
213
+ if (!newToken) {
214
+ throw new errors_1.TigerError(-1, '服务端返回空 token');
215
+ }
216
+ return newToken;
217
+ }
218
+ /**
219
+ * 刷新 token:调用接口获取新 token 后更新 config.token。
220
+ *
221
+ * @param tokenManager - 可选外部 TokenManager;若提供则调用 setToken() 写文件并触发回调。
222
+ * 若 NewHttpClient 已自动启动内部 TokenManager,其内存 token 也会同步更新。
223
+ */
224
+ async refreshToken(tokenManager) {
225
+ const newToken = await this.queryToken();
226
+ this.config.token = newToken;
227
+ // Keep internal tokenManager in sync so shouldTokenRefresh stays accurate.
228
+ if (this.tokenManager && tokenManager !== this.tokenManager) {
229
+ this.tokenManager.syncToken(newToken);
230
+ }
231
+ if (tokenManager) {
232
+ tokenManager.setToken(newToken);
233
+ }
234
+ }
235
+ /**
236
+ * 启动后台 token 自动刷新。
237
+ *
238
+ * @param tokenManager - 可为 null:SDK 内部自动创建一个仅内存的 TokenManager,
239
+ * 适合直接通过 token 在代码里设置、不使用文件的场景。
240
+ * @param options - 仅在 tokenManager 为 null 时生效,用于配置内部 TokenManager
241
+ * (refreshDuration / refreshInterval / tokenWriter / tokenLoader)。
242
+ * @returns 使用或创建的 TokenManager 实例
243
+ */
244
+ startTokenAutoRefresh(tokenManager, options) {
245
+ if (!tokenManager) {
246
+ tokenManager = new token_manager_1.TokenManager(options);
247
+ // 从 config.token 同步当前 token,使 shouldTokenRefresh 能正确判断。
248
+ // 若 config.token 暂时为空(异步 tokenLoader 尚未 resolve),则先异步加载。
249
+ if (this.config.token) {
250
+ tokenManager.syncToken(this.config.token);
251
+ }
252
+ else if (options?.tokenLoader) {
253
+ // tokenLoader 可能是异步的;在后台 resolve 后同步到 config.token 和 TokenManager。
254
+ Promise.resolve(options.tokenLoader()).then((t) => {
255
+ if (t) {
256
+ this.config.token = t;
257
+ tokenManager.syncToken(t);
258
+ }
259
+ }).catch(() => { });
260
+ }
261
+ }
262
+ tokenManager.startAutoRefresh(async () => {
263
+ const newToken = await this.queryToken();
264
+ this.config.token = newToken;
265
+ return newToken;
266
+ });
267
+ return tokenManager;
268
+ }
154
269
  /** Delay for the specified milliseconds */
155
270
  sleep(ms) {
156
271
  return new Promise((resolve) => setTimeout(resolve, ms));
@@ -164,7 +279,8 @@ class HttpClient {
164
279
  */
165
280
  verifyResponseSign(timestamp, signBase64) {
166
281
  if (!signBase64) {
167
- throw new errors_1.TigerError(-1, 'Response signature is missing');
282
+ // Some endpoints don't return a signature; skip verification silently.
283
+ return;
168
284
  }
169
285
  const valid = (0, signer_1.verifyWithRSA)(this.config.tigerPublicKey, timestamp, signBase64);
170
286
  if (!valid) {
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.queryToken = queryToken;
4
+ exports.refreshToken = refreshToken;
5
+ exports.startTokenAutoRefresh = startTokenAutoRefresh;
6
+ /**
7
+ * Call the `user_token_refresh` API and return the new token string.
8
+ * Read-only: does NOT update the stored token.
9
+ * Use `refreshToken()` to also update the in-memory config and optionally persist.
10
+ */
11
+ async function queryToken(httpClient) {
12
+ return httpClient.queryToken();
13
+ }
14
+ /**
15
+ * Refresh the token: call the API, update the in-memory config token, and
16
+ * optionally persist via the provided TokenManager (file + writer callback).
17
+ *
18
+ * @param httpClient - The underlying HTTP client
19
+ * @param tokenManager - optional TokenManager for file persistence and writer callback
20
+ */
21
+ async function refreshToken(httpClient, tokenManager) {
22
+ return httpClient.refreshToken(tokenManager);
23
+ }
24
+ /**
25
+ * Start background token auto-refresh. Returns a TokenManager that can be
26
+ * used to stop the background task via `tm.stopAutoRefresh()`.
27
+ *
28
+ * @param httpClient - The underlying HTTP client
29
+ * @param refreshDurationSecs - Refresh threshold in seconds (minimum 30).
30
+ * When the token age exceeds this value the refresh is triggered.
31
+ * @param checkIntervalMs - How often to check whether a refresh is needed,
32
+ * in milliseconds. Defaults to 300 000 ms (5 minutes).
33
+ * @param tokenWriter - Optional callback invoked with the new token string
34
+ * after each successful refresh.
35
+ */
36
+ function startTokenAutoRefresh(httpClient, refreshDurationSecs, checkIntervalMs, tokenWriter) {
37
+ return httpClient.startTokenAutoRefresh(null, {
38
+ refreshDuration: refreshDurationSecs,
39
+ refreshInterval: checkIntervalMs,
40
+ tokenWriter,
41
+ });
42
+ }