@stxapp/stx-typescript 0.8.3 → 0.9.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,14 +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;// src/enums.ts
2
- var Region = {
3
- US: "us",
4
- ONTARIO: "ontario"
5
- };
6
- var Environment = {
7
- PRODUCTION: "production",
8
- DEMO: "demo"
9
- };
10
-
11
- // src/geo.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/geo.ts
12
2
  var IP_NOT_ALLOWED = /from this IP address (\S+?) is disallowed/i;
13
3
  function geoRejection(message) {
14
4
  const ip = IP_NOT_ALLOWED.exec(message);
@@ -68,6 +58,16 @@ var STXInvalidTokenException = class extends STXAuthenticationException {
68
58
  };
69
59
  var STXInsufficientScopeException = class extends STXForbiddenException {
70
60
  };
61
+ var STXTermsRequiredException = class extends STXForbiddenException {
62
+ /** The STX page where the member accepts the terms, when the answer names it. */
63
+
64
+ constructor(message, opts = {}) {
65
+ super(message, opts);
66
+ this.termsUrl = opts.termsUrl;
67
+ }
68
+ };
69
+ var STXIPNotAllowedException = class extends STXForbiddenException {
70
+ };
71
71
  var STXNotFoundException = class extends STXAPIException {
72
72
  };
73
73
  var STXRejectedException = class extends STXAPIException {
@@ -114,8 +114,69 @@ var STXChannelException = class extends STXException {
114
114
  };
115
115
  var STXTimeoutException = class extends STXChannelException {
116
116
  };
117
- var STXCombosUnavailableException = class extends STXChannelException {
117
+ var NOT_AVAILABLE = /* @__PURE__ */ Symbol.for("@stxapp/stx-typescript.notAvailable");
118
+ var FEATURE_PHRASES = {
119
+ oauth: "OAuth is",
120
+ "oauth.member": "Member sign-in with OAuth is",
121
+ "oauth.app": "App tokens are",
122
+ connect: "Sign in with STX is",
123
+ "terms.stx_page": "Accepting terms on an STX page is",
124
+ "markets.create": "Creating markets is",
125
+ market_types: "Market types are",
126
+ event_players: "Event players are",
127
+ leaderboard: "The leaderboard is",
128
+ combos: "Combos are"
129
+ };
130
+ function notAvailableMessage(feature, host) {
131
+ const phrase = feature.startsWith("scope:") ? `The ${feature.slice("scope:".length)} scope is` : _nullishCoalesce(FEATURE_PHRASES[feature], () => ( `${feature} is`));
132
+ return `${phrase} not available on ${host} yet.`;
133
+ }
134
+ var STXNotAvailableException = class _STXNotAvailableException extends STXAPIException {
135
+ /** The feature id, e.g. `"combos"`. */
136
+
137
+ /** The exchange host that lacks it, e.g. `"demo.stxapp.ca"`. */
138
+
139
+ constructor(feature, host, opts = {}) {
140
+ super(_nullishCoalesce(opts.message, () => ( notAvailableMessage(feature, host))), opts);
141
+ this.feature = feature;
142
+ this.host = host;
143
+ markNotAvailable(this);
144
+ }
145
+ // `this` is the class on the right of `instanceof`: a subclass keeps the
146
+ // ordinary check, only the base class also accepts marked exceptions.
147
+ static [Symbol.hasInstance](value) {
148
+ const cls = this;
149
+ if (Function.prototype[Symbol.hasInstance].call(cls, value)) return true;
150
+ return cls === _STXNotAvailableException && typeof value === "object" && value !== null && value[NOT_AVAILABLE] === true;
151
+ }
118
152
  };
153
+ function markNotAvailable(err) {
154
+ Object.defineProperty(err, NOT_AVAILABLE, { value: true, enumerable: false });
155
+ }
156
+ var STXCombosUnavailableException = (_class = class extends STXChannelException {
157
+ __init() {this.feature = "combos"}
158
+ /** The exchange host that lacks combos. */
159
+
160
+ constructor(message, opts = {}) {
161
+ super(message, opts);_class.prototype.__init.call(this);;
162
+ this.host = _nullishCoalesce(opts.host, () => ( ""));
163
+ markNotAvailable(this);
164
+ }
165
+ }, _class);
166
+ function isMissingRoute(err) {
167
+ if (!(err instanceof STXNotFoundException)) return false;
168
+ const body = err.body;
169
+ return !!body && typeof body === "object" && body.error === "not_found" && Object.keys(body).length === 1;
170
+ }
171
+ function isEdgeBlock(status, text) {
172
+ if (status !== 403) return false;
173
+ try {
174
+ JSON.parse(text);
175
+ return false;
176
+ } catch (e2) {
177
+ return true;
178
+ }
179
+ }
119
180
  var STXComboRefusedException = class extends STXChannelException {
120
181
 
121
182
 
@@ -150,6 +211,16 @@ function errorForStatus(statusCode, body, opts) {
150
211
  case 401:
151
212
  return bearerError(opts.wwwAuthenticate) === "invalid_token" ? new STXInvalidTokenException(message, base) : new STXAuthenticationException(message, base);
152
213
  case 403: {
214
+ const fields = body && typeof body === "object" ? body : {};
215
+ if (fields.error === "ip_not_allowed") {
216
+ const description = typeof fields.error_description === "string" ? fields.error_description : message;
217
+ return new STXIPNotAllowedException(description, base);
218
+ }
219
+ if (fields.error === "terms_required") {
220
+ const description = typeof fields.error_description === "string" ? fields.error_description : message;
221
+ const termsUrl = typeof fields.terms_url === "string" ? fields.terms_url : void 0;
222
+ return new STXTermsRequiredException(description, { ...base, termsUrl });
223
+ }
153
224
  if (bearerError(opts.wwwAuthenticate) === "insufficient_scope" || /insufficient scope/i.test(message)) {
154
225
  return new STXInsufficientScopeException(message, {
155
226
  ...base,
@@ -188,6 +259,147 @@ function insufficientScopes(header, body) {
188
259
  return raw ? raw.split(/\s+/).filter(Boolean) : [];
189
260
  }
190
261
 
262
+ // src/capabilities.ts
263
+ var FEATURES = [
264
+ "oauth",
265
+ "oauth.member",
266
+ "oauth.app",
267
+ "connect",
268
+ "terms.stx_page",
269
+ "markets.create",
270
+ "market_types",
271
+ "event_players",
272
+ "leaderboard",
273
+ "combos"
274
+ ];
275
+ var MEMBER_SCOPES = [
276
+ "profile.read",
277
+ "balance.read",
278
+ "portfolio.read",
279
+ "orders.read",
280
+ "transfers.read",
281
+ "orders.write"
282
+ ];
283
+ var Capabilities = class {
284
+ /** The exchange host, e.g. `"demo.stxapp.io"`. */
285
+
286
+ /** `GET /api_version`, e.g. `"3.3.196-rnd.9"`, or null when it did not answer. */
287
+
288
+ /** When the checks ran. */
289
+
290
+ /** The scopes the exchange's OAuth discovery document lists; empty without OAuth. */
291
+
292
+ /** Every feature and whether the exchange has it. */
293
+
294
+ constructor(init) {
295
+ this.host = init.host;
296
+ this.apiVersion = init.apiVersion;
297
+ this.checkedAt = init.checkedAt;
298
+ this.scopesSupported = init.scopesSupported;
299
+ this.features = init.features;
300
+ }
301
+ /** True only when the exchange is known to have `feature`. */
302
+ has(feature) {
303
+ return this.features[feature] === true;
304
+ }
305
+ /**
306
+ * Throw `STXNotAvailableException` unless the exchange is known to have
307
+ * `feature`. A feature that could not be checked (`null`) does not throw:
308
+ * the call itself will say.
309
+ */
310
+ require(feature) {
311
+ if (this.features[feature] === false) throw new STXNotAvailableException(feature, this.host);
312
+ }
313
+ toJSON() {
314
+ return {
315
+ host: this.host,
316
+ apiVersion: this.apiVersion,
317
+ checkedAt: this.checkedAt.toISOString(),
318
+ scopesSupported: this.scopesSupported,
319
+ features: this.features
320
+ };
321
+ }
322
+ };
323
+ var NOBODY = "00000000-0000-0000-0000-000000000000";
324
+ function json(answer) {
325
+ if (!answer) return null;
326
+ try {
327
+ const parsed = JSON.parse(answer.text);
328
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
329
+ } catch (e3) {
330
+ return null;
331
+ }
332
+ }
333
+ function strings(value) {
334
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
335
+ }
336
+ function missingRoute(answer) {
337
+ if (!answer || answer.status !== 404) return false;
338
+ const body = json(answer);
339
+ return !!body && body.error === "not_found" && Object.keys(body).length === 1;
340
+ }
341
+ function oauthMetadataFrom(answer) {
342
+ if (!answer) return null;
343
+ const body = json(answer);
344
+ if (answer.status === 404) return false;
345
+ if (answer.status === 403 && !body) return false;
346
+ if (answer.status !== 200 || !body) return null;
347
+ if (typeof body.issuer !== "string" || typeof body.authorization_endpoint !== "string" || typeof body.token_endpoint !== "string") {
348
+ return null;
349
+ }
350
+ return body;
351
+ }
352
+ async function discoverCapabilities(probes) {
353
+ const swallow = (p) => p ? p.catch(() => null) : Promise.resolve(null);
354
+ const [version, discovery, types, players, board, combos] = await Promise.all([
355
+ swallow(probes.get("/api_version")),
356
+ swallow(probes.get("/.well-known/oauth-authorization-server")),
357
+ swallow(probes.signedGet("/api/v1/types")),
358
+ swallow(probes.signedGet(`/api/v1/events/${NOBODY}/players`)),
359
+ swallow(probes.signedGet("/api/v1/leaderboard?limit=1")),
360
+ swallow(probes.joinReason(`rfq:${NOBODY}`))
361
+ ]);
362
+ const apiVersion = _optionalChain([json, 'call', _5 => _5(version), 'optionalAccess', _6 => _6.api_version]);
363
+ const meta = oauthMetadataFrom(discovery);
364
+ const scopes = meta ? strings(meta.scopes_supported) : [];
365
+ const grants = meta ? strings(meta.grant_types_supported) : [];
366
+ const fromMeta = (decide) => meta === null ? null : meta === false ? false : decide();
367
+ const oauth = fromMeta(() => true);
368
+ const member = fromMeta(() => grants.includes("authorization_code") && scopes.some((s) => MEMBER_SCOPES.includes(s)));
369
+ const app = fromMeta(() => grants.includes("client_credentials"));
370
+ const features = {
371
+ oauth,
372
+ "oauth.member": member,
373
+ "oauth.app": app,
374
+ connect: fromMeta(() => scopes.includes("openid")),
375
+ "terms.stx_page": fromMeta(() => member === true && !scopes.includes("terms.write")),
376
+ "markets.create": fromMeta(() => app === true && scopes.includes("markets.write")),
377
+ market_types: types === null ? null : types.status >= 200 && types.status < 300 ? true : missingRoute(types) ? false : null,
378
+ // A 404 about the event (not about the route) means the route is there.
379
+ event_players: players === null ? null : missingRoute(players) ? false : players.status === 404 || players.status < 300 ? true : null,
380
+ // Switched off answers 404 too ("Leaderboard is not enabled").
381
+ leaderboard: board === null ? null : board.status >= 200 && board.status < 300 ? true : board.status === 404 ? false : null,
382
+ combos: combos === null ? null : combos !== "unmatched topic"
383
+ };
384
+ return new Capabilities({
385
+ host: probes.host,
386
+ apiVersion: typeof apiVersion === "string" ? apiVersion : null,
387
+ checkedAt: /* @__PURE__ */ new Date(),
388
+ scopesSupported: scopes,
389
+ features
390
+ });
391
+ }
392
+
393
+ // src/enums.ts
394
+ var Region = {
395
+ US: "us",
396
+ ONTARIO: "ontario"
397
+ };
398
+ var Environment = {
399
+ PRODUCTION: "production",
400
+ DEMO: "demo"
401
+ };
402
+
191
403
  // src/config.ts
192
404
  var Environments = {
193
405
  /** United States demo. Shared by every integrator. No real money. */
@@ -269,7 +481,7 @@ function baseUrlFor(region, env, host) {
269
481
  let parsed;
270
482
  try {
271
483
  parsed = new URL(h);
272
- } catch (e2) {
484
+ } catch (e4) {
273
485
  throw new STXConfigException(`Cannot parse host ${JSON.stringify(h)}.`);
274
486
  }
275
487
  return `${parsed.protocol}//${parsed.host}`;
@@ -571,6 +783,17 @@ var OPERATIONS = {
571
783
  model: "",
572
784
  isList: false,
573
785
  paginated: false
786
+ },
787
+ types_get: {
788
+ method: "GET",
789
+ path: "/api/v1/types",
790
+ query: [],
791
+ pathParams: [],
792
+ hasBody: false,
793
+ responseKey: "",
794
+ model: "",
795
+ isList: false,
796
+ paginated: false
574
797
  }
575
798
  };
576
799
 
@@ -792,7 +1015,7 @@ function parseIni(text) {
792
1015
  function readProfile(profileName, path) {
793
1016
  try {
794
1017
  if (!_fs.statSync.call(void 0, path).isFile()) return [{}, false];
795
- } catch (e3) {
1018
+ } catch (e5) {
796
1019
  return [{}, false];
797
1020
  }
798
1021
  let sections;
@@ -812,7 +1035,7 @@ function readProfile(profileName, path) {
812
1035
  }
813
1036
  function processEnv() {
814
1037
  const p = globalThis.process;
815
- return _nullishCoalesce(_optionalChain([p, 'optionalAccess', _5 => _5.env]), () => ( {}));
1038
+ return _nullishCoalesce(_optionalChain([p, 'optionalAccess', _7 => _7.env]), () => ( {}));
816
1039
  }
817
1040
  function resolveSettings(input = {}) {
818
1041
  const environ = _nullishCoalesce(input.environ, () => ( processEnv()));
@@ -886,7 +1109,7 @@ function loadPrivateKey(value) {
886
1109
  let isFile = false;
887
1110
  try {
888
1111
  isFile = _fs.statSync.call(void 0, path).isFile();
889
- } catch (e4) {
1112
+ } catch (e6) {
890
1113
  isFile = false;
891
1114
  }
892
1115
  if (!isFile) {
@@ -904,7 +1127,7 @@ function loadPrivateKey(value) {
904
1127
  let key;
905
1128
  try {
906
1129
  key = _crypto.createPrivateKey.call(void 0, { key: Buffer.from(pem), format: "pem" });
907
- } catch (e5) {
1130
+ } catch (e7) {
908
1131
  throw new STXConfigException(
909
1132
  "Private key is not valid PEM. Expected a PKCS#8 block beginning '-----BEGIN PRIVATE KEY-----'."
910
1133
  );
@@ -921,11 +1144,11 @@ function signerFromPrivateKey(value) {
921
1144
  const key = loadPrivateKey(value);
922
1145
  return (message) => new Uint8Array(_crypto.sign.call(void 0, null, message, key));
923
1146
  }
924
- var ApiKeyCredentials = (_class = class {
925
- __init() {this.kind = "api_key"}
1147
+ var ApiKeyCredentials = (_class2 = class {
1148
+ __init2() {this.kind = "api_key"}
926
1149
 
927
1150
  #sign;
928
- constructor(keyId, privateKey, opts = {}) {;_class.prototype.__init.call(this);
1151
+ constructor(keyId, privateKey, opts = {}) {;_class2.prototype.__init2.call(this);
929
1152
  if (!keyId || !String(keyId).trim()) throw new STXConfigException("API key id is required.");
930
1153
  const signer = opts.signer;
931
1154
  if (!signer && (privateKey === void 0 || privateKey === null)) {
@@ -968,7 +1191,7 @@ var ApiKeyCredentials = (_class = class {
968
1191
  [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
969
1192
  return this.toString();
970
1193
  }
971
- }, _class);
1194
+ }, _class2);
972
1195
  function credentialsFromSettings(keyId, privateKey, signer) {
973
1196
  const hasMaterial = privateKey !== void 0 && privateKey !== null || signer !== void 0;
974
1197
  if (!keyId && !hasMaterial) return void 0;
@@ -986,7 +1209,7 @@ function credentialsFromSettings(keyId, privateKey, signer) {
986
1209
  }
987
1210
 
988
1211
  // src/version.ts
989
- var VERSION = "0.8.3";
1212
+ var VERSION = "0.9.0";
990
1213
  var USER_AGENT = `stx-typescript/${VERSION}`;
991
1214
  var ASYNC_DISPOSE = _nullishCoalesce(Symbol.asyncDispose, () => ( /* @__PURE__ */ Symbol.for("Symbol.asyncDispose")));
992
1215
 
@@ -1005,13 +1228,13 @@ function stamp(item) {
1005
1228
  const t = Date.parse(String(_nullishCoalesce(_nullishCoalesce(item.time, () => ( item.inserted_at)), () => ( ""))));
1006
1229
  return Number.isNaN(t) ? 0 : t * 1e3;
1007
1230
  }
1008
- var AccountView = (_class2 = class {
1231
+ var AccountView = (_class3 = class {
1009
1232
 
1010
1233
 
1011
1234
  /** The joined channels, by name. */
1012
- __init2() {this.channels = {}}
1235
+ __init3() {this.channels = {}}
1013
1236
  /** Join snapshots applied so far, per channel: 1 after the first seed, more after reconnects. */
1014
- __init3() {this.seeds = { balances: 0, orders: 0, fills: 0, positions: 0 }}
1237
+ __init4() {this.seeds = { balances: 0, orders: 0, fills: 0, positions: 0 }}
1015
1238
  #balance = null;
1016
1239
  #orders = /* @__PURE__ */ new Map();
1017
1240
  #fills = /* @__PURE__ */ new Map();
@@ -1020,7 +1243,7 @@ var AccountView = (_class2 = class {
1020
1243
  #maxFills;
1021
1244
  #closed = false;
1022
1245
  /** @internal Use `ws.accountView()`. */
1023
- constructor(ws, opts = {}) {;_class2.prototype.__init2.call(this);_class2.prototype.__init3.call(this);
1246
+ constructor(ws, opts = {}) {;_class3.prototype.__init3.call(this);_class3.prototype.__init4.call(this);
1024
1247
  this.ws = ws;
1025
1248
  this.onChange = opts.onChange;
1026
1249
  this.#keepFlat = _nullishCoalesce(opts.keepFlatPositions, () => ( false));
@@ -1118,7 +1341,7 @@ var AccountView = (_class2 = class {
1118
1341
  case "all_orders":
1119
1342
  this.seeds.orders = (_nullishCoalesce(this.seeds.orders, () => ( 0))) + 1;
1120
1343
  this.#orders.clear();
1121
- for (const o of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _6 => _6.orders]), () => ( []))) this.#upsertOrder(o);
1344
+ for (const o of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _8 => _8.orders]), () => ( []))) this.#upsertOrder(o);
1122
1345
  return change("orders", true);
1123
1346
  case "new_open_order":
1124
1347
  this.#upsertOrder(payload);
@@ -1126,7 +1349,7 @@ var AccountView = (_class2 = class {
1126
1349
  case "all_trades":
1127
1350
  this.seeds.fills = (_nullishCoalesce(this.seeds.fills, () => ( 0))) + 1;
1128
1351
  this.#fills.clear();
1129
- for (const t of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _7 => _7.trades]), () => ( []))) this.#upsertFill(t);
1352
+ for (const t of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _9 => _9.trades]), () => ( []))) this.#upsertFill(t);
1130
1353
  return change("fills", true);
1131
1354
  case "trade":
1132
1355
  this.#upsertFill(payload);
@@ -1134,22 +1357,22 @@ var AccountView = (_class2 = class {
1134
1357
  case "all_positions":
1135
1358
  this.seeds.positions = (_nullishCoalesce(this.seeds.positions, () => ( 0))) + 1;
1136
1359
  this.#positions.clear();
1137
- for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _8 => _8.positions]), () => ( []))) this.#upsertPosition(p);
1360
+ for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _10 => _10.positions]), () => ( []))) this.#upsertPosition(p);
1138
1361
  return change("positions", true);
1139
1362
  case "updated_positions":
1140
- for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _9 => _9.positions]), () => ( []))) this.#upsertPosition(p);
1363
+ for (const p of _nullishCoalesce(_optionalChain([payload, 'optionalAccess', _11 => _11.positions]), () => ( []))) this.#upsertPosition(p);
1141
1364
  return change("positions", false);
1142
1365
  default:
1143
1366
  return void 0;
1144
1367
  }
1145
1368
  }
1146
1369
  #upsertOrder(order) {
1147
- if (!_optionalChain([order, 'optionalAccess', _10 => _10.id])) return;
1370
+ if (!_optionalChain([order, 'optionalAccess', _12 => _12.id])) return;
1148
1371
  if (TERMINAL_ORDER_STATUSES.has(String(order.status))) this.#orders.delete(order.id);
1149
1372
  else this.#orders.set(order.id, order);
1150
1373
  }
1151
1374
  #upsertFill(fill) {
1152
- if (!_optionalChain([fill, 'optionalAccess', _11 => _11.id])) return;
1375
+ if (!_optionalChain([fill, 'optionalAccess', _13 => _13.id])) return;
1153
1376
  this.#fills.delete(fill.id);
1154
1377
  this.#fills.set(fill.id, fill);
1155
1378
  if (this.#fills.size > this.#maxFills) {
@@ -1158,7 +1381,7 @@ var AccountView = (_class2 = class {
1158
1381
  }
1159
1382
  }
1160
1383
  #upsertPosition(position) {
1161
- const key = _nullishCoalesce(_optionalChain([position, 'optionalAccess', _12 => _12.market_id]), () => ( _optionalChain([position, 'optionalAccess', _13 => _13.id])));
1384
+ const key = _nullishCoalesce(_optionalChain([position, 'optionalAccess', _14 => _14.market_id]), () => ( _optionalChain([position, 'optionalAccess', _15 => _15.id])));
1162
1385
  if (!key) return;
1163
1386
  if (!this.#keepFlat && isZero(position.position)) this.#positions.delete(key);
1164
1387
  else this.#positions.set(key, position);
@@ -1171,7 +1394,7 @@ var AccountView = (_class2 = class {
1171
1394
  CHANNELS.map((name) => this.channels[name]).filter((c) => c !== void 0 && !c.closed).map((c) => c.leave())
1172
1395
  );
1173
1396
  }
1174
- }, _class2);
1397
+ }, _class3);
1175
1398
 
1176
1399
  // src/combos.ts
1177
1400
  var COMBO_PLAYER_CHANNEL = "rfq";
@@ -1187,13 +1410,14 @@ var MAKER_EVENTS = /* @__PURE__ */ new Set([
1187
1410
  "placed",
1188
1411
  "negotiation_closed"
1189
1412
  ]);
1190
- function comboRefusal(command, topic, response) {
1413
+ function comboRefusal(command, topic, response, host = "") {
1191
1414
  const reply = response && typeof response === "object" ? response : {};
1192
1415
  const reason = typeof reply.reason === "string" ? reply.reason : void 0;
1193
1416
  if (reason === UNAVAILABLE_REASON) {
1194
- return new STXCombosUnavailableException("Combos are not available on this environment.", {
1417
+ return new STXCombosUnavailableException(notAvailableMessage("combos", host || "this exchange"), {
1195
1418
  topic,
1196
- reply: response
1419
+ reply: response,
1420
+ host
1197
1421
  });
1198
1422
  }
1199
1423
  if (reason === void 0) {
@@ -1226,10 +1450,10 @@ function comboRefusal(command, topic, response) {
1226
1450
  }
1227
1451
  return new STXComboRefusedException(message, { topic, reply: response, command, code, detail });
1228
1452
  }
1229
- function comboJoinError(err) {
1453
+ function comboJoinError(err, host = "") {
1230
1454
  if (err instanceof STXChannelException && !(err instanceof STXCombosUnavailableException) && err.reply !== void 0) {
1231
1455
  if (err.constructor !== STXChannelException) return err;
1232
- return comboRefusal("phx_join", err.topic, err.reply);
1456
+ return comboRefusal("phx_join", err.topic, err.reply, host);
1233
1457
  }
1234
1458
  return err;
1235
1459
  }
@@ -1340,7 +1564,16 @@ var ComboSession = class {
1340
1564
  this.#waiters.push(waiter);
1341
1565
  });
1342
1566
  }
1343
- /** Leave the topic. Requests opened and quotes placed on this channel end, as on any close. */
1567
+ /**
1568
+ * Leave the topic. Requests opened and quotes placed on this channel end
1569
+ * (`cancelled`), as on any close, and delivery on this channel stops when
1570
+ * `leave()` resolves: the exchange's `negotiation_closed` for those requests
1571
+ * arrives after the channel has closed and is not passed to `onEvent` or to
1572
+ * an iterator. Treat every request still open here as cancelled once
1573
+ * `leave()` resolves. To see each request's own close first, `cancel()` it
1574
+ * and wait for its `negotiation_closed` before leaving. Other connections of
1575
+ * the same member still receive the close.
1576
+ */
1344
1577
  leave() {
1345
1578
  return this.channel.leave();
1346
1579
  }
@@ -1595,7 +1828,7 @@ function buildRequest(operationId, args = {}) {
1595
1828
  const op = OPERATIONS[operationId];
1596
1829
  let path = op.path;
1597
1830
  for (const name of op.pathParams) {
1598
- const value = _optionalChain([args, 'access', _14 => _14.pathParams, 'optionalAccess', _15 => _15[name]]);
1831
+ const value = _optionalChain([args, 'access', _16 => _16.pathParams, 'optionalAccess', _17 => _17[name]]);
1599
1832
  if (!value) throw new TypeError(`${name} is required`);
1600
1833
  path = path.replace(`{${name}}`, quote(String(value)));
1601
1834
  }
@@ -1618,7 +1851,7 @@ function decodeResponse(request, status, text, headers = {}) {
1618
1851
  let body;
1619
1852
  try {
1620
1853
  body = text ? JSON.parse(text) : null;
1621
- } catch (e6) {
1854
+ } catch (e8) {
1622
1855
  body = text;
1623
1856
  }
1624
1857
  if (status >= 200 && status < 300) {
@@ -1649,7 +1882,7 @@ function toBatchOrderResult(raw) {
1649
1882
  const obj = raw && typeof raw === "object" ? raw : {};
1650
1883
  const order = _nullishCoalesce(obj.order, () => ( null));
1651
1884
  const errors = Array.isArray(obj.errors) ? obj.errors : null;
1652
- return { ...obj, order, errors, ok: order !== null && !_optionalChain([errors, 'optionalAccess', _16 => _16.length]) };
1885
+ return { ...obj, order, errors, ok: order !== null && !_optionalChain([errors, 'optionalAccess', _18 => _18.length]) };
1653
1886
  }
1654
1887
 
1655
1888
  // src/client.ts
@@ -1713,7 +1946,16 @@ function ids(value) {
1713
1946
  return typeof value === "string" ? [value] : [...value];
1714
1947
  }
1715
1948
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1716
- var STX = (_class3 = class _STX {
1949
+ var GATED_OPERATIONS = {
1950
+ types_get: "market_types",
1951
+ events__id_players_get: "event_players",
1952
+ markets_post: "markets.create",
1953
+ leaderboard_get: "leaderboard",
1954
+ leaderboard_me_get: "leaderboard",
1955
+ me_profile_patch: "leaderboard"
1956
+ };
1957
+ var LEADERBOARD_OFF = "Leaderboard is not enabled";
1958
+ var STX = (_class4 = class _STX {
1717
1959
 
1718
1960
 
1719
1961
 
@@ -1728,9 +1970,10 @@ var STX = (_class3 = class _STX {
1728
1970
 
1729
1971
  #fetch;
1730
1972
  #me;
1973
+ #capabilities;
1731
1974
  /** Test hook: how retries wait. */
1732
- __init4() {this._sleep = sleep}
1733
- constructor(opts = {}) {;_class3.prototype.__init4.call(this);
1975
+ __init5() {this._sleep = sleep}
1976
+ constructor(opts = {}) {;_class4.prototype.__init5.call(this);
1734
1977
  if (opts.auth && (opts.keyId || opts.privateKey || opts.signer)) {
1735
1978
  throw new STXConfigException("Pass `auth` or an API key (keyId with privateKey or signer), not both.");
1736
1979
  }
@@ -1779,7 +2022,75 @@ var STX = (_class3 = class _STX {
1779
2022
  this.#fetch = fetchImpl;
1780
2023
  }
1781
2024
  toString() {
1782
- return `STX(baseUrl=${JSON.stringify(this.baseUrl)}, keyId=${JSON.stringify(_nullishCoalesce(_optionalChain([this, 'access', _17 => _17.credentials, 'optionalAccess', _18 => _18.keyId]), () => ( null)))})`;
2025
+ return `STX(baseUrl=${JSON.stringify(this.baseUrl)}, keyId=${JSON.stringify(_nullishCoalesce(_optionalChain([this, 'access', _19 => _19.credentials, 'optionalAccess', _20 => _20.keyId]), () => ( null)))})`;
2026
+ }
2027
+ /** The exchange host, e.g. `"demo.stxapp.io"`: the name `STXNotAvailableException` and `capabilities()` report. */
2028
+ get host() {
2029
+ return new URL(this.baseUrl).host;
2030
+ }
2031
+ // ------------------------------------------------------------------
2032
+ // Capabilities
2033
+ // ------------------------------------------------------------------
2034
+ /**
2035
+ * Which features this exchange has, from what it publishes: its OAuth
2036
+ * discovery document, `/api_version`, a signed GET of the routes that not
2037
+ * every exchange has yet, and a join of a combos topic nobody owns. Nothing
2038
+ * is created or changed. Checked once per client and cached; pass
2039
+ * `{ refresh: true }` to check again.
2040
+ *
2041
+ * const caps = await stx.capabilities();
2042
+ * caps.features.combos; // false on demo.stxapp.ca
2043
+ * caps.require("combos"); // throws STXNotAvailableException there
2044
+ *
2045
+ * Each feature is `true`, `false`, or `null` when it could not be checked
2046
+ * (no credentials for a signed check, or no answer). A missing feature never
2047
+ * throws here; the call that needs it throws `STXNotAvailableException`.
2048
+ */
2049
+ capabilities(opts = {}) {
2050
+ if (opts.refresh || !this.#capabilities) {
2051
+ const run = discoverCapabilities({
2052
+ host: this.host,
2053
+ get: (path) => this.#rawGet(path, false),
2054
+ signedGet: (path) => this.auth ? this.#rawGet(path, true) : null,
2055
+ joinReason: (topic) => this.#joinReason(topic)
2056
+ });
2057
+ this.#capabilities = run;
2058
+ run.catch(() => {
2059
+ if (this.#capabilities === run) this.#capabilities = void 0;
2060
+ });
2061
+ }
2062
+ return this.#capabilities;
2063
+ }
2064
+ async #rawGet(path, signed) {
2065
+ const headers = { "User-Agent": USER_AGENT, Accept: "application/json" };
2066
+ if (signed && this.auth) Object.assign(headers, await this.auth.authHeaders({ method: "GET", path }));
2067
+ const controller = new AbortController();
2068
+ const timer = setTimeout(() => controller.abort(), Math.min(this.timeoutMs, 15e3));
2069
+ try {
2070
+ const res = await this.#fetch(this.baseUrl + path, { method: "GET", headers, signal: controller.signal });
2071
+ return { status: res.status, text: await res.text() };
2072
+ } catch (e9) {
2073
+ return null;
2074
+ } finally {
2075
+ clearTimeout(timer);
2076
+ }
2077
+ }
2078
+ async #joinReason(topic) {
2079
+ if (!this.auth) return null;
2080
+ const ws = this.websocket({ reconnect: false, joinTimeoutMs: 8e3 });
2081
+ try {
2082
+ const channel = await ws.join(topic);
2083
+ await channel.leave().catch(() => {
2084
+ });
2085
+ return "ok";
2086
+ } catch (err) {
2087
+ if (err instanceof STXTimeoutException) return null;
2088
+ if (err instanceof STXChannelException) return _nullishCoalesce(err.reason, () => ( null));
2089
+ return null;
2090
+ } finally {
2091
+ await ws.close().catch(() => {
2092
+ });
2093
+ }
1783
2094
  }
1784
2095
  /** Nothing to release (fetch pools connections itself); present so `await using` and explicit cleanup work. */
1785
2096
  async close() {
@@ -1814,11 +2125,11 @@ var STX = (_class3 = class _STX {
1814
2125
  status,
1815
2126
  attempt,
1816
2127
  durationMs: Date.now() - started,
1817
- authKind: _optionalChain([this, 'access', _19 => _19.auth, 'optionalAccess', _20 => _20.kind]),
2128
+ authKind: _optionalChain([this, 'access', _21 => _21.auth, 'optionalAccess', _22 => _22.kind]),
1818
2129
  requestBody: request.body,
1819
2130
  responseBody
1820
2131
  });
1821
- } catch (e7) {
2132
+ } catch (e10) {
1822
2133
  }
1823
2134
  }
1824
2135
  async #sendOnce(request, attempt = 1) {
@@ -1846,7 +2157,7 @@ var STX = (_class3 = class _STX {
1846
2157
  });
1847
2158
  }
1848
2159
  throw new STXTransportException(
1849
- `${request.method} ${request.path} failed: ${_nullishCoalesce(_optionalChain([err, 'optionalAccess', _21 => _21.message]), () => ( String(err)))}`,
2160
+ `${request.method} ${request.path} failed: ${_nullishCoalesce(_optionalChain([err, 'optionalAccess', _23 => _23.message]), () => ( String(err)))}`,
1850
2161
  { method: request.method, path: request.path, cause: err }
1851
2162
  );
1852
2163
  } finally {
@@ -1868,7 +2179,7 @@ var STX = (_class3 = class _STX {
1868
2179
  return await this.#sendOnce(request, sent);
1869
2180
  } catch (err) {
1870
2181
  if (!(err instanceof STXException)) throw err;
1871
- if (err.statusCode === 401 && !reauthenticated && _optionalChain([this, 'access', _22 => _22.auth, 'optionalAccess', _23 => _23.onUnauthorized])) {
2182
+ if (err.statusCode === 401 && !reauthenticated && _optionalChain([this, 'access', _24 => _24.auth, 'optionalAccess', _25 => _25.onUnauthorized])) {
1872
2183
  reauthenticated = true;
1873
2184
  if (await this.auth.onUnauthorized()) continue;
1874
2185
  }
@@ -1879,7 +2190,22 @@ var STX = (_class3 = class _STX {
1879
2190
  }
1880
2191
  }
1881
2192
  async #call(operationId, args = {}) {
1882
- return this.#send(buildRequest(operationId, args));
2193
+ try {
2194
+ return await this.#send(buildRequest(operationId, args));
2195
+ } catch (err) {
2196
+ 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;
2198
+ if (feature && (isMissingRoute(err) || off)) {
2199
+ throw new STXNotAvailableException(feature, this.host, {
2200
+ statusCode: err.statusCode,
2201
+ body: err.body,
2202
+ method: err.method,
2203
+ path: err.path,
2204
+ cause: err
2205
+ });
2206
+ }
2207
+ throw err;
2208
+ }
1883
2209
  }
1884
2210
  async #one(operationId, args = {}) {
1885
2211
  const body = await this.#call(operationId, args);
@@ -1904,7 +2230,7 @@ var STX = (_class3 = class _STX {
1904
2230
  }
1905
2231
  }
1906
2232
  async #geoBody(body, opts) {
1907
- const packet = _optionalChain([opts, 'optionalAccess', _24 => _24.geoLocation]) !== void 0 ? _nullishCoalesce(opts.geoLocation, () => ( void 0)) : await resolveGeoLocation(this.geoLocation);
2233
+ const packet = _optionalChain([opts, 'optionalAccess', _28 => _28.geoLocation]) !== void 0 ? _nullishCoalesce(opts.geoLocation, () => ( void 0)) : await resolveGeoLocation(this.geoLocation);
1908
2234
  return packet === void 0 ? body : { ...body, geo_location: packet };
1909
2235
  }
1910
2236
  // ------------------------------------------------------------------
@@ -1925,7 +2251,7 @@ var STX = (_class3 = class _STX {
1925
2251
  * `user_id`.
1926
2252
  */
1927
2253
  async userId() {
1928
- if (_optionalChain([this, 'access', _25 => _25.#me, 'optionalAccess', _26 => _26.user_id])) return this.#me.user_id;
2254
+ if (_optionalChain([this, 'access', _29 => _29.#me, 'optionalAccess', _30 => _30.user_id])) return this.#me.user_id;
1929
2255
  try {
1930
2256
  await this.me();
1931
2257
  } catch (err) {
@@ -1936,7 +2262,7 @@ var STX = (_class3 = class _STX {
1936
2262
  if (!balance.user_id) throw err;
1937
2263
  this.#me = { ..._nullishCoalesce(this.#me, () => ( {})), user_id: balance.user_id };
1938
2264
  }
1939
- if (!_optionalChain([this, 'access', _27 => _27.#me, 'optionalAccess', _28 => _28.user_id])) throw new STXException("GET /api/v1/me returned no user_id");
2265
+ if (!_optionalChain([this, 'access', _31 => _31.#me, 'optionalAccess', _32 => _32.user_id])) throw new STXException("GET /api/v1/me returned no user_id");
1940
2266
  return this.#me.user_id;
1941
2267
  }
1942
2268
  // ------------------------------------------------------------------
@@ -2015,9 +2341,21 @@ var STX = (_class3 = class _STX {
2015
2341
  return (await this.eventPlayers(eventId)).stats;
2016
2342
  }
2017
2343
  /**
2018
- * `POST /api/v1/markets`: create player-prop markets on a scheduled event,
2019
- * up to `MAX_MARKETS_PER_REQUEST` per call. Needs an OAuth app token with
2020
- * `markets.write`, which STX grants, from the client's IP allow-list.
2344
+ * `GET /api/v1/types`: the market types, keyed by rule. One with
2345
+ * `partner_create: true` can be created with `createMarkets()`, and lists
2346
+ * the `fields` an entry takes and, per event type, the `stats` on offer. It
2347
+ * changes only when STX adds a rule or a stat, so read it once and keep it.
2348
+ * Needs an OAuth app token with `events`, or an API key.
2349
+ */
2350
+ marketTypes() {
2351
+ return this.#one("types_get");
2352
+ }
2353
+ /**
2354
+ * `POST /api/v1/markets`: create markets on a scheduled event, up to
2355
+ * `MAX_MARKETS_PER_REQUEST` per call. Each market names its `rule` and the
2356
+ * fields that rule takes. Needs an OAuth app token with `markets.write`,
2357
+ * which STX grants, from an address on the client's IP allow-list (it
2358
+ * applies to every call that client makes).
2021
2359
  *
2022
2360
  * Returns one result per market, in order: `created` or `exists` (both with
2023
2361
  * `market_id`), `valid` with `dryRun`, or `rejected` with a `reason`. Each
@@ -2284,9 +2622,41 @@ var STX = (_class3 = class _STX {
2284
2622
  return this.#iterate("portfolio_loyalty_get", { limit: query.limit });
2285
2623
  }
2286
2624
  // ------------------------------------------------------------------
2625
+ // Leaderboard and public profile
2626
+ // ------------------------------------------------------------------
2627
+ /**
2628
+ * `GET /api/v1/leaderboard`: ranked members for a period, sport and metric.
2629
+ * Rows carry a public handle and avatar, never an account id. Throws
2630
+ * `STXNotAvailableException` (feature `leaderboard`) where the exchange does
2631
+ * not have the leaderboard.
2632
+ */
2633
+ leaderboard(query = {}) {
2634
+ const { period, category, metric, limit } = query;
2635
+ return this.#one("leaderboard_get", { query: { period, category, metric, limit } });
2636
+ }
2637
+ /** `GET /api/v1/leaderboard/me`: your own standing, including your rank outside the list. */
2638
+ leaderboardMe(query = {}) {
2639
+ return this.#one("leaderboard_me_get", { query: { period: query.period, category: query.category } });
2640
+ }
2641
+ /**
2642
+ * `PATCH /api/v1/me/profile`: change your public handle, avatar or
2643
+ * leaderboard opt-in. Resolves to the updated `me`.
2644
+ */
2645
+ async updateProfile(update) {
2646
+ this.#me = await this.#one("me_profile_patch", { body: update });
2647
+ return this.#me;
2648
+ }
2649
+ // ------------------------------------------------------------------
2287
2650
  // Terms
2288
2651
  // ------------------------------------------------------------------
2289
- /** `POST /api/v1/tnc/accept`: accept the current terms. Resolves to the server's message. */
2652
+ /**
2653
+ * `POST /api/v1/tnc/accept`: accept the current terms for your own account,
2654
+ * with your own API key. Resolves to the server's message.
2655
+ *
2656
+ * An app cannot accept the terms for a member: called with a member's OAuth
2657
+ * access token, the exchange answers 403 `terms_not_delegable`
2658
+ * (`STXForbiddenException`). The member accepts on an STX page instead.
2659
+ */
2290
2660
  async acceptTerms(deviceId, opts = {}) {
2291
2661
  const body = {
2292
2662
  device_id: deviceId,
@@ -2307,7 +2677,7 @@ var STX = (_class3 = class _STX {
2307
2677
  websocket(opts = {}) {
2308
2678
  return new STXWebSocket({ ...opts, rest: this });
2309
2679
  }
2310
- }, _class3);
2680
+ }, _class4);
2311
2681
 
2312
2682
  // src/ws.ts
2313
2683
  var PHOENIX_TOPIC = "phoenix";
@@ -2400,7 +2770,8 @@ var MessageQueue = class {
2400
2770
  });
2401
2771
  }
2402
2772
  };
2403
- var Channel = (_class4 = class {
2773
+ var UNPINGED_CHANNELS = /* @__PURE__ */ new Set(["market", "rfq", "combo_quote"]);
2774
+ var Channel = (_class5 = class {
2404
2775
  /** The wire topic, e.g. `orders:<user_id>`. */
2405
2776
 
2406
2777
  /** The topic without the user id, e.g. `orders`. */
@@ -2410,21 +2781,21 @@ var Channel = (_class4 = class {
2410
2781
 
2411
2782
 
2412
2783
  /** The `response` object from the latest join reply, e.g. `{selected_market_ids: null}`. */
2413
- __init5() {this.reply = {}}
2784
+ __init6() {this.reply = {}}
2414
2785
  /** The latest snapshot payload per snapshot event name. */
2415
- __init6() {this.snapshots = {}}
2786
+ __init7() {this.snapshots = {}}
2416
2787
  /** Market ids watched on `market_updates`; re-sent after a reconnect. */
2417
- __init7() {this.watches = []}
2418
- __init8() {this.joinRef = null}
2419
- __init9() {this.joined = false}
2420
- __init10() {this.closed = false}
2788
+ __init8() {this.watches = []}
2789
+ __init9() {this.joinRef = null}
2790
+ __init10() {this.joined = false}
2791
+ __init11() {this.closed = false}
2421
2792
  /** @internal Runs before every (re)join, e.g. to refresh a geolocation packet in `joinPayload`. */
2422
2793
 
2423
2794
  #ws;
2424
2795
  #queue;
2425
2796
  #snapshotWaiters = [];
2426
2797
  #pingTimer;
2427
- constructor(ws, topic, joinPayload, onMessage, opts) {;_class4.prototype.__init5.call(this);_class4.prototype.__init6.call(this);_class4.prototype.__init7.call(this);_class4.prototype.__init8.call(this);_class4.prototype.__init9.call(this);_class4.prototype.__init10.call(this);
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);
2428
2799
  this.#ws = ws;
2429
2800
  this.topic = topic;
2430
2801
  this.name = topic.split(":", 1)[0];
@@ -2589,7 +2960,7 @@ var Channel = (_class4 = class {
2589
2960
  _startPinger() {
2590
2961
  this._stopPinger();
2591
2962
  let interval = this.pingIntervalMs;
2592
- const granted = _optionalChain([this, 'access', _29 => _29.reply, 'optionalAccess', _30 => _30.ping_timeout]);
2963
+ const granted = _optionalChain([this, 'access', _33 => _33.reply, 'optionalAccess', _34 => _34.ping_timeout]);
2593
2964
  if (typeof granted === "number" && this.joinPayload.cancel_on_disconnect) {
2594
2965
  const cod = granted * 0.6;
2595
2966
  interval = interval === null ? cod : Math.min(interval, cod);
@@ -2602,7 +2973,7 @@ var Channel = (_class4 = class {
2602
2973
  (err) => this.#ws.logger.warn(`${this.topic} ping failed: ${err.message}`)
2603
2974
  );
2604
2975
  }, every);
2605
- _optionalChain([this, 'access', _31 => _31.#pingTimer, 'access', _32 => _32.unref, 'optionalCall', _33 => _33()]);
2976
+ _optionalChain([this, 'access', _35 => _35.#pingTimer, 'access', _36 => _36.unref, 'optionalCall', _37 => _37()]);
2606
2977
  }
2607
2978
  }
2608
2979
  /** @internal */
@@ -2623,7 +2994,7 @@ var Channel = (_class4 = class {
2623
2994
  this._stopPinger();
2624
2995
  this.#queue.put(null);
2625
2996
  }
2626
- }, _class4);
2997
+ }, _class5);
2627
2998
  var DEFAULT_LOGGER = {
2628
2999
  debug: () => {
2629
3000
  },
@@ -2632,7 +3003,7 @@ var DEFAULT_LOGGER = {
2632
3003
  warn: (...a) => console.warn("[stx.ws]", ...a),
2633
3004
  error: (...a) => console.error("[stx.ws]", ...a)
2634
3005
  };
2635
- var STXWebSocket = (_class5 = class {
3006
+ var STXWebSocket = (_class6 = class {
2636
3007
 
2637
3008
 
2638
3009
 
@@ -2646,9 +3017,9 @@ var STXWebSocket = (_class5 = class {
2646
3017
 
2647
3018
 
2648
3019
 
2649
- __init11() {this.channels = /* @__PURE__ */ new Map()}
3020
+ __init12() {this.channels = /* @__PURE__ */ new Map()}
2650
3021
  /** Successful reconnects so far. */
2651
- __init12() {this.reconnects = 0}
3022
+ __init13() {this.reconnects = 0}
2652
3023
  #userId;
2653
3024
  #conn;
2654
3025
  #ref = 0;
@@ -2662,7 +3033,7 @@ var STXWebSocket = (_class5 = class {
2662
3033
  // Frames are handled one at a time, in arrival order: each waits for the
2663
3034
  // previous one's handler to finish.
2664
3035
  #inbox = Promise.resolve();
2665
- constructor(opts = {}) {;_class5.prototype.__init11.call(this);_class5.prototype.__init12.call(this);
3036
+ constructor(opts = {}) {;_class6.prototype.__init12.call(this);_class6.prototype.__init13.call(this);
2666
3037
  if (opts.rest) {
2667
3038
  this.rest = opts.rest;
2668
3039
  } else {
@@ -2797,7 +3168,7 @@ var STXWebSocket = (_class5 = class {
2797
3168
  */
2798
3169
  async marketUpdates(opts = {}) {
2799
3170
  const channel = await this.join("market_updates", {}, opts.onMessage);
2800
- if (_optionalChain([opts, 'access', _34 => _34.watch, 'optionalAccess', _35 => _35.length])) await channel.watch(opts.watch);
3171
+ if (_optionalChain([opts, 'access', _38 => _38.watch, 'optionalAccess', _39 => _39.length])) await channel.watch(opts.watch);
2801
3172
  return channel;
2802
3173
  }
2803
3174
  /**
@@ -2921,7 +3292,7 @@ var STXWebSocket = (_class5 = class {
2921
3292
  try {
2922
3293
  channel = await this.#joinAccount(name, await comboJoinPayload(opts.geoLocation), onMessage);
2923
3294
  } catch (err) {
2924
- throw comboJoinError(err);
3295
+ throw comboJoinError(err, new URL(this.rest.baseUrl).host);
2925
3296
  }
2926
3297
  if (typeof opts.geoLocation === "function") {
2927
3298
  const geo = opts.geoLocation;
@@ -2943,8 +3314,9 @@ var STXWebSocket = (_class5 = class {
2943
3314
  const existing = this.channels.get(topic);
2944
3315
  if (existing && !existing.closed) throw new STXChannelException(`Already joined ${topic}`, { topic });
2945
3316
  await this.connect();
3317
+ const name = topic.split(":", 1)[0];
2946
3318
  const channel = new Channel(this, topic, payload, onMessage, {
2947
- pingIntervalMs: opts.pingIntervalMs === void 0 ? this.channelPingIntervalMs : opts.pingIntervalMs,
3319
+ pingIntervalMs: opts.pingIntervalMs !== void 0 ? opts.pingIntervalMs : UNPINGED_CHANNELS.has(name) ? null : this.channelPingIntervalMs,
2948
3320
  queueSize: this.queueSize
2949
3321
  });
2950
3322
  this.channels.set(topic, channel);
@@ -3012,12 +3384,12 @@ var STXWebSocket = (_class5 = class {
3012
3384
  if (!(err instanceof STXTransportException)) return false;
3013
3385
  if (err.statusCode !== 401 && err.statusCode !== 403) return false;
3014
3386
  const auth = this.rest.auth;
3015
- if (!_optionalChain([auth, 'optionalAccess', _36 => _36.onUnauthorized])) return false;
3387
+ if (!_optionalChain([auth, 'optionalAccess', _40 => _40.onUnauthorized])) return false;
3016
3388
  return auth.onUnauthorized();
3017
3389
  }
3018
3390
  async #open(reconnect = false) {
3019
3391
  const headers = { "User-Agent": USER_AGENT };
3020
- if (_optionalChain([this, 'access', _37 => _37.rest, 'access', _38 => _38.auth, 'optionalAccess', _39 => _39.websocketHeaders])) Object.assign(headers, await this.rest.auth.websocketHeaders({ reconnect }));
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 }));
3021
3393
  const conn = new (0, _ws2.default)(this.url, {
3022
3394
  headers,
3023
3395
  rejectUnauthorized: this.rest.verifyTls,
@@ -3031,7 +3403,7 @@ var STXWebSocket = (_class5 = class {
3031
3403
  const onUnexpected = (_req, res) => {
3032
3404
  cleanup();
3033
3405
  conn.terminate();
3034
- const reason = _optionalChain([res, 'access', _40 => _40.headers, 'optionalAccess', _41 => _41["x-stx-error"]]);
3406
+ const reason = _optionalChain([res, 'access', _44 => _44.headers, 'optionalAccess', _45 => _45["x-stx-error"]]);
3035
3407
  reject(
3036
3408
  new STXTransportException(
3037
3409
  `Could not open ${this.url}: HTTP ${res.statusCode}${reason ? ` (${String(reason)})` : ""}`,
@@ -3066,7 +3438,7 @@ var STXWebSocket = (_class5 = class {
3066
3438
  if (conn) {
3067
3439
  try {
3068
3440
  conn.terminate();
3069
- } catch (e8) {
3441
+ } catch (e11) {
3070
3442
  }
3071
3443
  }
3072
3444
  }
@@ -3105,7 +3477,7 @@ var STXWebSocket = (_class5 = class {
3105
3477
  let frame;
3106
3478
  try {
3107
3479
  frame = JSON.parse(raw);
3108
- } catch (e9) {
3480
+ } catch (e12) {
3109
3481
  this.logger.warn(`unparseable frame: ${raw.slice(0, 200)}`);
3110
3482
  return;
3111
3483
  }
@@ -3176,7 +3548,7 @@ var STXWebSocket = (_class5 = class {
3176
3548
  } catch (err) {
3177
3549
  this.logger.error(`rejoin ${channel.topic} failed: ${err.message}`);
3178
3550
  const reply = err instanceof STXChannelException ? err.reply : void 0;
3179
- if (_optionalChain([reply, 'optionalAccess', _42 => _42.reason]) === "unauthorized" || _optionalChain([reply, 'optionalAccess', _43 => _43.reason]) === COMBOS_UNAVAILABLE_REASON && COMBO_CHANNELS.has(channel.name)) {
3551
+ if (_optionalChain([reply, 'optionalAccess', _46 => _46.reason]) === "unauthorized" || _optionalChain([reply, 'optionalAccess', _47 => _47.reason]) === COMBOS_UNAVAILABLE_REASON && COMBO_CHANNELS.has(channel.name)) {
3180
3552
  channel._close();
3181
3553
  return;
3182
3554
  }
@@ -3190,15 +3562,15 @@ var STXWebSocket = (_class5 = class {
3190
3562
  if (!this.connected) return;
3191
3563
  if (this.#pendingHeartbeat !== null) {
3192
3564
  this.logger.warn("heartbeat unanswered; reconnecting");
3193
- _optionalChain([this, 'access', _44 => _44.#conn, 'optionalAccess', _45 => _45.terminate, 'call', _46 => _46()]);
3565
+ _optionalChain([this, 'access', _48 => _48.#conn, 'optionalAccess', _49 => _49.terminate, 'call', _50 => _50()]);
3194
3566
  return;
3195
3567
  }
3196
3568
  const ref = this.#nextRef();
3197
3569
  this.#pendingHeartbeat = ref;
3198
3570
  try {
3199
3571
  this.#send([null, ref, PHOENIX_TOPIC, "heartbeat", {}]);
3200
- } catch (e10) {
3201
- _optionalChain([this, 'access', _47 => _47.#conn, 'optionalAccess', _48 => _48.terminate, 'call', _49 => _49()]);
3572
+ } catch (e13) {
3573
+ _optionalChain([this, 'access', _51 => _51.#conn, 'optionalAccess', _52 => _52.terminate, 'call', _53 => _53()]);
3202
3574
  }
3203
3575
  }, this.heartbeatIntervalMs);
3204
3576
  }
@@ -3274,7 +3646,7 @@ var STXWebSocket = (_class5 = class {
3274
3646
  this.error = err;
3275
3647
  this.#shutdownAfterDrop();
3276
3648
  try {
3277
- _optionalChain([this, 'access', _50 => _50.onAuthError, 'optionalCall', _51 => _51(err)]);
3649
+ _optionalChain([this, 'access', _54 => _54.onAuthError, 'optionalCall', _55 => _55(err)]);
3278
3650
  } catch (hookErr) {
3279
3651
  this.logger.error("onAuthError threw", hookErr);
3280
3652
  }
@@ -3290,7 +3662,7 @@ var STXWebSocket = (_class5 = class {
3290
3662
  this.#closedWaiters = [];
3291
3663
  for (const w of waiters) w();
3292
3664
  }
3293
- }, _class5);
3665
+ }, _class6);
3294
3666
  function dropUndefined(payload) {
3295
3667
  return Object.fromEntries(
3296
3668
  Object.entries(payload).filter(([, v]) => v !== void 0).map(([k, v]) => [k, Array.isArray(v) ? [...v] : v])
@@ -3364,5 +3736,12 @@ function dropUndefined(payload) {
3364
3736
 
3365
3737
 
3366
3738
 
3367
- exports.Region = Region; exports.Environment = Environment; 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.STXNotFoundException = STXNotFoundException; exports.STXRejectedException = STXRejectedException; exports.STXGeoLocationException = STXGeoLocationException; exports.STXRateLimitException = STXRateLimitException; exports.STXServerException = STXServerException; exports.STXTransportException = STXTransportException; exports.STXChannelException = STXChannelException; exports.STXTimeoutException = STXTimeoutException; exports.STXCombosUnavailableException = STXCombosUnavailableException; exports.STXComboRefusedException = STXComboRefusedException; exports.STXComboPriceMovedException = STXComboPriceMovedException; exports.errorForStatus = errorForStatus; 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;
3368
- //# sourceMappingURL=chunk-SI3EILHN.cjs.map
3739
+
3740
+
3741
+
3742
+
3743
+
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