@brokerize/client 1.12.0 → 1.12.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/apiCtx.js CHANGED
@@ -1,6 +1,4 @@
1
- /* Import/Export the DOM parts we rely on. Those are partial copies from the official TypeScript DOM library definitions (https://github.com/microsoft/TypeScript/blob/master/lib/lib.dom.d.ts),
2
- but reduced to the parts actually used by bg-trading. */
3
- import { BrokerizeError } from "./index.js";
1
+ import { createTokenRefreshError } from "./errors.js";
4
2
  import { Configuration } from "./swagger/index.js";
5
3
  /**
6
4
  * Resolves the configured `Accept-Language` value (static or via a getter function) to a string,
@@ -64,10 +62,7 @@ export function createAuth({ authCfg, cfg, options, tokenRefreshCallback, }) {
64
62
  body: `grant_type=refresh_token&refresh_token=${encodeURIComponent(guestAuthCfg.tokens.response.refreshToken)}`,
65
63
  });
66
64
  if (!response.ok) {
67
- throw new BrokerizeError(401, {
68
- msg: "The token could not be refreshed. Please log in again.",
69
- code: "AUTH",
70
- });
65
+ throw await createTokenRefreshError(response);
71
66
  }
72
67
  const responseJson = (await response.json());
73
68
  guestAuthCfg.idToken = responseJson.access_token;
@@ -32,6 +32,21 @@ export declare class AuthorizedApiContext {
32
32
  private readonly _syncApi;
33
33
  private readonly _decoupledOperationsApi;
34
34
  constructor(cfg: BrokerizeConfig, auth: Auth, wsClient?: BrokerizeWebSocketClient);
35
+ /**
36
+ * The websocket client keeps one context around to refetch the status of a decoupled operation
37
+ * with after an interrupted connection. That context has to outlive the connection, so it must
38
+ * not simply be whichever one was constructed last: child contexts are commonly created per
39
+ * request and destroyed again, and a destroyed context cannot perform that request.
40
+ *
41
+ * The first context attaches and keeps the client - that is the one that created it, and the
42
+ * children, which are handed the very same client, leave it alone.
43
+ */
44
+ private _attachToWsClient;
45
+ /**
46
+ * Counterpart of `_attachToWsClient`: leave no destroyed context behind, so that a context
47
+ * created later can take over.
48
+ */
49
+ private _detachFromWsClient;
35
50
  createChildContext(): AuthorizedApiContext;
36
51
  private _initRequestInit;
37
52
  getBrokers(): Promise<openApiClient.GetBrokersResponse>;
@@ -53,11 +53,43 @@ export class AuthorizedApiContext {
53
53
  this._abortController = cfg.createAbortController();
54
54
  this._ownsWsClient = !wsClient;
55
55
  this._wsClient = wsClient || this._initInternalWebSocketClient();
56
- if (this._wsClient._setAuthorizedApiContext) {
57
- this._wsClient._setAuthorizedApiContext(this);
58
- }
56
+ this._attachToWsClient();
59
57
  this._cache = {};
60
58
  }
59
+ /**
60
+ * The websocket client keeps one context around to refetch the status of a decoupled operation
61
+ * with after an interrupted connection. That context has to outlive the connection, so it must
62
+ * not simply be whichever one was constructed last: child contexts are commonly created per
63
+ * request and destroyed again, and a destroyed context cannot perform that request.
64
+ *
65
+ * The first context attaches and keeps the client - that is the one that created it, and the
66
+ * children, which are handed the very same client, leave it alone.
67
+ */
68
+ _attachToWsClient() {
69
+ const wsClient = this._wsClient;
70
+ /* an application may pass in its own implementation of the interface. */
71
+ if (!wsClient._setAuthorizedApiContext ||
72
+ !wsClient._getAuthorizedApiContext) {
73
+ return;
74
+ }
75
+ if (!wsClient._getAuthorizedApiContext()) {
76
+ wsClient._setAuthorizedApiContext(this);
77
+ }
78
+ }
79
+ /**
80
+ * Counterpart of `_attachToWsClient`: leave no destroyed context behind, so that a context
81
+ * created later can take over.
82
+ */
83
+ _detachFromWsClient() {
84
+ const wsClient = this._wsClient;
85
+ if (!wsClient._setAuthorizedApiContext ||
86
+ !wsClient._getAuthorizedApiContext) {
87
+ return;
88
+ }
89
+ if (wsClient._getAuthorizedApiContext() === this) {
90
+ wsClient._setAuthorizedApiContext(null);
91
+ }
92
+ }
61
93
  createChildContext() {
62
94
  const result = new AuthorizedApiContext(this._cfg, this._auth, this._wsClient);
63
95
  const childContexts = this._childContexts;
@@ -444,6 +476,7 @@ export class AuthorizedApiContext {
444
476
  destroy() {
445
477
  this._isDestroyed = true;
446
478
  this._abortController.abort();
479
+ this._detachFromWsClient();
447
480
  if (this._ownsWsClient) {
448
481
  /* otherwise its reconnect timer would keep running and keep reconnecting with the
449
482
  tokens of a context that is gone. */
@@ -4,9 +4,7 @@ exports.resolveAcceptLanguage = resolveAcceptLanguage;
4
4
  exports.withAcceptLanguage = withAcceptLanguage;
5
5
  exports.createConfiguration = createConfiguration;
6
6
  exports.createAuth = createAuth;
7
- /* Import/Export the DOM parts we rely on. Those are partial copies from the official TypeScript DOM library definitions (https://github.com/microsoft/TypeScript/blob/master/lib/lib.dom.d.ts),
8
- but reduced to the parts actually used by bg-trading. */
9
- const _1 = require(".");
7
+ const errors_1 = require("./errors");
10
8
  const swagger_1 = require("./swagger");
11
9
  /**
12
10
  * Resolves the configured `Accept-Language` value (static or via a getter function) to a string,
@@ -70,10 +68,7 @@ function createAuth({ authCfg, cfg, options, tokenRefreshCallback, }) {
70
68
  body: `grant_type=refresh_token&refresh_token=${encodeURIComponent(guestAuthCfg.tokens.response.refreshToken)}`,
71
69
  });
72
70
  if (!response.ok) {
73
- throw new _1.BrokerizeError(401, {
74
- msg: "The token could not be refreshed. Please log in again.",
75
- code: "AUTH",
76
- });
71
+ throw await (0, errors_1.createTokenRefreshError)(response);
77
72
  }
78
73
  const responseJson = (await response.json());
79
74
  guestAuthCfg.idToken = responseJson.access_token;
@@ -32,6 +32,21 @@ export declare class AuthorizedApiContext {
32
32
  private readonly _syncApi;
33
33
  private readonly _decoupledOperationsApi;
34
34
  constructor(cfg: BrokerizeConfig, auth: Auth, wsClient?: BrokerizeWebSocketClient);
35
+ /**
36
+ * The websocket client keeps one context around to refetch the status of a decoupled operation
37
+ * with after an interrupted connection. That context has to outlive the connection, so it must
38
+ * not simply be whichever one was constructed last: child contexts are commonly created per
39
+ * request and destroyed again, and a destroyed context cannot perform that request.
40
+ *
41
+ * The first context attaches and keeps the client - that is the one that created it, and the
42
+ * children, which are handed the very same client, leave it alone.
43
+ */
44
+ private _attachToWsClient;
45
+ /**
46
+ * Counterpart of `_attachToWsClient`: leave no destroyed context behind, so that a context
47
+ * created later can take over.
48
+ */
49
+ private _detachFromWsClient;
35
50
  createChildContext(): AuthorizedApiContext;
36
51
  private _initRequestInit;
37
52
  getBrokers(): Promise<openApiClient.GetBrokersResponse>;
@@ -90,11 +90,43 @@ class AuthorizedApiContext {
90
90
  this._abortController = cfg.createAbortController();
91
91
  this._ownsWsClient = !wsClient;
92
92
  this._wsClient = wsClient || this._initInternalWebSocketClient();
93
- if (this._wsClient._setAuthorizedApiContext) {
94
- this._wsClient._setAuthorizedApiContext(this);
95
- }
93
+ this._attachToWsClient();
96
94
  this._cache = {};
97
95
  }
96
+ /**
97
+ * The websocket client keeps one context around to refetch the status of a decoupled operation
98
+ * with after an interrupted connection. That context has to outlive the connection, so it must
99
+ * not simply be whichever one was constructed last: child contexts are commonly created per
100
+ * request and destroyed again, and a destroyed context cannot perform that request.
101
+ *
102
+ * The first context attaches and keeps the client - that is the one that created it, and the
103
+ * children, which are handed the very same client, leave it alone.
104
+ */
105
+ _attachToWsClient() {
106
+ const wsClient = this._wsClient;
107
+ /* an application may pass in its own implementation of the interface. */
108
+ if (!wsClient._setAuthorizedApiContext ||
109
+ !wsClient._getAuthorizedApiContext) {
110
+ return;
111
+ }
112
+ if (!wsClient._getAuthorizedApiContext()) {
113
+ wsClient._setAuthorizedApiContext(this);
114
+ }
115
+ }
116
+ /**
117
+ * Counterpart of `_attachToWsClient`: leave no destroyed context behind, so that a context
118
+ * created later can take over.
119
+ */
120
+ _detachFromWsClient() {
121
+ const wsClient = this._wsClient;
122
+ if (!wsClient._setAuthorizedApiContext ||
123
+ !wsClient._getAuthorizedApiContext) {
124
+ return;
125
+ }
126
+ if (wsClient._getAuthorizedApiContext() === this) {
127
+ wsClient._setAuthorizedApiContext(null);
128
+ }
129
+ }
98
130
  createChildContext() {
99
131
  const result = new AuthorizedApiContext(this._cfg, this._auth, this._wsClient);
100
132
  const childContexts = this._childContexts;
@@ -481,6 +513,7 @@ class AuthorizedApiContext {
481
513
  destroy() {
482
514
  this._isDestroyed = true;
483
515
  this._abortController.abort();
516
+ this._detachFromWsClient();
484
517
  if (this._ownsWsClient) {
485
518
  /* otherwise its reconnect timer would keep running and keep reconnecting with the
486
519
  tokens of a context that is gone. */
@@ -63,7 +63,17 @@ export declare class BrokerizeError extends Error {
63
63
  */
64
64
  code: string;
65
65
  httpStatusCode: number;
66
- constructor(statusCode: number, body: ErrorResponse);
66
+ /**
67
+ * The delay in milliseconds the server asked the client to wait before retrying, taken from the
68
+ * `Retry-After` response header. Set for rate limits, but not for all of them - a rate limit
69
+ * hit on the way to a broker has no reliable wait time to announce.
70
+ *
71
+ * This client never retries on its own: whether waiting is acceptable depends on the call (a
72
+ * background poll may wait and try again, placing an order must not), so the application
73
+ * decides. Treat this as the minimum delay and add a backoff of your own.
74
+ */
75
+ retryAfterMs?: number;
76
+ constructor(statusCode: number, body: ErrorResponse, retryAfterMs?: number);
67
77
  }
68
78
  /**
69
79
  * Thrown if a request to the brokerize API timed out (HTTP status 504). This is typically sent by
@@ -73,12 +83,33 @@ export declare class BrokerizeError extends Error {
73
83
  export declare class BrokerizeTimeoutError extends BrokerizeError {
74
84
  constructor(body: ErrorResponse);
75
85
  }
86
+ /**
87
+ * Whether the given error is a rate limit the caller may retry after waiting. Check
88
+ * {@link BrokerizeError.retryAfterMs} for the delay the server asked for - it is not always set.
89
+ */
90
+ export declare function isRateLimitError(err: unknown): err is BrokerizeError;
91
+ /**
92
+ * Parses a `Retry-After` header into milliseconds. The brokerize API sends a (possibly fractional)
93
+ * number of seconds; the HTTP spec also allows an absolute date, which a proxy in front of the API
94
+ * may produce. Returns `undefined` if the header is absent or cannot be understood.
95
+ */
96
+ export declare function parseRetryAfter(value: string | null | undefined): number | undefined;
76
97
  /**
77
98
  * Create the error for a failed (status >= 400) API response. If the body is not a valid `ErrorResponse`
78
99
  * (e.g. an HTML error page from a load balancer), a generic error body is used instead of failing with a
79
100
  * JSON parse error.
80
101
  */
81
102
  export declare function createErrorFromResponse(response: Response): Promise<BrokerizeError>;
103
+ /**
104
+ * Create the error for a failed token refresh (`POST /user/token`).
105
+ *
106
+ * A rejected token means the user has to log in again, and callers act on that by discarding the
107
+ * stored session - so only an actual rejection may be reported that way. Everything else (a rate
108
+ * limit, a server error, maintenance) is transient and is passed through unchanged: flattening
109
+ * those into an auth error throws away a session that is still good, and turns one rate-limited
110
+ * request into a fresh login.
111
+ */
112
+ export declare function createTokenRefreshError(response: Response): Promise<BrokerizeError>;
82
113
  /**
83
114
  * Error codes used by {@link BrokerizeWebSocketError}.
84
115
  *
@@ -1,7 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.BrokerizeAbortError = exports.BrokerizeWebSocketError = exports.BrokerizeTimeoutError = exports.BrokerizeError = exports.TradingError = void 0;
4
+ exports.isRateLimitError = isRateLimitError;
5
+ exports.parseRetryAfter = parseRetryAfter;
4
6
  exports.createErrorFromResponse = createErrorFromResponse;
7
+ exports.createTokenRefreshError = createTokenRefreshError;
5
8
  exports.isBrokerizeWebSocketError = isBrokerizeWebSocketError;
6
9
  class TradingError extends Error {
7
10
  constructor({ msg, code, brokerCode, brokerError, msgBrokerName, httpStatusCode, hint, }) {
@@ -18,9 +21,10 @@ class TradingError extends Error {
18
21
  }
19
22
  exports.TradingError = TradingError;
20
23
  class BrokerizeError extends Error {
21
- constructor(statusCode, body) {
24
+ constructor(statusCode, body, retryAfterMs) {
22
25
  super(body.msg);
23
26
  this.httpStatusCode = statusCode;
27
+ this.retryAfterMs = retryAfterMs;
24
28
  this.name = "BrokerizeError";
25
29
  this.msg = body.msg;
26
30
  this.code = body.code;
@@ -42,6 +46,34 @@ class BrokerizeTimeoutError extends BrokerizeError {
42
46
  }
43
47
  }
44
48
  exports.BrokerizeTimeoutError = BrokerizeTimeoutError;
49
+ /**
50
+ * Whether the given error is a rate limit the caller may retry after waiting. Check
51
+ * {@link BrokerizeError.retryAfterMs} for the delay the server asked for - it is not always set.
52
+ */
53
+ function isRateLimitError(err) {
54
+ return (err instanceof BrokerizeError &&
55
+ (err.code === "RATE_LIMITED" || err.httpStatusCode === 429));
56
+ }
57
+ /**
58
+ * Parses a `Retry-After` header into milliseconds. The brokerize API sends a (possibly fractional)
59
+ * number of seconds; the HTTP spec also allows an absolute date, which a proxy in front of the API
60
+ * may produce. Returns `undefined` if the header is absent or cannot be understood.
61
+ */
62
+ function parseRetryAfter(value) {
63
+ const raw = value === null || value === void 0 ? void 0 : value.trim();
64
+ if (!raw) {
65
+ return undefined;
66
+ }
67
+ const seconds = Number(raw);
68
+ if (Number.isFinite(seconds)) {
69
+ return seconds >= 0 ? Math.round(seconds * 1000) : undefined;
70
+ }
71
+ const date = Date.parse(raw);
72
+ if (isNaN(date)) {
73
+ return undefined;
74
+ }
75
+ return Math.max(0, date - Date.now());
76
+ }
45
77
  function isErrorResponse(x) {
46
78
  return (!!x &&
47
79
  typeof x === "object" &&
@@ -55,6 +87,7 @@ function isErrorResponse(x) {
55
87
  */
56
88
  async function createErrorFromResponse(response) {
57
89
  const statusCode = response.status;
90
+ const retryAfterMs = parseRetryAfter(response.headers.get("Retry-After"));
58
91
  let body;
59
92
  try {
60
93
  const parsed = JSON.parse(await response.text());
@@ -74,7 +107,26 @@ async function createErrorFromResponse(response) {
74
107
  return new BrokerizeError(statusCode, body || {
75
108
  msg: "The request failed with status " + statusCode + ".",
76
109
  code: "INTERNAL_SERVER_ERROR",
77
- });
110
+ }, retryAfterMs);
111
+ }
112
+ /**
113
+ * Create the error for a failed token refresh (`POST /user/token`).
114
+ *
115
+ * A rejected token means the user has to log in again, and callers act on that by discarding the
116
+ * stored session - so only an actual rejection may be reported that way. Everything else (a rate
117
+ * limit, a server error, maintenance) is transient and is passed through unchanged: flattening
118
+ * those into an auth error throws away a session that is still good, and turns one rate-limited
119
+ * request into a fresh login.
120
+ */
121
+ async function createTokenRefreshError(response) {
122
+ const err = await createErrorFromResponse(response);
123
+ if (err.httpStatusCode === 401 || err.httpStatusCode === 403) {
124
+ return new BrokerizeError(401, {
125
+ msg: "The token could not be refreshed. Please log in again.",
126
+ code: "AUTH",
127
+ });
128
+ }
129
+ return err;
78
130
  }
79
131
  const DEFAULT_STATUS_CODES = {
80
132
  AUTH: 401,
@@ -1,12 +1,12 @@
1
1
  import { Auth, AuthContextConfiguration, BrokerizeConfig, CognitoConfig, CognitoFacade, CognitoPoolConfig, GetTokenOptions, GuestAuthContextConfiguration, RegisteredUserAuthContextConfiguration, TokenSet } from "./apiCtx";
2
2
  import { AuthorizedApiContext } from "./authorizedApiContext";
3
- import { BrokerizeAbortError, BrokerizeError, BrokerizeTimeoutError, BrokerizeWebSocketError, BrokerizeWebSocketErrorCode, BrokerizeWebSocketErrorParams, isBrokerizeWebSocketError } from "./errors";
3
+ import { BrokerizeAbortError, BrokerizeError, BrokerizeTimeoutError, BrokerizeWebSocketError, BrokerizeWebSocketErrorCode, BrokerizeWebSocketErrorParams, isBrokerizeWebSocketError, isRateLimitError, parseRetryAfter } from "./errors";
4
4
  import * as openApiClient from "./swagger";
5
5
  import * as Models from "./modelExports";
6
6
  import { BrokerizeWebSocketClient, BrokerizeWebSocketClientOptions, Callback, ConnectionStateCallback, Subscription, WebSocketConnectionState, WebSocketConnectionStatus } from "./websocketClient";
7
7
  import * as WebSocketTypes from "./websocketTypes";
8
8
  import * as Utils from "./utils";
9
- export { BrokerizeConfig, AuthContextConfiguration, AuthorizedApiContext, BrokerizeWebSocketClient, Models, WebSocketTypes, Subscription, Callback, Utils, BrokerizeError, BrokerizeTimeoutError, BrokerizeWebSocketError, BrokerizeWebSocketErrorCode, BrokerizeWebSocketErrorParams, BrokerizeAbortError, GetTokenOptions, isBrokerizeWebSocketError, ConnectionStateCallback, BrokerizeWebSocketClientOptions, WebSocketConnectionState, WebSocketConnectionStatus, Auth, TokenSet, };
9
+ export { BrokerizeConfig, AuthContextConfiguration, AuthorizedApiContext, BrokerizeWebSocketClient, Models, WebSocketTypes, Subscription, Callback, Utils, BrokerizeError, BrokerizeTimeoutError, BrokerizeWebSocketError, BrokerizeWebSocketErrorCode, BrokerizeWebSocketErrorParams, BrokerizeAbortError, GetTokenOptions, isBrokerizeWebSocketError, isRateLimitError, parseRetryAfter, ConnectionStateCallback, BrokerizeWebSocketClientOptions, WebSocketConnectionState, WebSocketConnectionStatus, Auth, TokenSet, };
10
10
  export { CognitoPoolConfig, RegisteredUserAuthContextConfiguration };
11
11
  export { CognitoConfig, CognitoFacade };
12
12
  export declare class Brokerize {
package/dist/cjs/index.js CHANGED
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.Brokerize = exports.isBrokerizeWebSocketError = exports.BrokerizeAbortError = exports.BrokerizeWebSocketError = exports.BrokerizeTimeoutError = exports.BrokerizeError = exports.Utils = exports.WebSocketTypes = exports.Models = exports.AuthorizedApiContext = void 0;
36
+ exports.Brokerize = exports.parseRetryAfter = exports.isRateLimitError = exports.isBrokerizeWebSocketError = exports.BrokerizeAbortError = exports.BrokerizeWebSocketError = exports.BrokerizeTimeoutError = exports.BrokerizeError = exports.Utils = exports.WebSocketTypes = exports.Models = exports.AuthorizedApiContext = void 0;
37
37
  /* Import/Export the DOM parts we rely on. Those are partial copies from the official TypeScript DOM library definitions (https://github.com/microsoft/TypeScript/blob/master/lib/lib.dom.d.ts),
38
38
  but reduced to the parts actually used by bg-trading. */
39
39
  const apiCtx_1 = require("./apiCtx");
@@ -45,6 +45,8 @@ Object.defineProperty(exports, "BrokerizeError", { enumerable: true, get: functi
45
45
  Object.defineProperty(exports, "BrokerizeTimeoutError", { enumerable: true, get: function () { return errors_1.BrokerizeTimeoutError; } });
46
46
  Object.defineProperty(exports, "BrokerizeWebSocketError", { enumerable: true, get: function () { return errors_1.BrokerizeWebSocketError; } });
47
47
  Object.defineProperty(exports, "isBrokerizeWebSocketError", { enumerable: true, get: function () { return errors_1.isBrokerizeWebSocketError; } });
48
+ Object.defineProperty(exports, "isRateLimitError", { enumerable: true, get: function () { return errors_1.isRateLimitError; } });
49
+ Object.defineProperty(exports, "parseRetryAfter", { enumerable: true, get: function () { return errors_1.parseRetryAfter; } });
48
50
  const openApiClient = __importStar(require("./swagger"));
49
51
  const Models = __importStar(require("./modelExports"));
50
52
  exports.Models = Models;
@@ -98,10 +100,7 @@ class Brokerize {
98
100
  body: `grant_type=refresh_token&refresh_token=${encodeURIComponent(refreshToken)}`,
99
101
  });
100
102
  if (!response.ok) {
101
- throw new errors_1.BrokerizeError(401, {
102
- msg: "The token could not be refreshed. Please log in again.",
103
- code: "AUTH",
104
- });
103
+ throw await (0, errors_1.createTokenRefreshError)(response);
105
104
  }
106
105
  const responseJson = (await response.json());
107
106
  return {
@@ -89,8 +89,16 @@ export declare class BrokerizeWebSocketClientImpl implements BrokerizeWebSocketC
89
89
  /**
90
90
  * Internal method for setting a related AuthorizedApiContext. This is used to retrieve
91
91
  * decoupled operation status on interrupted connections.
92
+ *
93
+ * `null` detaches the current one, which a context does when it is destroyed: a destroyed
94
+ * context cannot perform that request, so holding on to it would be worse than holding none.
95
+ */
96
+ _setAuthorizedApiContext(ctx: AuthorizedApiContext | null): void;
97
+ /**
98
+ * Internal counterpart of `_setAuthorizedApiContext`, so that a context can tell whether the
99
+ * client is already attached to one - and whether that one is itself.
92
100
  */
93
- _setAuthorizedApiContext(ctx: AuthorizedApiContext): void;
101
+ _getAuthorizedApiContext(): AuthorizedApiContext | null;
94
102
  _startOrStopDisconnectTimeout(): void;
95
103
  private _sendWs;
96
104
  /**
@@ -351,10 +351,20 @@ class BrokerizeWebSocketClientImpl {
351
351
  /**
352
352
  * Internal method for setting a related AuthorizedApiContext. This is used to retrieve
353
353
  * decoupled operation status on interrupted connections.
354
+ *
355
+ * `null` detaches the current one, which a context does when it is destroyed: a destroyed
356
+ * context cannot perform that request, so holding on to it would be worse than holding none.
354
357
  */
355
358
  _setAuthorizedApiContext(ctx) {
356
359
  this._apiCtx = ctx;
357
360
  }
361
+ /**
362
+ * Internal counterpart of `_setAuthorizedApiContext`, so that a context can tell whether the
363
+ * client is already attached to one - and whether that one is itself.
364
+ */
365
+ _getAuthorizedApiContext() {
366
+ return this._apiCtx;
367
+ }
358
368
  _startOrStopDisconnectTimeout() {
359
369
  if (this._shouldConnect()) {
360
370
  if (this._disconnectTimeout) {
package/dist/client.d.ts CHANGED
@@ -1104,6 +1104,21 @@ export declare class AuthorizedApiContext {
1104
1104
  private readonly _syncApi;
1105
1105
  private readonly _decoupledOperationsApi;
1106
1106
  constructor(cfg: BrokerizeConfig, auth: Auth, wsClient?: BrokerizeWebSocketClient);
1107
+ /**
1108
+ * The websocket client keeps one context around to refetch the status of a decoupled operation
1109
+ * with after an interrupted connection. That context has to outlive the connection, so it must
1110
+ * not simply be whichever one was constructed last: child contexts are commonly created per
1111
+ * request and destroyed again, and a destroyed context cannot perform that request.
1112
+ *
1113
+ * The first context attaches and keeps the client - that is the one that created it, and the
1114
+ * children, which are handed the very same client, leave it alone.
1115
+ */
1116
+ private _attachToWsClient;
1117
+ /**
1118
+ * Counterpart of `_attachToWsClient`: leave no destroyed context behind, so that a context
1119
+ * created later can take over.
1120
+ */
1121
+ private _detachFromWsClient;
1107
1122
  createChildContext(): AuthorizedApiContext;
1108
1123
  private _initRequestInit;
1109
1124
  getBrokers(): Promise<openApiClient.GetBrokersResponse>;
@@ -1582,7 +1597,17 @@ export declare class BrokerizeError extends Error {
1582
1597
  */
1583
1598
  code: string;
1584
1599
  httpStatusCode: number;
1585
- constructor(statusCode: number, body: ErrorResponse);
1600
+ /**
1601
+ * The delay in milliseconds the server asked the client to wait before retrying, taken from the
1602
+ * `Retry-After` response header. Set for rate limits, but not for all of them - a rate limit
1603
+ * hit on the way to a broker has no reliable wait time to announce.
1604
+ *
1605
+ * This client never retries on its own: whether waiting is acceptable depends on the call (a
1606
+ * background poll may wait and try again, placing an order must not), so the application
1607
+ * decides. Treat this as the minimum delay and add a backoff of your own.
1608
+ */
1609
+ retryAfterMs?: number;
1610
+ constructor(statusCode: number, body: ErrorResponse, retryAfterMs?: number);
1586
1611
  }
1587
1612
 
1588
1613
  /**
@@ -7440,6 +7465,12 @@ declare type InvalidateMessage = {
7440
7465
  */
7441
7466
  export declare function isBrokerizeWebSocketError(x: unknown): x is BrokerizeWebSocketError;
7442
7467
 
7468
+ /**
7469
+ * Whether the given error is a rate limit the caller may retry after waiting. Check
7470
+ * {@link BrokerizeError.retryAfterMs} for the delay the server asked for - it is not always set.
7471
+ */
7472
+ export declare function isRateLimitError(err: unknown): err is BrokerizeError;
7473
+
7443
7474
  declare type Json = any;
7444
7475
 
7445
7476
  declare class JSONApiResponse<T> {
@@ -11123,6 +11154,13 @@ declare function PagesConfigurationResponseToJSON(value?: PagesConfigurationResp
11123
11154
 
11124
11155
  declare function PagesConfigurationResponseToJSONRecursive(value?: PagesConfigurationResponse | null, ignoreParent?: boolean): any;
11125
11156
 
11157
+ /**
11158
+ * Parses a `Retry-After` header into milliseconds. The brokerize API sends a (possibly fractional)
11159
+ * number of seconds; the HTTP spec also allows an absolute date, which a proxy in front of the API
11160
+ * may produce. Returns `undefined` if the header is absent or cannot be understood.
11161
+ */
11162
+ export declare function parseRetryAfter(value: string | null | undefined): number | undefined;
11163
+
11126
11164
  /**
11127
11165
  *
11128
11166
  * @export
package/dist/errors.d.ts CHANGED
@@ -63,7 +63,17 @@ export declare class BrokerizeError extends Error {
63
63
  */
64
64
  code: string;
65
65
  httpStatusCode: number;
66
- constructor(statusCode: number, body: ErrorResponse);
66
+ /**
67
+ * The delay in milliseconds the server asked the client to wait before retrying, taken from the
68
+ * `Retry-After` response header. Set for rate limits, but not for all of them - a rate limit
69
+ * hit on the way to a broker has no reliable wait time to announce.
70
+ *
71
+ * This client never retries on its own: whether waiting is acceptable depends on the call (a
72
+ * background poll may wait and try again, placing an order must not), so the application
73
+ * decides. Treat this as the minimum delay and add a backoff of your own.
74
+ */
75
+ retryAfterMs?: number;
76
+ constructor(statusCode: number, body: ErrorResponse, retryAfterMs?: number);
67
77
  }
68
78
  /**
69
79
  * Thrown if a request to the brokerize API timed out (HTTP status 504). This is typically sent by
@@ -73,12 +83,33 @@ export declare class BrokerizeError extends Error {
73
83
  export declare class BrokerizeTimeoutError extends BrokerizeError {
74
84
  constructor(body: ErrorResponse);
75
85
  }
86
+ /**
87
+ * Whether the given error is a rate limit the caller may retry after waiting. Check
88
+ * {@link BrokerizeError.retryAfterMs} for the delay the server asked for - it is not always set.
89
+ */
90
+ export declare function isRateLimitError(err: unknown): err is BrokerizeError;
91
+ /**
92
+ * Parses a `Retry-After` header into milliseconds. The brokerize API sends a (possibly fractional)
93
+ * number of seconds; the HTTP spec also allows an absolute date, which a proxy in front of the API
94
+ * may produce. Returns `undefined` if the header is absent or cannot be understood.
95
+ */
96
+ export declare function parseRetryAfter(value: string | null | undefined): number | undefined;
76
97
  /**
77
98
  * Create the error for a failed (status >= 400) API response. If the body is not a valid `ErrorResponse`
78
99
  * (e.g. an HTML error page from a load balancer), a generic error body is used instead of failing with a
79
100
  * JSON parse error.
80
101
  */
81
102
  export declare function createErrorFromResponse(response: Response): Promise<BrokerizeError>;
103
+ /**
104
+ * Create the error for a failed token refresh (`POST /user/token`).
105
+ *
106
+ * A rejected token means the user has to log in again, and callers act on that by discarding the
107
+ * stored session - so only an actual rejection may be reported that way. Everything else (a rate
108
+ * limit, a server error, maintenance) is transient and is passed through unchanged: flattening
109
+ * those into an auth error throws away a session that is still good, and turns one rate-limited
110
+ * request into a fresh login.
111
+ */
112
+ export declare function createTokenRefreshError(response: Response): Promise<BrokerizeError>;
82
113
  /**
83
114
  * Error codes used by {@link BrokerizeWebSocketError}.
84
115
  *
package/dist/errors.js CHANGED
@@ -12,9 +12,10 @@ export class TradingError extends Error {
12
12
  }
13
13
  }
14
14
  export class BrokerizeError extends Error {
15
- constructor(statusCode, body) {
15
+ constructor(statusCode, body, retryAfterMs) {
16
16
  super(body.msg);
17
17
  this.httpStatusCode = statusCode;
18
+ this.retryAfterMs = retryAfterMs;
18
19
  this.name = "BrokerizeError";
19
20
  this.msg = body.msg;
20
21
  this.code = body.code;
@@ -34,6 +35,34 @@ export class BrokerizeTimeoutError extends BrokerizeError {
34
35
  this.name = "BrokerizeTimeoutError";
35
36
  }
36
37
  }
38
+ /**
39
+ * Whether the given error is a rate limit the caller may retry after waiting. Check
40
+ * {@link BrokerizeError.retryAfterMs} for the delay the server asked for - it is not always set.
41
+ */
42
+ export function isRateLimitError(err) {
43
+ return (err instanceof BrokerizeError &&
44
+ (err.code === "RATE_LIMITED" || err.httpStatusCode === 429));
45
+ }
46
+ /**
47
+ * Parses a `Retry-After` header into milliseconds. The brokerize API sends a (possibly fractional)
48
+ * number of seconds; the HTTP spec also allows an absolute date, which a proxy in front of the API
49
+ * may produce. Returns `undefined` if the header is absent or cannot be understood.
50
+ */
51
+ export function parseRetryAfter(value) {
52
+ const raw = value === null || value === void 0 ? void 0 : value.trim();
53
+ if (!raw) {
54
+ return undefined;
55
+ }
56
+ const seconds = Number(raw);
57
+ if (Number.isFinite(seconds)) {
58
+ return seconds >= 0 ? Math.round(seconds * 1000) : undefined;
59
+ }
60
+ const date = Date.parse(raw);
61
+ if (isNaN(date)) {
62
+ return undefined;
63
+ }
64
+ return Math.max(0, date - Date.now());
65
+ }
37
66
  function isErrorResponse(x) {
38
67
  return (!!x &&
39
68
  typeof x === "object" &&
@@ -47,6 +76,7 @@ function isErrorResponse(x) {
47
76
  */
48
77
  export async function createErrorFromResponse(response) {
49
78
  const statusCode = response.status;
79
+ const retryAfterMs = parseRetryAfter(response.headers.get("Retry-After"));
50
80
  let body;
51
81
  try {
52
82
  const parsed = JSON.parse(await response.text());
@@ -66,7 +96,26 @@ export async function createErrorFromResponse(response) {
66
96
  return new BrokerizeError(statusCode, body || {
67
97
  msg: "The request failed with status " + statusCode + ".",
68
98
  code: "INTERNAL_SERVER_ERROR",
69
- });
99
+ }, retryAfterMs);
100
+ }
101
+ /**
102
+ * Create the error for a failed token refresh (`POST /user/token`).
103
+ *
104
+ * A rejected token means the user has to log in again, and callers act on that by discarding the
105
+ * stored session - so only an actual rejection may be reported that way. Everything else (a rate
106
+ * limit, a server error, maintenance) is transient and is passed through unchanged: flattening
107
+ * those into an auth error throws away a session that is still good, and turns one rate-limited
108
+ * request into a fresh login.
109
+ */
110
+ export async function createTokenRefreshError(response) {
111
+ const err = await createErrorFromResponse(response);
112
+ if (err.httpStatusCode === 401 || err.httpStatusCode === 403) {
113
+ return new BrokerizeError(401, {
114
+ msg: "The token could not be refreshed. Please log in again.",
115
+ code: "AUTH",
116
+ });
117
+ }
118
+ return err;
70
119
  }
71
120
  const DEFAULT_STATUS_CODES = {
72
121
  AUTH: 401,
package/dist/index.d.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  import { Auth, AuthContextConfiguration, BrokerizeConfig, CognitoConfig, CognitoFacade, CognitoPoolConfig, GetTokenOptions, GuestAuthContextConfiguration, RegisteredUserAuthContextConfiguration, TokenSet } from "./apiCtx";
2
2
  import { AuthorizedApiContext } from "./authorizedApiContext";
3
- import { BrokerizeAbortError, BrokerizeError, BrokerizeTimeoutError, BrokerizeWebSocketError, BrokerizeWebSocketErrorCode, BrokerizeWebSocketErrorParams, isBrokerizeWebSocketError } from "./errors";
3
+ import { BrokerizeAbortError, BrokerizeError, BrokerizeTimeoutError, BrokerizeWebSocketError, BrokerizeWebSocketErrorCode, BrokerizeWebSocketErrorParams, isBrokerizeWebSocketError, isRateLimitError, parseRetryAfter } from "./errors";
4
4
  import * as openApiClient from "./swagger";
5
5
  import * as Models from "./modelExports";
6
6
  import { BrokerizeWebSocketClient, BrokerizeWebSocketClientOptions, Callback, ConnectionStateCallback, Subscription, WebSocketConnectionState, WebSocketConnectionStatus } from "./websocketClient";
7
7
  import * as WebSocketTypes from "./websocketTypes";
8
8
  import * as Utils from "./utils";
9
- export { BrokerizeConfig, AuthContextConfiguration, AuthorizedApiContext, BrokerizeWebSocketClient, Models, WebSocketTypes, Subscription, Callback, Utils, BrokerizeError, BrokerizeTimeoutError, BrokerizeWebSocketError, BrokerizeWebSocketErrorCode, BrokerizeWebSocketErrorParams, BrokerizeAbortError, GetTokenOptions, isBrokerizeWebSocketError, ConnectionStateCallback, BrokerizeWebSocketClientOptions, WebSocketConnectionState, WebSocketConnectionStatus, Auth, TokenSet, };
9
+ export { BrokerizeConfig, AuthContextConfiguration, AuthorizedApiContext, BrokerizeWebSocketClient, Models, WebSocketTypes, Subscription, Callback, Utils, BrokerizeError, BrokerizeTimeoutError, BrokerizeWebSocketError, BrokerizeWebSocketErrorCode, BrokerizeWebSocketErrorParams, BrokerizeAbortError, GetTokenOptions, isBrokerizeWebSocketError, isRateLimitError, parseRetryAfter, ConnectionStateCallback, BrokerizeWebSocketClientOptions, WebSocketConnectionState, WebSocketConnectionStatus, Auth, TokenSet, };
10
10
  export { CognitoPoolConfig, RegisteredUserAuthContextConfiguration };
11
11
  export { CognitoConfig, CognitoFacade };
12
12
  export declare class Brokerize {
package/dist/index.js CHANGED
@@ -2,13 +2,13 @@
2
2
  but reduced to the parts actually used by bg-trading. */
3
3
  import { createAuth, createConfiguration, withAcceptLanguage, } from "./apiCtx.js";
4
4
  import { AuthorizedApiContext, getWebSocketURLByBasePath, } from "./authorizedApiContext.js";
5
- import { BrokerizeAbortError, BrokerizeError, BrokerizeTimeoutError, BrokerizeWebSocketError, createErrorFromResponse, isBrokerizeWebSocketError, } from "./errors.js";
5
+ import { BrokerizeAbortError, BrokerizeError, BrokerizeTimeoutError, BrokerizeWebSocketError, createErrorFromResponse, createTokenRefreshError, isBrokerizeWebSocketError, isRateLimitError, parseRetryAfter, } from "./errors.js";
6
6
  import * as openApiClient from "./swagger/index.js";
7
7
  import * as Models from "./modelExports.js";
8
8
  import { BrokerizeWebSocketClientImpl, } from "./websocketClient.js";
9
9
  import * as WebSocketTypes from "./websocketTypes.js";
10
10
  import * as Utils from "./utils.js";
11
- export { AuthorizedApiContext, Models, WebSocketTypes, Utils, BrokerizeError, BrokerizeTimeoutError, BrokerizeWebSocketError, BrokerizeAbortError, isBrokerizeWebSocketError, };
11
+ export { AuthorizedApiContext, Models, WebSocketTypes, Utils, BrokerizeError, BrokerizeTimeoutError, BrokerizeWebSocketError, BrokerizeAbortError, isBrokerizeWebSocketError, isRateLimitError, parseRetryAfter, };
12
12
  export class Brokerize {
13
13
  constructor(cfg) {
14
14
  if (!cfg.fetch) {
@@ -54,10 +54,7 @@ export class Brokerize {
54
54
  body: `grant_type=refresh_token&refresh_token=${encodeURIComponent(refreshToken)}`,
55
55
  });
56
56
  if (!response.ok) {
57
- throw new BrokerizeError(401, {
58
- msg: "The token could not be refreshed. Please log in again.",
59
- code: "AUTH",
60
- });
57
+ throw await createTokenRefreshError(response);
61
58
  }
62
59
  const responseJson = (await response.json());
63
60
  return {
@@ -89,8 +89,16 @@ export declare class BrokerizeWebSocketClientImpl implements BrokerizeWebSocketC
89
89
  /**
90
90
  * Internal method for setting a related AuthorizedApiContext. This is used to retrieve
91
91
  * decoupled operation status on interrupted connections.
92
+ *
93
+ * `null` detaches the current one, which a context does when it is destroyed: a destroyed
94
+ * context cannot perform that request, so holding on to it would be worse than holding none.
95
+ */
96
+ _setAuthorizedApiContext(ctx: AuthorizedApiContext | null): void;
97
+ /**
98
+ * Internal counterpart of `_setAuthorizedApiContext`, so that a context can tell whether the
99
+ * client is already attached to one - and whether that one is itself.
92
100
  */
93
- _setAuthorizedApiContext(ctx: AuthorizedApiContext): void;
101
+ _getAuthorizedApiContext(): AuthorizedApiContext | null;
94
102
  _startOrStopDisconnectTimeout(): void;
95
103
  private _sendWs;
96
104
  /**
@@ -348,10 +348,20 @@ export class BrokerizeWebSocketClientImpl {
348
348
  /**
349
349
  * Internal method for setting a related AuthorizedApiContext. This is used to retrieve
350
350
  * decoupled operation status on interrupted connections.
351
+ *
352
+ * `null` detaches the current one, which a context does when it is destroyed: a destroyed
353
+ * context cannot perform that request, so holding on to it would be worse than holding none.
351
354
  */
352
355
  _setAuthorizedApiContext(ctx) {
353
356
  this._apiCtx = ctx;
354
357
  }
358
+ /**
359
+ * Internal counterpart of `_setAuthorizedApiContext`, so that a context can tell whether the
360
+ * client is already attached to one - and whether that one is itself.
361
+ */
362
+ _getAuthorizedApiContext() {
363
+ return this._apiCtx;
364
+ }
355
365
  _startOrStopDisconnectTimeout() {
356
366
  if (this._shouldConnect()) {
357
367
  if (this._disconnectTimeout) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@brokerize/client",
3
- "version": "1.12.0",
3
+ "version": "1.12.2",
4
4
  "description": "Client for the brokerize.com API",
5
5
  "keywords": [],
6
6
  "homepage": "https://github.com/brokerize/client-js#readme",
@@ -63,14 +63,14 @@
63
63
  },
64
64
  "devDependencies": {
65
65
  "@microsoft/api-extractor": "7.60.1",
66
- "@openapitools/openapi-generator-cli": "2.42.1",
66
+ "@openapitools/openapi-generator-cli": "2.42.2",
67
67
  "@types/node": "24.19.2",
68
68
  "@typescript-eslint/eslint-plugin": "8.72.2",
69
- "eslint": "10.14.0",
69
+ "eslint": "10.15.0",
70
70
  "eslint-config-prettier": "10.1.8",
71
71
  "husky": "9.1.7",
72
72
  "lint-staged": "17.6.0",
73
- "prettier": "3.9.10",
73
+ "prettier": "3.10.1",
74
74
  "sort-package-json": "4.1.0",
75
75
  "typescript": "6.0.3"
76
76
  },