@flexemarkets/fm-sdk 0.4.0 → 0.5.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.
package/dist/client.d.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Port of fm.client (Python) / fm.Flexemarkets (Java).
5
5
  */
6
- import type { Account, Allotment, ClientConnection, Holding, ManagerOtpBundle, Market, Marketplace, Order, ParticipantState, Person, Security, Session, TickGrid, Token, Widget, WidgetPush } from "./types.js";
6
+ import type { Account, Allotment, ClientConnection, Holding, ManagerOtpBundle, Market, Marketplace, Order, ParticipantState, Person, Security, Session, TickGrid, Token, Widget, WidgetPush, MarketplaceRobot, RobotParameterConfig, RobotParameterControl } from "./types.js";
7
7
  import { EventListener, type EventCallback } from "./stomp.js";
8
8
  import { type Desk, type Subscription } from "./desk.js";
9
9
  import type { Snapshot } from "./snapshot.js";
@@ -16,6 +16,20 @@ export declare class AuthorizationError extends FlexemarketsError {
16
16
  }
17
17
  export declare class InvalidArgumentError extends FlexemarketsError {
18
18
  }
19
+ /**
20
+ * An order the desk did not send, because fm-server would refuse it.
21
+ *
22
+ * Rejected by `Desk.submitLimit` when the session the desk holds is not open,
23
+ * or the holding it holds does not grant the order's side in that market --
24
+ * the two refusals fm-server answers with 400 `SESSION_CLOSED` and
25
+ * `ORDER_NOT_ALLOWED`, which `reason` names. An {@link InvalidArgumentError},
26
+ * so a caller catching the server's answer catches this too.
27
+ * `flexemarkets.desk(id, { refuseLocally: false })` sends every order instead.
28
+ */
29
+ export declare class OrderRefusedLocallyError extends InvalidArgumentError {
30
+ readonly reason: "SESSION_CLOSED" | "ORDER_NOT_ALLOWED";
31
+ constructor(reason: "SESSION_CLOSED" | "ORDER_NOT_ALLOWED", message: string);
32
+ }
19
33
  export declare class ConnectionFailedError extends FlexemarketsError {
20
34
  }
21
35
  export declare class ConfigurationError extends FlexemarketsError {
@@ -77,6 +91,8 @@ export declare function parseMarketplace(data: JsonObject): Marketplace;
77
91
  export declare function parseSession(data: JsonObject): Session;
78
92
  export declare function parseOrder(data: JsonObject): Order;
79
93
  export declare function parseParticipantState(data: JsonObject): ParticipantState;
94
+ export declare function parseRobotParameterConfig(data: JsonObject): RobotParameterConfig;
95
+ export declare function parseMarketplaceRobot(data: JsonObject): MarketplaceRobot;
80
96
  export declare function parseWidget(data: JsonObject): Widget;
81
97
  export declare function parseHolding(data: JsonObject): Holding;
82
98
  export declare function parseConnection(data: JsonObject): ClientConnection;
@@ -130,10 +146,17 @@ export declare class Flexemarkets {
130
146
  private readonly _clientDescription;
131
147
  private readonly _endpoint;
132
148
  private readonly _baseUrl;
133
- private readonly _bearerToken;
149
+ /**
150
+ * The sign-in this client presents, replaced whole when an expired one is
151
+ * renewed (see {@link _renewToken}); the bearer header is derived from it,
152
+ * so `token()` and every request agree on which token is current.
153
+ */
154
+ private _tokenObj;
155
+ /** Kept only to sign in again when the token runs out; null for a client given a token. */
156
+ private _credentials;
157
+ private _renewing;
134
158
  private _account;
135
159
  private _user;
136
- private _tokenObj;
137
160
  private _eventListener;
138
161
  private constructor();
139
162
  /** Connect to the Flexemarkets API. */
@@ -146,6 +169,24 @@ export declare class Flexemarkets {
146
169
  get endpointUrl(): string;
147
170
  get endpointMarketplaceId(): number;
148
171
  private _authHeaders;
172
+ /** The Authorization header for the current sign-in. */
173
+ private get _bearerToken();
174
+ /**
175
+ * fetch with this client's token; if it has expired, renew it once and send
176
+ * again. Tokens live 24 hours, so a robot that ran longer ended the first
177
+ * time it asked for anything after that, or looped on the refusal -- a Utah
178
+ * poller, about 250 times a day at 00Z.
179
+ */
180
+ private _fetch;
181
+ /**
182
+ * Sign in again with the credentials this client was made with. False when
183
+ * it was given a token rather than credentials, or the sign-in fails; the
184
+ * caller then answers with the refusal it had. `presented` is the header
185
+ * the refused request or stream connect carried: one another caller has
186
+ * already replaced is not renewed again, and concurrent callers share one
187
+ * sign-in.
188
+ */
189
+ private _renewToken;
149
190
  private _get;
150
191
  /**
151
192
  * GET helper that returns the parsed body bundled with the
@@ -156,6 +197,9 @@ export declare class Flexemarkets {
156
197
  private _getSnapshot;
157
198
  /** PATCH with a JSON body -- the shape every session transition takes. */
158
199
  private _patch;
200
+ /** PUT with a JSON body -- a robot parameter's configuration, say. */
201
+ private _put;
202
+ private _sendJson;
159
203
  /**
160
204
  * GET returning the body verbatim, for endpoints that answer with something
161
205
  * other than JSON — the holdings download is a CSV, and JSON.parse dies on
@@ -455,6 +499,29 @@ export declare class Flexemarkets {
455
499
  * participant -- what a manager reads to check on a robot.
456
500
  */
457
501
  allWidgets(marketplaceId: number): Promise<Widget[]>;
502
+ /**
503
+ * Every robot the marketplace's robot host offers, with whether it is
504
+ * enabled here and how a manager has configured its parameters.
505
+ *
506
+ * Readable by participants as well as managers: it is what a launch form is
507
+ * built from. Asks the robot host for its catalogue, so it fails when the
508
+ * host cannot be reached.
509
+ */
510
+ marketplaceRobots(marketplaceId: number): Promise<MarketplaceRobot[]>;
511
+ /**
512
+ * Set a robot parameter's value in a marketplace, and whether participants
513
+ * may move it, returning the configuration as stored.
514
+ *
515
+ * A null `control` fixes the value: participants launching the robot see it
516
+ * read-only. A control exposes it within that range, starting at `value`,
517
+ * which must lie inside it. The server refuses a parameter the robot does
518
+ * not declare, a platform parameter, and a range outside the robot's own
519
+ * bounds.
520
+ *
521
+ * The control goes up flat beside the value, and a fixed parameter sends the
522
+ * value alone: the server reads any bound as a control.
523
+ */
524
+ configureRobotParameter(marketplaceId: number, robotId: string, paramName: string, value: string, control: RobotParameterControl | null): Promise<RobotParameterConfig>;
458
525
  private readonly _sharedViews;
459
526
  private readonly _sharedViewPromises;
460
527
  /**
@@ -468,8 +535,16 @@ export declare class Flexemarkets {
468
535
  * callers with different identities each get their own desk —
469
536
  * multi-tenant WS multiplexing is a server-side concern, not a
470
537
  * client-side one.
471
- */
472
- desk(marketplaceId: number): Promise<Desk>;
538
+ *
539
+ * `submitLimit` on the returned handle rejects, without sending, an order
540
+ * the desk knows fm-server would refuse -- a session that is not open, a
541
+ * side the holding does not grant -- with {@link OrderRefusedLocallyError}.
542
+ * `{ refuseLocally: false }` sends every order and leaves the answer to the
543
+ * server.
544
+ */
545
+ desk(marketplaceId: number, options?: {
546
+ refuseLocally?: boolean;
547
+ }): Promise<Desk>;
473
548
  _releaseSharedView(marketplaceId: number): void;
474
549
  /** Start receiving real-time events via WebSocket STOMP. */
475
550
  listen(marketplaceId: number, callback: EventCallback): Promise<void>;
package/dist/client.js CHANGED
@@ -32,6 +32,23 @@ export class AuthorizationError extends FlexemarketsError {
32
32
  }
33
33
  export class InvalidArgumentError extends FlexemarketsError {
34
34
  }
35
+ /**
36
+ * An order the desk did not send, because fm-server would refuse it.
37
+ *
38
+ * Rejected by `Desk.submitLimit` when the session the desk holds is not open,
39
+ * or the holding it holds does not grant the order's side in that market --
40
+ * the two refusals fm-server answers with 400 `SESSION_CLOSED` and
41
+ * `ORDER_NOT_ALLOWED`, which `reason` names. An {@link InvalidArgumentError},
42
+ * so a caller catching the server's answer catches this too.
43
+ * `flexemarkets.desk(id, { refuseLocally: false })` sends every order instead.
44
+ */
45
+ export class OrderRefusedLocallyError extends InvalidArgumentError {
46
+ reason;
47
+ constructor(reason, message) {
48
+ super(message);
49
+ this.reason = reason;
50
+ }
51
+ }
35
52
  export class ConnectionFailedError extends FlexemarketsError {
36
53
  }
37
54
  export class ConfigurationError extends FlexemarketsError {
@@ -209,6 +226,53 @@ export function parseParticipantState(data) {
209
226
  fields: { ...(data.fields ?? {}) },
210
227
  };
211
228
  }
229
+ function numberOrNull(value) {
230
+ return value === null || value === undefined ? null : Number(value);
231
+ }
232
+ function parseRobotParameter(data) {
233
+ return {
234
+ name: data.name ?? "",
235
+ label: data.label ?? null,
236
+ description: data.description ?? null,
237
+ type: data.type ?? null,
238
+ valueType: data.valueType ?? null,
239
+ // The robots write "required": null for a parameter that is not.
240
+ required: data.required === true,
241
+ defaultValue: data.default ?? null,
242
+ unit: data.unit ?? null,
243
+ min: numberOrNull(data.min),
244
+ max: numberOrNull(data.max),
245
+ };
246
+ }
247
+ export function parseRobotParameterConfig(data) {
248
+ const control = data.control ?? null;
249
+ return {
250
+ marketplaceId: data.marketplaceId ?? null,
251
+ robotId: data.robotId ?? "",
252
+ paramName: data.paramName ?? "",
253
+ value: data.value ?? "",
254
+ control: control === null
255
+ ? null
256
+ : { min: Number(control.min), max: Number(control.max), step: Number(control.step) },
257
+ exposed: data.exposed === true,
258
+ };
259
+ }
260
+ export function parseMarketplaceRobot(data) {
261
+ const manifest = data.manifest ?? {};
262
+ const groups = manifest.parameters ?? {};
263
+ const group = (name) => (groups[name] ?? []).map(parseRobotParameter);
264
+ return {
265
+ manifest: {
266
+ id: manifest.id ?? "",
267
+ version: manifest.version ?? null,
268
+ name: manifest.name ?? null,
269
+ description: manifest.description ?? null,
270
+ parameters: { manager: group("manager"), user: group("user"), platform: group("platform") },
271
+ },
272
+ enabled: data.enabled === true,
273
+ configuration: (data.configuration ?? []).map(parseRobotParameterConfig),
274
+ };
275
+ }
212
276
  export function parseWidget(data) {
213
277
  return {
214
278
  id: data.id ?? null,
@@ -542,19 +606,38 @@ function suggestedNameIn(body) {
542
606
  // ---------------------------------------------------------------------------
543
607
  // Flexemarkets client
544
608
  // ---------------------------------------------------------------------------
609
+ /** A 401 that says the token ran out, as distinct from one that is wrong. */
610
+ async function tokenExpired(resp) {
611
+ if (resp.status !== 401)
612
+ return false;
613
+ try {
614
+ const body = JSON.parse(await resp.clone().text());
615
+ return body.error === "ACCOUNT_TOKEN_EXPIRED";
616
+ }
617
+ catch {
618
+ return false;
619
+ }
620
+ }
545
621
  export class Flexemarkets {
546
622
  _clientDescription;
547
623
  _endpoint;
548
624
  _baseUrl;
549
- _bearerToken;
625
+ /**
626
+ * The sign-in this client presents, replaced whole when an expired one is
627
+ * renewed (see {@link _renewToken}); the bearer header is derived from it,
628
+ * so `token()` and every request agree on which token is current.
629
+ */
630
+ _tokenObj;
631
+ /** Kept only to sign in again when the token runs out; null for a client given a token. */
632
+ _credentials = null;
633
+ _renewing = null;
550
634
  _account;
551
635
  _user;
552
- _tokenObj;
553
636
  _eventListener = null;
554
- constructor(endpoint, baseUrl, bearerToken, clientDescription) {
637
+ constructor(endpoint, baseUrl, tokenObj, clientDescription) {
555
638
  this._endpoint = endpoint;
556
639
  this._baseUrl = baseUrl;
557
- this._bearerToken = bearerToken;
640
+ this._tokenObj = tokenObj;
558
641
  this._clientDescription = clientDescription;
559
642
  }
560
643
  /** Connect to the Flexemarkets API. */
@@ -579,9 +662,10 @@ export class Flexemarkets {
579
662
  const baseUrl = server(ep);
580
663
  // Authenticate
581
664
  const tokenObj = await signIn(baseUrl, config, desc);
582
- const bearer = `Bearer ${tokenObj.token}`;
583
- const fm = new Flexemarkets(ep, baseUrl, bearer, desc);
584
- fm._tokenObj = tokenObj;
665
+ const fm = new Flexemarkets(ep, baseUrl, tokenObj, desc);
666
+ if (config.account && config.email && config.password && !(config.token && isValidToken(config.token))) {
667
+ fm._credentials = { ...config };
668
+ }
585
669
  fm._account = tokenObj.account;
586
670
  fm._user = tokenObj.person;
587
671
  return fm;
@@ -612,8 +696,55 @@ export class Flexemarkets {
612
696
  _authHeaders() {
613
697
  return { Authorization: this._bearerToken };
614
698
  }
699
+ /** The Authorization header for the current sign-in. */
700
+ get _bearerToken() {
701
+ return `Bearer ${this._tokenObj.token}`;
702
+ }
703
+ /**
704
+ * fetch with this client's token; if it has expired, renew it once and send
705
+ * again. Tokens live 24 hours, so a robot that ran longer ended the first
706
+ * time it asked for anything after that, or looped on the refusal -- a Utah
707
+ * poller, about 250 times a day at 00Z.
708
+ */
709
+ async _fetch(url, init) {
710
+ const presented = this._bearerToken;
711
+ const resp = await fetch(url, init);
712
+ if (!(await tokenExpired(resp)) || !(await this._renewToken(presented)))
713
+ return resp;
714
+ const headers = { ...init.headers, Authorization: this._bearerToken };
715
+ return fetch(url, { ...init, headers });
716
+ }
717
+ /**
718
+ * Sign in again with the credentials this client was made with. False when
719
+ * it was given a token rather than credentials, or the sign-in fails; the
720
+ * caller then answers with the refusal it had. `presented` is the header
721
+ * the refused request or stream connect carried: one another caller has
722
+ * already replaced is not renewed again, and concurrent callers share one
723
+ * sign-in.
724
+ */
725
+ async _renewToken(presented) {
726
+ if (this._credentials === null)
727
+ return false;
728
+ if (presented !== this._bearerToken)
729
+ return true;
730
+ if (this._renewing === null) {
731
+ this._renewing = (async () => {
732
+ try {
733
+ this._tokenObj = await signIn(this._baseUrl, this._credentials, this._clientDescription);
734
+ return true;
735
+ }
736
+ catch {
737
+ return false;
738
+ }
739
+ finally {
740
+ this._renewing = null;
741
+ }
742
+ })();
743
+ }
744
+ return this._renewing;
745
+ }
615
746
  async _get(url) {
616
- const resp = await fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
747
+ const resp = await this._fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
617
748
  headers: {
618
749
  ...this._authHeaders(),
619
750
  Accept: "application/json",
@@ -631,7 +762,7 @@ export class Flexemarkets {
631
762
  * `Snapshot.NO_SEQ` when the header is absent.
632
763
  */
633
764
  async _getSnapshot(url) {
634
- const resp = await fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
765
+ const resp = await this._fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
635
766
  headers: {
636
767
  ...this._authHeaders(),
637
768
  Accept: "application/json",
@@ -646,8 +777,15 @@ export class Flexemarkets {
646
777
  }
647
778
  /** PATCH with a JSON body -- the shape every session transition takes. */
648
779
  async _patch(url, json) {
649
- const resp = await fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
650
- method: "PATCH",
780
+ return this._sendJson("PATCH", url, json);
781
+ }
782
+ /** PUT with a JSON body -- a robot parameter's configuration, say. */
783
+ async _put(url, json) {
784
+ return this._sendJson("PUT", url, json);
785
+ }
786
+ async _sendJson(method, url, json) {
787
+ const resp = await this._fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
788
+ method,
651
789
  headers: {
652
790
  ...this._authHeaders(),
653
791
  "Content-Type": "application/json",
@@ -666,7 +804,7 @@ export class Flexemarkets {
666
804
  * the header row.
667
805
  */
668
806
  async _getText(url) {
669
- const resp = await fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
807
+ const resp = await this._fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
670
808
  headers: {
671
809
  ...this._authHeaders(),
672
810
  Accept: "text/csv, */*",
@@ -678,7 +816,7 @@ export class Flexemarkets {
678
816
  return body;
679
817
  }
680
818
  async _post(url, json) {
681
- const resp = await fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
819
+ const resp = await this._fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
682
820
  method: "POST",
683
821
  headers: {
684
822
  ...this._authHeaders(),
@@ -844,7 +982,7 @@ export class Flexemarkets {
844
982
  }
845
983
  /** DELETE, whose answer is a status and nothing worth parsing. */
846
984
  async _delete(url) {
847
- const resp = await fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
985
+ const resp = await this._fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
848
986
  method: "DELETE",
849
987
  headers: { ...this._authHeaders(), Accept: "application/json" },
850
988
  });
@@ -855,7 +993,7 @@ export class Flexemarkets {
855
993
  * DELETE whose answer is the resource as it ended -- an order's CANCEL.
856
994
  */
857
995
  async _deleteFor(url) {
858
- const resp = await fetch(url, {
996
+ const resp = await this._fetch(url, {
859
997
  method: "DELETE",
860
998
  headers: { ...this._authHeaders(), Accept: "application/json", "User-Agent": FM_NETWORK_CLIENT },
861
999
  });
@@ -869,7 +1007,7 @@ export class Flexemarkets {
869
1007
  * segment. Bytes, not a string, so the file's own encoding survives.
870
1008
  */
871
1009
  async _sendCsv(method, url, filename) {
872
- const resp = await fetch(url, {
1010
+ const resp = await this._fetch(url, {
873
1011
  method,
874
1012
  headers: {
875
1013
  ...this._authHeaders(),
@@ -1269,7 +1407,7 @@ export class Flexemarkets {
1269
1407
  async removeWidget(marketplaceId, key, userId) {
1270
1408
  const owner = userId !== undefined && userId !== null ? `/participants/${userId}` : "";
1271
1409
  const url = `${this._marketplace(marketplaceId)}${owner}/widgets/${encodeURIComponent(key)}`;
1272
- const resp = await fetch(url, {
1410
+ const resp = await this._fetch(url, {
1273
1411
  method: "DELETE",
1274
1412
  headers: { ...this._authHeaders(), Accept: "application/json", "User-Agent": FM_NETWORK_CLIENT },
1275
1413
  });
@@ -1287,6 +1425,42 @@ export class Flexemarkets {
1287
1425
  const data = await this._get(`${this._marketplace(marketplaceId)}/widgets?participant=all`);
1288
1426
  return data.map(parseWidget);
1289
1427
  }
1428
+ /**
1429
+ * Every robot the marketplace's robot host offers, with whether it is
1430
+ * enabled here and how a manager has configured its parameters.
1431
+ *
1432
+ * Readable by participants as well as managers: it is what a launch form is
1433
+ * built from. Asks the robot host for its catalogue, so it fails when the
1434
+ * host cannot be reached.
1435
+ */
1436
+ async marketplaceRobots(marketplaceId) {
1437
+ const data = await this._get(`${this._marketplace(marketplaceId)}/robots`);
1438
+ return data.map(parseMarketplaceRobot);
1439
+ }
1440
+ /**
1441
+ * Set a robot parameter's value in a marketplace, and whether participants
1442
+ * may move it, returning the configuration as stored.
1443
+ *
1444
+ * A null `control` fixes the value: participants launching the robot see it
1445
+ * read-only. A control exposes it within that range, starting at `value`,
1446
+ * which must lie inside it. The server refuses a parameter the robot does
1447
+ * not declare, a platform parameter, and a range outside the robot's own
1448
+ * bounds.
1449
+ *
1450
+ * The control goes up flat beside the value, and a fixed parameter sends the
1451
+ * value alone: the server reads any bound as a control.
1452
+ */
1453
+ async configureRobotParameter(marketplaceId, robotId, paramName, value, control) {
1454
+ const body = { value };
1455
+ if (control !== null) {
1456
+ body.min = control.min;
1457
+ body.max = control.max;
1458
+ body.step = control.step;
1459
+ }
1460
+ const url = `${this._marketplace(marketplaceId)}/robots/${encodeURIComponent(robotId)}`
1461
+ + `/parameters/${encodeURIComponent(paramName)}`;
1462
+ return parseRobotParameterConfig(await this._put(url, body));
1463
+ }
1290
1464
  // -- events / WebSocket ----------------------------------------------------
1291
1465
  _sharedViews = new Map();
1292
1466
  _sharedViewPromises = new Map();
@@ -1301,12 +1475,19 @@ export class Flexemarkets {
1301
1475
  * callers with different identities each get their own desk —
1302
1476
  * multi-tenant WS multiplexing is a server-side concern, not a
1303
1477
  * client-side one.
1478
+ *
1479
+ * `submitLimit` on the returned handle rejects, without sending, an order
1480
+ * the desk knows fm-server would refuse -- a session that is not open, a
1481
+ * side the holding does not grant -- with {@link OrderRefusedLocallyError}.
1482
+ * `{ refuseLocally: false }` sends every order and leaves the answer to the
1483
+ * server.
1304
1484
  */
1305
- async desk(marketplaceId) {
1485
+ async desk(marketplaceId, options = {}) {
1486
+ const refuseLocally = options.refuseLocally ?? true;
1306
1487
  const existing = this._sharedViews.get(marketplaceId);
1307
1488
  if (existing !== undefined) {
1308
1489
  existing.refCount++;
1309
- return new DeskHandle(existing.desk, () => this._releaseSharedView(marketplaceId));
1490
+ return new DeskHandle(existing.desk, () => this._releaseSharedView(marketplaceId), refuseLocally);
1310
1491
  }
1311
1492
  // Two concurrent desk() calls for the same marketplaceId need
1312
1493
  // to dedupe — JS is single-threaded but awaits introduce
@@ -1333,10 +1514,10 @@ export class Flexemarkets {
1333
1514
  if (registered.desk !== shared)
1334
1515
  shared.close();
1335
1516
  registered.refCount++;
1336
- return new DeskHandle(registered.desk, () => this._releaseSharedView(marketplaceId));
1517
+ return new DeskHandle(registered.desk, () => this._releaseSharedView(marketplaceId), refuseLocally);
1337
1518
  }
1338
1519
  this._sharedViews.set(marketplaceId, { desk: shared, refCount: 1 });
1339
- return new DeskHandle(shared, () => this._releaseSharedView(marketplaceId));
1520
+ return new DeskHandle(shared, () => this._releaseSharedView(marketplaceId), refuseLocally);
1340
1521
  }
1341
1522
  _releaseSharedView(marketplaceId) {
1342
1523
  const entry = this._sharedViews.get(marketplaceId);
@@ -1349,7 +1530,18 @@ export class Flexemarkets {
1349
1530
  }
1350
1531
  /** Start receiving real-time events via WebSocket STOMP. */
1351
1532
  async listen(marketplaceId, callback) {
1352
- this._eventListener = await this._connectEvents(marketplaceId, callback);
1533
+ // The stream this replaces is closed, not dropped with its socket,
1534
+ // heartbeats and reconnects still running.
1535
+ const previous = this._eventListener;
1536
+ this._eventListener = null;
1537
+ if (previous !== null)
1538
+ previous.close();
1539
+ const listener = await this._connectEvents(marketplaceId, callback);
1540
+ // Another listen() may have finished while this one connected.
1541
+ const raced = this._eventListener;
1542
+ if (raced !== null)
1543
+ raced.close();
1544
+ this._eventListener = listener;
1353
1545
  }
1354
1546
  /**
1355
1547
  * Open an *independent* event subscription, delivering to `callback` until
@@ -1382,7 +1574,7 @@ export class Flexemarkets {
1382
1574
  const wsUrl = server(this._endpoint)
1383
1575
  .replace("https://", "wss://")
1384
1576
  .replace("http://", "ws://") + "/events";
1385
- const events = new EventListener(wsUrl, this._bearerToken, marketplaceId, callback, this._clientDescription, parseHolding, parseOrder);
1577
+ const events = new EventListener(wsUrl, () => this._bearerToken, marketplaceId, callback, this._clientDescription, parseHolding, parseOrder, (presented) => this._renewToken(presented));
1386
1578
  await events.start();
1387
1579
  return events;
1388
1580
  }