@stxapp/stx-typescript 0.6.3 → 0.8.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,4 +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(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await 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
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
2
  var Region = {
3
3
  US: "us",
4
4
  ONTARIO: "ontario"
@@ -185,7 +185,7 @@ var Environments = {
185
185
  name: "ontario-production",
186
186
  region: Region.ONTARIO,
187
187
  env: Environment.PRODUCTION,
188
- host: "stxapp.ca",
188
+ host: "api.on.stxapp.ca",
189
189
  realMoney: true
190
190
  }
191
191
  };
@@ -299,6 +299,17 @@ var OPERATIONS = {
299
299
  isList: true,
300
300
  paginated: true
301
301
  },
302
+ events__id_players_get: {
303
+ method: "GET",
304
+ path: "/api/v1/events/{event_id}/players",
305
+ query: [],
306
+ pathParams: ["event_id"],
307
+ hasBody: false,
308
+ responseKey: "",
309
+ model: "",
310
+ isList: false,
311
+ paginated: false
312
+ },
302
313
  fills_get: {
303
314
  method: "GET",
304
315
  path: "/api/v1/fills",
@@ -310,6 +321,28 @@ var OPERATIONS = {
310
321
  isList: true,
311
322
  paginated: true
312
323
  },
324
+ leaderboard_get: {
325
+ method: "GET",
326
+ path: "/api/v1/leaderboard",
327
+ query: ["period", "category", "metric", "limit"],
328
+ pathParams: [],
329
+ hasBody: false,
330
+ responseKey: "",
331
+ model: "",
332
+ isList: false,
333
+ paginated: false
334
+ },
335
+ leaderboard_me_get: {
336
+ method: "GET",
337
+ path: "/api/v1/leaderboard/me",
338
+ query: ["period", "category"],
339
+ pathParams: [],
340
+ hasBody: false,
341
+ responseKey: "",
342
+ model: "",
343
+ isList: false,
344
+ paginated: false
345
+ },
313
346
  markets_get: {
314
347
  method: "GET",
315
348
  path: "/api/v1/markets",
@@ -321,6 +354,17 @@ var OPERATIONS = {
321
354
  isList: true,
322
355
  paginated: true
323
356
  },
357
+ markets_post: {
358
+ method: "POST",
359
+ path: "/api/v1/markets",
360
+ query: [],
361
+ pathParams: [],
362
+ hasBody: true,
363
+ responseKey: "",
364
+ model: "",
365
+ isList: false,
366
+ paginated: false
367
+ },
324
368
  me_get: {
325
369
  method: "GET",
326
370
  path: "/api/v1/me",
@@ -332,6 +376,17 @@ var OPERATIONS = {
332
376
  isList: false,
333
377
  paginated: false
334
378
  },
379
+ me_profile_patch: {
380
+ method: "PATCH",
381
+ path: "/api/v1/me/profile",
382
+ query: [],
383
+ pathParams: [],
384
+ hasBody: true,
385
+ responseKey: "me",
386
+ model: "Me",
387
+ isList: false,
388
+ paginated: false
389
+ },
335
390
  orders_get: {
336
391
  method: "GET",
337
392
  path: "/api/v1/orders",
@@ -359,7 +414,7 @@ var OPERATIONS = {
359
414
  path: "/api/v1/orders/all",
360
415
  query: [],
361
416
  pathParams: [],
362
- hasBody: false,
417
+ hasBody: true,
363
418
  responseKey: "cancellations",
364
419
  model: "Cancellation",
365
420
  isList: true,
@@ -392,7 +447,7 @@ var OPERATIONS = {
392
447
  path: "/api/v1/orders/{order_id}",
393
448
  query: [],
394
449
  pathParams: ["order_id"],
395
- hasBody: false,
450
+ hasBody: true,
396
451
  responseKey: "",
397
452
  model: "",
398
453
  isList: false,
@@ -499,6 +554,103 @@ var OPERATIONS = {
499
554
  }
500
555
  };
501
556
 
557
+ // src/markets.ts
558
+ var Stats = {
559
+ Baseball: {
560
+ BASES: "BASES",
561
+ BK: "BK",
562
+ DOUBLES: "DOUBLES",
563
+ HITS: "HITS",
564
+ HIT_RUN_RBI: "HIT_RUN_RBI",
565
+ HOMERUN: "HOMERUN",
566
+ PERA: "PERA",
567
+ PHITA: "PHITA",
568
+ PK: "PK",
569
+ POUTS: "POUTS",
570
+ PRUNSALOWED: "PRUNSALOWED",
571
+ PWALKSA: "PWALKSA",
572
+ RBI: "RBI",
573
+ RUNS: "RUNS",
574
+ SINGLES: "SINGLES",
575
+ STOLENBASES: "STOLENBASES",
576
+ TRIPLES: "TRIPLES",
577
+ WALKS: "WALKS"
578
+ },
579
+ Basketball: {
580
+ ASSISTS: "ASSISTS",
581
+ BLOCKS: "BLOCKS",
582
+ POINTS: "POINTS",
583
+ POINTS_ASSISTS: "POINTS_ASSISTS",
584
+ POINTS_REBOUNDS: "POINTS_REBOUNDS",
585
+ POINTS_REBOUNDS_ASSISTS: "POINTS_REBOUNDS_ASSISTS",
586
+ REBOUNDS: "REBOUNDS",
587
+ REBOUNDS_ASSISTS: "REBOUNDS_ASSISTS",
588
+ STEALS: "STEALS",
589
+ STEALS_BLOCKS: "STEALS_BLOCKS",
590
+ THREE_POINTS: "THREE_POINTS",
591
+ TURNOVERS: "TURNOVERS"
592
+ },
593
+ Football: {
594
+ DEF_INTERCEPT: "DEF_INTERCEPT",
595
+ DEF_TD: "DEF_TD",
596
+ FG_MADE: "FG_MADE",
597
+ INTERCEPT: "INTERCEPT",
598
+ PASS_ATT: "PASS_ATT",
599
+ PASS_CMP: "PASS_CMP",
600
+ PASS_RUSH_YDS: "PASS_RUSH_YDS",
601
+ PASS_SACKS: "PASS_SACKS",
602
+ PASS_TD: "PASS_TD",
603
+ PASS_YDS: "PASS_YDS",
604
+ REC: "REC",
605
+ RECV_LONG: "RECV_LONG",
606
+ RECV_TD: "RECV_TD",
607
+ RECV_YDS: "RECV_YDS",
608
+ RUSH_ATT: "RUSH_ATT",
609
+ RUSH_LONG: "RUSH_LONG",
610
+ RUSH_REC_YDS: "RUSH_REC_YDS",
611
+ RUSH_TD: "RUSH_TD",
612
+ RUSH_YDS: "RUSH_YDS",
613
+ SACKS: "SACKS",
614
+ TACKLES_ASSIST: "TACKLES_ASSIST",
615
+ TACKLES_SOLO: "TACKLES_SOLO",
616
+ TACKLES_TOTAL: "TACKLES_TOTAL",
617
+ TD_SCORE: "TD_SCORE"
618
+ },
619
+ Hockey: {
620
+ ASSISTS: "ASSISTS",
621
+ GOALS: "GOALS",
622
+ GOAL_AG: "GOAL_AG",
623
+ GOAL_SO: "GOAL_SO",
624
+ POINTS: "POINTS",
625
+ SAVES: "SAVES"
626
+ }
627
+ };
628
+ var MAX_MARKETS_PER_REQUEST = 25;
629
+ function isValidLine(line) {
630
+ return typeof line === "number" && Number.isFinite(line) && line > 0 && line * 2 % 2 === 1;
631
+ }
632
+ function marketEntry(m) {
633
+ return {
634
+ stat_detail: { player_id: m.playerId, stat: m.stat, prop_type: _nullishCoalesce(m.propType, () => ( "ou")), line: m.line }
635
+ };
636
+ }
637
+ function toCreateMarketResult(raw) {
638
+ const market = _nullishCoalesce(_nullishCoalesce(raw.market, () => ( raw.stat_detail)), () => ( {}));
639
+ return { ...raw, market };
640
+ }
641
+ function rejected(m, reason) {
642
+ const market = marketEntry(m).stat_detail;
643
+ return { status: "rejected", reason, market };
644
+ }
645
+ function checkMarket(m, players) {
646
+ if (!isValidLine(m.line)) return { reason: "invalid_line" };
647
+ const stat = players.stats.find((s) => String(s.stat).toUpperCase() === String(m.stat).toUpperCase());
648
+ if (!stat) return { reason: "unsupported_stat" };
649
+ const ids2 = new Set(players.teams.flatMap((t) => t.players.map((p) => p.player_id)));
650
+ if (!ids2.has(m.playerId)) return { reason: "unknown_player" };
651
+ return { market: { ...m, stat: stat.stat } };
652
+ }
653
+
502
654
  // src/paging.ts
503
655
  var Page = class {
504
656
 
@@ -809,7 +961,7 @@ function credentialsFromSettings(keyId, privateKey, signer) {
809
961
  }
810
962
 
811
963
  // src/version.ts
812
- var VERSION = "0.6.3";
964
+ var VERSION = "0.8.0";
813
965
  var USER_AGENT = `stx-typescript/${VERSION}`;
814
966
  var ASYNC_DISPOSE = _nullishCoalesce(Symbol.asyncDispose, () => ( /* @__PURE__ */ Symbol.for("Symbol.asyncDispose")));
815
967
 
@@ -1140,7 +1292,8 @@ function buildRequest(operationId, args = {}) {
1140
1292
  if (unknown.length) throw new TypeError(`${operationId} does not take ${unknown.sort().join(", ")}`);
1141
1293
  const qs = encodeQuery(query);
1142
1294
  if (qs) path = `${path}?${qs}`;
1143
- const body = op.hasBody || args.body !== void 0 ? JSON.stringify(_nullishCoalesce(args.body, () => ( {}))) : void 0;
1295
+ const declared = op.hasBody && op.method !== "DELETE";
1296
+ const body = declared || args.body !== void 0 ? JSON.stringify(_nullishCoalesce(args.body, () => ( {}))) : void 0;
1144
1297
  return {
1145
1298
  operationId,
1146
1299
  method: op.method,
@@ -1187,160 +1340,6 @@ function toBatchOrderResult(raw) {
1187
1340
  return { ...obj, order, errors, ok: order !== null && !_optionalChain([errors, 'optionalAccess', _16 => _16.length]) };
1188
1341
  }
1189
1342
 
1190
- // src/legacy-routes.ts
1191
- function isRouteMissing(err) {
1192
- return err instanceof STXNotFoundException && err.statusCode === 404 && typeof err.body === "string";
1193
- }
1194
- var QUIET = { debug() {
1195
- }, info() {
1196
- }, warn() {
1197
- }, error() {
1198
- } };
1199
- var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1200
- async function channelSnapshot(client, join3, event) {
1201
- const me = await client._identity();
1202
- const ws = client.websocket({
1203
- userId: me.user_id,
1204
- reconnect: false,
1205
- channelPingIntervalMs: null,
1206
- joinTimeoutMs: client.timeoutMs,
1207
- logger: QUIET
1208
- });
1209
- try {
1210
- const channel = await join3(ws, me);
1211
- const snapshot = await channel.waitSnapshot(client.timeoutMs);
1212
- return snapshot[event];
1213
- } finally {
1214
- await ws.close();
1215
- }
1216
- }
1217
- async function balanceFromChannel(client) {
1218
- const payload = await channelSnapshot(
1219
- client,
1220
- (ws, me) => ws.balances(me.account_id ? { accountId: me.account_id } : {}),
1221
- "balances"
1222
- );
1223
- if (!payload || typeof payload !== "object") {
1224
- throw new STXException("The balances channel sent no balance", { path: "/api/v1/account/balance" });
1225
- }
1226
- return payload;
1227
- }
1228
- function positionsFilter(marketIds) {
1229
- if (marketIds === void 0 || marketIds === null) return null;
1230
- const list = typeof marketIds === "string" ? [marketIds] : [...marketIds];
1231
- if (list.length === 0) return null;
1232
- const joined = list.join(",");
1233
- if (joined === "") return null;
1234
- const ids2 = joined.split(",").map((s) => s.trim());
1235
- for (const id of ids2) {
1236
- if (!UUID.test(id)) {
1237
- throw new STXValidationException(`${id} is not a valid UUID`, {
1238
- statusCode: 400,
1239
- body: { error: `${id} is not a valid UUID` },
1240
- method: "GET",
1241
- path: "/api/v1/positions"
1242
- });
1243
- }
1244
- }
1245
- return new Set(ids2.map((id) => id.toLowerCase()));
1246
- }
1247
- async function positionsFromChannel(client, query = {}) {
1248
- const filter = positionsFilter(query.marketIds);
1249
- const payload = await channelSnapshot(client, (ws) => ws.positions(), "all_positions");
1250
- const rows = payload && Array.isArray(payload.positions) ? payload.positions : null;
1251
- if (!rows) throw new STXException("The positions channel sent no positions", { path: "/api/v1/positions" });
1252
- return filter ? rows.filter((p) => filter.has(String(p.market_id).toLowerCase())) : rows;
1253
- }
1254
- var MAX_BATCH_ORDERS = 100;
1255
- var ORDER_TYPES = ["limit", "market"];
1256
- var ACTIONS = ["buy", "sell"];
1257
- var EXPIRATIONS = ["good_till_start", "good_till_time"];
1258
- function batchRefusal(message) {
1259
- return new STXValidationException(message, {
1260
- statusCode: 400,
1261
- body: { error: message },
1262
- method: "POST",
1263
- path: "/api/v1/orders/batched"
1264
- });
1265
- }
1266
- function enumError(field, value, allowed, required) {
1267
- if (value === void 0 || value === null) return required ? `${field} is required` : void 0;
1268
- if (typeof value !== "string") return `${field} is invalid`;
1269
- return allowed.includes(value) ? void 0 : `${field} has invalid value: ${value}`;
1270
- }
1271
- function parseDecimal(text) {
1272
- if (/^[+-]?(inf|infinity|nan)$/i.test(text)) return { special: true };
1273
- const m = /^([+-]?)(?:(\d+)\.?(\d*)|\.(\d+))(?:[eE]([+-]?\d+))?$/.exec(text);
1274
- if (!m) return void 0;
1275
- const int = _nullishCoalesce(m[2], () => ( ""));
1276
- const frac = _nullishCoalesce(_nullishCoalesce(m[3], () => ( m[4])), () => ( ""));
1277
- return { special: false, sign: m[1] === "-" ? -1 : 1, digits: int + frac, exp: Number(_nullishCoalesce(m[5], () => ( 0))) - frac.length };
1278
- }
1279
- var scaleOf = (exp) => Math.max(0, -exp);
1280
- function priceError(value) {
1281
- if (value === void 0 || value === null) return void 0;
1282
- const format2 = 'price must be a dollar amount as a string, e.g. "30.00"';
1283
- if (typeof value !== "string") return format2;
1284
- const d = parseDecimal(value);
1285
- if (!d || d.special) return format2;
1286
- if (scaleOf(d.exp) > 7) return "price supports at most 7 decimal places";
1287
- const trailingZeros = /0*$/.exec(d.digits)[0].length;
1288
- const significant = /^0*$/.test(d.digits) ? 0 : scaleOf(d.exp + trailingZeros);
1289
- if (significant > 2) {
1290
- return `price must be a whole number of cents \u2014 at most 2 decimal places, not counting trailing zeros (got ${JSON.stringify(value)})`;
1291
- }
1292
- if (d.sign < 0 || /^0*$/.test(d.digits)) return "price must be greater than 0";
1293
- return void 0;
1294
- }
1295
- function marketIdError(value) {
1296
- if (value === void 0 || value === null) return "market_id is required";
1297
- return typeof value === "string" && UUID.test(value) ? void 0 : "market_id is not a valid UUID";
1298
- }
1299
- function quantityError(value) {
1300
- if (value === void 0 || value === null) return "quantity is required";
1301
- const d = typeof value === "string" ? parseDecimal(value) : void 0;
1302
- return d && !d.special ? void 0 : 'quantity must be a decimal string, e.g. "10" or "10.00"';
1303
- }
1304
- function validateBatch(orders) {
1305
- if (orders.length === 0) throw batchRefusal("orders must not be empty");
1306
- if (orders.length > MAX_BATCH_ORDERS) {
1307
- throw batchRefusal(`orders may contain at most ${MAX_BATCH_ORDERS} orders per batch`);
1308
- }
1309
- for (const order of orders) {
1310
- const { marketId, action, orderType, ...fields } = order;
1311
- const body = orderBody(marketId, action, orderType, fields);
1312
- const message = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(marketIdError(body.market_id), () => ( enumError("order_type", body.order_type, ORDER_TYPES, true))), () => ( enumError("action", body.action, ACTIONS, true))), () => ( priceError(body.price))), () => ( quantityError(body.quantity))), () => ( enumError("expiration", body.expiration, EXPIRATIONS, false))), () => ( (body.expiration !== void 0 && body.order_type !== "limit" ? "Order expiration is only supported for limit orders." : void 0)));
1313
- if (message) throw batchRefusal(message);
1314
- }
1315
- }
1316
- async function placeOrdersOneByOne(client, orders, opts) {
1317
- validateBatch(orders);
1318
- const packet = _optionalChain([opts, 'optionalAccess', _17 => _17.geoLocation]) !== void 0 ? opts.geoLocation : await _asyncNullishCoalesce(await resolveGeoLocation(client.geoLocation), async () => ( null));
1319
- const results = [];
1320
- let placed = 0;
1321
- for (let i = 0; i < orders.length; i++) {
1322
- const { marketId, action, orderType, ...fields } = orders[i];
1323
- try {
1324
- const order = await client.placeOrder(marketId, action, orderType, { ...fields, geoLocation: packet });
1325
- results.push(toBatchOrderResult({ order }));
1326
- placed += 1;
1327
- } catch (err) {
1328
- if (!(err instanceof STXException)) throw err;
1329
- if (err instanceof STXRejectedException && !(err instanceof STXGeoLocationException)) {
1330
- results.push(toBatchOrderResult({ errors: [err.message] }));
1331
- continue;
1332
- }
1333
- if (err instanceof STXServerException || err instanceof STXTransportException) throw err;
1334
- if (placed === 0) throw err;
1335
- results.push(toBatchOrderResult({ errors: [err.message] }));
1336
- if (err instanceof STXValidationException) continue;
1337
- for (let j = i + 1; j < orders.length; j++) results.push(toBatchOrderResult({ errors: [err.message] }));
1338
- break;
1339
- }
1340
- }
1341
- return results;
1342
- }
1343
-
1344
1343
  // src/client.ts
1345
1344
  var NEW_ORDER_FIELDS = {
1346
1345
  marketId: "market_id",
@@ -1417,8 +1416,6 @@ var STX = (_class3 = class _STX {
1417
1416
 
1418
1417
  #fetch;
1419
1418
  #me;
1420
- // Exchanges older than v3.3.172: the routes this exchange turned out not to serve.
1421
- #missingRoutes = /* @__PURE__ */ new Set();
1422
1419
  /** Test hook: how retries wait. */
1423
1420
  __init4() {this._sleep = sleep}
1424
1421
  constructor(opts = {}) {;_class3.prototype.__init4.call(this);
@@ -1470,7 +1467,7 @@ var STX = (_class3 = class _STX {
1470
1467
  this.#fetch = fetchImpl;
1471
1468
  }
1472
1469
  toString() {
1473
- return `STX(baseUrl=${JSON.stringify(this.baseUrl)}, keyId=${JSON.stringify(_nullishCoalesce(_optionalChain([this, 'access', _18 => _18.credentials, 'optionalAccess', _19 => _19.keyId]), () => ( null)))})`;
1470
+ return `STX(baseUrl=${JSON.stringify(this.baseUrl)}, keyId=${JSON.stringify(_nullishCoalesce(_optionalChain([this, 'access', _17 => _17.credentials, 'optionalAccess', _18 => _18.keyId]), () => ( null)))})`;
1474
1471
  }
1475
1472
  /** Nothing to release (fetch pools connections itself); present so `await using` and explicit cleanup work. */
1476
1473
  async close() {
@@ -1505,7 +1502,7 @@ var STX = (_class3 = class _STX {
1505
1502
  status,
1506
1503
  attempt,
1507
1504
  durationMs: Date.now() - started,
1508
- authKind: _optionalChain([this, 'access', _20 => _20.auth, 'optionalAccess', _21 => _21.kind]),
1505
+ authKind: _optionalChain([this, 'access', _19 => _19.auth, 'optionalAccess', _20 => _20.kind]),
1509
1506
  requestBody: request.body,
1510
1507
  responseBody
1511
1508
  });
@@ -1537,7 +1534,7 @@ var STX = (_class3 = class _STX {
1537
1534
  });
1538
1535
  }
1539
1536
  throw new STXTransportException(
1540
- `${request.method} ${request.path} failed: ${_nullishCoalesce(_optionalChain([err, 'optionalAccess', _22 => _22.message]), () => ( String(err)))}`,
1537
+ `${request.method} ${request.path} failed: ${_nullishCoalesce(_optionalChain([err, 'optionalAccess', _21 => _21.message]), () => ( String(err)))}`,
1541
1538
  { method: request.method, path: request.path, cause: err }
1542
1539
  );
1543
1540
  } finally {
@@ -1559,7 +1556,7 @@ var STX = (_class3 = class _STX {
1559
1556
  return await this.#sendOnce(request, sent);
1560
1557
  } catch (err) {
1561
1558
  if (!(err instanceof STXException)) throw err;
1562
- if (err.statusCode === 401 && !reauthenticated && _optionalChain([this, 'access', _23 => _23.auth, 'optionalAccess', _24 => _24.onUnauthorized])) {
1559
+ if (err.statusCode === 401 && !reauthenticated && _optionalChain([this, 'access', _22 => _22.auth, 'optionalAccess', _23 => _23.onUnauthorized])) {
1563
1560
  reauthenticated = true;
1564
1561
  if (await this.auth.onUnauthorized()) continue;
1565
1562
  }
@@ -1595,7 +1592,7 @@ var STX = (_class3 = class _STX {
1595
1592
  }
1596
1593
  }
1597
1594
  async #geoBody(body, opts) {
1598
- const packet = _optionalChain([opts, 'optionalAccess', _25 => _25.geoLocation]) !== void 0 ? _nullishCoalesce(opts.geoLocation, () => ( void 0)) : await resolveGeoLocation(this.geoLocation);
1595
+ const packet = _optionalChain([opts, 'optionalAccess', _24 => _24.geoLocation]) !== void 0 ? _nullishCoalesce(opts.geoLocation, () => ( void 0)) : await resolveGeoLocation(this.geoLocation);
1599
1596
  return packet === void 0 ? body : { ...body, geo_location: packet };
1600
1597
  }
1601
1598
  // ------------------------------------------------------------------
@@ -1610,21 +1607,13 @@ var STX = (_class3 = class _STX {
1610
1607
  this.#me = await this.#one("me_get");
1611
1608
  return this.#me;
1612
1609
  }
1613
- /**
1614
- * @internal The cached `me()` when it has both ids, else a fresh `me()`.
1615
- * Never falls back to `balance()`, so the channel fallbacks can use it.
1616
- */
1617
- async _identity() {
1618
- if (_optionalChain([this, 'access', _26 => _26.#me, 'optionalAccess', _27 => _27.user_id]) && this.#me.account_id) return this.#me;
1619
- return this.me();
1620
- }
1621
1610
  /**
1622
1611
  * The user id from `me()`, fetched once and cached. If `me()` is not
1623
1612
  * permitted, the id comes from `balance()`, which carries the same
1624
1613
  * `user_id`.
1625
1614
  */
1626
1615
  async userId() {
1627
- if (_optionalChain([this, 'access', _28 => _28.#me, 'optionalAccess', _29 => _29.user_id])) return this.#me.user_id;
1616
+ if (_optionalChain([this, 'access', _25 => _25.#me, 'optionalAccess', _26 => _26.user_id])) return this.#me.user_id;
1628
1617
  try {
1629
1618
  await this.me();
1630
1619
  } catch (err) {
@@ -1635,7 +1624,7 @@ var STX = (_class3 = class _STX {
1635
1624
  if (!balance.user_id) throw err;
1636
1625
  this.#me = { ..._nullishCoalesce(this.#me, () => ( {})), user_id: balance.user_id };
1637
1626
  }
1638
- if (!_optionalChain([this, 'access', _30 => _30.#me, 'optionalAccess', _31 => _31.user_id])) throw new STXException("GET /api/v1/me returned no user_id");
1627
+ if (!_optionalChain([this, 'access', _27 => _27.#me, 'optionalAccess', _28 => _28.user_id])) throw new STXException("GET /api/v1/me returned no user_id");
1639
1628
  return this.#me.user_id;
1640
1629
  }
1641
1630
  // ------------------------------------------------------------------
@@ -1697,6 +1686,63 @@ var STX = (_class3 = class _STX {
1697
1686
  return this.#iterate("events_get", _STX.#eventsQuery({ ...query, cursor: void 0 }));
1698
1687
  }
1699
1688
  // ------------------------------------------------------------------
1689
+ // Creating markets
1690
+ // ------------------------------------------------------------------
1691
+ /**
1692
+ * `GET /api/v1/events/{event_id}/players`: the event's team rosters and the
1693
+ * stats a market on it can use. `teams` is empty until the rosters are
1694
+ * published. Needs an OAuth app token with `events`, or an API key.
1695
+ */
1696
+ eventPlayers(eventId) {
1697
+ return this.#one("events__id_players_get", { pathParams: { event_id: eventId } });
1698
+ }
1699
+ /** The stats `event` accepts for new markets. */
1700
+ async statsFor(event) {
1701
+ const eventId = typeof event === "string" ? event : event.event_id;
1702
+ if (!eventId) throw new TypeError("statsFor needs an event id");
1703
+ return (await this.eventPlayers(eventId)).stats;
1704
+ }
1705
+ /**
1706
+ * `POST /api/v1/markets`: create player-prop markets on a scheduled event,
1707
+ * up to `MAX_MARKETS_PER_REQUEST` per call. Needs an OAuth app token with
1708
+ * `markets.write`, which STX grants, from the client's IP allow-list.
1709
+ *
1710
+ * Returns one result per market, in order: `created` or `exists` (both with
1711
+ * `market_id`), or `rejected` with a `reason`. A rejected market is a
1712
+ * result, not an error, and resending is safe: a market that is already
1713
+ * listed comes back `exists`. A refused request throws (`403` without
1714
+ * `markets.write`, `404` unknown event, `422` event not open).
1715
+ *
1716
+ * Each `line` must be a positive number ending in `.5`, e.g. `18.5`. More
1717
+ * than `MAX_MARKETS_PER_REQUEST` markets throws `TypeError` before any
1718
+ * request. `validate` also needs the `events` scope.
1719
+ */
1720
+ async createMarkets(eventId, markets, opts = {}) {
1721
+ if (markets.length < 1 || markets.length > MAX_MARKETS_PER_REQUEST) {
1722
+ throw new TypeError(`createMarkets takes 1 to ${MAX_MARKETS_PER_REQUEST} markets; got ${markets.length}`);
1723
+ }
1724
+ const results = new Array(markets.length);
1725
+ let send = markets.map((m, i) => ({ m, i }));
1726
+ if (opts.validate) {
1727
+ const players = await this.eventPlayers(eventId);
1728
+ send = send.flatMap(({ m, i }) => {
1729
+ const checked = checkMarket(m, players);
1730
+ if ("market" in checked) return [{ m: checked.market, i }];
1731
+ results[i] = rejected(m, checked.reason);
1732
+ return [];
1733
+ });
1734
+ }
1735
+ if (send.length) {
1736
+ const body = { event_id: eventId, markets: send.map(({ m }) => marketEntry(m)) };
1737
+ const raw = await this.#one("markets_post", { body });
1738
+ (_nullishCoalesce(raw.markets, () => ( []))).forEach((r, k) => {
1739
+ const slot = send[k];
1740
+ if (slot) results[slot.i] = toCreateMarketResult(r);
1741
+ });
1742
+ }
1743
+ return results.map((r, i) => _nullishCoalesce(r, () => ( rejected(markets[i], "not_created"))));
1744
+ }
1745
+ // ------------------------------------------------------------------
1700
1746
  // Orders
1701
1747
  // ------------------------------------------------------------------
1702
1748
  static #ordersQuery(q) {
@@ -1750,15 +1796,7 @@ var STX = (_class3 = class _STX {
1750
1796
  */
1751
1797
  async placeOrders(orders, opts) {
1752
1798
  const body = { orders: orders.map(normalizeOrder) };
1753
- if (this.#missingRoutes.has("batch")) return placeOrdersOneByOne(this, orders, opts);
1754
- let raw;
1755
- try {
1756
- raw = await this.#list("orders_batched_post", { body: await this.#geoBody(body, opts) });
1757
- } catch (err) {
1758
- if (!isRouteMissing(err)) throw err;
1759
- this.#missingRoutes.add("batch");
1760
- return placeOrdersOneByOne(this, orders, opts);
1761
- }
1799
+ const raw = await this.#list("orders_batched_post", { body: await this.#geoBody(body, opts) });
1762
1800
  return raw.map(toBatchOrderResult);
1763
1801
  }
1764
1802
  /**
@@ -1843,28 +1881,14 @@ var STX = (_class3 = class _STX {
1843
1881
  * negative when short.
1844
1882
  */
1845
1883
  async positions(query = {}) {
1846
- if (this.#missingRoutes.has("positions")) return positionsFromChannel(this, query);
1847
- try {
1848
- return await this.#list("positions_get", { query: { market_ids: ids(query.marketIds) } });
1849
- } catch (err) {
1850
- if (!isRouteMissing(err)) throw err;
1851
- this.#missingRoutes.add("positions");
1852
- return positionsFromChannel(this, query);
1853
- }
1884
+ return this.#list("positions_get", { query: { market_ids: ids(query.marketIds) } });
1854
1885
  }
1855
1886
  /**
1856
1887
  * `GET /api/v1/account/balance`: balance, liabilities and fee schedule.
1857
1888
  * The same object the `balances` channel pushes.
1858
1889
  */
1859
1890
  async balance() {
1860
- if (this.#missingRoutes.has("balance")) return balanceFromChannel(this);
1861
- try {
1862
- return await this.#one("account_balance_get");
1863
- } catch (err) {
1864
- if (!isRouteMissing(err)) throw err;
1865
- this.#missingRoutes.add("balance");
1866
- return balanceFromChannel(this);
1867
- }
1891
+ return this.#one("account_balance_get");
1868
1892
  }
1869
1893
  static #marketStatsQuery(q) {
1870
1894
  return {
@@ -1881,7 +1905,7 @@ var STX = (_class3 = class _STX {
1881
1905
  }
1882
1906
  /**
1883
1907
  * `GET /api/v1/account/market_stats`: your exposure and P&L per market.
1884
- * Not the public `market_stats` channel, which carries prices.
1908
+ * Not the `market_stats` WebSocket channel, which carries price history.
1885
1909
  */
1886
1910
  accountMarketStats(query = {}) {
1887
1911
  return this.#page("account_market_stats_get", _STX.#marketStatsQuery(query));
@@ -2247,7 +2271,7 @@ var Channel = (_class4 = class {
2247
2271
  _startPinger() {
2248
2272
  this._stopPinger();
2249
2273
  let interval = this.pingIntervalMs;
2250
- const granted = _optionalChain([this, 'access', _32 => _32.reply, 'optionalAccess', _33 => _33.ping_timeout]);
2274
+ const granted = _optionalChain([this, 'access', _29 => _29.reply, 'optionalAccess', _30 => _30.ping_timeout]);
2251
2275
  if (typeof granted === "number" && this.joinPayload.cancel_on_disconnect) {
2252
2276
  const cod = granted * 0.6;
2253
2277
  interval = interval === null ? cod : Math.min(interval, cod);
@@ -2260,7 +2284,7 @@ var Channel = (_class4 = class {
2260
2284
  (err) => this.#ws.logger.warn(`${this.topic} ping failed: ${err.message}`)
2261
2285
  );
2262
2286
  }, every);
2263
- _optionalChain([this, 'access', _34 => _34.#pingTimer, 'access', _35 => _35.unref, 'optionalCall', _36 => _36()]);
2287
+ _optionalChain([this, 'access', _31 => _31.#pingTimer, 'access', _32 => _32.unref, 'optionalCall', _33 => _33()]);
2264
2288
  }
2265
2289
  }
2266
2290
  /** @internal */
@@ -2407,7 +2431,7 @@ var STXWebSocket = (_class5 = class {
2407
2431
  return this.#userId;
2408
2432
  }
2409
2433
  // ------------------------------------------------------------------
2410
- // Public market channels
2434
+ // Market data channels
2411
2435
  // ------------------------------------------------------------------
2412
2436
  /**
2413
2437
  * `orderbook`: the aggregated book, one `book` push per market. Each push
@@ -2455,7 +2479,7 @@ var STXWebSocket = (_class5 = class {
2455
2479
  */
2456
2480
  async marketUpdates(opts = {}) {
2457
2481
  const channel = await this.join("market_updates", {}, opts.onMessage);
2458
- if (_optionalChain([opts, 'access', _37 => _37.watch, 'optionalAccess', _38 => _38.length])) await channel.watch(opts.watch);
2482
+ if (_optionalChain([opts, 'access', _34 => _34.watch, 'optionalAccess', _35 => _35.length])) await channel.watch(opts.watch);
2459
2483
  return channel;
2460
2484
  }
2461
2485
  /**
@@ -2612,12 +2636,12 @@ var STXWebSocket = (_class5 = class {
2612
2636
  if (!(err instanceof STXTransportException)) return false;
2613
2637
  if (err.statusCode !== 401 && err.statusCode !== 403) return false;
2614
2638
  const auth = this.rest.auth;
2615
- if (!_optionalChain([auth, 'optionalAccess', _39 => _39.onUnauthorized])) return false;
2639
+ if (!_optionalChain([auth, 'optionalAccess', _36 => _36.onUnauthorized])) return false;
2616
2640
  return auth.onUnauthorized();
2617
2641
  }
2618
2642
  async #open(reconnect = false) {
2619
2643
  const headers = { "User-Agent": USER_AGENT };
2620
- if (_optionalChain([this, 'access', _40 => _40.rest, 'access', _41 => _41.auth, 'optionalAccess', _42 => _42.websocketHeaders])) Object.assign(headers, await this.rest.auth.websocketHeaders({ reconnect }));
2644
+ if (_optionalChain([this, 'access', _37 => _37.rest, 'access', _38 => _38.auth, 'optionalAccess', _39 => _39.websocketHeaders])) Object.assign(headers, await this.rest.auth.websocketHeaders({ reconnect }));
2621
2645
  const conn = new (0, _ws2.default)(this.url, {
2622
2646
  headers,
2623
2647
  rejectUnauthorized: this.rest.verifyTls,
@@ -2631,7 +2655,7 @@ var STXWebSocket = (_class5 = class {
2631
2655
  const onUnexpected = (_req, res) => {
2632
2656
  cleanup();
2633
2657
  conn.terminate();
2634
- const reason = _optionalChain([res, 'access', _43 => _43.headers, 'optionalAccess', _44 => _44["x-stx-error"]]);
2658
+ const reason = _optionalChain([res, 'access', _40 => _40.headers, 'optionalAccess', _41 => _41["x-stx-error"]]);
2635
2659
  reject(
2636
2660
  new STXTransportException(
2637
2661
  `Could not open ${this.url}: HTTP ${res.statusCode}${reason ? ` (${String(reason)})` : ""}`,
@@ -2776,7 +2800,7 @@ var STXWebSocket = (_class5 = class {
2776
2800
  } catch (err) {
2777
2801
  this.logger.error(`rejoin ${channel.topic} failed: ${err.message}`);
2778
2802
  const reply = err instanceof STXChannelException ? err.reply : void 0;
2779
- if (_optionalChain([reply, 'optionalAccess', _45 => _45.reason]) === "unauthorized") {
2803
+ if (_optionalChain([reply, 'optionalAccess', _42 => _42.reason]) === "unauthorized") {
2780
2804
  channel._close();
2781
2805
  return;
2782
2806
  }
@@ -2790,7 +2814,7 @@ var STXWebSocket = (_class5 = class {
2790
2814
  if (!this.connected) return;
2791
2815
  if (this.#pendingHeartbeat !== null) {
2792
2816
  this.logger.warn("heartbeat unanswered; reconnecting");
2793
- _optionalChain([this, 'access', _46 => _46.#conn, 'optionalAccess', _47 => _47.terminate, 'call', _48 => _48()]);
2817
+ _optionalChain([this, 'access', _43 => _43.#conn, 'optionalAccess', _44 => _44.terminate, 'call', _45 => _45()]);
2794
2818
  return;
2795
2819
  }
2796
2820
  const ref = this.#nextRef();
@@ -2798,7 +2822,7 @@ var STXWebSocket = (_class5 = class {
2798
2822
  try {
2799
2823
  this.#send([null, ref, PHOENIX_TOPIC, "heartbeat", {}]);
2800
2824
  } catch (e10) {
2801
- _optionalChain([this, 'access', _49 => _49.#conn, 'optionalAccess', _50 => _50.terminate, 'call', _51 => _51()]);
2825
+ _optionalChain([this, 'access', _46 => _46.#conn, 'optionalAccess', _47 => _47.terminate, 'call', _48 => _48()]);
2802
2826
  }
2803
2827
  }, this.heartbeatIntervalMs);
2804
2828
  }
@@ -2874,7 +2898,7 @@ var STXWebSocket = (_class5 = class {
2874
2898
  this.error = err;
2875
2899
  this.#shutdownAfterDrop();
2876
2900
  try {
2877
- _optionalChain([this, 'access', _52 => _52.onAuthError, 'optionalCall', _53 => _53(err)]);
2901
+ _optionalChain([this, 'access', _49 => _49.onAuthError, 'optionalCall', _50 => _50(err)]);
2878
2902
  } catch (hookErr) {
2879
2903
  this.logger.error("onAuthError threw", hookErr);
2880
2904
  }
@@ -2956,5 +2980,8 @@ function dropUndefined(payload) {
2956
2980
 
2957
2981
 
2958
2982
 
2959
- 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.errorForStatus = errorForStatus; exports.Environments = Environments; exports.HOSTS = HOSTS; exports.environmentNamed = environmentNamed; exports.resolveHost = resolveHost; exports.baseUrlFor = baseUrlFor; exports.socketUrlFor = socketUrlFor; exports.OPERATIONS = OPERATIONS; 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.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;
2960
- //# sourceMappingURL=chunk-CSHPFQ2V.cjs.map
2983
+
2984
+
2985
+
2986
+ 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.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.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;
2987
+ //# sourceMappingURL=chunk-L2DEU7R6.cjs.map