@flexemarkets/fm-sdk 0.3.4 → 0.4.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.js CHANGED
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import { readFileSync, existsSync } from "node:fs";
7
7
  import { homedir } from "node:os";
8
- import { basename, join } from "node:path";
8
+ import { join } from "node:path";
9
9
  import { orderedSecurities, toOrderType, toSide, unitGrid } from "./types.js";
10
10
  import { toInstant } from "./timestamps.js";
11
11
  import { EventListener, NO_SEQ } from "./stomp.js";
@@ -13,6 +13,12 @@ import { DefaultDesk, DeskHandle, } from "./desk.js";
13
13
  import { readVersion } from "./version.js";
14
14
  const FM_NETWORK_CLIENT = `fm-sdk-typescript/${readVersion()}`;
15
15
  export const DEFAULT_ENDPOINT = "https://api.flexemarkets.com";
16
+ /**
17
+ * The most traded legs fm-server answers in one read. The route `trades`
18
+ * replaced had no limit; asking for the ceiling keeps as much of that as the
19
+ * server allows.
20
+ */
21
+ const MAX_TRADED_LEGS = 5000;
16
22
  const BCRYPT_RE = /^\$2[abxy]?\$\d{2}\$[./A-Za-z0-9]{53}$/;
17
23
  const JWT_RE = /^[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+$/;
18
24
  // ---------------------------------------------------------------------------
@@ -52,7 +58,7 @@ export class HttpError extends FlexemarketsError {
52
58
  *
53
59
  * Distinct from {@link HttpError}, which means the server answered and the
54
60
  * answer was an error. This means there was no usable answer at all — a
55
- * malformed body, or a link the API root does not carry.
61
+ * malformed body.
56
62
  */
57
63
  export class ApiError extends FlexemarketsError {
58
64
  }
@@ -333,42 +339,25 @@ export function parseConnection(data) {
333
339
  };
334
340
  }
335
341
  /**
336
- * The orders inside a HAL envelope.
342
+ * The orders in a snapshot answer, which is a bare JSON array or a failure.
337
343
  *
338
- * The server embeds them under `orders`. It was `orderDtoes` — Spring HATEOAS
339
- * pluralising `OrderDto` — and every SDK still read that name long after the
340
- * server stopped sending it, so `activeOrders` and `recentTrades` returned an
341
- * empty array always. `Desk` seeds from `activeOrders`, so its books were
342
- * never seeded; they filled from live deltas and looked plausible.
344
+ * Only the array is read because the V1 route never sent anything else:
345
+ * `GET /api/v1/marketplaces/{id}/orders` has always answered a bare array, and
346
+ * 0.4 requires fm-server 4.6.2. The HAL envelopes earlier SDKs tolerated
347
+ * belonged to the routes 0.4 no longer calls.
343
348
  *
344
- * Then the envelope itself went: fm-server now sends a bare array. Accepting
345
- * both *names* did not survive that, and this SDK failed the same silent way a
346
- * second time — `._embedded` on an array is `undefined`, so it returned an
347
- * empty book rather than throwing, while Java and Python at least raised.
349
+ * Anything else throws rather than reading as empty. An empty snapshot is the
350
+ * failure that hid twice before: `Desk` seeded an empty book, filled it from
351
+ * live deltas, and looked plausible.
348
352
  *
349
- * So read the shape rather than assume one. All three are accepted, because
350
- * all three are still deployed somewhere.
353
+ * @throws ApiError when the answer is not a JSON array
351
354
  */
352
- export function embeddedOrders(data) {
353
- if (Array.isArray(data))
354
- return data;
355
- if (data === null || typeof data !== "object")
356
- return [];
357
- const embedded = data._embedded;
358
- return embedded?.orders ?? embedded?.orderDtoes ?? [];
359
- }
360
- function parseApiRoot(data) {
361
- const linksRaw = data._links ?? {};
362
- const links = {};
363
- for (const [name, value] of Object.entries(linksRaw)) {
364
- if (typeof value === "object" && value !== null && "href" in value) {
365
- links[name] = value.href ?? "";
366
- }
367
- else if (typeof value === "string") {
368
- links[name] = value;
369
- }
355
+ export function ordersOf(data) {
356
+ if (!Array.isArray(data)) {
357
+ const kind = data === null || data === undefined ? "null" : typeof data;
358
+ throw new ApiError(`The orders snapshot answer was not a list of orders: got ${kind}`);
370
359
  }
371
- return { links };
360
+ return data;
372
361
  }
373
362
  /**
374
363
  * The most aggressive price this market will accept on `side`.
@@ -396,110 +385,6 @@ export function marketableLimit(market, side) {
396
385
  const span = market.priceMaximum - market.priceMinimum;
397
386
  return market.priceMinimum + Math.floor(span / market.priceTick) * market.priceTick;
398
387
  }
399
- /**
400
- * The `scheme://host:port` of an absolute http(s) URL, else undefined.
401
- *
402
- * A relative href already resolves against the origin it was fetched from,
403
- * and a scheme that is not HTTP is not ours to rewrite.
404
- */
405
- function httpOrigin(url) {
406
- if (!url)
407
- return undefined;
408
- const end = url.indexOf("://");
409
- if (end < 0)
410
- return undefined;
411
- const scheme = url.substring(0, end).toLowerCase();
412
- if (scheme !== "http" && scheme !== "https")
413
- return undefined;
414
- const pathStart = url.indexOf("/", end + 3);
415
- return pathStart < 0 ? url : url.substring(0, pathStart);
416
- }
417
- /**
418
- * Point the API root's links back at the host that was dialled.
419
- *
420
- * The server builds these hrefs from the request it believes it received, and
421
- * behind a proxy that belief can be wrong: an origin reached over a plaintext
422
- * leg reports `http://` even though the caller arrived on `https://`. Every
423
- * call that goes through a link — which is most of them — then leaves on plain
424
- * HTTP and meets the edge's redirect. A GET survives it. A POST does not: a
425
- * 301 is followed as a GET with the body dropped, so placing an order or
426
- * opening a session fails with nothing placed and nothing pointing at the
427
- * scheme.
428
- *
429
- * Only the origin is replaced. The path, query and any URI template are the
430
- * server's to choose; where it is reachable is not, and the token in hand was
431
- * issued by the origin dialled, not by whatever the links name.
432
- */
433
- export function rebaseApiRoot(root, endpoint) {
434
- const origin = httpOrigin(endpoint);
435
- if (!origin)
436
- return root;
437
- const links = {};
438
- const moved = [];
439
- for (const [name, href] of Object.entries(root.links)) {
440
- const named = httpOrigin(href);
441
- if (!named || named === origin) {
442
- links[name] = href;
443
- continue;
444
- }
445
- if (!moved.includes(named))
446
- moved.push(named);
447
- links[name] = origin + href.substring(named.length);
448
- }
449
- if (moved.length > 0) {
450
- // Said out loud, because the rewrite would otherwise hide a deployment
451
- // that is genuinely misconfigured — and a silent correction here is how it
452
- // stays misconfigured. The SDK keeps working; the operator still gets told
453
- // where to look.
454
- console.warn(`[fm-sdk] The API root names ${moved.join(", ")} but this client dialled ${origin}; ` +
455
- `rewriting ${moved.length} link origin(s) to match. The server is behind a proxy ` +
456
- `that is not forwarding the request scheme, so its links are wrong. Fix it at the ` +
457
- `edge — this rewrite only keeps calls working.`);
458
- }
459
- return { links };
460
- }
461
- // ---------------------------------------------------------------------------
462
- // HATEOAS link resolution
463
- // ---------------------------------------------------------------------------
464
- function processTemplate(href) {
465
- const idx = href.indexOf("{");
466
- return idx >= 0 ? href.substring(0, idx) : href;
467
- }
468
- /**
469
- * A V1 route, addressed from the server rather than through a HAL link.
470
- *
471
- * V1 is flat and versioned: the path is knowable without fetching the API root
472
- * first, which is the point of it. Every call that moves here loses a HAL
473
- * dependency as well as a version.
474
- */
475
- function v1(endpoint, path) {
476
- return `${server(endpoint)}/v1${path}`;
477
- }
478
- function uri(root, linkName) {
479
- const href = root.links[linkName];
480
- if (href === undefined)
481
- throw new ApiError(`Link '${linkName}' not found in API root.`);
482
- return processTemplate(href);
483
- }
484
- function uriId(root, linkName, id) {
485
- return `${uri(root, linkName)}/${id}`;
486
- }
487
- function uriIdSegment(root, linkName, id, segment) {
488
- return `${uriId(root, linkName, id)}/${segment}`;
489
- }
490
- function uriParam(root, linkName, param) {
491
- return `${uri(root, linkName)}?${param}`;
492
- }
493
- function uriIdSegmentParam(root, linkName, id, segment, param) {
494
- const base = uriIdSegment(root, linkName, id, segment);
495
- return param ? `${base}?${param}` : base;
496
- }
497
- function uriParamMarketplaceIdParam(root, linkName, id, param) {
498
- let u = uriParam(root, linkName, `marketplaceId=${id}`);
499
- if (param)
500
- u += `&${param}`;
501
- return u;
502
- }
503
388
  // ---------------------------------------------------------------------------
504
389
  // Credential / configuration helpers
505
390
  // ---------------------------------------------------------------------------
@@ -557,11 +442,6 @@ export function resolveEndpoint(endpoint) {
557
442
  }
558
443
  return { endpoint };
559
444
  }
560
- function sessionIdsParam(sessionIds) {
561
- if (!sessionIds || sessionIds.length === 0)
562
- return "";
563
- return "sessionIds=" + sessionIds.join(",");
564
- }
565
445
  export function loadPropertiesFile(path) {
566
446
  const props = {};
567
447
  if (!existsSync(path))
@@ -619,6 +499,20 @@ export function detail(body) {
619
499
  }
620
500
  return body;
621
501
  }
502
+ /**
503
+ * The body of a successful answer, parsed. A 200 that is not JSON -- an edge
504
+ * proxy's HTML error page, a truncated body -- is an answer the SDK cannot
505
+ * read, so it is an {@link ApiError}, as in the Java SDK, rather than a bare
506
+ * SyntaxError escaping past a caller who catches FlexemarketsError.
507
+ */
508
+ function readBody(body) {
509
+ try {
510
+ return JSON.parse(body);
511
+ }
512
+ catch {
513
+ throw new ApiError("Failed to parse the response body");
514
+ }
515
+ }
622
516
  function checkResponse(response, body) {
623
517
  const status = response.status;
624
518
  if (status >= 200 && status < 300)
@@ -653,7 +547,6 @@ export class Flexemarkets {
653
547
  _endpoint;
654
548
  _baseUrl;
655
549
  _bearerToken;
656
- _apiRoot;
657
550
  _account;
658
551
  _user;
659
552
  _tokenObj;
@@ -691,8 +584,6 @@ export class Flexemarkets {
691
584
  fm._tokenObj = tokenObj;
692
585
  fm._account = tokenObj.account;
693
586
  fm._user = tokenObj.person;
694
- // Fetch API root for HATEOAS links
695
- fm._apiRoot = await fm._fetchApiRoot();
696
587
  return fm;
697
588
  }
698
589
  // -- properties ------------------------------------------------------------
@@ -725,13 +616,13 @@ export class Flexemarkets {
725
616
  const resp = await fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
726
617
  headers: {
727
618
  ...this._authHeaders(),
728
- Accept: "application/json, application/hal+json",
619
+ Accept: "application/json",
729
620
  "User-Agent": FM_NETWORK_CLIENT,
730
621
  },
731
622
  });
732
623
  const body = await resp.text();
733
624
  checkResponse(resp, body);
734
- return JSON.parse(body);
625
+ return readBody(body);
735
626
  }
736
627
  /**
737
628
  * GET helper that returns the parsed body bundled with the
@@ -743,7 +634,7 @@ export class Flexemarkets {
743
634
  const resp = await fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
744
635
  headers: {
745
636
  ...this._authHeaders(),
746
- Accept: "application/json, application/hal+json",
637
+ Accept: "application/json",
747
638
  "User-Agent": FM_NETWORK_CLIENT,
748
639
  },
749
640
  });
@@ -751,24 +642,23 @@ export class Flexemarkets {
751
642
  checkResponse(resp, body);
752
643
  const raw = resp.headers.get("x-fm-as-of-seq");
753
644
  const asOfSeq = raw === null ? NO_SEQ : Number.parseInt(raw, 10);
754
- return { data: JSON.parse(body), asOfSeq: Number.isFinite(asOfSeq) ? asOfSeq : NO_SEQ };
645
+ return { data: readBody(body), asOfSeq: Number.isFinite(asOfSeq) ? asOfSeq : NO_SEQ };
755
646
  }
756
- /**
757
- * PATCH with no body — the shape every session transition takes: the verb and
758
- * the path carry the whole request.
759
- */
760
- async _patch(url) {
647
+ /** PATCH with a JSON body -- the shape every session transition takes. */
648
+ async _patch(url, json) {
761
649
  const resp = await fetch(url.startsWith("/") ? `${this._baseUrl}${url}` : url, {
762
650
  method: "PATCH",
763
651
  headers: {
764
652
  ...this._authHeaders(),
765
- Accept: "application/json, application/hal+json",
653
+ "Content-Type": "application/json",
654
+ Accept: "application/json",
766
655
  "User-Agent": FM_NETWORK_CLIENT,
767
656
  },
657
+ body: JSON.stringify(json),
768
658
  });
769
659
  const body = await resp.text();
770
660
  checkResponse(resp, body);
771
- return JSON.parse(body);
661
+ return readBody(body);
772
662
  }
773
663
  /**
774
664
  * GET returning the body verbatim, for endpoints that answer with something
@@ -793,14 +683,14 @@ export class Flexemarkets {
793
683
  headers: {
794
684
  ...this._authHeaders(),
795
685
  "Content-Type": "application/json",
796
- Accept: "application/json, application/hal+json",
686
+ Accept: "application/json",
797
687
  "User-Agent": FM_NETWORK_CLIENT,
798
688
  },
799
689
  body: JSON.stringify(json),
800
690
  });
801
691
  const body = await resp.text();
802
692
  checkResponse(resp, body);
803
- return JSON.parse(body);
693
+ return readBody(body);
804
694
  }
805
695
  // -- administration --------------------------------------------------------
806
696
  /*
@@ -820,7 +710,7 @@ export class Flexemarkets {
820
710
  * cannot sign in as.
821
711
  */
822
712
  async signup(accountName, email, password, firstName, lastName) {
823
- const url = uri(this._apiRoot, "accounts");
713
+ const url = this._v1("/accounts");
824
714
  try {
825
715
  const data = await this._post(url, {
826
716
  accountName,
@@ -843,49 +733,58 @@ export class Flexemarkets {
843
733
  throw e;
844
734
  }
845
735
  }
846
- /** Approve an account by name, returning it as it now stands. */
736
+ /**
737
+ * Approve an account by name, returning it as it now stands.
738
+ *
739
+ * V1 approves an account by id; the name is looked up in the account list
740
+ * first, so callers keep naming the account they signed up.
741
+ */
847
742
  async approveAccount(accountName) {
848
- const url = `${server(this._endpoint)}/approvals`;
849
- const data = await this._post(url, { name: accountName, approval: true });
743
+ const account = (await this.accounts()).find((a) => a.name === accountName);
744
+ if (account === undefined) {
745
+ throw new InvalidArgumentError(`No account named '${accountName}'`);
746
+ }
747
+ const data = await this._post(this._v1(`/accounts/${account.id}/approvals`), { approve: true });
850
748
  return parseAccount(data.account);
851
749
  }
852
750
  /** One account by id. */
853
751
  async accountById(accountId) {
854
- return parseAccount(await this._get(uriId(this._apiRoot, "accounts", accountId)));
752
+ return parseAccount(await this._get(this._v1(`/accounts/${accountId}`)));
855
753
  }
856
754
  /** One user by id. */
857
755
  async userById(userId) {
858
- return parsePerson(await this._get(v1(this._endpoint, `/users/${userId}`)));
756
+ return parsePerson(await this._get(this._v1(`/users/${userId}`)));
859
757
  }
860
- /** The marketplace's private-trader identifiers. */
758
+ /**
759
+ * The names of the participants a caller may target: `GET participants`,
760
+ * names only. A row carries the user id too, for a manager; not needed here.
761
+ */
861
762
  async identifiers(marketplaceId) {
862
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "privateTraders");
863
- return (await this._get(url));
763
+ const rows = (await this._get(`${this._marketplace(marketplaceId)}/participants`));
764
+ return rows.map((r) => r.name);
864
765
  }
865
766
  /** Delete the caller's own account. Its own route, not accounts/{yourId}. */
866
767
  async deleteMyAccount() {
867
- await this._delete(`${server(this._endpoint)}/accounts/me`);
768
+ await this._delete(this._v1("/accounts/me"));
868
769
  }
869
770
  /** Every account on the server. Admin-only. */
870
771
  async accounts() {
871
- const url = uriParam(this._apiRoot, "accounts", "format=application/json");
872
- const data = await this._get(url);
772
+ const data = await this._get(this._v1("/accounts"));
873
773
  return data.map(parseAccount);
874
774
  }
875
775
  /** Delete an account. Destructive, and takes its users with it. */
876
776
  async deleteAccount(accountId) {
877
- await this._delete(uriId(this._apiRoot, "accounts", accountId));
777
+ await this._delete(this._v1(`/accounts/${accountId}`));
878
778
  }
879
779
  /** Create a user in the caller's account. */
880
780
  async createUser(email, password, firstName, lastName, roles = []) {
881
- const url = v1(this._endpoint, "/users");
882
- const data = await this._post(url, { email, password, firstName, lastName, roles });
781
+ const data = await this._post(this._v1("/users"), { email, password, firstName, lastName, roles });
883
782
  return parsePerson(data);
884
783
  }
885
784
  /** Delete a user. Destructive. */
886
785
  async deleteUser(userId) {
887
786
  try {
888
- await this._delete(uriId(this._apiRoot, "users", userId));
787
+ await this._delete(this._v1(`/users/${userId}`));
889
788
  }
890
789
  catch (e) {
891
790
  // The user still owns orders or allotments. Deleting them would orphan
@@ -900,7 +799,7 @@ export class Flexemarkets {
900
799
  /** Create an empty marketplace. See also {@link createMarketplaceFromJson}. */
901
800
  /** Delete a marketplace, and with it its sessions and their history. */
902
801
  async deleteMarketplace(marketplaceId) {
903
- await this._delete(uriId(this._apiRoot, "marketplaces", marketplaceId));
802
+ await this._delete(this._marketplace(marketplaceId));
904
803
  }
905
804
  /**
906
805
  * Add a market to a marketplace.
@@ -912,8 +811,7 @@ export class Flexemarkets {
912
811
  * `units` keeps the old default.
913
812
  */
914
813
  async createMarket(marketplaceId, symbol, name, price, units = unitGrid(), privateMarket = false) {
915
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "markets");
916
- return parseMarket(await this._post(url, {
814
+ return parseMarket(await this._post(`${this._marketplace(marketplaceId)}/markets`, {
917
815
  symbol,
918
816
  name,
919
817
  priceMinimum: price.minimum,
@@ -932,7 +830,8 @@ export class Flexemarkets {
932
830
  * delivered to the person they belong to.
933
831
  */
934
832
  async managerOtpBundle(userIds) {
935
- const url = `${server(this._endpoint)}/otp/manager`;
833
+ // Unversioned: fm-server has no V1 route for passcodes.
834
+ const url = `${this._baseUrl}/otp/manager`;
936
835
  const data = await this._post(url, { userIds });
937
836
  return {
938
837
  expiresAt: toInstant(data.expiresAt),
@@ -952,27 +851,64 @@ export class Flexemarkets {
952
851
  const body = await resp.text();
953
852
  checkResponse(resp, body);
954
853
  }
955
- async _fetchApiRoot() {
956
- const data = await this._get(this._baseUrl);
957
- return rebaseApiRoot(parseApiRoot(data), this._baseUrl);
854
+ /**
855
+ * DELETE whose answer is the resource as it ended -- an order's CANCEL.
856
+ */
857
+ async _deleteFor(url) {
858
+ const resp = await fetch(url, {
859
+ method: "DELETE",
860
+ headers: { ...this._authHeaders(), Accept: "application/json", "User-Agent": FM_NETWORK_CLIENT },
861
+ });
862
+ const body = await resp.text();
863
+ checkResponse(resp, body);
864
+ return readBody(body);
865
+ }
866
+ /**
867
+ * Send one CSV file as the body, `Content-Type: text/csv` -- format by
868
+ * header, where 0.3 posted it as a multipart upload to an `/uploads`
869
+ * segment. Bytes, not a string, so the file's own encoding survives.
870
+ */
871
+ async _sendCsv(method, url, filename) {
872
+ const resp = await fetch(url, {
873
+ method,
874
+ headers: {
875
+ ...this._authHeaders(),
876
+ "Content-Type": "text/csv",
877
+ Accept: "application/json",
878
+ "User-Agent": FM_NETWORK_CLIENT,
879
+ },
880
+ body: readFileSync(filename),
881
+ });
882
+ const body = await resp.text();
883
+ checkResponse(resp, body);
884
+ return readBody(body);
885
+ }
886
+ /**
887
+ * A V1 route. 0.4 addresses every route from the server rather than through
888
+ * the HAL root's links: the path is knowable without fetching anything
889
+ * first, and a root that drops a link can no longer take a call with it.
890
+ */
891
+ _v1(path) {
892
+ return `${this._baseUrl}/v1${path}`;
893
+ }
894
+ /** The V1 route of one marketplace, under which nearly everything lives. */
895
+ _marketplace(marketplaceId) {
896
+ return this._v1(`/marketplaces/${marketplaceId}`);
958
897
  }
959
898
  // ======================================================================
960
899
  // REST APIs
961
900
  // ======================================================================
962
901
  // -- marketplaces ----------------------------------------------------------
963
902
  async marketplaces() {
964
- const url = uriParam(this._apiRoot, "marketplaces", "format=application/json");
965
- const data = await this._get(url);
903
+ const data = await this._get(this._v1("/marketplaces"));
966
904
  return data.map(parseMarketplace);
967
905
  }
968
906
  async marketplace(marketplaceId) {
969
- const url = uriId(this._apiRoot, "marketplaces", marketplaceId);
970
- return parseMarketplace(await this._get(url));
907
+ return parseMarketplace(await this._get(this._marketplace(marketplaceId)));
971
908
  }
972
909
  // -- markets ---------------------------------------------------------------
973
910
  async markets(marketplaceId) {
974
- const url = uriIdSegmentParam(this._apiRoot, "marketplaces", marketplaceId, "markets", "format=application/json");
975
- const data = await this._get(url);
911
+ const data = await this._get(`${this._marketplace(marketplaceId)}/markets`);
976
912
  return data.map(parseMarket);
977
913
  }
978
914
  /**
@@ -999,9 +935,9 @@ export class Flexemarkets {
999
935
  hasRole(role) {
1000
936
  return (this._user?.roles ?? []).includes(role);
1001
937
  }
938
+ /** The symbols of the marketplace's markets, read from the markets themselves. */
1002
939
  async symbols(marketplaceId) {
1003
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "symbols");
1004
- return (await this._get(url));
940
+ return (await this.markets(marketplaceId)).map((m) => m.symbol);
1005
941
  }
1006
942
  // -- sessions --------------------------------------------------------------
1007
943
  /**
@@ -1011,23 +947,17 @@ export class Flexemarkets {
1011
947
  * the `sessionIds` this used to accept was silently ignored: it returned the
1012
948
  * whole history and looked like it had filtered. Filter the result; fm-ui
1013
949
  * already does.
1014
- *
1015
- * On `GET /api/v1/marketplaces/{id}/sessions`, which answers with the same
1016
- * fields as the V0 route it replaces — verified against a running server,
1017
- * not assumed — and needs no `format=application/json` to avoid HAL.
1018
950
  */
1019
951
  async sessions(marketplaceId) {
1020
- const url = v1(this._endpoint, `/marketplaces/${marketplaceId}/sessions`);
952
+ const url = `${this._marketplace(marketplaceId)}/sessions`;
1021
953
  return (await this._get(url)).map(parseSession);
1022
954
  }
1023
955
  async session(marketplaceId) {
1024
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "currentSession");
1025
- return parseSession(await this._get(url));
956
+ return parseSession(await this._get(`${this._marketplace(marketplaceId)}/sessions/current`));
1026
957
  }
1027
958
  // -- orders ----------------------------------------------------------------
1028
959
  async submitLimit(marketplaceId, marketId, side, units, price) {
1029
- const url = uri(this._apiRoot, "orders");
1030
- const data = await this._post(url, {
960
+ const data = await this._post(`${this._marketplace(marketplaceId)}/orders`, {
1031
961
  marketplaceId,
1032
962
  marketId,
1033
963
  type: "LIMIT",
@@ -1077,18 +1007,13 @@ export class Flexemarkets {
1077
1007
  }
1078
1008
  throw new InvalidArgumentError(`Market ${marketId} is not in marketplace ${marketplaceId}`);
1079
1009
  }
1010
+ /**
1011
+ * DELETE the order: the server builds the CANCEL from the order's own
1012
+ * lineage and market, and answers with it. `marketId` is no longer sent --
1013
+ * the order already says which market it is in.
1014
+ */
1080
1015
  async submitCancel(marketplaceId, marketId, originalId) {
1081
- const url = uri(this._apiRoot, "orders");
1082
- const data = await this._post(url, {
1083
- marketplaceId,
1084
- marketId,
1085
- type: "CANCEL",
1086
- id: originalId,
1087
- original: originalId,
1088
- supplier: originalId,
1089
- clientDescription: this._clientDescription,
1090
- });
1091
- return parseOrder(data);
1016
+ return parseOrder(await this._deleteFor(`${this._marketplace(marketplaceId)}/orders/${originalId}`));
1092
1017
  }
1093
1018
  /**
1094
1019
  * The active-orders snapshot: every resting limit order on the
@@ -1098,10 +1023,9 @@ export class Flexemarkets {
1098
1023
  * value and skip those whose seq is less than or equal.
1099
1024
  */
1100
1025
  async activeOrders(marketplaceId) {
1101
- const baseRest = this._baseUrl;
1102
- const url = `${baseRest}/v1/marketplaces/${marketplaceId}/orders/active`;
1026
+ const url = `${this._marketplace(marketplaceId)}/orders?state=ACTIVE`;
1103
1027
  const { data, asOfSeq } = await this._getSnapshot(url);
1104
- const orders = embeddedOrders(data).map(parseOrder);
1028
+ const orders = ordersOf(data).map(parseOrder);
1105
1029
  return { body: orders, asOfSeq };
1106
1030
  }
1107
1031
  /**
@@ -1115,73 +1039,75 @@ export class Flexemarkets {
1115
1039
  * order differs. `Tape` sorts what it is given, so a caller seeding a tape
1116
1040
  * through `Desk` is unaffected; a caller reading this list directly
1117
1041
  * should not assume one.
1042
+ *
1043
+ * With `marketId`, only that market's legs (`&market=`), `size` of them,
1044
+ * two to a trade. What `Desk` seeds each tape from: read for every market
1045
+ * at once, a busy market's legs fill the limit and a quiet market's tape
1046
+ * comes up empty, though it has traded.
1118
1047
  */
1119
- async recentTrades(marketplaceId, size = 1000) {
1120
- const url = `${this._baseUrl}/v1/marketplaces/${marketplaceId}/orders/recent-trades?size=${size}`;
1048
+ async recentTrades(marketplaceId, size = 1000, marketId) {
1049
+ const market = marketId === undefined ? "" : `&market=${marketId}`;
1050
+ const url = `${this._marketplace(marketplaceId)}/orders?state=TRADED${market}&limit=${size}`;
1121
1051
  const { data, asOfSeq } = await this._getSnapshot(url);
1122
- const orders = embeddedOrders(data).map(parseOrder);
1052
+ const orders = ordersOf(data).map(parseOrder);
1123
1053
  return { body: orders, asOfSeq };
1124
1054
  }
1055
+ /**
1056
+ * The marketplace's orders.
1057
+ *
1058
+ * With no option, the current session's orders less every cancelled one, the
1059
+ * CANCEL that consumed it, and both legs of a self-cross -- what a study
1060
+ * ranking participants needs. Without `cancelled=false` the V1 read is the
1061
+ * raw lifecycle, which is what `sessionIds` asks for: every LIMIT and CANCEL
1062
+ * row of the named runs, as the exchange stored them. `symbol` reads one
1063
+ * market's active orders, with the symbol filled in.
1064
+ */
1125
1065
  async orders(marketplaceId, options) {
1066
+ const base = `${this._marketplace(marketplaceId)}/orders`;
1126
1067
  if (options?.symbol != null) {
1127
- const url = uriParamMarketplaceIdParam(this._apiRoot, "symbolOrdersJson", marketplaceId, `symbol=${options.symbol}`);
1128
- const data = await this._get(url);
1068
+ const symbol = options.symbol;
1069
+ const data = await this._get(`${base}?state=ACTIVE&symbol=${encodeURIComponent(symbol)}`);
1129
1070
  const orders = data.map(parseOrder);
1130
1071
  for (const o of orders)
1131
- o.symbol = options.symbol;
1072
+ o.symbol = symbol;
1132
1073
  return orders;
1133
1074
  }
1134
- if (options?.sessionIds != null) {
1135
- const url = uriParamMarketplaceIdParam(this._apiRoot, "sessionOrdersJson", marketplaceId, sessionIdsParam(options.sessionIds));
1136
- const data = await this._get(url);
1137
- return data.map(parseOrder);
1138
- }
1139
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "orders");
1140
- const data = await this._get(url);
1141
- return data.map(parseOrder);
1075
+ const url = options?.sessionIds != null && options.sessionIds.length > 0
1076
+ ? `${base}?sessions=${options.sessionIds.join(",")}`
1077
+ : `${base}?cancelled=false`;
1078
+ return (await this._get(url)).map(parseOrder);
1142
1079
  }
1143
1080
  /**
1144
- * Tape in one market, in ascending order id.
1081
+ * One market's traded legs, as many as the server gives in one read
1082
+ * ({@link MAX_TRADED_LEGS}), in the server's order.
1145
1083
  *
1146
- * Answered by a symbol-keyed route, so the orders come back without the
1147
- * symbol on them and with the trade id in `original`; both are filled in
1148
- * before returning, which is what makes the result a trade list rather than
1149
- * a set of half-populated orders.
1150
- *
1151
- * This is the FM-3 surface (`/api/orders-json/symbol-trades`) and its order
1152
- * is the server's, which sorts by order id and nothing else. It is neither
1153
- * chronological by trade time nor most-recent-first — the first element is
1154
- * the lowest id, not the latest trade. Sort by `lastModifiedDate` if you
1155
- * want time order.
1084
+ * The answer carries the trade id in `original` and no symbol on the orders,
1085
+ * because the query already fixed the symbol. Both are filled in before
1086
+ * returning, which is what makes the result a trade list rather than a set of
1087
+ * half-populated orders. Sort by `lastModifiedDate` if you want time order.
1156
1088
  */
1157
1089
  async trades(marketplaceId, symbol) {
1158
- const url = uriParamMarketplaceIdParam(this._apiRoot, "symbolTradesJson", marketplaceId, `symbol=${symbol}`);
1090
+ const url = `${this._marketplace(marketplaceId)}/orders?state=TRADED` +
1091
+ `&symbol=${encodeURIComponent(symbol)}&limit=${MAX_TRADED_LEGS}`;
1159
1092
  const data = await this._get(url);
1160
1093
  const orders = data.map(parseOrder);
1161
1094
  for (const o of orders) {
1162
- // The symbol-keyed route answers with the trade id in `original` and no
1163
- // symbol, because the query already fixed it. Filling both in is what
1164
- // makes the result a trade list rather than half-populated orders.
1165
1095
  o.id = o.original;
1166
1096
  o.symbol = symbol;
1167
1097
  }
1168
1098
  return orders;
1169
1099
  }
1170
1100
  // -- holdings --------------------------------------------------------------
1101
+ /** Comma-separated ids, matching the server's `?sessions=` filter. */
1171
1102
  async holdings(marketplaceId, sessionIds) {
1172
- let url;
1173
- if (sessionIds && sessionIds.length > 0) {
1174
- url = uriIdSegmentParam(this._apiRoot, "marketplaces", marketplaceId, "holdings", `sessions=${sessionIds.join(",")}`);
1175
- }
1176
- else {
1177
- url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "holdings");
1178
- }
1103
+ let url = `${this._marketplace(marketplaceId)}/holdings`;
1104
+ if (sessionIds && sessionIds.length > 0)
1105
+ url += `?sessions=${sessionIds.join(",")}`;
1179
1106
  const data = await this._get(url);
1180
1107
  return data.map(parseHolding);
1181
1108
  }
1182
1109
  async holding(marketplaceId) {
1183
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "currentHolding");
1184
- return parseHolding(await this._get(url));
1110
+ return parseHolding(await this._get(`${this._marketplace(marketplaceId)}/participants/me/holding`));
1185
1111
  }
1186
1112
  // -- connections -----------------------------------------------------------
1187
1113
  /**
@@ -1192,7 +1118,7 @@ export class Flexemarkets {
1192
1118
  * filter on the result.
1193
1119
  */
1194
1120
  async connections(marketplaceId) {
1195
- const url = uriIdSegmentParam(this._apiRoot, "marketplaces", marketplaceId, "connections", "format=application/json");
1121
+ const url = `${this._marketplace(marketplaceId)}/connections`;
1196
1122
  return (await this._get(url)).map(parseConnection);
1197
1123
  }
1198
1124
  // -- management ------------------------------------------------------------
@@ -1221,28 +1147,34 @@ export class Flexemarkets {
1221
1147
  catch (e) {
1222
1148
  throw new InvalidArgumentError(`Marketplace definition is not valid JSON: ${e.message}`);
1223
1149
  }
1224
- const url = `${server(this._endpoint)}/v1/marketplaces`;
1225
- return parseMarketplace(await this._post(url, parsed));
1150
+ return parseMarketplace(await this._post(this._v1("/marketplaces"), parsed));
1226
1151
  }
1227
1152
  /** Opens the marketplace's session, returning it in its new state. */
1228
1153
  async openSession(marketplaceId) {
1229
- return parseSession(await this._patch(uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "open")));
1154
+ return this._sessionState(marketplaceId, "OPEN");
1230
1155
  }
1231
1156
  async pauseSession(marketplaceId) {
1232
- return parseSession(await this._patch(uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "pause")));
1157
+ return this._sessionState(marketplaceId, "PAUSED");
1233
1158
  }
1234
1159
  async closeSession(marketplaceId) {
1235
- return parseSession(await this._patch(uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "close")));
1160
+ return this._sessionState(marketplaceId, "CLOSED");
1161
+ }
1162
+ /**
1163
+ * A session's lifecycle is its state, PATCHed. Asking for the state it is
1164
+ * already in changes nothing; one it cannot reach from where it is --
1165
+ * pausing a closed session -- is refused.
1166
+ */
1167
+ async _sessionState(marketplaceId, state) {
1168
+ return parseSession(await this._patch(`${this._marketplace(marketplaceId)}/sessions/current`, { state }));
1236
1169
  }
1237
- /** Everyone in the caller's account. `usersJson`, not the HAL `users` form. */
1170
+ /** Everyone in the caller's account. */
1238
1171
  async users() {
1239
- const data = await this._get(uri(this._apiRoot, "usersJson"));
1172
+ const data = await this._get(this._v1("/users"));
1240
1173
  return data.map((u) => parsePerson(u));
1241
1174
  }
1242
- /** The opening positions of one allocation. A V1 route, not on the API root. */
1175
+ /** The opening positions of one allocation. */
1243
1176
  async allotments(marketplaceId, allocationId) {
1244
- const url = `${server(this._endpoint)}/v1/marketplaces/${marketplaceId}` +
1245
- `/allotments?allocation=${allocationId}`;
1177
+ const url = `${this._marketplace(marketplaceId)}/allocations/${allocationId}/allotments`;
1246
1178
  const data = await this._get(url);
1247
1179
  return data.map(parseAllotment);
1248
1180
  }
@@ -1257,7 +1189,7 @@ export class Flexemarkets {
1257
1189
  * computes with; the allotment encoding is applied here.
1258
1190
  */
1259
1191
  async allocate(marketplaceId, holdings) {
1260
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "allocations");
1192
+ const url = `${this._marketplace(marketplaceId)}/allocations`;
1261
1193
  const body = holdings.map((h) => holdingToAllotment(marketplaceId, h));
1262
1194
  const data = await this._post(url, body);
1263
1195
  return allotmentsToHoldings(data.map(parseAllotment));
@@ -1265,32 +1197,23 @@ export class Flexemarkets {
1265
1197
  /**
1266
1198
  * The holdings CSV, verbatim, for the current session or for given ones.
1267
1199
  *
1268
- * The filter is spelled `sessions=` on this route and `sessionIds=` on
1269
- * sessions and connections. Using the wrong one is not an error — it is an
1270
- * unfiltered answer.
1200
+ * The same route as {@link holdings}, asked for `text/csv`: the format is
1201
+ * chosen by the Accept header, not by a `/downloads` segment.
1271
1202
  */
1272
1203
  async downloadHoldings(marketplaceId, sessionIds) {
1273
- if (sessionIds && sessionIds.length > 0) {
1274
- return this._getText(uriIdSegmentParam(this._apiRoot, "marketplaces", marketplaceId, "holdings/downloads", `sessions=${sessionIds.join(",")}`));
1275
- }
1276
- return this._getText(uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "holdings/downloads"));
1204
+ let url = `${this._marketplace(marketplaceId)}/holdings`;
1205
+ if (sessionIds && sessionIds.length > 0)
1206
+ url += `?sessions=${sessionIds.join(",")}`;
1207
+ return this._getText(url);
1277
1208
  }
1278
1209
  /**
1279
1210
  * Load opening positions from a holdings CSV. Stages the next allocation on
1280
1211
  * the same terms as {@link allocate}.
1281
1212
  */
1282
1213
  async uploadHoldings(marketplaceId, filename) {
1283
- const url = uriIdSegment(this._apiRoot, "marketplaces", marketplaceId, "holdings/uploads");
1284
- const form = new FormData();
1285
- form.append("file", new Blob([readFileSync(filename)]), basename(filename));
1286
- const resp = await fetch(url, {
1287
- method: "POST",
1288
- headers: { ...this._authHeaders(), "User-Agent": FM_NETWORK_CLIENT },
1289
- body: form,
1290
- });
1291
- const body = await resp.text();
1292
- checkResponse(resp, body);
1293
- return allotmentsToHoldings(JSON.parse(body).map(parseAllotment));
1214
+ const url = `${this._marketplace(marketplaceId)}/allocations`;
1215
+ const data = (await this._sendCsv("POST", url, filename));
1216
+ return allotmentsToHoldings(data.map(parseAllotment));
1294
1217
  }
1295
1218
  /**
1296
1219
  * Load per-participant private state from a CSV, returning what was stored.
@@ -1307,17 +1230,9 @@ export class Flexemarkets {
1307
1230
  * resolves to. A study's existing values file needs no change.
1308
1231
  */
1309
1232
  async uploadState(marketplaceId, filename) {
1310
- const url = v1(this._endpoint, `/marketplaces/${marketplaceId}/state/uploads`);
1311
- const form = new FormData();
1312
- form.append("file", new Blob([readFileSync(filename)]), basename(filename));
1313
- const resp = await fetch(url, {
1314
- method: "POST",
1315
- headers: { ...this._authHeaders(), "User-Agent": FM_NETWORK_CLIENT },
1316
- body: form,
1317
- });
1318
- const body = await resp.text();
1319
- checkResponse(resp, body);
1320
- return JSON.parse(body).map(parseParticipantState);
1233
+ const url = `${this._marketplace(marketplaceId)}/state`;
1234
+ const data = (await this._sendCsv("PUT", url, filename));
1235
+ return data.map(parseParticipantState);
1321
1236
  }
1322
1237
  /**
1323
1238
  * Push widgets to participants' screens, returning them as stored.
@@ -1336,7 +1251,7 @@ export class Flexemarkets {
1336
1251
  * that status: back off and push again.
1337
1252
  */
1338
1253
  async pushWidgets(marketplaceId, widgets) {
1339
- const url = v1(this._endpoint, `/marketplaces/${marketplaceId}/widgets`);
1254
+ const url = `${this._marketplace(marketplaceId)}/widgets`;
1340
1255
  const data = await this._post(url, widgets.map(widgetPushJson));
1341
1256
  return data.map(parseWidget);
1342
1257
  }
@@ -1344,17 +1259,16 @@ export class Flexemarkets {
1344
1259
  * Take down a widget: the marketplace's for `key`, or one participant's.
1345
1260
  *
1346
1261
  * True if one was removed, false if there was none to remove. With `userId`,
1347
- * only that participant's widget goes; their marketplace widget for the same
1348
- * key, if any, shows again.
1262
+ * only that participant's widget goes -- `participants/{userId}/widgets/{key}`
1263
+ * -- and their marketplace widget for the same key, if any, shows again.
1349
1264
  *
1350
1265
  * An empty 404 is the server saying nothing was there. A 404 carrying a
1351
1266
  * failure document -- no such marketplace -- still throws, so a robot pointed
1352
1267
  * at the wrong marketplace does not read its clean-up as done.
1353
1268
  */
1354
1269
  async removeWidget(marketplaceId, key, userId) {
1355
- let url = v1(this._endpoint, `/marketplaces/${marketplaceId}/widgets/${encodeURIComponent(key)}`);
1356
- if (userId !== undefined && userId !== null)
1357
- url += `?userId=${userId}`;
1270
+ const owner = userId !== undefined && userId !== null ? `/participants/${userId}` : "";
1271
+ const url = `${this._marketplace(marketplaceId)}${owner}/widgets/${encodeURIComponent(key)}`;
1358
1272
  const resp = await fetch(url, {
1359
1273
  method: "DELETE",
1360
1274
  headers: { ...this._authHeaders(), Accept: "application/json", "User-Agent": FM_NETWORK_CLIENT },
@@ -1370,7 +1284,7 @@ export class Flexemarkets {
1370
1284
  * participant -- what a manager reads to check on a robot.
1371
1285
  */
1372
1286
  async allWidgets(marketplaceId) {
1373
- const data = await this._get(v1(this._endpoint, `/marketplaces/${marketplaceId}/widgets/all`));
1287
+ const data = await this._get(`${this._marketplace(marketplaceId)}/widgets?participant=all`);
1374
1288
  return data.map(parseWidget);
1375
1289
  }
1376
1290
  // -- events / WebSocket ----------------------------------------------------
@@ -1511,8 +1425,9 @@ async function signIn(baseUrl, config, clientDescription) {
1511
1425
  // dropped it, and the Java SDK restored it with a test. This SDK and the
1512
1426
  // Python one never had it, so token auth returned 400 in both from the day
1513
1427
  // it was written.
1428
+ // POST, as minting a token is (fm-server 4.6).
1514
1429
  const resp = await fetch(`${baseUrl}/tokens/refresh`, {
1515
- method: "GET",
1430
+ method: "POST",
1516
1431
  headers: {
1517
1432
  Authorization: `Bearer ${tok}`,
1518
1433
  Accept: "application/json",
@@ -1521,7 +1436,7 @@ async function signIn(baseUrl, config, clientDescription) {
1521
1436
  });
1522
1437
  const body = await resp.text();
1523
1438
  checkResponse(resp, body);
1524
- return parseToken(JSON.parse(body));
1439
+ return parseToken(readBody(body));
1525
1440
  }
1526
1441
  const acct = config.account ?? "";
1527
1442
  const email = config.email ?? "";
@@ -1547,6 +1462,6 @@ async function signIn(baseUrl, config, clientDescription) {
1547
1462
  });
1548
1463
  const body = await resp.text();
1549
1464
  checkResponse(resp, body);
1550
- return parseToken(JSON.parse(body));
1465
+ return parseToken(readBody(body));
1551
1466
  }
1552
1467
  //# sourceMappingURL=client.js.map