@brokerize/client 1.10.0 → 1.12.0

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 (94) hide show
  1. package/README.md +45 -0
  2. package/dist/apiCtx.d.ts +10 -2
  3. package/dist/apiCtx.js +4 -4
  4. package/dist/authorizedApiContext.d.ts +5 -0
  5. package/dist/authorizedApiContext.js +12 -4
  6. package/dist/cjs/apiCtx.d.ts +10 -2
  7. package/dist/cjs/apiCtx.js +4 -4
  8. package/dist/cjs/authorizedApiContext.d.ts +5 -0
  9. package/dist/cjs/authorizedApiContext.js +11 -3
  10. package/dist/cjs/errors.d.ts +74 -0
  11. package/dist/cjs/errors.js +95 -1
  12. package/dist/cjs/index.d.ts +4 -4
  13. package/dist/cjs/index.js +6 -4
  14. package/dist/cjs/modelExports.d.ts +3 -0
  15. package/dist/cjs/modelExports.js +5 -1
  16. package/dist/cjs/swagger/models/BrokerClientCfg.d.ts +7 -0
  17. package/dist/cjs/swagger/models/BrokerClientCfg.js +5 -0
  18. package/dist/cjs/swagger/models/BrokerMeta.d.ts +15 -0
  19. package/dist/cjs/swagger/models/BrokerMeta.js +2 -0
  20. package/dist/cjs/swagger/models/ClientConfigUpdateOAuthLoginForm.d.ts +12 -1
  21. package/dist/cjs/swagger/models/ClientConfigUpdateOAuthLoginForm.js +2 -0
  22. package/dist/cjs/swagger/models/OAuthLoginFormConfig.d.ts +12 -1
  23. package/dist/cjs/swagger/models/OAuthLoginFormConfig.js +2 -0
  24. package/dist/cjs/swagger/models/Order.d.ts +9 -1
  25. package/dist/cjs/swagger/models/OrderCreate.d.ts +2 -1
  26. package/dist/cjs/swagger/models/PortfolioOrderDetailsSyncInfo.d.ts +60 -0
  27. package/dist/cjs/swagger/models/PortfolioOrderDetailsSyncInfo.js +51 -0
  28. package/dist/cjs/swagger/models/PortfolioOrderDetailsSyncInfoStatus.d.ts +22 -0
  29. package/dist/cjs/swagger/models/PortfolioOrderDetailsSyncInfoStatus.js +35 -0
  30. package/dist/cjs/swagger/models/PortfolioSyncInfoComplete.d.ts +7 -0
  31. package/dist/cjs/swagger/models/PortfolioSyncInfoComplete.js +6 -0
  32. package/dist/cjs/swagger/models/PortfolioSyncInfoCompleteSpecifics.d.ts +7 -0
  33. package/dist/cjs/swagger/models/PortfolioSyncInfoCompleteSpecifics.js +5 -0
  34. package/dist/cjs/swagger/models/PortfolioSyncInfoIncomplete.d.ts +7 -0
  35. package/dist/cjs/swagger/models/PortfolioSyncInfoIncomplete.js +6 -0
  36. package/dist/cjs/swagger/models/PortfolioSyncInfoIncompleteSpecifics.d.ts +7 -0
  37. package/dist/cjs/swagger/models/PortfolioSyncInfoIncompleteSpecifics.js +5 -0
  38. package/dist/cjs/swagger/models/SmartbrokerClientCfg.d.ts +27 -0
  39. package/dist/cjs/swagger/models/SmartbrokerClientCfg.js +46 -0
  40. package/dist/cjs/swagger/models/SummarizedTrade.d.ts +14 -0
  41. package/dist/cjs/swagger/models/SummarizedTrade.js +4 -0
  42. package/dist/cjs/swagger/models/TradeWarning.d.ts +31 -1
  43. package/dist/cjs/swagger/models/TradeWarning.js +13 -0
  44. package/dist/cjs/swagger/models/TradeWarningReason.d.ts +46 -0
  45. package/dist/cjs/swagger/models/TradeWarningReason.js +59 -0
  46. package/dist/cjs/swagger/models/index.d.ts +4 -0
  47. package/dist/cjs/swagger/models/index.js +4 -0
  48. package/dist/cjs/websocketClient.d.ts +109 -2
  49. package/dist/cjs/websocketClient.js +416 -74
  50. package/dist/cjs/websocketTypes.d.ts +10 -0
  51. package/dist/client.d.ts +437 -61
  52. package/dist/errors.d.ts +74 -0
  53. package/dist/errors.js +89 -0
  54. package/dist/index.d.ts +4 -4
  55. package/dist/index.js +3 -5
  56. package/dist/modelExports.d.ts +3 -0
  57. package/dist/modelExports.js +2 -0
  58. package/dist/swagger/models/BrokerClientCfg.d.ts +7 -0
  59. package/dist/swagger/models/BrokerClientCfg.js +5 -0
  60. package/dist/swagger/models/BrokerMeta.d.ts +15 -0
  61. package/dist/swagger/models/BrokerMeta.js +2 -0
  62. package/dist/swagger/models/ClientConfigUpdateOAuthLoginForm.d.ts +12 -1
  63. package/dist/swagger/models/ClientConfigUpdateOAuthLoginForm.js +2 -0
  64. package/dist/swagger/models/OAuthLoginFormConfig.d.ts +12 -1
  65. package/dist/swagger/models/OAuthLoginFormConfig.js +2 -0
  66. package/dist/swagger/models/Order.d.ts +9 -1
  67. package/dist/swagger/models/OrderCreate.d.ts +2 -1
  68. package/dist/swagger/models/PortfolioOrderDetailsSyncInfo.d.ts +60 -0
  69. package/dist/swagger/models/PortfolioOrderDetailsSyncInfo.js +45 -0
  70. package/dist/swagger/models/PortfolioOrderDetailsSyncInfoStatus.d.ts +22 -0
  71. package/dist/swagger/models/PortfolioOrderDetailsSyncInfoStatus.js +29 -0
  72. package/dist/swagger/models/PortfolioSyncInfoComplete.d.ts +7 -0
  73. package/dist/swagger/models/PortfolioSyncInfoComplete.js +6 -0
  74. package/dist/swagger/models/PortfolioSyncInfoCompleteSpecifics.d.ts +7 -0
  75. package/dist/swagger/models/PortfolioSyncInfoCompleteSpecifics.js +5 -0
  76. package/dist/swagger/models/PortfolioSyncInfoIncomplete.d.ts +7 -0
  77. package/dist/swagger/models/PortfolioSyncInfoIncomplete.js +6 -0
  78. package/dist/swagger/models/PortfolioSyncInfoIncompleteSpecifics.d.ts +7 -0
  79. package/dist/swagger/models/PortfolioSyncInfoIncompleteSpecifics.js +5 -0
  80. package/dist/swagger/models/SmartbrokerClientCfg.d.ts +27 -0
  81. package/dist/swagger/models/SmartbrokerClientCfg.js +40 -0
  82. package/dist/swagger/models/SummarizedTrade.d.ts +14 -0
  83. package/dist/swagger/models/SummarizedTrade.js +4 -0
  84. package/dist/swagger/models/TradeWarning.d.ts +31 -1
  85. package/dist/swagger/models/TradeWarning.js +13 -0
  86. package/dist/swagger/models/TradeWarningReason.d.ts +46 -0
  87. package/dist/swagger/models/TradeWarningReason.js +53 -0
  88. package/dist/swagger/models/index.d.ts +4 -0
  89. package/dist/swagger/models/index.js +4 -0
  90. package/dist/tsdoc-metadata.json +1 -1
  91. package/dist/websocketClient.d.ts +109 -2
  92. package/dist/websocketClient.js +416 -74
  93. package/dist/websocketTypes.d.ts +10 -0
  94. package/package.json +11 -10
package/README.md CHANGED
@@ -63,6 +63,51 @@ async function someBrokerizeActions() {
63
63
  someBrokerizeActions().then(console.log, console.error)
64
64
  ```
65
65
 
66
+ # websocket error handling
67
+
68
+ Every error reported by the websocket client is a `BrokerizeWebSocketError`, a subclass of
69
+ `BrokerizeError`, so it can be handled like any other error of this library. Errors reach an
70
+ application through two separate channels:
71
+
72
+ - **Subscription callbacks** only receive _terminal_ errors: the subscription is over and will not
73
+ receive any further data. This maps directly onto e.g. an RxJS `subscriber.error()`.
74
+ - **`subscribeConnectionState`** reports the state of the underlying connection, including the
75
+ errors that the client recovers from on its own. Use it to tell the user that live updates are
76
+ currently unavailable, instead of tearing down subscriptions on every connection hiccup.
77
+
78
+ ```js
79
+ const client = ctx.createWebSocketClient();
80
+
81
+ client.subscribeConnectionState(({ status, error }) => {
82
+ /* 'closed' | 'connecting' | 'open' | 'reconnecting' | 'fatal' */
83
+ if (status == "fatal") {
84
+ /* the client is unusable, all subscriptions were terminated with `error`. */
85
+ console.error("live updates stopped", error);
86
+ client.reconnect(); /* ... and subscribe again */
87
+ }
88
+ });
89
+
90
+ client.subscribeInvalidate({ entity: "sessions" }, (err) => {
91
+ if (err) {
92
+ /* err is a BrokerizeWebSocketError with err.terminal === true. */
93
+ console.error("subscription ended", err.code, err.message);
94
+ return;
95
+ }
96
+ reloadSessions();
97
+ });
98
+ ```
99
+
100
+ A connection that cannot be authenticated is not a special case: the client refreshes the token
101
+ and keeps retrying with a wide backoff, staying in `reconnecting` with the rejection as `error`.
102
+ The usual cause is an id token that expired in flight, and the first retry fixes it without the
103
+ application noticing more than a short gap - the subscriptions stay alive throughout. Only a token
104
+ that is still being rejected after several minutes makes the client `fatal`, because by then the
105
+ session is gone rather than stale.
106
+
107
+ This means an application does not need its own retry: it only has to decide what to show while
108
+ `status` is `reconnecting`, and how to react to `fatal` - usually the same way it reacts to a `401`
109
+ on the REST API, which it will have seen by then anyway.
110
+
66
111
  # development & maintenance
67
112
 
68
113
  The code in `src/swagger` is generated by the npm script `npm run generate` from the OpenAPI spec and will be regenerated whenever API changes are made. No manual changes should be made in the `src/swagger` directory. `npm run download-spec` will download the current spec from `api-preview.brokerize.com`.
package/dist/apiCtx.d.ts CHANGED
@@ -64,8 +64,16 @@ export interface GuestAuthContextConfiguration {
64
64
  response: Models.CreateGuestUserResponse;
65
65
  };
66
66
  }
67
+ export type GetTokenOptions = {
68
+ /**
69
+ * Request a fresh token even if the currently known one is not expired yet. Used by the
70
+ * websocket client to retry once after the server rejected a token, before giving up.
71
+ * Implementations that cannot refresh on demand may ignore this.
72
+ */
73
+ forceRefresh?: boolean;
74
+ };
67
75
  export interface Auth {
68
- getToken: () => Promise<{
76
+ getToken: (opts?: GetTokenOptions) => Promise<{
69
77
  idToken: string;
70
78
  }>;
71
79
  }
@@ -87,7 +95,7 @@ export type CognitoPoolConfig = {
87
95
  };
88
96
  export type CognitoFacade = {
89
97
  createSession: (cognitoPoolConfig: CognitoPoolConfig, authCfg: RegisteredUserAuthContextConfiguration) => {
90
- getToken: () => Promise<{
98
+ getToken: (opts?: GetTokenOptions) => Promise<{
91
99
  idToken: string;
92
100
  }>;
93
101
  };
package/dist/apiCtx.js CHANGED
@@ -39,7 +39,7 @@ export function createAuth({ authCfg, cfg, options, tokenRefreshCallback, }) {
39
39
  if (authCfg.type == "guest") {
40
40
  const guestAuthCfg = JSON.parse(JSON.stringify(authCfg)); // clone it
41
41
  return {
42
- async getToken() {
42
+ async getToken(opts) {
43
43
  if (guestAuthCfg.tokens) {
44
44
  let expiresIn = guestAuthCfg.tokens.response.expiresIn;
45
45
  if (expiresIn == null) {
@@ -49,7 +49,7 @@ export function createAuth({ authCfg, cfg, options, tokenRefreshCallback, }) {
49
49
  }
50
50
  /* modern tokens */
51
51
  const tokenExpiresAt = guestAuthCfg.tokens.updatedAt + expiresIn * 1000 - 10000;
52
- const needsRefresh = Date.now() > tokenExpiresAt;
52
+ const needsRefresh = (opts === null || opts === void 0 ? void 0 : opts.forceRefresh) || Date.now() > tokenExpiresAt;
53
53
  if (needsRefresh && guestAuthCfg.tokens.response.refreshToken) {
54
54
  if (!cfg.fetch) {
55
55
  throw new Error("Invalid cfg: fetch is required for refreshing tokens.");
@@ -104,8 +104,8 @@ export function createAuth({ authCfg, cfg, options, tokenRefreshCallback, }) {
104
104
  }
105
105
  const session = options.cognitoFacade.createSession((_a = cfg.cognito) === null || _a === void 0 ? void 0 : _a.poolConfig, authCfg);
106
106
  return {
107
- async getToken() {
108
- return session.getToken();
107
+ async getToken(opts) {
108
+ return session.getToken(opts);
109
109
  },
110
110
  };
111
111
  }
@@ -18,6 +18,11 @@ export declare class AuthorizedApiContext {
18
18
  private readonly _orderApiCryptoService;
19
19
  private readonly _logoutSubject;
20
20
  private readonly _wsClient;
21
+ /**
22
+ * `true` if this context created the websocket client itself and therefore has to destroy it.
23
+ * A client passed in by the application is owned by the application.
24
+ */
25
+ private readonly _ownsWsClient;
21
26
  private readonly _cache;
22
27
  private readonly _exportApi;
23
28
  private readonly _adminApi;
@@ -1,6 +1,6 @@
1
1
  import { Subject } from "rxjs";
2
2
  import { createConfiguration, withAcceptLanguage, } from "./apiCtx.js";
3
- import { BrokerizeError } from "./errors.js";
3
+ import { BrokerizeAbortError, createErrorFromResponse } from "./errors.js";
4
4
  import { createPollingSubscription } from "./pollingSubscription.js";
5
5
  import * as openApiClient from "./swagger/index.js";
6
6
  import { BrokerizeWebSocketClientImpl, } from "./websocketClient.js";
@@ -25,8 +25,7 @@ export class AuthorizedApiContext {
25
25
  const postMiddleware = async (r) => {
26
26
  const statusCode = r.response.status;
27
27
  if (statusCode >= 400) {
28
- const decJson = (await r.response.json());
29
- const err = new BrokerizeError(statusCode, decJson);
28
+ const err = await createErrorFromResponse(r.response);
30
29
  if (statusCode == 401) {
31
30
  this._logoutSubject.error(err);
32
31
  }
@@ -52,6 +51,7 @@ export class AuthorizedApiContext {
52
51
  throw new Error("createAbortController not provided. This should not happen as there should be a default implementation.");
53
52
  }
54
53
  this._abortController = cfg.createAbortController();
54
+ this._ownsWsClient = !wsClient;
55
55
  this._wsClient = wsClient || this._initInternalWebSocketClient();
56
56
  if (this._wsClient._setAuthorizedApiContext) {
57
57
  this._wsClient._setAuthorizedApiContext(this);
@@ -71,7 +71,7 @@ export class AuthorizedApiContext {
71
71
  }
72
72
  async _initRequestInit() {
73
73
  if (this._isDestroyed) {
74
- throw new Error("AuthorizedApiContext is destroyed");
74
+ throw new BrokerizeAbortError("AuthorizedApiContext is destroyed");
75
75
  }
76
76
  const tok = await this._auth.getToken();
77
77
  const headers = await withAcceptLanguage(this._cfg, {
@@ -435,12 +435,20 @@ export class AuthorizedApiContext {
435
435
  const wrappedClient = {
436
436
  subscribeDecoupledOperation: this._wsClient.subscribeDecoupledOperation.bind(this._wsClient),
437
437
  subscribeInvalidate: this._wsClient.subscribeInvalidate.bind(this._wsClient),
438
+ subscribeConnectionState: this._wsClient.subscribeConnectionState.bind(this._wsClient),
439
+ getConnectionState: this._wsClient.getConnectionState.bind(this._wsClient),
440
+ reconnect: this._wsClient.reconnect.bind(this._wsClient),
438
441
  };
439
442
  return wrappedClient;
440
443
  }
441
444
  destroy() {
442
445
  this._isDestroyed = true;
443
446
  this._abortController.abort();
447
+ if (this._ownsWsClient) {
448
+ /* otherwise its reconnect timer would keep running and keep reconnecting with the
449
+ tokens of a context that is gone. */
450
+ this._wsClient.destroy();
451
+ }
444
452
  }
445
453
  subscribeLogout(callback) {
446
454
  const s = this._logoutSubject.subscribe({
@@ -64,8 +64,16 @@ export interface GuestAuthContextConfiguration {
64
64
  response: Models.CreateGuestUserResponse;
65
65
  };
66
66
  }
67
+ export type GetTokenOptions = {
68
+ /**
69
+ * Request a fresh token even if the currently known one is not expired yet. Used by the
70
+ * websocket client to retry once after the server rejected a token, before giving up.
71
+ * Implementations that cannot refresh on demand may ignore this.
72
+ */
73
+ forceRefresh?: boolean;
74
+ };
67
75
  export interface Auth {
68
- getToken: () => Promise<{
76
+ getToken: (opts?: GetTokenOptions) => Promise<{
69
77
  idToken: string;
70
78
  }>;
71
79
  }
@@ -87,7 +95,7 @@ export type CognitoPoolConfig = {
87
95
  };
88
96
  export type CognitoFacade = {
89
97
  createSession: (cognitoPoolConfig: CognitoPoolConfig, authCfg: RegisteredUserAuthContextConfiguration) => {
90
- getToken: () => Promise<{
98
+ getToken: (opts?: GetTokenOptions) => Promise<{
91
99
  idToken: string;
92
100
  }>;
93
101
  };
@@ -45,7 +45,7 @@ function createAuth({ authCfg, cfg, options, tokenRefreshCallback, }) {
45
45
  if (authCfg.type == "guest") {
46
46
  const guestAuthCfg = JSON.parse(JSON.stringify(authCfg)); // clone it
47
47
  return {
48
- async getToken() {
48
+ async getToken(opts) {
49
49
  if (guestAuthCfg.tokens) {
50
50
  let expiresIn = guestAuthCfg.tokens.response.expiresIn;
51
51
  if (expiresIn == null) {
@@ -55,7 +55,7 @@ function createAuth({ authCfg, cfg, options, tokenRefreshCallback, }) {
55
55
  }
56
56
  /* modern tokens */
57
57
  const tokenExpiresAt = guestAuthCfg.tokens.updatedAt + expiresIn * 1000 - 10000;
58
- const needsRefresh = Date.now() > tokenExpiresAt;
58
+ const needsRefresh = (opts === null || opts === void 0 ? void 0 : opts.forceRefresh) || Date.now() > tokenExpiresAt;
59
59
  if (needsRefresh && guestAuthCfg.tokens.response.refreshToken) {
60
60
  if (!cfg.fetch) {
61
61
  throw new Error("Invalid cfg: fetch is required for refreshing tokens.");
@@ -110,8 +110,8 @@ function createAuth({ authCfg, cfg, options, tokenRefreshCallback, }) {
110
110
  }
111
111
  const session = options.cognitoFacade.createSession((_a = cfg.cognito) === null || _a === void 0 ? void 0 : _a.poolConfig, authCfg);
112
112
  return {
113
- async getToken() {
114
- return session.getToken();
113
+ async getToken(opts) {
114
+ return session.getToken(opts);
115
115
  },
116
116
  };
117
117
  }
@@ -18,6 +18,11 @@ export declare class AuthorizedApiContext {
18
18
  private readonly _orderApiCryptoService;
19
19
  private readonly _logoutSubject;
20
20
  private readonly _wsClient;
21
+ /**
22
+ * `true` if this context created the websocket client itself and therefore has to destroy it.
23
+ * A client passed in by the application is owned by the application.
24
+ */
25
+ private readonly _ownsWsClient;
21
26
  private readonly _cache;
22
27
  private readonly _exportApi;
23
28
  private readonly _adminApi;
@@ -62,8 +62,7 @@ class AuthorizedApiContext {
62
62
  const postMiddleware = async (r) => {
63
63
  const statusCode = r.response.status;
64
64
  if (statusCode >= 400) {
65
- const decJson = (await r.response.json());
66
- const err = new errors_1.BrokerizeError(statusCode, decJson);
65
+ const err = await (0, errors_1.createErrorFromResponse)(r.response);
67
66
  if (statusCode == 401) {
68
67
  this._logoutSubject.error(err);
69
68
  }
@@ -89,6 +88,7 @@ class AuthorizedApiContext {
89
88
  throw new Error("createAbortController not provided. This should not happen as there should be a default implementation.");
90
89
  }
91
90
  this._abortController = cfg.createAbortController();
91
+ this._ownsWsClient = !wsClient;
92
92
  this._wsClient = wsClient || this._initInternalWebSocketClient();
93
93
  if (this._wsClient._setAuthorizedApiContext) {
94
94
  this._wsClient._setAuthorizedApiContext(this);
@@ -108,7 +108,7 @@ class AuthorizedApiContext {
108
108
  }
109
109
  async _initRequestInit() {
110
110
  if (this._isDestroyed) {
111
- throw new Error("AuthorizedApiContext is destroyed");
111
+ throw new errors_1.BrokerizeAbortError("AuthorizedApiContext is destroyed");
112
112
  }
113
113
  const tok = await this._auth.getToken();
114
114
  const headers = await (0, apiCtx_1.withAcceptLanguage)(this._cfg, {
@@ -472,12 +472,20 @@ class AuthorizedApiContext {
472
472
  const wrappedClient = {
473
473
  subscribeDecoupledOperation: this._wsClient.subscribeDecoupledOperation.bind(this._wsClient),
474
474
  subscribeInvalidate: this._wsClient.subscribeInvalidate.bind(this._wsClient),
475
+ subscribeConnectionState: this._wsClient.subscribeConnectionState.bind(this._wsClient),
476
+ getConnectionState: this._wsClient.getConnectionState.bind(this._wsClient),
477
+ reconnect: this._wsClient.reconnect.bind(this._wsClient),
475
478
  };
476
479
  return wrappedClient;
477
480
  }
478
481
  destroy() {
479
482
  this._isDestroyed = true;
480
483
  this._abortController.abort();
484
+ if (this._ownsWsClient) {
485
+ /* otherwise its reconnect timer would keep running and keep reconnecting with the
486
+ tokens of a context that is gone. */
487
+ this._wsClient.destroy();
488
+ }
481
489
  }
482
490
  subscribeLogout(callback) {
483
491
  const s = this._logoutSubject.subscribe({
@@ -65,3 +65,77 @@ export declare class BrokerizeError extends Error {
65
65
  httpStatusCode: number;
66
66
  constructor(statusCode: number, body: ErrorResponse);
67
67
  }
68
+ /**
69
+ * Thrown if a request to the brokerize API timed out (HTTP status 504). This is typically sent by
70
+ * a load balancer or gateway in front of the API, so the response body usually is not a regular
71
+ * `ErrorResponse`.
72
+ */
73
+ export declare class BrokerizeTimeoutError extends BrokerizeError {
74
+ constructor(body: ErrorResponse);
75
+ }
76
+ /**
77
+ * Create the error for a failed (status >= 400) API response. If the body is not a valid `ErrorResponse`
78
+ * (e.g. an HTML error page from a load balancer), a generic error body is used instead of failing with a
79
+ * JSON parse error.
80
+ */
81
+ export declare function createErrorFromResponse(response: Response): Promise<BrokerizeError>;
82
+ /**
83
+ * Error codes used by {@link BrokerizeWebSocketError}.
84
+ *
85
+ * - `AUTH`: the websocket connection could not be authenticated. Same code as a failed token
86
+ * refresh on the REST API, so applications can treat both identically.
87
+ * - `WEBSOCKET_CONNECTION_FAILED`: the connection could not be established or was lost
88
+ * (network error, failed handshake, closed socket). The client retries these automatically.
89
+ * - `WEBSOCKET_PROTOCOL_ERROR`: a message from the server could not be parsed.
90
+ * - `WEBSOCKET_ERROR`: any other error reported by the server.
91
+ */
92
+ export type BrokerizeWebSocketErrorCode = "AUTH" | "WEBSOCKET_CONNECTION_FAILED" | "WEBSOCKET_PROTOCOL_ERROR" | "WEBSOCKET_ERROR";
93
+ export type BrokerizeWebSocketErrorParams = {
94
+ msg: string;
95
+ code: BrokerizeWebSocketErrorCode;
96
+ httpStatusCode?: number;
97
+ /**
98
+ * See {@link BrokerizeWebSocketError.terminal}.
99
+ */
100
+ terminal?: boolean;
101
+ /**
102
+ * The underlying error or event, if any (e.g. the rejection of `Auth.getToken` or the
103
+ * `error` event of the websocket).
104
+ */
105
+ cause?: unknown;
106
+ };
107
+ /**
108
+ * Every error reported by the websocket client is an instance of this class, so applications can
109
+ * handle it like any other error (`instanceof Error`, `err.message`, stack trace) and can use the
110
+ * same error handling as for the REST API, which reports `BrokerizeError`.
111
+ */
112
+ export declare class BrokerizeWebSocketError extends BrokerizeError {
113
+ /**
114
+ * If `true`, the affected subscription is over and will not receive any further data. Errors
115
+ * that are passed to a subscription callback are always terminal; non-terminal errors are only
116
+ * reported via `BrokerizeWebSocketClient.subscribeConnectionState`, because the client
117
+ * recovers from them on its own.
118
+ */
119
+ readonly terminal: boolean;
120
+ /**
121
+ * The underlying error or event, if any.
122
+ */
123
+ readonly cause?: unknown;
124
+ constructor({ msg, code, httpStatusCode, terminal, cause, }: BrokerizeWebSocketErrorParams);
125
+ }
126
+ /**
127
+ * Check whether the given value is a `BrokerizeWebSocketError`. Prefer this over `instanceof`,
128
+ * which fails if more than one copy of this package ends up in a dependency tree.
129
+ */
130
+ export declare function isBrokerizeWebSocketError(x: unknown): x is BrokerizeWebSocketError;
131
+ /**
132
+ * Thrown when a request is made on an `AuthorizedApiContext` that was already destroyed.
133
+ *
134
+ * `destroy()` aborts the context's `AbortController`, so a request that is already in flight
135
+ * rejects with a `DOMException` named `AbortError`. This error carries the same `name`, so that
136
+ * both cases can be handled with a single check (`err.name === "AbortError"`), the way `fetch`
137
+ * itself rejects when handed an already-aborted signal.
138
+ */
139
+ export declare class BrokerizeAbortError extends Error {
140
+ constructor(msg: string);
141
+ }
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BrokerizeError = exports.TradingError = void 0;
3
+ exports.BrokerizeAbortError = exports.BrokerizeWebSocketError = exports.BrokerizeTimeoutError = exports.BrokerizeError = exports.TradingError = void 0;
4
+ exports.createErrorFromResponse = createErrorFromResponse;
5
+ exports.isBrokerizeWebSocketError = isBrokerizeWebSocketError;
4
6
  class TradingError extends Error {
5
7
  constructor({ msg, code, brokerCode, brokerError, msgBrokerName, httpStatusCode, hint, }) {
6
8
  super(msg);
@@ -28,3 +30,95 @@ class BrokerizeError extends Error {
28
30
  }
29
31
  }
30
32
  exports.BrokerizeError = BrokerizeError;
33
+ /**
34
+ * Thrown if a request to the brokerize API timed out (HTTP status 504). This is typically sent by
35
+ * a load balancer or gateway in front of the API, so the response body usually is not a regular
36
+ * `ErrorResponse`.
37
+ */
38
+ class BrokerizeTimeoutError extends BrokerizeError {
39
+ constructor(body) {
40
+ super(504, body);
41
+ this.name = "BrokerizeTimeoutError";
42
+ }
43
+ }
44
+ exports.BrokerizeTimeoutError = BrokerizeTimeoutError;
45
+ function isErrorResponse(x) {
46
+ return (!!x &&
47
+ typeof x === "object" &&
48
+ typeof x.msg === "string" &&
49
+ typeof x.code === "string");
50
+ }
51
+ /**
52
+ * Create the error for a failed (status >= 400) API response. If the body is not a valid `ErrorResponse`
53
+ * (e.g. an HTML error page from a load balancer), a generic error body is used instead of failing with a
54
+ * JSON parse error.
55
+ */
56
+ async function createErrorFromResponse(response) {
57
+ const statusCode = response.status;
58
+ let body;
59
+ try {
60
+ const parsed = JSON.parse(await response.text());
61
+ if (isErrorResponse(parsed)) {
62
+ body = parsed;
63
+ }
64
+ }
65
+ catch (_a) {
66
+ /* not JSON, use the fallback below */
67
+ }
68
+ if (statusCode == 504) {
69
+ return new BrokerizeTimeoutError(body || {
70
+ msg: "The request timed out. Please try again.",
71
+ code: "TIMEOUT",
72
+ });
73
+ }
74
+ return new BrokerizeError(statusCode, body || {
75
+ msg: "The request failed with status " + statusCode + ".",
76
+ code: "INTERNAL_SERVER_ERROR",
77
+ });
78
+ }
79
+ const DEFAULT_STATUS_CODES = {
80
+ AUTH: 401,
81
+ WEBSOCKET_CONNECTION_FAILED: 503,
82
+ WEBSOCKET_PROTOCOL_ERROR: 500,
83
+ WEBSOCKET_ERROR: 500,
84
+ };
85
+ /**
86
+ * Every error reported by the websocket client is an instance of this class, so applications can
87
+ * handle it like any other error (`instanceof Error`, `err.message`, stack trace) and can use the
88
+ * same error handling as for the REST API, which reports `BrokerizeError`.
89
+ */
90
+ class BrokerizeWebSocketError extends BrokerizeError {
91
+ constructor({ msg, code, httpStatusCode, terminal, cause, }) {
92
+ super(httpStatusCode !== null && httpStatusCode !== void 0 ? httpStatusCode : DEFAULT_STATUS_CODES[code], { msg, code });
93
+ Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain (https://stackoverflow.com/questions/41102060/typescript-extending-error-class)
94
+ this.name = "BrokerizeWebSocketError";
95
+ this.terminal = terminal !== null && terminal !== void 0 ? terminal : false;
96
+ this.cause = cause;
97
+ }
98
+ }
99
+ exports.BrokerizeWebSocketError = BrokerizeWebSocketError;
100
+ /**
101
+ * Check whether the given value is a `BrokerizeWebSocketError`. Prefer this over `instanceof`,
102
+ * which fails if more than one copy of this package ends up in a dependency tree.
103
+ */
104
+ function isBrokerizeWebSocketError(x) {
105
+ return (!!x &&
106
+ typeof x === "object" &&
107
+ x.name === "BrokerizeWebSocketError");
108
+ }
109
+ /**
110
+ * Thrown when a request is made on an `AuthorizedApiContext` that was already destroyed.
111
+ *
112
+ * `destroy()` aborts the context's `AbortController`, so a request that is already in flight
113
+ * rejects with a `DOMException` named `AbortError`. This error carries the same `name`, so that
114
+ * both cases can be handled with a single check (`err.name === "AbortError"`), the way `fetch`
115
+ * itself rejects when handed an already-aborted signal.
116
+ */
117
+ class BrokerizeAbortError extends Error {
118
+ constructor(msg) {
119
+ super(msg);
120
+ Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain (https://stackoverflow.com/questions/41102060/typescript-extending-error-class)
121
+ this.name = "AbortError";
122
+ }
123
+ }
124
+ exports.BrokerizeAbortError = BrokerizeAbortError;
@@ -1,12 +1,12 @@
1
- import { Auth, AuthContextConfiguration, BrokerizeConfig, CognitoConfig, CognitoFacade, CognitoPoolConfig, GuestAuthContextConfiguration, RegisteredUserAuthContextConfiguration, TokenSet } from "./apiCtx";
1
+ import { Auth, AuthContextConfiguration, BrokerizeConfig, CognitoConfig, CognitoFacade, CognitoPoolConfig, GetTokenOptions, GuestAuthContextConfiguration, RegisteredUserAuthContextConfiguration, TokenSet } from "./apiCtx";
2
2
  import { AuthorizedApiContext } from "./authorizedApiContext";
3
- import { BrokerizeError } from "./errors";
3
+ import { BrokerizeAbortError, BrokerizeError, BrokerizeTimeoutError, BrokerizeWebSocketError, BrokerizeWebSocketErrorCode, BrokerizeWebSocketErrorParams, isBrokerizeWebSocketError } from "./errors";
4
4
  import * as openApiClient from "./swagger";
5
5
  import * as Models from "./modelExports";
6
- import { BrokerizeWebSocketClient, Callback, Subscription } from "./websocketClient";
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, Auth, TokenSet, };
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, };
10
10
  export { CognitoPoolConfig, RegisteredUserAuthContextConfiguration };
11
11
  export { CognitoConfig, CognitoFacade };
12
12
  export declare class Brokerize {
package/dist/cjs/index.js CHANGED
@@ -33,14 +33,18 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.Brokerize = exports.BrokerizeError = exports.Utils = exports.WebSocketTypes = exports.Models = exports.AuthorizedApiContext = void 0;
36
+ exports.Brokerize = 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");
40
40
  const authorizedApiContext_1 = require("./authorizedApiContext");
41
41
  Object.defineProperty(exports, "AuthorizedApiContext", { enumerable: true, get: function () { return authorizedApiContext_1.AuthorizedApiContext; } });
42
42
  const errors_1 = require("./errors");
43
+ Object.defineProperty(exports, "BrokerizeAbortError", { enumerable: true, get: function () { return errors_1.BrokerizeAbortError; } });
43
44
  Object.defineProperty(exports, "BrokerizeError", { enumerable: true, get: function () { return errors_1.BrokerizeError; } });
45
+ Object.defineProperty(exports, "BrokerizeTimeoutError", { enumerable: true, get: function () { return errors_1.BrokerizeTimeoutError; } });
46
+ Object.defineProperty(exports, "BrokerizeWebSocketError", { enumerable: true, get: function () { return errors_1.BrokerizeWebSocketError; } });
47
+ Object.defineProperty(exports, "isBrokerizeWebSocketError", { enumerable: true, get: function () { return errors_1.isBrokerizeWebSocketError; } });
44
48
  const openApiClient = __importStar(require("./swagger"));
45
49
  const Models = __importStar(require("./modelExports"));
46
50
  exports.Models = Models;
@@ -78,9 +82,7 @@ class Brokerize {
78
82
  const postMiddleware = async (r) => {
79
83
  const statusCode = r.response.status;
80
84
  if (statusCode >= 400) {
81
- const decJson = (await r.response.json());
82
- const err = new errors_1.BrokerizeError(statusCode, decJson);
83
- throw err;
85
+ throw await (0, errors_1.createErrorFromResponse)(r.response);
84
86
  }
85
87
  };
86
88
  this._userApi = new openApiClient.UserApi((0, apiCtx_1.createConfiguration)(cfg)).withPostMiddleware(postMiddleware);
@@ -86,6 +86,8 @@ export { GetBrokersResponse } from "./swagger/models/GetBrokersResponse";
86
86
  export { GetCostEstimationParams } from "./swagger/models/GetCostEstimationParams";
87
87
  export { GetOrderResponse } from "./swagger/models/GetOrderResponse";
88
88
  export { GetPortfolioOrdersResponse } from "./swagger/models/GetPortfolioOrdersResponse";
89
+ export { PortfolioOrderDetailsSyncInfo } from "./swagger/models/PortfolioOrderDetailsSyncInfo";
90
+ export { PortfolioOrderDetailsSyncInfoStatus } from "./swagger/models/PortfolioOrderDetailsSyncInfoStatus";
89
91
  export { GetPortfolioPositionsResponse } from "./swagger/models/GetPortfolioPositionsResponse";
90
92
  export { GetPortfolioQuotesResponse } from "./swagger/models/GetPortfolioQuotesResponse";
91
93
  export { GetQuoteParams } from "./swagger/models/GetQuoteParams";
@@ -157,6 +159,7 @@ export { OrderIntent } from "./swagger/models/OrderIntent";
157
159
  export { OrderIntentAvailability } from "./swagger/models/OrderIntentAvailability";
158
160
  export { SummarizedTrade } from "./swagger/models/SummarizedTrade";
159
161
  export { TradeWarning } from "./swagger/models/TradeWarning";
162
+ export { TradeWarningReason } from "./swagger/models/TradeWarningReason";
160
163
  export { GetPortfolioTradesResponse } from "./swagger/models/GetPortfolioTradesResponse";
161
164
  export { GetPortfolioTradeStatisticsResponse } from "./swagger/models/GetPortfolioTradeStatisticsResponse";
162
165
  export { TradeStatisticsItem } from "./swagger/models/TradeStatisticsItem";
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  /* tslint:disable */
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.OrderIntent = exports.TrailingDistanceModeEnum = exports.SessionSyncInfoStatus = exports.PrepareOAuthRedirectParamsAppearanceEnum = exports.PortfolioSyncInfoStatus = exports.OrderValidityType = exports.OrderStatus = exports.OrderModel = exports.OrderExtension = exports.LoginResponseState = exports.GenericTableRowValueType = exports.GenericTableRowValueLinkValueType = exports.GenericTableRowType = exports.EnableSessionTanParamsKind = exports.Direction = exports.DecoupledOperationState = exports.CashQuotation = exports.CancelOrderParamsMode = exports.BrokerEnvFilterType = exports.AuthMethodFlow = void 0;
4
+ exports.TradeWarningReason = exports.OrderIntent = exports.TrailingDistanceModeEnum = exports.SessionSyncInfoStatus = exports.PrepareOAuthRedirectParamsAppearanceEnum = exports.PortfolioSyncInfoStatus = exports.OrderValidityType = exports.OrderStatus = exports.OrderModel = exports.OrderExtension = exports.LoginResponseState = exports.PortfolioOrderDetailsSyncInfoStatus = exports.GenericTableRowValueType = exports.GenericTableRowValueLinkValueType = exports.GenericTableRowType = exports.EnableSessionTanParamsKind = exports.Direction = exports.DecoupledOperationState = exports.CashQuotation = exports.CancelOrderParamsMode = exports.BrokerEnvFilterType = exports.AuthMethodFlow = void 0;
5
5
  var AuthMethodFlow_1 = require("./swagger/models/AuthMethodFlow");
6
6
  Object.defineProperty(exports, "AuthMethodFlow", { enumerable: true, get: function () { return AuthMethodFlow_1.AuthMethodFlow; } });
7
7
  var BrokerEnvFilterType_1 = require("./swagger/models/BrokerEnvFilterType");
@@ -22,6 +22,8 @@ var GenericTableRowValueLinkValueType_1 = require("./swagger/models/GenericTable
22
22
  Object.defineProperty(exports, "GenericTableRowValueLinkValueType", { enumerable: true, get: function () { return GenericTableRowValueLinkValueType_1.GenericTableRowValueLinkValueType; } });
23
23
  var GenericTableRowValueType_1 = require("./swagger/models/GenericTableRowValueType");
24
24
  Object.defineProperty(exports, "GenericTableRowValueType", { enumerable: true, get: function () { return GenericTableRowValueType_1.GenericTableRowValueType; } });
25
+ var PortfolioOrderDetailsSyncInfoStatus_1 = require("./swagger/models/PortfolioOrderDetailsSyncInfoStatus");
26
+ Object.defineProperty(exports, "PortfolioOrderDetailsSyncInfoStatus", { enumerable: true, get: function () { return PortfolioOrderDetailsSyncInfoStatus_1.PortfolioOrderDetailsSyncInfoStatus; } });
25
27
  var LoginResponseState_1 = require("./swagger/models/LoginResponseState");
26
28
  Object.defineProperty(exports, "LoginResponseState", { enumerable: true, get: function () { return LoginResponseState_1.LoginResponseState; } });
27
29
  var OrderExtension_1 = require("./swagger/models/OrderExtension");
@@ -42,3 +44,5 @@ var TrailingDistance_1 = require("./swagger/models/TrailingDistance");
42
44
  Object.defineProperty(exports, "TrailingDistanceModeEnum", { enumerable: true, get: function () { return TrailingDistance_1.TrailingDistanceModeEnum; } });
43
45
  var OrderIntent_1 = require("./swagger/models/OrderIntent");
44
46
  Object.defineProperty(exports, "OrderIntent", { enumerable: true, get: function () { return OrderIntent_1.OrderIntent; } });
47
+ var TradeWarningReason_1 = require("./swagger/models/TradeWarningReason");
48
+ Object.defineProperty(exports, "TradeWarningReason", { enumerable: true, get: function () { return TradeWarningReason_1.TradeWarningReason; } });
@@ -10,6 +10,7 @@
10
10
  */
11
11
  import { BitpandaClientCfg } from "./BitpandaClientCfg";
12
12
  import { CoinbaseClientCfg } from "./CoinbaseClientCfg";
13
+ import { SmartbrokerClientCfg } from "./SmartbrokerClientCfg";
13
14
  /**
14
15
  *
15
16
  * @export
@@ -28,6 +29,12 @@ export interface BrokerClientCfg {
28
29
  * @memberof BrokerClientCfg
29
30
  */
30
31
  coinbase?: CoinbaseClientCfg;
32
+ /**
33
+ *
34
+ * @type {SmartbrokerClientCfg}
35
+ * @memberof BrokerClientCfg
36
+ */
37
+ smartbroker?: SmartbrokerClientCfg;
31
38
  }
32
39
  export declare function BrokerClientCfgFromJSON(json: any): BrokerClientCfg;
33
40
  export declare function BrokerClientCfgFromJSONTyped(json: any, ignoreDiscriminator: boolean): BrokerClientCfg;
@@ -19,6 +19,7 @@ exports.BrokerClientCfgToJSON = BrokerClientCfgToJSON;
19
19
  const runtime_1 = require("../runtime");
20
20
  const BitpandaClientCfg_1 = require("./BitpandaClientCfg");
21
21
  const CoinbaseClientCfg_1 = require("./CoinbaseClientCfg");
22
+ const SmartbrokerClientCfg_1 = require("./SmartbrokerClientCfg");
22
23
  function BrokerClientCfgFromJSON(json) {
23
24
  return BrokerClientCfgFromJSONTyped(json, false);
24
25
  }
@@ -33,6 +34,9 @@ function BrokerClientCfgFromJSONTyped(json, ignoreDiscriminator) {
33
34
  coinbase: !(0, runtime_1.exists)(json, "coinbase")
34
35
  ? undefined
35
36
  : (0, CoinbaseClientCfg_1.CoinbaseClientCfgFromJSON)(json["coinbase"]),
37
+ smartbroker: !(0, runtime_1.exists)(json, "smartbroker")
38
+ ? undefined
39
+ : (0, SmartbrokerClientCfg_1.SmartbrokerClientCfgFromJSON)(json["smartbroker"]),
36
40
  };
37
41
  }
38
42
  function BrokerClientCfgToJSONRecursive(value, ignoreParent = false) {
@@ -45,6 +49,7 @@ function BrokerClientCfgToJSONRecursive(value, ignoreParent = false) {
45
49
  return {
46
50
  bitpanda: (0, BitpandaClientCfg_1.BitpandaClientCfgToJSON)(value.bitpanda),
47
51
  coinbase: (0, CoinbaseClientCfg_1.CoinbaseClientCfgToJSON)(value.coinbase),
52
+ smartbroker: (0, SmartbrokerClientCfg_1.SmartbrokerClientCfgToJSON)(value.smartbroker),
48
53
  };
49
54
  }
50
55
  function BrokerClientCfgToJSON(value) {
@@ -61,6 +61,21 @@ export interface BrokerMeta {
61
61
  * @memberof BrokerMeta
62
62
  */
63
63
  loginForm?: BrokerLoginForm;
64
+ /**
65
+ * All brokerize exchange ids this broker's exchanges are mapped to, ascending. Use it to tell
66
+ * upfront which brokers may be relevant for a given exchange, e.g. to preselect brokers for a
67
+ * security that is traded there.
68
+ *
69
+ * This is a static, broker-wide list: it means that brokerize knows how to translate between
70
+ * this broker's exchanges and the listed ids, not that every security can be traded at every
71
+ * one of them. The authoritative, security-specific list of tradable exchanges remains the
72
+ * `exchanges` field of a prepared trade.
73
+ *
74
+ * Every id is contained in the `GetExchanges` response, so it can always be resolved to a name.
75
+ * @type {Array<number>}
76
+ * @memberof BrokerMeta
77
+ */
78
+ supportedExchangeIds: Array<number>;
64
79
  /**
65
80
  * If true, the user can login at the broker via OAuth (this involves browser redirects). Use `prepareOAuthRedirect` to obtain a URL to redirect to.
66
81
  * @type {boolean}