@agg-build/sdk 4.27.3 → 4.27.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as loadImmutableHistory, c as orderbookCrc32, i as snapshotToOrderbook, l as projectedOrderbookChecksum, n as applyOrderbookDelta, r as computeChecksum, s as readChartHistoryText, t as AggWebSocket } from "./agg-websocket-DwVwCDvM.mjs";
1
+ import { a as loadImmutableHistory, c as orderbookCrc32, i as snapshotToOrderbook, l as projectedOrderbookChecksum, n as applyOrderbookDelta, r as computeChecksum, s as readChartHistoryText, t as AggWebSocket } from "./agg-websocket-BrkWNijv.mjs";
2
2
  import { t as CandleBuilder } from "./candle-builder-BNewIe9K.mjs";
3
3
  //#region ../common/src/enums/venue.ts
4
4
  /** Use these constants instead of hardcoding "kalshi" or "polymarket". */
@@ -1163,6 +1163,7 @@ function withTimeout(p, ms) {
1163
1163
  var AggClient = class {
1164
1164
  constructor(options) {
1165
1165
  this.listeners = /* @__PURE__ */ new Set();
1166
+ this.webSocketAuthCleanups = /* @__PURE__ */ new Set();
1166
1167
  this._authStatus = "unauthenticated";
1167
1168
  this.authChannel = null;
1168
1169
  this.pendingRefresh = null;
@@ -1260,6 +1261,7 @@ var AggClient = class {
1260
1261
  const { type } = event.data ?? {};
1261
1262
  if (type === "logout") {
1262
1263
  this.accessToken = void 0;
1264
+ this.accessTokenUserId = void 0;
1263
1265
  this.refreshTokenValue = void 0;
1264
1266
  this.currentUser = void 0;
1265
1267
  this._authStatus = "unauthenticated";
@@ -1275,6 +1277,7 @@ var AggClient = class {
1275
1277
  destroy() {
1276
1278
  this.authChannel?.close();
1277
1279
  this.authChannel = null;
1280
+ for (const cleanup of this.webSocketAuthCleanups) cleanup();
1278
1281
  }
1279
1282
  /**
1280
1283
  * Generic HTTP method with automatic header injection and 401 retry.
@@ -1381,6 +1384,7 @@ var AggClient = class {
1381
1384
  }
1382
1385
  /** Set the user access token (for future user-tier auth). */
1383
1386
  setAccessToken(token) {
1387
+ if (this.accessToken !== token) this.accessTokenUserId = void 0;
1384
1388
  this.accessToken = token;
1385
1389
  this._authStatus = "authenticated";
1386
1390
  this.persistSession();
@@ -1389,6 +1393,7 @@ var AggClient = class {
1389
1393
  /** Set the current auth session tokens and optionally seed the user profile. */
1390
1394
  setSession(session) {
1391
1395
  const wasAuthenticated = this.isAuthenticated;
1396
+ this.accessTokenUserId = session.user?.id ?? (this.accessToken === session.accessToken ? this.accessTokenUserId : void 0);
1392
1397
  this.accessToken = session.accessToken;
1393
1398
  if ("refreshToken" in session) this.refreshTokenValue = session.refreshToken;
1394
1399
  if (session.user !== void 0) this.currentUser = normalizeSessionUser(session.user, this.currentUser);
@@ -1400,6 +1405,7 @@ var AggClient = class {
1400
1405
  /** Clear the user access token, refresh token, and user info. Broadcasts cross-tab logout. */
1401
1406
  clearAccessToken() {
1402
1407
  this.accessToken = void 0;
1408
+ this.accessTokenUserId = void 0;
1403
1409
  this.refreshTokenValue = void 0;
1404
1410
  this.currentUser = void 0;
1405
1411
  this._authStatus = "unauthenticated";
@@ -1586,6 +1592,7 @@ var AggClient = class {
1586
1592
  async getCurrentUser() {
1587
1593
  const user = await this.request("/users/me");
1588
1594
  this.currentUser = user;
1595
+ this.accessTokenUserId = user.id;
1589
1596
  this.persistSession();
1590
1597
  this.notifyListeners();
1591
1598
  return user;
@@ -2329,7 +2336,8 @@ var AggClient = class {
2329
2336
  });
2330
2337
  }
2331
2338
  /**
2332
- * Create an AggWebSocket instance configured with this client's appId and optional auth token.
2339
+ * Create an AggWebSocket instance configured with this client's appId and current auth session.
2340
+ * Session changes update this socket until it or the client is destroyed.
2333
2341
  * Requires `wsUrl` to be set in the client options.
2334
2342
  */
2335
2343
  createWebSocket(callbacks, options) {
@@ -2340,7 +2348,7 @@ var AggClient = class {
2340
2348
  const watchdogHeaders = {};
2341
2349
  if (this._appId) watchdogHeaders["x-app-id"] = this._appId;
2342
2350
  if (this.apiKey) watchdogHeaders["x-app-api-key"] = this.apiKey;
2343
- return createSocket({
2351
+ const socket = createSocket({
2344
2352
  url: url.toString(),
2345
2353
  callbacks,
2346
2354
  initialToken: this.accessToken,
@@ -2351,6 +2359,101 @@ var AggClient = class {
2351
2359
  ...options?.bookWatchdog
2352
2360
  }
2353
2361
  });
2362
+ this.bindWebSocketAuth(socket, callbacks);
2363
+ return socket;
2364
+ }
2365
+ bindWebSocketAuth(socket, callbacks) {
2366
+ let token = this.accessToken;
2367
+ let userId = this.accessTokenUserId;
2368
+ let authenticatedUserId;
2369
+ let awaitingDisconnect = false;
2370
+ let connectRequested = false;
2371
+ let manuallyDisconnected = false;
2372
+ let currentCallbacks = callbacks ?? {};
2373
+ const originalSetCallbacks = socket.setCallbacks;
2374
+ const originalConnect = socket.connect;
2375
+ const originalDisconnect = socket.disconnect;
2376
+ const originalDestroy = socket.destroy;
2377
+ const canReceiveUserEvent = (eventUserId) => !!this.accessToken && !awaitingDisconnect && authenticatedUserId !== void 0 && (this.accessTokenUserId === void 0 || authenticatedUserId === this.accessTokenUserId) && (eventUserId === void 0 || eventUserId === authenticatedUserId);
2378
+ const wrapCallbacks = (handlers) => ({
2379
+ ...handlers,
2380
+ onConnectionStateChange: (connected) => {
2381
+ if (!connected) {
2382
+ authenticatedUserId = void 0;
2383
+ awaitingDisconnect = false;
2384
+ }
2385
+ handlers.onConnectionStateChange?.(connected);
2386
+ },
2387
+ onAuthenticated: (message) => {
2388
+ if (awaitingDisconnect || !this.accessToken || this.accessTokenUserId !== void 0 && this.accessTokenUserId !== message.userId) return;
2389
+ authenticatedUserId = message.userId;
2390
+ handlers.onAuthenticated?.(message);
2391
+ },
2392
+ onOrderEvent: (message) => {
2393
+ if (canReceiveUserEvent(message.userId)) handlers.onOrderEvent?.(message);
2394
+ },
2395
+ onOrderEventReceipt: (message) => {
2396
+ if (canReceiveUserEvent()) handlers.onOrderEventReceipt?.(message);
2397
+ },
2398
+ onOrderSubmitted: (message) => {
2399
+ if (canReceiveUserEvent()) handlers.onOrderSubmitted?.(message);
2400
+ },
2401
+ onBalanceUpdate: (message) => {
2402
+ if (canReceiveUserEvent()) handlers.onBalanceUpdate?.(message);
2403
+ },
2404
+ onRedeemEvent: (message) => {
2405
+ if (canReceiveUserEvent()) handlers.onRedeemEvent?.(message);
2406
+ },
2407
+ onWithdrawalLifecycle: (message) => {
2408
+ if (canReceiveUserEvent(message.userId)) handlers.onWithdrawalLifecycle?.(message);
2409
+ }
2410
+ });
2411
+ socket.setCallbacks = (handlers) => {
2412
+ currentCallbacks = handlers;
2413
+ originalSetCallbacks.call(socket, wrapCallbacks(handlers));
2414
+ };
2415
+ socket.setCallbacks(currentCallbacks);
2416
+ socket.connect = () => {
2417
+ connectRequested = true;
2418
+ manuallyDisconnected = false;
2419
+ originalConnect.call(socket);
2420
+ };
2421
+ socket.disconnect = () => {
2422
+ connectRequested = false;
2423
+ manuallyDisconnected = true;
2424
+ originalDisconnect.call(socket);
2425
+ };
2426
+ const unsubscribe = this.onAuthStateChange(() => {
2427
+ const nextToken = this.accessToken;
2428
+ const nextUserId = this.accessTokenUserId;
2429
+ if (token === nextToken && userId === nextUserId) return;
2430
+ const resetConnection = !nextToken || !!token && (userId !== nextUserId || nextUserId === void 0);
2431
+ token = nextToken;
2432
+ userId = nextUserId;
2433
+ if (resetConnection) {
2434
+ const diagnostics = socket.getDiagnostics();
2435
+ const reconnect = connectRequested || socket.connected || !manuallyDisconnected && (diagnostics.orderbookOutcomeIds.length > 0 || diagnostics.tradeOutcomeIds.length > 0 || diagnostics.arbMarketIds.length > 0 || diagnostics.arbFeedSubscribers > 0);
2436
+ authenticatedUserId = void 0;
2437
+ awaitingDisconnect = true;
2438
+ originalDisconnect.call(socket);
2439
+ socket.authenticate(nextToken ?? "");
2440
+ if (reconnect) originalConnect.call(socket);
2441
+ } else if (nextToken) socket.authenticate(nextToken);
2442
+ });
2443
+ const cleanup = () => {
2444
+ unsubscribe();
2445
+ this.webSocketAuthCleanups.delete(cleanup);
2446
+ socket.setCallbacks = originalSetCallbacks;
2447
+ socket.connect = originalConnect;
2448
+ socket.disconnect = originalDisconnect;
2449
+ socket.destroy = originalDestroy;
2450
+ socket.setCallbacks(currentCallbacks);
2451
+ };
2452
+ this.webSocketAuthCleanups.add(cleanup);
2453
+ socket.destroy = () => {
2454
+ cleanup();
2455
+ originalDestroy.call(socket);
2456
+ };
2354
2457
  }
2355
2458
  /** Execute a previously quoted managed trade. Returns pending order IDs. */
2356
2459
  async executeManaged(params) {