@stxapp/stx-typescript 0.9.0 → 0.10.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.
@@ -1,29 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6;// src/geo.ts
2
- var IP_NOT_ALLOWED = /from this IP address (\S+?) is disallowed/i;
3
- function geoRejection(message) {
4
- const ip = IP_NOT_ALLOWED.exec(message);
5
- if (ip) return { reason: "ip_not_allowed", ipAddress: ip[1] };
6
- if (/geo location check was not done by this user|unknown user in geocomply/i.test(message)) {
7
- return { reason: "packet_other_user" };
8
- }
9
- if (/IP address doesn't match geo location/i.test(message)) {
10
- return { reason: "packet_ip_mismatch" };
11
- }
12
- if (/geo ?location package is invalid|geocomply location response|unable to find expected tag/i.test(message)) {
13
- return { reason: "packet_invalid" };
14
- }
15
- if (/invalid geo ?location|geo[- ]?(location|fenc)/i.test(message)) {
16
- return { reason: "location_not_allowed" };
17
- }
18
- return void 0;
19
- }
20
- async function resolveGeoLocation(provider) {
21
- if (provider === void 0 || provider === null) return void 0;
22
- const value = typeof provider === "function" ? await provider() : provider;
23
- return value === null || value === void 0 || value === "" ? void 0 : value;
24
- }
25
-
26
- // src/exceptions.ts
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6;// src/exceptions.ts
27
2
  var STXException = class extends Error {
28
3
 
29
4
 
@@ -72,15 +47,6 @@ var STXNotFoundException = class extends STXAPIException {
72
47
  };
73
48
  var STXRejectedException = class extends STXAPIException {
74
49
  };
75
- var STXGeoLocationException = class extends STXRejectedException {
76
-
77
-
78
- constructor(message, rejection, opts = {}) {
79
- super(message, opts);
80
- this.reason = rejection.reason;
81
- this.ipAddress = rejection.ipAddress;
82
- }
83
- };
84
50
  var STXRateLimitException = class extends STXAPIException {
85
51
 
86
52
  constructor(message, opts = {}) {
@@ -125,6 +91,7 @@ var FEATURE_PHRASES = {
125
91
  market_types: "Market types are",
126
92
  event_players: "Event players are",
127
93
  leaderboard: "The leaderboard is",
94
+ loyalty: "The loyalty program is",
128
95
  combos: "Combos are"
129
96
  };
130
97
  function notAvailableMessage(feature, host) {
@@ -231,10 +198,8 @@ function errorForStatus(statusCode, body, opts) {
231
198
  }
232
199
  case 404:
233
200
  return new STXNotFoundException(message, base);
234
- case 422: {
235
- const geo = geoRejection(message);
236
- return geo ? new STXGeoLocationException(message, geo, base) : new STXRejectedException(message, base);
237
- }
201
+ case 422:
202
+ return new STXRejectedException(message, base);
238
203
  case 429:
239
204
  return new STXRateLimitException(message, { ...base, retryAfter: parseRetryAfter(opts.retryAfter) });
240
205
  default:
@@ -270,6 +235,7 @@ var FEATURES = [
270
235
  "market_types",
271
236
  "event_players",
272
237
  "leaderboard",
238
+ "loyalty",
273
239
  "combos"
274
240
  ];
275
241
  var MEMBER_SCOPES = [
@@ -351,12 +317,13 @@ function oauthMetadataFrom(answer) {
351
317
  }
352
318
  async function discoverCapabilities(probes) {
353
319
  const swallow = (p) => p ? p.catch(() => null) : Promise.resolve(null);
354
- const [version, discovery, types, players, board, combos] = await Promise.all([
320
+ const [version, discovery, types, players, board, loyalty, combos] = await Promise.all([
355
321
  swallow(probes.get("/api_version")),
356
322
  swallow(probes.get("/.well-known/oauth-authorization-server")),
357
323
  swallow(probes.signedGet("/api/v1/types")),
358
324
  swallow(probes.signedGet(`/api/v1/events/${NOBODY}/players`)),
359
325
  swallow(probes.signedGet("/api/v1/leaderboard?limit=1")),
326
+ swallow(probes.signedGet("/api/v1/portfolio/loyalty?limit=1")),
360
327
  swallow(probes.joinReason(`rfq:${NOBODY}`))
361
328
  ]);
362
329
  const apiVersion = _optionalChain([json, 'call', _5 => _5(version), 'optionalAccess', _6 => _6.api_version]);
@@ -379,6 +346,8 @@ async function discoverCapabilities(probes) {
379
346
  event_players: players === null ? null : missingRoute(players) ? false : players.status === 404 || players.status < 300 ? true : null,
380
347
  // Switched off answers 404 too ("Leaderboard is not enabled").
381
348
  leaderboard: board === null ? null : board.status >= 200 && board.status < 300 ? true : board.status === 404 ? false : null,
349
+ // Switched off answers 404 ("Loyalty program is not enabled").
350
+ loyalty: loyalty === null ? null : loyalty.status >= 200 && loyalty.status < 300 ? true : loyalty.status === 404 ? false : null,
382
351
  combos: combos === null ? null : combos !== "unmatched topic"
383
352
  };
384
353
  return new Capabilities({
@@ -1209,7 +1178,7 @@ function credentialsFromSettings(keyId, privateKey, signer) {
1209
1178
  }
1210
1179
 
1211
1180
  // src/version.ts
1212
- var VERSION = "0.9.0";
1181
+ var VERSION = "0.10.0";
1213
1182
  var USER_AGENT = `stx-typescript/${VERSION}`;
1214
1183
  var ASYNC_DISPOSE = _nullishCoalesce(Symbol.asyncDispose, () => ( /* @__PURE__ */ Symbol.for("Symbol.asyncDispose")));
1215
1184
 
@@ -1457,10 +1426,6 @@ function comboJoinError(err, host = "") {
1457
1426
  }
1458
1427
  return err;
1459
1428
  }
1460
- async function comboJoinPayload(geo) {
1461
- const packet = await resolveGeoLocation(geo);
1462
- return packet === void 0 ? {} : { geo_location: packet };
1463
- }
1464
1429
  function money(name, value) {
1465
1430
  if (typeof value !== "string") {
1466
1431
  throw new TypeError(`${name} must be a decimal string such as "250.00", got ${typeof value}`);
@@ -1484,10 +1449,6 @@ var ComboSession = class {
1484
1449
  get externalId() {
1485
1450
  return _nullishCoalesce(this.channel.reply.external_id, () => ( ""));
1486
1451
  }
1487
- /** When the geolocation packet this join used expires (ISO 8601), or null. Rejoin before it. */
1488
- get nextGeolocationAt() {
1489
- return _nullishCoalesce(this.channel.reply.next_geolocation_at, () => ( null));
1490
- }
1491
1452
  /** @internal */
1492
1453
  _typed(msg) {
1493
1454
  if (!this.#events.has(msg.event) || !msg.payload || typeof msg.payload !== "object") return void 0;
@@ -1952,9 +1913,13 @@ var GATED_OPERATIONS = {
1952
1913
  markets_post: "markets.create",
1953
1914
  leaderboard_get: "leaderboard",
1954
1915
  leaderboard_me_get: "leaderboard",
1955
- me_profile_patch: "leaderboard"
1916
+ me_profile_patch: "leaderboard",
1917
+ portfolio_loyalty_get: "loyalty"
1918
+ };
1919
+ var SWITCHED_OFF = {
1920
+ leaderboard: "Leaderboard is not enabled",
1921
+ loyalty: "Loyalty program is not enabled"
1956
1922
  };
1957
- var LEADERBOARD_OFF = "Leaderboard is not enabled";
1958
1923
  var STX = (_class4 = class _STX {
1959
1924
 
1960
1925
 
@@ -1967,7 +1932,6 @@ var STX = (_class4 = class _STX {
1967
1932
 
1968
1933
 
1969
1934
 
1970
-
1971
1935
  #fetch;
1972
1936
  #me;
1973
1937
  #capabilities;
@@ -2008,7 +1972,6 @@ var STX = (_class4 = class _STX {
2008
1972
  this.verifyTls = settings.verifyTls;
2009
1973
  this.retry = _nullishCoalesce(opts.retry, () => ( new RetryPolicy()));
2010
1974
  this.timeoutMs = _nullishCoalesce(opts.timeoutMs, () => ( 3e4));
2011
- this.geoLocation = opts.geoLocation;
2012
1975
  this.onResponse = opts.onResponse;
2013
1976
  const fetchImpl = _nullishCoalesce(opts.fetch, () => ( globalThis.fetch));
2014
1977
  if (typeof fetchImpl !== "function") {
@@ -2194,7 +2157,7 @@ var STX = (_class4 = class _STX {
2194
2157
  return await this.#send(buildRequest(operationId, args));
2195
2158
  } catch (err) {
2196
2159
  const feature = GATED_OPERATIONS[operationId];
2197
- const off = feature === "leaderboard" && err instanceof STXNotFoundException && _optionalChain([err, 'access', _26 => _26.body, 'optionalAccess', _27 => _27.error]) === LEADERBOARD_OFF;
2160
+ const off = feature !== void 0 && err instanceof STXNotFoundException && SWITCHED_OFF[feature] !== void 0 && _optionalChain([err, 'access', _26 => _26.body, 'optionalAccess', _27 => _27.error]) === SWITCHED_OFF[feature];
2198
2161
  if (feature && (isMissingRoute(err) || off)) {
2199
2162
  throw new STXNotAvailableException(feature, this.host, {
2200
2163
  statusCode: err.statusCode,
@@ -2229,10 +2192,6 @@ var STX = (_class4 = class _STX {
2229
2192
  q.cursor = page.cursor;
2230
2193
  }
2231
2194
  }
2232
- async #geoBody(body, opts) {
2233
- const packet = _optionalChain([opts, 'optionalAccess', _28 => _28.geoLocation]) !== void 0 ? _nullishCoalesce(opts.geoLocation, () => ( void 0)) : await resolveGeoLocation(this.geoLocation);
2234
- return packet === void 0 ? body : { ...body, geo_location: packet };
2235
- }
2236
2195
  // ------------------------------------------------------------------
2237
2196
  // Identity
2238
2197
  // ------------------------------------------------------------------
@@ -2251,7 +2210,7 @@ var STX = (_class4 = class _STX {
2251
2210
  * `user_id`.
2252
2211
  */
2253
2212
  async userId() {
2254
- if (_optionalChain([this, 'access', _29 => _29.#me, 'optionalAccess', _30 => _30.user_id])) return this.#me.user_id;
2213
+ if (_optionalChain([this, 'access', _28 => _28.#me, 'optionalAccess', _29 => _29.user_id])) return this.#me.user_id;
2255
2214
  try {
2256
2215
  await this.me();
2257
2216
  } catch (err) {
@@ -2262,7 +2221,7 @@ var STX = (_class4 = class _STX {
2262
2221
  if (!balance.user_id) throw err;
2263
2222
  this.#me = { ..._nullishCoalesce(this.#me, () => ( {})), user_id: balance.user_id };
2264
2223
  }
2265
- if (!_optionalChain([this, 'access', _31 => _31.#me, 'optionalAccess', _32 => _32.user_id])) throw new STXException("GET /api/v1/me returned no user_id");
2224
+ if (!_optionalChain([this, 'access', _30 => _30.#me, 'optionalAccess', _31 => _31.user_id])) throw new STXException("GET /api/v1/me returned no user_id");
2266
2225
  return this.#me.user_id;
2267
2226
  }
2268
2227
  // ------------------------------------------------------------------
@@ -2431,83 +2390,41 @@ var STX = (_class4 = class _STX {
2431
2390
  *
2432
2391
  * The exchange validates the order: a bad price step or a fractional
2433
2392
  * quantity throws `STXValidationException` (400) or `STXRejectedException`
2434
- * (422) with the API's message; a geo-fencing refusal throws
2435
- * `STXGeoLocationException`.
2393
+ * (422) with the API's message. An order from outside the region is also
2394
+ * an `STXRejectedException`.
2436
2395
  *
2437
2396
  * A POST is never retried after a 5xx or a dropped connection; pass
2438
2397
  * `clientOrderId` so you can look the order up if that happens.
2439
2398
  */
2440
2399
  async placeOrder(marketId, action, orderType, opts) {
2441
- const { geoLocation, ...fields } = _nullishCoalesce(opts, () => ( {}));
2442
- const body = orderBody(marketId, action, orderType, fields);
2443
- return this.#one("orders_post", { body: await this.#geoBody(body, { geoLocation }) });
2400
+ const body = orderBody(marketId, action, orderType, _nullishCoalesce(opts, () => ( {})));
2401
+ return this.#one("orders_post", { body });
2444
2402
  }
2445
2403
  /**
2446
- * `POST /api/v1/orders/batched`: place several orders in one call. One geo
2447
- * check covers the batch. Returns one result per order, in order; a
2448
- * rejected order has `errors` instead of `order` and does not stop the
2449
- * others.
2404
+ * `POST /api/v1/orders/batched`: place several orders in one call. Returns
2405
+ * one result per order, in order; a rejected order has `errors` instead of
2406
+ * `order` and does not stop the others.
2450
2407
  */
2451
- async placeOrders(orders, opts) {
2408
+ async placeOrders(orders) {
2452
2409
  const body = { orders: orders.map(normalizeOrder) };
2453
- const raw = await this.#list("orders_batched_post", { body: await this.#geoBody(body, opts) });
2410
+ const raw = await this.#list("orders_batched_post", { body });
2454
2411
  return raw.map(toBatchOrderResult);
2455
2412
  }
2456
2413
  /**
2457
2414
  * `DELETE /api/v1/orders/{order_id}`: request a cancel. A cancel is a
2458
2415
  * request: a fill already in flight can still land.
2459
2416
  */
2460
- async cancelOrder(orderId, opts) {
2461
- const geo = await this.#geoBody({}, opts);
2462
- return this.#one("orders__order_id_delete", {
2463
- pathParams: { order_id: orderId },
2464
- body: "geo_location" in geo ? geo : void 0
2465
- });
2417
+ async cancelOrder(orderId) {
2418
+ return this.#one("orders__order_id_delete", { pathParams: { order_id: orderId } });
2466
2419
  }
2467
2420
  /** `DELETE /api/v1/orders/batched`: cancel the named orders. */
2468
- async cancelOrders(orderIds, opts) {
2421
+ async cancelOrders(orderIds) {
2469
2422
  const body = { orders: orderIds.map((id) => ({ order_id: id })) };
2470
- return this.#list("orders_batched_delete", { body: await this.#geoBody(body, opts) });
2423
+ return this.#list("orders_batched_delete", { body });
2471
2424
  }
2472
2425
  /** `DELETE /api/v1/orders/all`: cancel everything resting on the account. */
2473
- async cancelAllOrders(opts) {
2474
- const geo = await this.#geoBody({}, opts);
2475
- return this.#list("orders_all_delete", { body: "geo_location" in geo ? geo : void 0 });
2476
- }
2477
- // ------------------------------------------------------------------
2478
- // Geo-fencing
2479
- // ------------------------------------------------------------------
2480
- /**
2481
- * Ask the exchange whether this machine may trade right now, without
2482
- * placing or cancelling anything.
2483
- *
2484
- * Sends `DELETE /api/v1/orders/00000000-0000-0000-0000-000000000000` (an
2485
- * order id that cannot exist) with the geolocation packet, if one is
2486
- * configured. The exchange runs its geo check before it looks the order
2487
- * up, so a 404 means the check passed, and a geo 422 means it did not. On
2488
- * an exchange without geo-fencing it always passes.
2489
- *
2490
- * Needs a `read_write` key (the probe is a write route). The exchange
2491
- * records a failed check in its geolocation log exactly as it would a real
2492
- * order from the same place, and may raise a compliance alert, so call it
2493
- * once at start-up, not in a loop.
2494
- */
2495
- async geoCheck(opts) {
2496
- const geo = await this.#geoBody({}, opts);
2497
- const sentPacket = "geo_location" in geo;
2498
- try {
2499
- await this.#one("orders__order_id_delete", {
2500
- pathParams: { order_id: "00000000-0000-0000-0000-000000000000" },
2501
- body: sentPacket ? geo : void 0
2502
- });
2503
- return { allowed: true, sentPacket };
2504
- } catch (err) {
2505
- if (err instanceof STXNotFoundException) return { allowed: true, sentPacket };
2506
- if (err instanceof STXGeoLocationException) {
2507
- return { allowed: false, reason: err.reason, message: err.message, ipAddress: err.ipAddress, sentPacket };
2508
- }
2509
- throw err;
2510
- }
2426
+ async cancelAllOrders() {
2427
+ return this.#list("orders_all_delete");
2511
2428
  }
2512
2429
  // ------------------------------------------------------------------
2513
2430
  // Fills, positions, balance
@@ -2613,11 +2530,15 @@ var STX = (_class4 = class _STX {
2613
2530
  iterFees(query = {}) {
2614
2531
  return this.#iterate("portfolio_fees_get", { limit: query.limit });
2615
2532
  }
2616
- /** `GET /api/v1/portfolio/loyalty`: loyalty entries. */
2533
+ /**
2534
+ * `GET /api/v1/portfolio/loyalty`: loyalty entries. Throws
2535
+ * `STXNotAvailableException` (feature `loyalty`) where the exchange has the
2536
+ * loyalty program switched off.
2537
+ */
2617
2538
  loyalty(query = {}) {
2618
2539
  return this.#page("portfolio_loyalty_get", { limit: query.limit, cursor: query.cursor });
2619
2540
  }
2620
- /** Every loyalty entry, following the cursor. */
2541
+ /** Every loyalty entry, following the cursor. Throws like `loyalty()`. */
2621
2542
  iterLoyalty(query = {}) {
2622
2543
  return this.#iterate("portfolio_loyalty_get", { limit: query.limit });
2623
2544
  }
@@ -2752,6 +2673,12 @@ var MessageQueue = class {
2752
2673
  this.#items.push(msg);
2753
2674
  return dropped;
2754
2675
  }
2676
+ /** Queue the end marker behind everything already queued, dropping nothing. */
2677
+ end() {
2678
+ const waiter = this.#waiters.shift();
2679
+ if (waiter) waiter(null);
2680
+ else this.#items.push(null);
2681
+ }
2755
2682
  get(timeoutMs) {
2756
2683
  if (this.#items.length) return Promise.resolve(this.#items.shift());
2757
2684
  return new Promise((resolve, reject) => {
@@ -2789,13 +2716,24 @@ var Channel = (_class5 = class {
2789
2716
  __init9() {this.joinRef = null}
2790
2717
  __init10() {this.joined = false}
2791
2718
  __init11() {this.closed = false}
2792
- /** @internal Runs before every (re)join, e.g. to refresh a geolocation packet in `joinPayload`. */
2793
-
2794
2719
  #ws;
2795
2720
  #queue;
2796
2721
  #snapshotWaiters = [];
2797
2722
  #pingTimer;
2798
- constructor(ws, topic, joinPayload, onMessage, opts) {;_class5.prototype.__init6.call(this);_class5.prototype.__init7.call(this);_class5.prototype.__init8.call(this);_class5.prototype.__init9.call(this);_class5.prototype.__init10.call(this);_class5.prototype.__init11.call(this);
2723
+ /** @internal Milliseconds between pings while joined; null when none are sent. */
2724
+ __init12() {this._pingEveryMs = null}
2725
+ // One phx_join per topic per connection (Phoenix answers a second join of a
2726
+ // joined topic by closing the first): joins run one after another, and a
2727
+ // join already made on the current connection is not repeated.
2728
+ /** @internal */
2729
+ __init13() {this._joinTail = Promise.resolve()}
2730
+ /** @internal */
2731
+ __init14() {this._joinedConnection = 0}
2732
+ /** @internal The connection whose join also restored watches and the pinger. */
2733
+ __init15() {this._restoredConnection = 0}
2734
+ /** @internal A phx_close/phx_error for the join in flight. */
2735
+ __init16() {this._endedJoin = null}
2736
+ constructor(ws, topic, joinPayload, onMessage, opts) {;_class5.prototype.__init6.call(this);_class5.prototype.__init7.call(this);_class5.prototype.__init8.call(this);_class5.prototype.__init9.call(this);_class5.prototype.__init10.call(this);_class5.prototype.__init11.call(this);_class5.prototype.__init12.call(this);_class5.prototype.__init13.call(this);_class5.prototype.__init14.call(this);_class5.prototype.__init15.call(this);_class5.prototype.__init16.call(this);
2799
2737
  this.#ws = ws;
2800
2738
  this.topic = topic;
2801
2739
  this.name = topic.split(":", 1)[0];
@@ -2960,11 +2898,12 @@ var Channel = (_class5 = class {
2960
2898
  _startPinger() {
2961
2899
  this._stopPinger();
2962
2900
  let interval = this.pingIntervalMs;
2963
- const granted = _optionalChain([this, 'access', _33 => _33.reply, 'optionalAccess', _34 => _34.ping_timeout]);
2901
+ const granted = _optionalChain([this, 'access', _32 => _32.reply, 'optionalAccess', _33 => _33.ping_timeout]);
2964
2902
  if (typeof granted === "number" && this.joinPayload.cancel_on_disconnect) {
2965
- const cod = granted * 0.6;
2903
+ const cod = granted / 3;
2966
2904
  interval = interval === null ? cod : Math.min(interval, cod);
2967
2905
  }
2906
+ this._pingEveryMs = interval || null;
2968
2907
  if (interval) {
2969
2908
  const every = interval;
2970
2909
  this.#pingTimer = setInterval(() => {
@@ -2973,7 +2912,7 @@ var Channel = (_class5 = class {
2973
2912
  (err) => this.#ws.logger.warn(`${this.topic} ping failed: ${err.message}`)
2974
2913
  );
2975
2914
  }, every);
2976
- _optionalChain([this, 'access', _35 => _35.#pingTimer, 'access', _36 => _36.unref, 'optionalCall', _37 => _37()]);
2915
+ _optionalChain([this, 'access', _34 => _34.#pingTimer, 'access', _35 => _35.unref, 'optionalCall', _36 => _36()]);
2977
2916
  }
2978
2917
  }
2979
2918
  /** @internal */
@@ -2984,9 +2923,17 @@ var Channel = (_class5 = class {
2984
2923
  /** @internal */
2985
2924
  _resetForRejoin() {
2986
2925
  this.joined = false;
2926
+ this._restoredConnection = 0;
2987
2927
  this.snapshots = {};
2988
2928
  this._stopPinger();
2989
2929
  }
2930
+ /** @internal End the channel after every queued message is read. */
2931
+ _finish() {
2932
+ this.closed = true;
2933
+ this.joined = false;
2934
+ this._stopPinger();
2935
+ this.#queue.end();
2936
+ }
2990
2937
  /** @internal */
2991
2938
  _close() {
2992
2939
  this.closed = true;
@@ -3017,23 +2964,27 @@ var STXWebSocket = (_class6 = class {
3017
2964
 
3018
2965
 
3019
2966
 
3020
- __init12() {this.channels = /* @__PURE__ */ new Map()}
2967
+ __init17() {this.channels = /* @__PURE__ */ new Map()}
3021
2968
  /** Successful reconnects so far. */
3022
- __init13() {this.reconnects = 0}
2969
+ __init18() {this.reconnects = 0}
2970
+ /** Channels rejoined after the server closed or errored them while the socket stayed up. */
2971
+ __init19() {this.channelRejoins = 0}
3023
2972
  #userId;
3024
2973
  #conn;
3025
2974
  #ref = 0;
2975
+ #connection = 0;
3026
2976
  #pending = /* @__PURE__ */ new Map();
3027
2977
  #heartbeat;
3028
2978
  #pendingHeartbeat = null;
3029
2979
  #closed = false;
3030
2980
  #connecting;
3031
2981
  #reconnecting = false;
2982
+ #reconnectDone = Promise.resolve();
3032
2983
  #closedWaiters = [];
3033
2984
  // Frames are handled one at a time, in arrival order: each waits for the
3034
2985
  // previous one's handler to finish.
3035
2986
  #inbox = Promise.resolve();
3036
- constructor(opts = {}) {;_class6.prototype.__init12.call(this);_class6.prototype.__init13.call(this);
2987
+ constructor(opts = {}) {;_class6.prototype.__init17.call(this);_class6.prototype.__init18.call(this);_class6.prototype.__init19.call(this);
3037
2988
  if (opts.rest) {
3038
2989
  this.rest = opts.rest;
3039
2990
  } else {
@@ -3078,6 +3029,11 @@ var STXWebSocket = (_class6 = class {
3078
3029
  async connect() {
3079
3030
  if (this.#closed) throw new STXTransportException("This STXWebSocket is closed; create a new one.");
3080
3031
  if (this.connected) return this;
3032
+ while (this.#reconnecting) {
3033
+ await this.#reconnectDone;
3034
+ if (this.#closed) throw new STXTransportException("This STXWebSocket is closed; create a new one.");
3035
+ if (this.connected) return this;
3036
+ }
3081
3037
  if (!this.#connecting) {
3082
3038
  this.#connecting = this.#openAuthenticated().finally(() => {
3083
3039
  this.#connecting = void 0;
@@ -3168,7 +3124,7 @@ var STXWebSocket = (_class6 = class {
3168
3124
  */
3169
3125
  async marketUpdates(opts = {}) {
3170
3126
  const channel = await this.join("market_updates", {}, opts.onMessage);
3171
- if (_optionalChain([opts, 'access', _38 => _38.watch, 'optionalAccess', _39 => _39.length])) await channel.watch(opts.watch);
3127
+ if (_optionalChain([opts, 'access', _37 => _37.watch, 'optionalAccess', _38 => _38.length])) await channel.watch(opts.watch);
3172
3128
  return channel;
3173
3129
  }
3174
3130
  /**
@@ -3197,7 +3153,7 @@ var STXWebSocket = (_class6 = class {
3197
3153
  * `cancelOnDisconnect: true` arms cancel-on-disconnect for orders placed
3198
3154
  * with `cancelOnDisconnect: true`. `pingTimeout` is in milliseconds,
3199
3155
  * clamped by the server to 5000 to 20000; the granted value is in
3200
- * `channel.reply.ping_timeout` and the SDK pings at 60% of it for as long
3156
+ * `channel.reply.ping_timeout` and the SDK pings at a third of it for as long
3201
3157
  * as the channel is joined.
3202
3158
  */
3203
3159
  orders(opts = {}) {
@@ -3252,7 +3208,6 @@ var STXWebSocket = (_class6 = class {
3252
3208
  * Join `rfq:{user_id}` and return a `ComboPlayer`: request quotes on a
3253
3209
  * combination, cash one out, accept, cancel and read a request.
3254
3210
  *
3255
- * Available on US demo.
3256
3211
  * Where combos are not available, rejects with
3257
3212
  * `STXCombosUnavailableException`. Other join refusals (a read-only key, an
3258
3213
  * account that may not trade) reject with `STXComboRefusedException`.
@@ -3272,7 +3227,6 @@ var STXWebSocket = (_class6 = class {
3272
3227
  * Join `combo_quote:{user_id}` and return a `ComboMaker`: receive every
3273
3228
  * request opened from now on (`rfq_opened`), quote and withdraw quotes.
3274
3229
  *
3275
- * Available on US demo.
3276
3230
  * Where combos are not available, rejects with
3277
3231
  * `STXCombosUnavailableException`.
3278
3232
  */
@@ -3288,19 +3242,11 @@ var STXWebSocket = (_class6 = class {
3288
3242
  return maker;
3289
3243
  }
3290
3244
  async #joinCombo(name, opts, onMessage) {
3291
- let channel;
3292
3245
  try {
3293
- channel = await this.#joinAccount(name, await comboJoinPayload(opts.geoLocation), onMessage);
3246
+ return await this.#joinAccount(name, {}, onMessage);
3294
3247
  } catch (err) {
3295
3248
  throw comboJoinError(err, new URL(this.rest.baseUrl).host);
3296
3249
  }
3297
- if (typeof opts.geoLocation === "function") {
3298
- const geo = opts.geoLocation;
3299
- channel._beforeJoin = async () => {
3300
- channel.joinPayload = await comboJoinPayload(geo);
3301
- };
3302
- }
3303
- return channel;
3304
3250
  }
3305
3251
  // ------------------------------------------------------------------
3306
3252
  // Generic join
@@ -3311,9 +3257,13 @@ var STXWebSocket = (_class6 = class {
3311
3257
  * `market_ids_required` or `unauthorized`) if the join is refused.
3312
3258
  */
3313
3259
  async join(topic, payload = {}, onMessage, opts = {}) {
3314
- const existing = this.channels.get(topic);
3315
- if (existing && !existing.closed) throw new STXChannelException(`Already joined ${topic}`, { topic });
3260
+ const already = () => {
3261
+ const existing = this.channels.get(topic);
3262
+ if (existing && !existing.closed) throw new STXChannelException(`Already joined ${topic}`, { topic });
3263
+ };
3264
+ already();
3316
3265
  await this.connect();
3266
+ already();
3317
3267
  const name = topic.split(":", 1)[0];
3318
3268
  const channel = new Channel(this, topic, payload, onMessage, {
3319
3269
  pingIntervalMs: opts.pingIntervalMs !== void 0 ? opts.pingIntervalMs : UNPINGED_CHANNELS.has(name) ? null : this.channelPingIntervalMs,
@@ -3337,17 +3287,56 @@ var STXWebSocket = (_class6 = class {
3337
3287
  }
3338
3288
  return this.join(`${name}:${await this.userId()}`, payload, onMessage);
3339
3289
  }
3340
- async #join(channel) {
3290
+ /**
3291
+ * Join `channel` on the current connection unless it already is, then
3292
+ * restore its watches and pinger; resolves to whether anything was done.
3293
+ */
3294
+ #join(channel) {
3295
+ const run = channel._joinTail.then(async () => {
3296
+ const connection = this.#connection;
3297
+ if (channel.closed) return false;
3298
+ if (channel.joined && channel._joinedConnection === connection) {
3299
+ if (channel._restoredConnection === connection) return false;
3300
+ await this.#restore(channel, connection);
3301
+ return true;
3302
+ }
3303
+ await this.#joinNow(channel, connection);
3304
+ await this.#restore(channel, connection);
3305
+ return true;
3306
+ });
3307
+ channel._joinTail = run.catch(() => {
3308
+ });
3309
+ return run;
3310
+ }
3311
+ async #joinNow(channel, connection) {
3341
3312
  const ref = this.#nextRef();
3342
3313
  channel.joinRef = ref;
3343
3314
  channel._resetForRejoin();
3344
- if (channel._beforeJoin) await channel._beforeJoin();
3315
+ channel._endedJoin = null;
3345
3316
  const reply = await this._request(channel.topic, "phx_join", channel.joinPayload, ref, void 0, ref);
3317
+ const ended = channel._endedJoin;
3318
+ if (ended && ended.joinRef === ref) {
3319
+ channel._endedJoin = null;
3320
+ throw joinInterrupted(channel, ended.event);
3321
+ }
3346
3322
  channel.reply = reply && typeof reply === "object" && !Array.isArray(reply) ? reply : { response: reply };
3347
3323
  if (channel.name === "market") channel.reply = convertMarketChannelPayload(channel.reply);
3324
+ channel._joinedConnection = connection;
3348
3325
  channel.joined = true;
3349
- if (channel.watches.length) await channel.push("watch", [...channel.watches]);
3326
+ }
3327
+ async #restore(channel, connection) {
3328
+ if (channel.watches.length) {
3329
+ await channel.push("watch", [...channel.watches]);
3330
+ if (channel.closed || !channel.joined || channel._joinedConnection !== connection) {
3331
+ throw joinInterrupted(channel, "phx_close");
3332
+ }
3333
+ }
3350
3334
  channel._startPinger();
3335
+ channel._restoredConnection = connection;
3336
+ }
3337
+ #finishMarket(channel) {
3338
+ channel._finish();
3339
+ if (this.channels.get(channel.topic) === channel) this.channels.delete(channel.topic);
3351
3340
  }
3352
3341
  /** @internal */
3353
3342
  async _leave(channel) {
@@ -3384,12 +3373,12 @@ var STXWebSocket = (_class6 = class {
3384
3373
  if (!(err instanceof STXTransportException)) return false;
3385
3374
  if (err.statusCode !== 401 && err.statusCode !== 403) return false;
3386
3375
  const auth = this.rest.auth;
3387
- if (!_optionalChain([auth, 'optionalAccess', _40 => _40.onUnauthorized])) return false;
3376
+ if (!_optionalChain([auth, 'optionalAccess', _39 => _39.onUnauthorized])) return false;
3388
3377
  return auth.onUnauthorized();
3389
3378
  }
3390
3379
  async #open(reconnect = false) {
3391
3380
  const headers = { "User-Agent": USER_AGENT };
3392
- if (_optionalChain([this, 'access', _41 => _41.rest, 'access', _42 => _42.auth, 'optionalAccess', _43 => _43.websocketHeaders])) Object.assign(headers, await this.rest.auth.websocketHeaders({ reconnect }));
3381
+ if (_optionalChain([this, 'access', _40 => _40.rest, 'access', _41 => _41.auth, 'optionalAccess', _42 => _42.websocketHeaders])) Object.assign(headers, await this.rest.auth.websocketHeaders({ reconnect }));
3393
3382
  const conn = new (0, _ws2.default)(this.url, {
3394
3383
  headers,
3395
3384
  rejectUnauthorized: this.rest.verifyTls,
@@ -3402,8 +3391,10 @@ var STXWebSocket = (_class6 = class {
3402
3391
  };
3403
3392
  const onUnexpected = (_req, res) => {
3404
3393
  cleanup();
3394
+ conn.on("error", () => {
3395
+ });
3405
3396
  conn.terminate();
3406
- const reason = _optionalChain([res, 'access', _44 => _44.headers, 'optionalAccess', _45 => _45["x-stx-error"]]);
3397
+ const reason = _optionalChain([res, 'access', _43 => _43.headers, 'optionalAccess', _44 => _44["x-stx-error"]]);
3407
3398
  reject(
3408
3399
  new STXTransportException(
3409
3400
  `Could not open ${this.url}: HTTP ${res.statusCode}${reason ? ` (${String(reason)})` : ""}`,
@@ -3428,6 +3419,7 @@ var STXWebSocket = (_class6 = class {
3428
3419
  conn.on("message", (data) => this.#onFrame(data.toString()));
3429
3420
  conn.on("close", () => this.#onConnClose(conn));
3430
3421
  this.#conn = conn;
3422
+ this.#connection += 1;
3431
3423
  this.#pendingHeartbeat = null;
3432
3424
  this.#startHeartbeat();
3433
3425
  this.logger.debug(`connected to ${this.url}`);
@@ -3511,15 +3503,29 @@ var STXWebSocket = (_class6 = class {
3511
3503
  }
3512
3504
  const channel = this.channels.get(topic);
3513
3505
  if (!channel) return;
3514
- if (joinRef !== null && joinRef !== void 0 && channel.joinRef !== null && String(joinRef) !== channel.joinRef) {
3515
- return;
3516
- }
3517
3506
  if (event === "phx_error" || event === "phx_close") {
3518
- if (!channel.closed && !this.#closed) {
3519
- this.logger.warn(`${topic}: server sent ${event}; rejoining`);
3520
- channel._resetForRejoin();
3521
- void this.#rejoinLater(channel);
3507
+ if (joinRef === null || joinRef === void 0 || String(joinRef) !== channel.joinRef) return;
3508
+ if (channel.closed || this.#closed) return;
3509
+ if (!channel.joined) {
3510
+ channel._endedJoin = { joinRef: String(joinRef), event };
3511
+ const pending = this.#pending.get(String(joinRef));
3512
+ if (_optionalChain([pending, 'optionalAccess', _45 => _45.event]) === "phx_join") pending.reject(joinInterrupted(channel, event));
3513
+ if (event === "phx_close" && channel.name === "market") this.#finishMarket(channel);
3514
+ return;
3515
+ }
3516
+ for (const pending of [...this.#pending.values()]) {
3517
+ if (pending.topic === channel.topic) pending.reject(joinInterrupted(channel, event));
3518
+ }
3519
+ if (event === "phx_close" && channel.name === "market") {
3520
+ this.#finishMarket(channel);
3521
+ return;
3522
3522
  }
3523
+ this.logger.warn(`${topic}: server sent ${event}; rejoining`);
3524
+ channel._resetForRejoin();
3525
+ void this.#rejoinLater(channel, true);
3526
+ return;
3527
+ }
3528
+ if (joinRef !== null && joinRef !== void 0 && channel.joinRef !== null && String(joinRef) !== channel.joinRef) {
3523
3529
  return;
3524
3530
  }
3525
3531
  if (channel.name === "markets") payload = convertMarketsFrame(payload);
@@ -3537,13 +3543,21 @@ var STXWebSocket = (_class6 = class {
3537
3543
  )
3538
3544
  );
3539
3545
  }
3540
- async #rejoinLater(channel) {
3546
+ /**
3547
+ * Rejoin `channel` with backoff. `serverClosed`: the server closed or
3548
+ * errored it while the socket stayed up (counted in `channelRejoins`);
3549
+ * otherwise a rejoin refused during a socket reconnect is being retried.
3550
+ */
3551
+ async #rejoinLater(channel, serverClosed) {
3541
3552
  let attempt = 1;
3542
3553
  while (!channel.closed && !this.#closed) {
3543
3554
  await sleep2(this.reconnectPolicy.delayMs(attempt));
3544
3555
  if (!this.connected) return;
3545
3556
  try {
3546
- await this.#join(channel);
3557
+ if (await this.#join(channel) && channel.joined && !channel.closed) {
3558
+ if (serverClosed) this.channelRejoins += 1;
3559
+ await this.#raiseReconnect();
3560
+ }
3547
3561
  return;
3548
3562
  } catch (err) {
3549
3563
  this.logger.error(`rejoin ${channel.topic} failed: ${err.message}`);
@@ -3593,6 +3607,8 @@ var STXWebSocket = (_class6 = class {
3593
3607
  }
3594
3608
  async #reconnectLoop() {
3595
3609
  this.#reconnecting = true;
3610
+ let finished;
3611
+ this.#reconnectDone = new Promise((r) => finished = r);
3596
3612
  let ok = false;
3597
3613
  try {
3598
3614
  let attempt = 1;
@@ -3614,13 +3630,13 @@ var STXWebSocket = (_class6 = class {
3614
3630
  } catch (err) {
3615
3631
  if (!(err instanceof STXChannelException)) throw err;
3616
3632
  this.logger.error(`rejoin ${channel.topic} failed: ${err.message}; retrying`);
3617
- void this.#rejoinLater(channel);
3633
+ void this.#rejoinLater(channel, false);
3618
3634
  }
3619
3635
  }
3620
3636
  this.reconnects += 1;
3621
3637
  this.logger.info(`reconnected (${this.reconnects})`);
3622
3638
  ok = true;
3623
- if (this.onReconnect) await this.onReconnect();
3639
+ void this.#raiseReconnect();
3624
3640
  return;
3625
3641
  } catch (err) {
3626
3642
  this.#closeConn();
@@ -3636,12 +3652,21 @@ var STXWebSocket = (_class6 = class {
3636
3652
  }
3637
3653
  } finally {
3638
3654
  this.#reconnecting = false;
3655
+ finished();
3639
3656
  if (ok && !this.#closed && !this.connected) {
3640
3657
  for (const channel of this.channels.values()) channel._resetForRejoin();
3641
3658
  void this.#reconnectLoop();
3642
3659
  }
3643
3660
  }
3644
3661
  }
3662
+ async #raiseReconnect() {
3663
+ if (!this.onReconnect) return;
3664
+ try {
3665
+ await this.onReconnect();
3666
+ } catch (err) {
3667
+ this.logger.error("onReconnect threw", err);
3668
+ }
3669
+ }
3645
3670
  #failAuth(err) {
3646
3671
  this.error = err;
3647
3672
  this.#shutdownAfterDrop();
@@ -3663,6 +3688,12 @@ var STXWebSocket = (_class6 = class {
3663
3688
  for (const w of waiters) w();
3664
3689
  }
3665
3690
  }, _class6);
3691
+ function joinInterrupted(channel, event) {
3692
+ return new STXChannelException(`${event} on ${channel.topic} while joining`, {
3693
+ topic: channel.topic,
3694
+ reply: { reason: event }
3695
+ });
3696
+ }
3666
3697
  function dropUndefined(payload) {
3667
3698
  return Object.fromEntries(
3668
3699
  Object.entries(payload).filter(([, v]) => v !== void 0).map(([k, v]) => [k, Array.isArray(v) ? [...v] : v])
@@ -3741,7 +3772,5 @@ function dropUndefined(payload) {
3741
3772
 
3742
3773
 
3743
3774
 
3744
-
3745
-
3746
- exports.geoRejection = geoRejection; exports.STXException = STXException; exports.STXConfigException = STXConfigException; exports.STXAPIException = STXAPIException; exports.STXValidationException = STXValidationException; exports.STXAuthenticationException = STXAuthenticationException; exports.STXForbiddenException = STXForbiddenException; exports.STXInvalidTokenException = STXInvalidTokenException; exports.STXInsufficientScopeException = STXInsufficientScopeException; exports.STXTermsRequiredException = STXTermsRequiredException; exports.STXIPNotAllowedException = STXIPNotAllowedException; exports.STXNotFoundException = STXNotFoundException; exports.STXRejectedException = STXRejectedException; exports.STXGeoLocationException = STXGeoLocationException; exports.STXRateLimitException = STXRateLimitException; exports.STXServerException = STXServerException; exports.STXTransportException = STXTransportException; exports.STXChannelException = STXChannelException; exports.STXTimeoutException = STXTimeoutException; exports.notAvailableMessage = notAvailableMessage; exports.STXNotAvailableException = STXNotAvailableException; exports.STXCombosUnavailableException = STXCombosUnavailableException; exports.isEdgeBlock = isEdgeBlock; exports.STXComboRefusedException = STXComboRefusedException; exports.STXComboPriceMovedException = STXComboPriceMovedException; exports.errorForStatus = errorForStatus; exports.FEATURES = FEATURES; exports.Capabilities = Capabilities; exports.Region = Region; exports.Environment = Environment; exports.Environments = Environments; exports.HOSTS = HOSTS; exports.environmentNamed = environmentNamed; exports.resolveHost = resolveHost; exports.baseUrlFor = baseUrlFor; exports.socketUrlFor = socketUrlFor; exports.OPERATIONS = OPERATIONS; exports.Stats = Stats; exports.MAX_MARKETS_PER_REQUEST = MAX_MARKETS_PER_REQUEST; exports.isValidLine = isValidLine; exports.Page = Page; exports.RetryPolicy = RetryPolicy; exports.NO_RETRY = NO_RETRY; exports.resolveSettings = resolveSettings; exports.KEY_HEADER = KEY_HEADER; exports.TIMESTAMP_HEADER = TIMESTAMP_HEADER; exports.SIGNATURE_HEADER = SIGNATURE_HEADER; exports.buildMessage = buildMessage; exports.requestPath = requestPath; exports.handshakePath = handshakePath; exports.loadPrivateKey = loadPrivateKey; exports.signerFromPrivateKey = signerFromPrivateKey; exports.ApiKeyCredentials = ApiKeyCredentials; exports.VERSION = VERSION; exports.USER_AGENT = USER_AGENT; exports.TERMINAL_ORDER_STATUSES = TERMINAL_ORDER_STATUSES; exports.AccountView = AccountView; exports.ComboPlayer = ComboPlayer; exports.ComboMaker = ComboMaker; exports.centsToDollars = centsToDollars; exports.toDollarString = toDollarString; exports.toQuantity = toQuantity; exports.convertMarketPayload = convertMarketPayload; exports.convertMarketsFrame = convertMarketsFrame; exports.convertBook = convertBook; exports.convertMarketChannelPayload = convertMarketChannelPayload; exports.SNAPSHOT_EVENTS = SNAPSHOT_EVENTS; exports.ChannelMessage = ChannelMessage; exports.ReconnectPolicy = ReconnectPolicy; exports.Channel = Channel; exports.STXWebSocket = STXWebSocket; exports.orderBody = orderBody; exports.STX = STX;
3747
- //# sourceMappingURL=chunk-R77AZ5UH.cjs.map
3775
+ exports.STXException = STXException; exports.STXConfigException = STXConfigException; exports.STXAPIException = STXAPIException; exports.STXValidationException = STXValidationException; exports.STXAuthenticationException = STXAuthenticationException; exports.STXForbiddenException = STXForbiddenException; exports.STXInvalidTokenException = STXInvalidTokenException; exports.STXInsufficientScopeException = STXInsufficientScopeException; exports.STXTermsRequiredException = STXTermsRequiredException; exports.STXIPNotAllowedException = STXIPNotAllowedException; exports.STXNotFoundException = STXNotFoundException; exports.STXRejectedException = STXRejectedException; exports.STXRateLimitException = STXRateLimitException; exports.STXServerException = STXServerException; exports.STXTransportException = STXTransportException; exports.STXChannelException = STXChannelException; exports.STXTimeoutException = STXTimeoutException; exports.notAvailableMessage = notAvailableMessage; exports.STXNotAvailableException = STXNotAvailableException; exports.STXCombosUnavailableException = STXCombosUnavailableException; exports.isEdgeBlock = isEdgeBlock; exports.STXComboRefusedException = STXComboRefusedException; exports.STXComboPriceMovedException = STXComboPriceMovedException; exports.errorForStatus = errorForStatus; exports.FEATURES = FEATURES; exports.Capabilities = Capabilities; exports.Region = Region; exports.Environment = Environment; exports.Environments = Environments; exports.HOSTS = HOSTS; exports.environmentNamed = environmentNamed; exports.resolveHost = resolveHost; exports.baseUrlFor = baseUrlFor; exports.socketUrlFor = socketUrlFor; exports.OPERATIONS = OPERATIONS; exports.Stats = Stats; exports.MAX_MARKETS_PER_REQUEST = MAX_MARKETS_PER_REQUEST; exports.isValidLine = isValidLine; exports.Page = Page; exports.RetryPolicy = RetryPolicy; exports.NO_RETRY = NO_RETRY; exports.resolveSettings = resolveSettings; exports.KEY_HEADER = KEY_HEADER; exports.TIMESTAMP_HEADER = TIMESTAMP_HEADER; exports.SIGNATURE_HEADER = SIGNATURE_HEADER; exports.buildMessage = buildMessage; exports.requestPath = requestPath; exports.handshakePath = handshakePath; exports.loadPrivateKey = loadPrivateKey; exports.signerFromPrivateKey = signerFromPrivateKey; exports.ApiKeyCredentials = ApiKeyCredentials; exports.VERSION = VERSION; exports.USER_AGENT = USER_AGENT; exports.TERMINAL_ORDER_STATUSES = TERMINAL_ORDER_STATUSES; exports.AccountView = AccountView; exports.ComboPlayer = ComboPlayer; exports.ComboMaker = ComboMaker; exports.centsToDollars = centsToDollars; exports.toDollarString = toDollarString; exports.toQuantity = toQuantity; exports.convertMarketPayload = convertMarketPayload; exports.convertMarketsFrame = convertMarketsFrame; exports.convertBook = convertBook; exports.convertMarketChannelPayload = convertMarketChannelPayload; exports.SNAPSHOT_EVENTS = SNAPSHOT_EVENTS; exports.ChannelMessage = ChannelMessage; exports.ReconnectPolicy = ReconnectPolicy; exports.Channel = Channel; exports.STXWebSocket = STXWebSocket; exports.orderBody = orderBody; exports.STX = STX;
3776
+ //# sourceMappingURL=chunk-42OCIF3G.cjs.map