nsekit 0.3.8 → 0.3.9

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.
Files changed (40) hide show
  1. package/dist/brokers/dhan/DhanBroker.d.ts +2 -0
  2. package/dist/brokers/dhan/DhanBroker.d.ts.map +1 -1
  3. package/dist/brokers/dhan/dhan-auth.d.ts +9 -4
  4. package/dist/brokers/dhan/dhan-auth.d.ts.map +1 -1
  5. package/dist/brokers/dhan/dhan-instruments.d.ts +4 -0
  6. package/dist/brokers/dhan/dhan-instruments.d.ts.map +1 -1
  7. package/dist/brokers/dhan/dhan-socket.d.ts +15 -3
  8. package/dist/brokers/dhan/dhan-socket.d.ts.map +1 -1
  9. package/dist/brokers/finvasia/FinvasiaBroker.d.ts +2 -0
  10. package/dist/brokers/finvasia/FinvasiaBroker.d.ts.map +1 -1
  11. package/dist/brokers/finvasia/finvasia-auth.d.ts +11 -2
  12. package/dist/brokers/finvasia/finvasia-auth.d.ts.map +1 -1
  13. package/dist/brokers/finvasia/finvasia-instruments.d.ts +5 -0
  14. package/dist/brokers/finvasia/finvasia-instruments.d.ts.map +1 -1
  15. package/dist/brokers/finvasia/finvasia-socket.d.ts +2 -1
  16. package/dist/brokers/finvasia/finvasia-socket.d.ts.map +1 -1
  17. package/dist/brokers/fivepaisa/FivePaisaBroker.d.ts +2 -0
  18. package/dist/brokers/fivepaisa/FivePaisaBroker.d.ts.map +1 -1
  19. package/dist/brokers/fivepaisa/fivepaisa-auth.d.ts +10 -3
  20. package/dist/brokers/fivepaisa/fivepaisa-auth.d.ts.map +1 -1
  21. package/dist/brokers/fivepaisa/fivepaisa-instruments.d.ts +4 -0
  22. package/dist/brokers/fivepaisa/fivepaisa-instruments.d.ts.map +1 -1
  23. package/dist/brokers/fivepaisa/fivepaisa-socket.d.ts +2 -1
  24. package/dist/brokers/fivepaisa/fivepaisa-socket.d.ts.map +1 -1
  25. package/dist/brokers/paper/PaperBroker.d.ts +5 -0
  26. package/dist/brokers/paper/PaperBroker.d.ts.map +1 -1
  27. package/dist/brokers/zerodha/ZerodhaBroker.d.ts +2 -0
  28. package/dist/brokers/zerodha/ZerodhaBroker.d.ts.map +1 -1
  29. package/dist/brokers/zerodha/zerodha-auth.d.ts +8 -3
  30. package/dist/brokers/zerodha/zerodha-auth.d.ts.map +1 -1
  31. package/dist/brokers/zerodha/zerodha-instruments.d.ts +4 -0
  32. package/dist/brokers/zerodha/zerodha-instruments.d.ts.map +1 -1
  33. package/dist/index.d.ts +9 -2
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +143 -98
  36. package/dist/instruments/instrument-master.d.ts +15 -2
  37. package/dist/instruments/instrument-master.d.ts.map +1 -1
  38. package/dist/shared/egress-ip.d.ts +12 -0
  39. package/dist/shared/egress-ip.d.ts.map +1 -0
  40. package/package.json +7 -6
package/dist/index.js CHANGED
@@ -17284,7 +17284,7 @@ var require_utils = __commonJS((exports, module) => {
17284
17284
  var hexTable = function() {
17285
17285
  var array = [];
17286
17286
  for (var i = 0;i < 256; ++i) {
17287
- array[array.length] = "%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase();
17287
+ array.push("%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase());
17288
17288
  }
17289
17289
  return array;
17290
17290
  }();
@@ -17296,7 +17296,7 @@ var require_utils = __commonJS((exports, module) => {
17296
17296
  var compacted = [];
17297
17297
  for (var j = 0;j < obj.length; ++j) {
17298
17298
  if (typeof obj[j] !== "undefined") {
17299
- compacted[compacted.length] = obj[j];
17299
+ compacted.push(obj[j]);
17300
17300
  }
17301
17301
  }
17302
17302
  item.obj[item.prop] = compacted;
@@ -17318,11 +17318,7 @@ var require_utils = __commonJS((exports, module) => {
17318
17318
  }
17319
17319
  if (typeof source !== "object" && typeof source !== "function") {
17320
17320
  if (isArray(target)) {
17321
- var nextIndex = target.length;
17322
- if (options && typeof options.arrayLimit === "number" && nextIndex > options.arrayLimit) {
17323
- return markOverflow(arrayToObject(target.concat(source), options), nextIndex);
17324
- }
17325
- target[nextIndex] = source;
17321
+ target.push(source);
17326
17322
  } else if (target && typeof target === "object") {
17327
17323
  if (isOverflow(target)) {
17328
17324
  var newIndex = getMaxIndex(target) + 1;
@@ -17346,11 +17342,7 @@ var require_utils = __commonJS((exports, module) => {
17346
17342
  }
17347
17343
  return markOverflow(result, getMaxIndex(source) + 1);
17348
17344
  }
17349
- var combined = [target].concat(source);
17350
- if (options && typeof options.arrayLimit === "number" && combined.length > options.arrayLimit) {
17351
- return markOverflow(arrayToObject(combined, options), combined.length - 1);
17352
- }
17353
- return combined;
17345
+ return [target].concat(source);
17354
17346
  }
17355
17347
  var mergeTarget = target;
17356
17348
  if (isArray(target) && !isArray(source)) {
@@ -17363,7 +17355,7 @@ var require_utils = __commonJS((exports, module) => {
17363
17355
  if (targetItem && typeof targetItem === "object" && item && typeof item === "object") {
17364
17356
  target[i] = merge2(targetItem, item, options);
17365
17357
  } else {
17366
- target[target.length] = item;
17358
+ target.push(item);
17367
17359
  }
17368
17360
  } else {
17369
17361
  target[i] = item;
@@ -17378,15 +17370,6 @@ var require_utils = __commonJS((exports, module) => {
17378
17370
  } else {
17379
17371
  acc[key] = value;
17380
17372
  }
17381
- if (isOverflow(source) && !isOverflow(acc)) {
17382
- markOverflow(acc, getMaxIndex(source));
17383
- }
17384
- if (isOverflow(acc)) {
17385
- var keyNum = parseInt(key, 10);
17386
- if (String(keyNum) === key && keyNum >= 0 && keyNum > getMaxIndex(acc)) {
17387
- setMaxIndex(acc, keyNum);
17388
- }
17389
- }
17390
17373
  return acc;
17391
17374
  }, mergeTarget);
17392
17375
  };
@@ -17464,8 +17447,8 @@ var require_utils = __commonJS((exports, module) => {
17464
17447
  var key = keys[j];
17465
17448
  var val = obj[key];
17466
17449
  if (typeof val === "object" && val !== null && refs.indexOf(val) === -1) {
17467
- queue[queue.length] = { obj, prop: key };
17468
- refs[refs.length] = val;
17450
+ queue.push({ obj, prop: key });
17451
+ refs.push(val);
17469
17452
  }
17470
17453
  }
17471
17454
  }
@@ -17498,7 +17481,7 @@ var require_utils = __commonJS((exports, module) => {
17498
17481
  if (isArray(val)) {
17499
17482
  var mapped = [];
17500
17483
  for (var i = 0;i < val.length; i += 1) {
17501
- mapped[mapped.length] = fn(val[i]);
17484
+ mapped.push(fn(val[i]));
17502
17485
  }
17503
17486
  return mapped;
17504
17487
  }
@@ -17514,7 +17497,6 @@ var require_utils = __commonJS((exports, module) => {
17514
17497
  isBuffer,
17515
17498
  isOverflow,
17516
17499
  isRegExp,
17517
- markOverflow,
17518
17500
  maybeMap,
17519
17501
  merge
17520
17502
  };
@@ -17856,12 +17838,6 @@ var require_parse = __commonJS((exports, module) => {
17856
17838
  if (part.indexOf("[]=") > -1) {
17857
17839
  val = isArray(val) ? [val] : val;
17858
17840
  }
17859
- if (options.comma && isArray(val) && val.length > options.arrayLimit) {
17860
- if (options.throwOnLimitExceeded) {
17861
- throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array.");
17862
- }
17863
- val = utils.combine([], val, options.arrayLimit, options.plainObjects);
17864
- }
17865
17841
  if (key !== null) {
17866
17842
  var existing = has.call(obj, key);
17867
17843
  if (existing && options.duplicates === "combine") {
@@ -17894,17 +17870,11 @@ var require_parse = __commonJS((exports, module) => {
17894
17870
  var cleanRoot = root.charAt(0) === "[" && root.charAt(root.length - 1) === "]" ? root.slice(1, -1) : root;
17895
17871
  var decodedRoot = options.decodeDotInKeys ? cleanRoot.replace(/%2E/g, ".") : cleanRoot;
17896
17872
  var index = parseInt(decodedRoot, 10);
17897
- var isValidArrayIndex = !isNaN(index) && root !== decodedRoot && String(index) === decodedRoot && index >= 0 && options.parseArrays;
17898
17873
  if (!options.parseArrays && decodedRoot === "") {
17899
17874
  obj = { 0: leaf };
17900
- } else if (isValidArrayIndex && index < options.arrayLimit) {
17875
+ } else if (!isNaN(index) && root !== decodedRoot && String(index) === decodedRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit)) {
17901
17876
  obj = [];
17902
17877
  obj[index] = leaf;
17903
- } else if (isValidArrayIndex && options.throwOnLimitExceeded) {
17904
- throw new RangeError("Array limit exceeded. Only " + options.arrayLimit + " element" + (options.arrayLimit === 1 ? "" : "s") + " allowed in an array.");
17905
- } else if (isValidArrayIndex) {
17906
- obj[index] = leaf;
17907
- utils.markOverflow(obj, index);
17908
17878
  } else if (decodedRoot !== "__proto__") {
17909
17879
  obj[decodedRoot] = leaf;
17910
17880
  }
@@ -17934,7 +17904,7 @@ var require_parse = __commonJS((exports, module) => {
17934
17904
  return;
17935
17905
  }
17936
17906
  }
17937
- keys[keys.length] = parent;
17907
+ keys.push(parent);
17938
17908
  }
17939
17909
  var i = 0;
17940
17910
  while ((segment = child.exec(key)) !== null && i < options.depth) {
@@ -17945,13 +17915,13 @@ var require_parse = __commonJS((exports, module) => {
17945
17915
  return;
17946
17916
  }
17947
17917
  }
17948
- keys[keys.length] = segment[1];
17918
+ keys.push(segment[1]);
17949
17919
  }
17950
17920
  if (segment) {
17951
17921
  if (options.strictDepth === true) {
17952
17922
  throw new RangeError("Input depth exceeded depth option of " + options.depth + " and strictDepth is true");
17953
17923
  }
17954
- keys[keys.length] = "[" + key.slice(segment.index) + "]";
17924
+ keys.push("[" + key.slice(segment.index) + "]");
17955
17925
  }
17956
17926
  return keys;
17957
17927
  };
@@ -20155,7 +20125,7 @@ var CANDLE_INTERVAL_TO_KITE = {
20155
20125
 
20156
20126
  // src/brokers/zerodha/zerodha-auth.ts
20157
20127
  import crypto from "crypto";
20158
- async function exchangeToken(requestToken, apiKey, apiSecret) {
20128
+ async function exchangeToken(requestToken, apiKey, apiSecret, opts) {
20159
20129
  try {
20160
20130
  const checksum = crypto.createHash("sha256").update(apiKey + requestToken + apiSecret).digest("hex");
20161
20131
  const response = await fetch("https://api.kite.trade/session/token", {
@@ -20165,7 +20135,8 @@ async function exchangeToken(requestToken, apiKey, apiSecret) {
20165
20135
  api_key: apiKey,
20166
20136
  request_token: requestToken,
20167
20137
  checksum
20168
- })
20138
+ }),
20139
+ dispatcher: opts?.dispatcher
20169
20140
  });
20170
20141
  if (!response.ok) {
20171
20142
  const body = await response.text();
@@ -20187,7 +20158,7 @@ async function exchangeToken(requestToken, apiKey, apiSecret) {
20187
20158
  return Err(err instanceof Error ? err : new Error(String(err)));
20188
20159
  }
20189
20160
  }
20190
- async function authenticate(creds) {
20161
+ async function authenticate(creds, opts) {
20191
20162
  const { apiKey, apiSecret, accessToken: requestToken } = creds;
20192
20163
  if (!apiKey)
20193
20164
  return Err(new Error("Missing apiKey in credentials"));
@@ -20195,9 +20166,9 @@ async function authenticate(creds) {
20195
20166
  return Err(new Error("Missing apiSecret in credentials"));
20196
20167
  if (!requestToken)
20197
20168
  return Err(new Error("Missing accessToken (request_token) in credentials"));
20198
- return exchangeToken(requestToken, apiKey, apiSecret);
20169
+ return exchangeToken(requestToken, apiKey, apiSecret, opts);
20199
20170
  }
20200
- async function refreshSession(_session) {
20171
+ async function refreshSession(_session, _opts) {
20201
20172
  return Err(new Error("Zerodha does not support token refresh. Re-authenticate with a new request_token."));
20202
20173
  }
20203
20174
  function isSessionValid(session) {
@@ -20581,8 +20552,12 @@ class ZerodhaInstruments {
20581
20552
  rawFileCache: true,
20582
20553
  rawFilePath: "data/instruments/zerodha-instruments.csv"
20583
20554
  };
20555
+ dispatcher;
20556
+ setDispatcher(dispatcher) {
20557
+ this.dispatcher = dispatcher;
20558
+ }
20584
20559
  async* streamDump() {
20585
- const response = await fetch(KITE_INSTRUMENTS_URL);
20560
+ const response = await fetch(KITE_INSTRUMENTS_URL, { dispatcher: this.dispatcher });
20586
20561
  if (!response.ok) {
20587
20562
  throw new Error(`Failed to fetch Kite instruments: ${response.status}`);
20588
20563
  }
@@ -20655,6 +20630,17 @@ class ZerodhaInstruments {
20655
20630
  }
20656
20631
  }
20657
20632
 
20633
+ // src/shared/egress-ip.ts
20634
+ import { Agent } from "undici";
20635
+ function egressDispatcher(egressIp) {
20636
+ if (!egressIp)
20637
+ return;
20638
+ return new Agent({ connect: { localAddress: egressIp } });
20639
+ }
20640
+ function wsEgressOptions(egressIp) {
20641
+ return egressIp ? { localAddress: egressIp } : {};
20642
+ }
20643
+
20658
20644
  // src/brokers/zerodha/ZerodhaBroker.ts
20659
20645
  class ZerodhaBroker {
20660
20646
  id = "zerodha";
@@ -20674,13 +20660,18 @@ class ZerodhaBroker {
20674
20660
  apiKey = "";
20675
20661
  KiteConnect = null;
20676
20662
  _iMaster;
20663
+ egressIp;
20664
+ dispatcher;
20677
20665
  constructor(options) {
20678
20666
  this.instruments = new ZerodhaInstruments;
20679
20667
  this._iMaster = new InstrumentMaster(options);
20668
+ this.egressIp = options?.egressIp;
20669
+ this.dispatcher = egressDispatcher(options?.egressIp);
20670
+ this.instruments.setDispatcher(this.dispatcher);
20680
20671
  }
20681
20672
  async authenticate(creds) {
20682
20673
  this.apiKey = creds.apiKey;
20683
- const result = await authenticate(creds);
20674
+ const result = await authenticate(creds, { dispatcher: this.dispatcher });
20684
20675
  if (!result.ok)
20685
20676
  return result;
20686
20677
  this.session = result.value;
@@ -20689,7 +20680,7 @@ class ZerodhaBroker {
20689
20680
  return result;
20690
20681
  }
20691
20682
  async refreshSession(session) {
20692
- return refreshSession(session);
20683
+ return refreshSession(session, { dispatcher: this.dispatcher });
20693
20684
  }
20694
20685
  isSessionValid() {
20695
20686
  return isSessionValid(this.session);
@@ -21172,7 +21163,7 @@ function generateTOTP(secret) {
21172
21163
  const code = (hmac[offset] & 127) << 24 | (hmac[offset + 1] & 255) << 16 | (hmac[offset + 2] & 255) << 8 | hmac[offset + 3] & 255;
21173
21164
  return String(code % 1e6).padStart(6, "0");
21174
21165
  }
21175
- async function authenticate2(creds) {
21166
+ async function authenticate2(creds, opts) {
21176
21167
  const { userId, password, totpSecret, apiKey, vendorCode } = creds;
21177
21168
  if (!userId)
21178
21169
  return Err(new Error("Missing userId in credentials"));
@@ -21207,7 +21198,8 @@ async function authenticate2(creds) {
21207
21198
  const response = await fetch(`${host}/QuickAuth`, {
21208
21199
  method: "POST",
21209
21200
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
21210
- body: `jData=${jData}`
21201
+ body: `jData=${jData}`,
21202
+ dispatcher: opts?.dispatcher
21211
21203
  });
21212
21204
  text = await response.text();
21213
21205
  try {
@@ -21246,7 +21238,7 @@ function getOAuthURL(clientId) {
21246
21238
  const uid = clientId.endsWith("_U") ? clientId.slice(0, -2) : clientId;
21247
21239
  return `${SHOONYA_OAUTH_BASE}?api_key=${encodeURIComponent(clientId)}&route_to=${encodeURIComponent(uid)}`;
21248
21240
  }
21249
- async function exchangeAuthCode(authCode, secretCode, clientId, uid) {
21241
+ async function exchangeAuthCode(authCode, secretCode, clientId, uid, opts) {
21250
21242
  if (!authCode)
21251
21243
  return Err(new Error("Missing authCode"));
21252
21244
  if (!secretCode)
@@ -21265,7 +21257,8 @@ async function exchangeAuthCode(authCode, secretCode, clientId, uid) {
21265
21257
  const response = await fetch(`${SHOONYA_API_BASE3}/GenAcsTok`, {
21266
21258
  method: "POST",
21267
21259
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
21268
- body: `jData=${jData}`
21260
+ body: `jData=${jData}`,
21261
+ dispatcher: opts?.dispatcher
21269
21262
  });
21270
21263
  const text = await response.text();
21271
21264
  let json;
@@ -21557,11 +21550,13 @@ class FinvasiaSocket {
21557
21550
  maxReconnects = 5;
21558
21551
  reconnectTimer = null;
21559
21552
  onAuthFailed;
21560
- constructor(userId, accessToken, onAuthFailed, authMethod = "totp") {
21553
+ egressIp;
21554
+ constructor(userId, accessToken, onAuthFailed, authMethod = "totp", egressIp) {
21561
21555
  this.userId = userId;
21562
21556
  this.accessToken = accessToken;
21563
21557
  this.authMethod = authMethod;
21564
21558
  this.onAuthFailed = onAuthFailed;
21559
+ this.egressIp = egressIp;
21565
21560
  }
21566
21561
  connect() {
21567
21562
  if (this.state === "CONNECTED" || this.state === "CONNECTING")
@@ -21569,7 +21564,7 @@ class FinvasiaSocket {
21569
21564
  this.state = "CONNECTING";
21570
21565
  const wsUrl = this.authMethod === "oauth" ? SHOONYA_WS_OAUTH_URL3 : SHOONYA_WS_URL3;
21571
21566
  try {
21572
- this.ws = new WS(wsUrl);
21567
+ this.ws = new WS(wsUrl, wsEgressOptions(this.egressIp));
21573
21568
  } catch {
21574
21569
  this.state = "DISCONNECTED";
21575
21570
  return;
@@ -21876,15 +21871,19 @@ class FinvasiaInstruments {
21876
21871
  };
21877
21872
  accessToken = "";
21878
21873
  userId = "";
21874
+ dispatcher;
21879
21875
  setCredentials(userId, accessToken) {
21880
21876
  this.userId = userId;
21881
21877
  this.accessToken = accessToken;
21882
21878
  }
21879
+ setDispatcher(dispatcher) {
21880
+ this.dispatcher = dispatcher;
21881
+ }
21883
21882
  async* streamDump() {
21884
21883
  for (const [exchange, filename] of Object.entries(SHOONYA_INSTRUMENT_FILES)) {
21885
21884
  const url = `${SHOONYA_INSTRUMENTS_BASE}${filename}`;
21886
21885
  try {
21887
- const response = await fetch(url);
21886
+ const response = await fetch(url, { dispatcher: this.dispatcher });
21888
21887
  if (!response.ok)
21889
21888
  continue;
21890
21889
  const text = extractTextFromZip(await response.arrayBuffer());
@@ -21943,7 +21942,8 @@ class FinvasiaInstruments {
21943
21942
  const response = await fetch(`${SHOONYA_API_BASE3}/SearchScrip`, {
21944
21943
  method: "POST",
21945
21944
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
21946
- body: `jData=${payload}&jKey=${this.accessToken}`
21945
+ body: `jData=${payload}&jKey=${this.accessToken}`,
21946
+ dispatcher: this.dispatcher
21947
21947
  });
21948
21948
  if (!response.ok) {
21949
21949
  return Err(new Error(`Shoonya search failed (${response.status})`));
@@ -22017,10 +22017,15 @@ class FinvasiaBroker {
22017
22017
  credentials = null;
22018
22018
  instrumentsImpl;
22019
22019
  _iMaster;
22020
+ egressIp;
22021
+ dispatcher;
22020
22022
  constructor(options) {
22021
22023
  this.instrumentsImpl = new FinvasiaInstruments;
22022
22024
  this.instruments = this.instrumentsImpl;
22023
22025
  this._iMaster = new InstrumentMaster(options);
22026
+ this.egressIp = options?.egressIp;
22027
+ this.dispatcher = egressDispatcher(options?.egressIp);
22028
+ this.instrumentsImpl.setDispatcher(this.dispatcher);
22024
22029
  }
22025
22030
  async authenticate(creds) {
22026
22031
  if (creds.accessToken && creds.userId) {
@@ -22034,7 +22039,7 @@ class FinvasiaBroker {
22034
22039
  if (!creds.clientId || !creds.secretCode || !creds.userId) {
22035
22040
  return Err(new Error("Finvasia OAuth: authCode requires clientId, secretCode, and userId"));
22036
22041
  }
22037
- const result2 = await exchangeAuthCode(creds.authCode, creds.secretCode, creds.clientId, creds.userId);
22042
+ const result2 = await exchangeAuthCode(creds.authCode, creds.secretCode, creds.clientId, creds.userId, { dispatcher: this.dispatcher });
22038
22043
  if (!result2.ok)
22039
22044
  return result2;
22040
22045
  this.credentials = creds;
@@ -22042,7 +22047,7 @@ class FinvasiaBroker {
22042
22047
  this.instrumentsImpl.setCredentials(this.session.userId, this.session.accessToken);
22043
22048
  return result2;
22044
22049
  }
22045
- const result = await authenticate2(creds);
22050
+ const result = await authenticate2(creds, { dispatcher: this.dispatcher });
22046
22051
  if (!result.ok)
22047
22052
  return result;
22048
22053
  this.credentials = creds;
@@ -22566,7 +22571,8 @@ class FinvasiaBroker {
22566
22571
  const response = await fetch(`${SHOONYA_API_BASE3}/${endpoint}`, {
22567
22572
  method: "POST",
22568
22573
  headers,
22569
- body
22574
+ body,
22575
+ dispatcher: this.dispatcher
22570
22576
  });
22571
22577
  const text = await response.text();
22572
22578
  let parsed;
@@ -22596,7 +22602,7 @@ class FinvasiaBroker {
22596
22602
  const authMethod = this.session.metadata?.authMethod === "oauth" ? "oauth" : "totp";
22597
22603
  this.socket = new FinvasiaSocket(this.session.userId, this.session.accessToken, () => {
22598
22604
  this.handleSocketAuthFailed();
22599
- }, authMethod);
22605
+ }, authMethod, this.egressIp);
22600
22606
  this.socket.connect();
22601
22607
  }
22602
22608
  handleSocketAuthFailed() {
@@ -22725,7 +22731,7 @@ var DHAN_WS_URL3 = active2.DHAN_WS_URL;
22725
22731
  var DHAN_INSTRUMENTS_URL3 = active2.DHAN_INSTRUMENTS_URL;
22726
22732
 
22727
22733
  // src/brokers/dhan/dhan-auth.ts
22728
- async function authenticate3(creds) {
22734
+ async function authenticate3(creds, opts) {
22729
22735
  const { apiKey: accessToken, userId: clientId } = creds;
22730
22736
  if (!accessToken)
22731
22737
  return Err(new Error("Missing apiKey (access_token) in credentials"));
@@ -22737,7 +22743,8 @@ async function authenticate3(creds) {
22737
22743
  "Content-Type": "application/json",
22738
22744
  "access-token": accessToken,
22739
22745
  "client-id": clientId
22740
- }
22746
+ },
22747
+ dispatcher: opts?.dispatcher
22741
22748
  });
22742
22749
  if (!response.ok) {
22743
22750
  const body = await response.text();
@@ -22759,7 +22766,7 @@ async function authenticate3(creds) {
22759
22766
  return Err(err instanceof Error ? err : new Error(String(err)));
22760
22767
  }
22761
22768
  }
22762
- async function generateConsent(creds) {
22769
+ async function generateConsent(creds, opts) {
22763
22770
  const { apiKey: appId, apiSecret: appSecret, userId: clientId } = creds;
22764
22771
  if (!appId)
22765
22772
  return Err(new Error("Missing apiKey (App ID) in credentials"));
@@ -22775,7 +22782,8 @@ async function generateConsent(creds) {
22775
22782
  app_id: appId,
22776
22783
  app_secret: appSecret
22777
22784
  },
22778
- body: JSON.stringify({})
22785
+ body: JSON.stringify({}),
22786
+ dispatcher: opts?.dispatcher
22779
22787
  });
22780
22788
  if (!response.ok) {
22781
22789
  const body = await response.text();
@@ -22791,7 +22799,7 @@ async function generateConsent(creds) {
22791
22799
  return Err(err instanceof Error ? err : new Error(String(err)));
22792
22800
  }
22793
22801
  }
22794
- async function consumeConsent(creds, tokenId) {
22802
+ async function consumeConsent(creds, tokenId, opts) {
22795
22803
  const { apiKey: appId, apiSecret: appSecret, userId: clientId } = creds;
22796
22804
  if (!appId)
22797
22805
  return Err(new Error("Missing apiKey (App ID) in credentials"));
@@ -22807,7 +22815,8 @@ async function consumeConsent(creds, tokenId) {
22807
22815
  app_id: appId,
22808
22816
  app_secret: appSecret
22809
22817
  },
22810
- body: JSON.stringify({})
22818
+ body: JSON.stringify({}),
22819
+ dispatcher: opts?.dispatcher
22811
22820
  });
22812
22821
  if (!response.ok) {
22813
22822
  const body = await response.text();
@@ -22833,7 +22842,7 @@ async function consumeConsent(creds, tokenId) {
22833
22842
  return Err(err instanceof Error ? err : new Error(String(err)));
22834
22843
  }
22835
22844
  }
22836
- async function refreshSession3(session) {
22845
+ async function refreshSession3(session, opts) {
22837
22846
  const { accessToken, userId: clientId } = session;
22838
22847
  if (!accessToken)
22839
22848
  return Err(new Error("Missing accessToken in session"));
@@ -22846,7 +22855,8 @@ async function refreshSession3(session) {
22846
22855
  "Content-Type": "application/json",
22847
22856
  "access-token": accessToken,
22848
22857
  dhanClientId: clientId
22849
- }
22858
+ },
22859
+ dispatcher: opts?.dispatcher
22850
22860
  });
22851
22861
  if (!response.ok) {
22852
22862
  const body = await response.text();
@@ -23084,20 +23094,24 @@ class DhanSocket {
23084
23094
  clientId;
23085
23095
  accessToken;
23086
23096
  reconnectAttempts = 0;
23087
- maxReconnects = 5;
23097
+ disposed = false;
23088
23098
  reconnectTimer = null;
23089
23099
  heartbeatTimer = null;
23090
- constructor(clientId, accessToken) {
23100
+ egressIp;
23101
+ constructor(clientId, accessToken, egressIp) {
23091
23102
  this.clientId = clientId;
23092
23103
  this.accessToken = accessToken;
23104
+ this.egressIp = egressIp;
23093
23105
  }
23094
23106
  connect() {
23107
+ if (this.disposed)
23108
+ return;
23095
23109
  if (this.state === "CONNECTED" || this.state === "CONNECTING")
23096
23110
  return;
23097
23111
  this.state = "CONNECTING";
23098
23112
  try {
23099
23113
  const url = `${DHAN_WS_URL3}?version=2&token=${this.accessToken}&clientId=${this.clientId}&authType=2`;
23100
- this.ws = new WS2(url);
23114
+ this.ws = new WS2(url, wsEgressOptions(this.egressIp));
23101
23115
  } catch {
23102
23116
  this.state = "DISCONNECTED";
23103
23117
  return;
@@ -23143,9 +23157,9 @@ class DhanSocket {
23143
23157
  });
23144
23158
  }
23145
23159
  disconnect() {
23160
+ this.disposed = true;
23146
23161
  this.clearReconnectTimer();
23147
23162
  this.stopHeartbeat();
23148
- this.reconnectAttempts = this.maxReconnects;
23149
23163
  if (this.ws) {
23150
23164
  this.ws.close();
23151
23165
  this.ws = null;
@@ -23357,12 +23371,13 @@ class DhanSocket {
23357
23371
  }
23358
23372
  }
23359
23373
  attemptReconnect() {
23360
- if (this.reconnectAttempts >= this.maxReconnects)
23374
+ if (this.disposed || this.reconnectTimer)
23361
23375
  return;
23362
23376
  this.state = "RECONNECTING";
23363
23377
  this.reconnectAttempts += 1;
23364
23378
  const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);
23365
23379
  this.reconnectTimer = setTimeout(() => {
23380
+ this.reconnectTimer = null;
23366
23381
  this.connect();
23367
23382
  }, delay);
23368
23383
  }
@@ -23442,12 +23457,16 @@ class DhanInstruments {
23442
23457
  };
23443
23458
  accessToken = "";
23444
23459
  clientId = "";
23460
+ dispatcher;
23445
23461
  setCredentials(clientId, accessToken) {
23446
23462
  this.clientId = clientId;
23447
23463
  this.accessToken = accessToken;
23448
23464
  }
23465
+ setDispatcher(dispatcher) {
23466
+ this.dispatcher = dispatcher;
23467
+ }
23449
23468
  async* streamDump() {
23450
- const response = await fetch(DHAN_INSTRUMENTS_URL3);
23469
+ const response = await fetch(DHAN_INSTRUMENTS_URL3, { dispatcher: this.dispatcher });
23451
23470
  if (!response.ok) {
23452
23471
  throw new Error(`Failed to fetch Dhan instruments: ${response.status}`);
23453
23472
  }
@@ -23507,7 +23526,8 @@ class DhanInstruments {
23507
23526
  "access-token": this.accessToken,
23508
23527
  "client-id": this.clientId
23509
23528
  },
23510
- body: JSON.stringify(payload)
23529
+ body: JSON.stringify(payload),
23530
+ dispatcher: this.dispatcher
23511
23531
  });
23512
23532
  if (!response.ok) {
23513
23533
  return Err(new Error(`Dhan search failed (${response.status})`));
@@ -23608,14 +23628,19 @@ class DhanBroker {
23608
23628
  oauthCreds = null;
23609
23629
  instrumentsImpl;
23610
23630
  _iMaster;
23631
+ egressIp;
23632
+ dispatcher;
23611
23633
  constructor(options) {
23612
23634
  this.instrumentsImpl = new DhanInstruments;
23613
23635
  this.instruments = this.instrumentsImpl;
23614
23636
  this._iMaster = new InstrumentMaster(options);
23637
+ this.egressIp = options?.egressIp;
23638
+ this.dispatcher = egressDispatcher(options?.egressIp);
23639
+ this.instrumentsImpl.setDispatcher(this.dispatcher);
23615
23640
  }
23616
23641
  async authenticate(creds) {
23617
23642
  this.clientId = creds.userId ?? "";
23618
- const result = await authenticate3(creds);
23643
+ const result = await authenticate3(creds, { dispatcher: this.dispatcher });
23619
23644
  if (!result.ok)
23620
23645
  return result;
23621
23646
  this.session = result.value;
@@ -23623,7 +23648,7 @@ class DhanBroker {
23623
23648
  return result;
23624
23649
  }
23625
23650
  async refreshSession(session) {
23626
- const result = await refreshSession3(session);
23651
+ const result = await refreshSession3(session, { dispatcher: this.dispatcher });
23627
23652
  if (result.ok) {
23628
23653
  this.session = result.value;
23629
23654
  if (!this.clientId && result.value.userId)
@@ -23646,13 +23671,13 @@ class DhanBroker {
23646
23671
  async generateConsent(creds) {
23647
23672
  this.oauthCreds = creds;
23648
23673
  this.clientId = creds.userId ?? "";
23649
- return generateConsent(creds);
23674
+ return generateConsent(creds, { dispatcher: this.dispatcher });
23650
23675
  }
23651
23676
  async consumeConsent(tokenId) {
23652
23677
  if (!this.oauthCreds) {
23653
23678
  return Err(new Error("Call generateConsent() before consumeConsent()"));
23654
23679
  }
23655
- const result = await consumeConsent(this.oauthCreds, tokenId);
23680
+ const result = await consumeConsent(this.oauthCreds, tokenId, { dispatcher: this.dispatcher });
23656
23681
  if (!result.ok)
23657
23682
  return result;
23658
23683
  this.session = result.value;
@@ -24054,7 +24079,7 @@ class DhanBroker {
24054
24079
  if (body && (method === "POST" || method === "PUT")) {
24055
24080
  options.body = JSON.stringify(body);
24056
24081
  }
24057
- const response = await fetch(url, options);
24082
+ const response = await fetch(url, { ...options, dispatcher: this.dispatcher });
24058
24083
  if (!response.ok) {
24059
24084
  const text = await response.text();
24060
24085
  throw new Error(`Dhan ${method} ${path} failed (${response.status}): ${text}`);
@@ -24066,7 +24091,7 @@ class DhanBroker {
24066
24091
  return;
24067
24092
  if (!this.session)
24068
24093
  throw new Error("Cannot create socket without an active session");
24069
- this.socket = new DhanSocket(this.clientId, this.session.accessToken);
24094
+ this.socket = new DhanSocket(this.clientId, this.session.accessToken, this.egressIp);
24070
24095
  this.socket.connect();
24071
24096
  }
24072
24097
  }
@@ -24975,7 +25000,7 @@ function generateTOTP2(secret) {
24975
25000
  const code = (hmac[offset] & 127) << 24 | (hmac[offset + 1] & 255) << 16 | (hmac[offset + 2] & 255) << 8 | hmac[offset + 3] & 255;
24976
25001
  return String(code % 1e6).padStart(6, "0");
24977
25002
  }
24978
- async function authenticate4(creds) {
25003
+ async function authenticate4(creds, opts) {
24979
25004
  const userKey = creds.userKey ?? creds.apiKey;
24980
25005
  const clientCode = creds.clientCode;
24981
25006
  const encryptionKey = creds.encryptionKey;
@@ -25003,7 +25028,8 @@ async function authenticate4(creds) {
25003
25028
  const totpRes = await fetch(ROUTES.TOTP_LOGIN, {
25004
25029
  method: "POST",
25005
25030
  headers: { "Content-Type": "application/json" },
25006
- body: JSON.stringify(totpPayload)
25031
+ body: JSON.stringify(totpPayload),
25032
+ dispatcher: opts?.dispatcher
25007
25033
  });
25008
25034
  let totpJson = await totpRes.json();
25009
25035
  if (!totpJson.body?.RequestToken && totpSecret && totpJson.body?.Message?.toLowerCase().includes("used in past")) {
@@ -25015,7 +25041,8 @@ async function authenticate4(creds) {
25015
25041
  const retryRes = await fetch(ROUTES.TOTP_LOGIN, {
25016
25042
  method: "POST",
25017
25043
  headers: { "Content-Type": "application/json" },
25018
- body: JSON.stringify({ head: { Key: userKey }, body: { Email_ID: clientCode, TOTP: freshTotp, PIN: pin } })
25044
+ body: JSON.stringify({ head: { Key: userKey }, body: { Email_ID: clientCode, TOTP: freshTotp, PIN: pin } }),
25045
+ dispatcher: opts?.dispatcher
25019
25046
  });
25020
25047
  totpJson = await retryRes.json();
25021
25048
  }
@@ -25023,12 +25050,12 @@ async function authenticate4(creds) {
25023
25050
  return Err(new Error(`5paisa TOTP login failed: ${totpJson.body?.Message ?? "No RequestToken returned"}`));
25024
25051
  }
25025
25052
  console.log("[5paisa] Step 1 OK: got RequestToken");
25026
- return exchangeRequestToken(totpJson.body.RequestToken, userKey, encryptionKey, userId, clientCode);
25053
+ return exchangeRequestToken(totpJson.body.RequestToken, userKey, encryptionKey, userId, clientCode, opts);
25027
25054
  } catch (err) {
25028
25055
  return Err(err instanceof Error ? err : new Error(String(err)));
25029
25056
  }
25030
25057
  }
25031
- async function exchangeRequestToken(requestToken, userKey, encryptionKey, userId, clientCode) {
25058
+ async function exchangeRequestToken(requestToken, userKey, encryptionKey, userId, clientCode, opts) {
25032
25059
  try {
25033
25060
  const accessPayload = {
25034
25061
  head: { Key: userKey },
@@ -25042,7 +25069,8 @@ async function exchangeRequestToken(requestToken, userKey, encryptionKey, userId
25042
25069
  const accessRes = await fetch(ROUTES.ACCESS_TOKEN, {
25043
25070
  method: "POST",
25044
25071
  headers: { "Content-Type": "application/json" },
25045
- body: JSON.stringify(accessPayload)
25072
+ body: JSON.stringify(accessPayload),
25073
+ dispatcher: opts?.dispatcher
25046
25074
  });
25047
25075
  const accessJson = await accessRes.json();
25048
25076
  if (!accessJson.body?.AccessToken) {
@@ -25064,7 +25092,7 @@ async function exchangeRequestToken(requestToken, userKey, encryptionKey, userId
25064
25092
  return Err(err instanceof Error ? err : new Error(String(err)));
25065
25093
  }
25066
25094
  }
25067
- async function authenticateWithToken(creds) {
25095
+ async function authenticateWithToken(creds, _opts) {
25068
25096
  const accessToken = creds.accessToken;
25069
25097
  const clientCode = creds.clientCode ?? creds.userId ?? "";
25070
25098
  if (!accessToken)
@@ -25364,9 +25392,11 @@ class FivePaisaSocket {
25364
25392
  reconnectAttempts = 0;
25365
25393
  maxReconnects = 5;
25366
25394
  reconnectTimer = null;
25367
- constructor(clientCode, accessToken) {
25395
+ egressIp;
25396
+ constructor(clientCode, accessToken, egressIp) {
25368
25397
  this.clientCode = clientCode;
25369
25398
  this.accessToken = accessToken;
25399
+ this.egressIp = egressIp;
25370
25400
  }
25371
25401
  connect() {
25372
25402
  if (this.state === "CONNECTED" || this.state === "CONNECTING")
@@ -25374,7 +25404,7 @@ class FivePaisaSocket {
25374
25404
  this.state = "CONNECTING";
25375
25405
  const baseUrl = getWsUrl(this.accessToken);
25376
25406
  const url = `${baseUrl}${this.accessToken}|${this.clientCode}`;
25377
- this.ws = new WS3(url);
25407
+ this.ws = new WS3(url, wsEgressOptions(this.egressIp));
25378
25408
  this.ws.on("open", () => {
25379
25409
  this.state = "CONNECTED";
25380
25410
  this.reconnectAttempts = 0;
@@ -25587,15 +25617,19 @@ class FivePaisaInstruments {
25587
25617
  };
25588
25618
  accessToken = "";
25589
25619
  clientCode = "";
25620
+ dispatcher;
25590
25621
  setCredentials(clientCode, accessToken) {
25591
25622
  this.clientCode = clientCode;
25592
25623
  this.accessToken = accessToken;
25593
25624
  }
25625
+ setDispatcher(dispatcher) {
25626
+ this.dispatcher = dispatcher;
25627
+ }
25594
25628
  async* streamDump() {
25595
25629
  for (const segment of SEGMENTS) {
25596
25630
  const url = `${FIVEPAISA_SCRIP_MASTER_BASE3}/${segment}`;
25597
25631
  try {
25598
- const response = await fetch(url);
25632
+ const response = await fetch(url, { dispatcher: this.dispatcher });
25599
25633
  if (!response.ok)
25600
25634
  continue;
25601
25635
  const text = await response.text();
@@ -25717,13 +25751,19 @@ class FivePaisaBroker {
25717
25751
  credentials = null;
25718
25752
  instrumentsImpl;
25719
25753
  _iMaster;
25754
+ egressIp;
25755
+ dispatcher;
25720
25756
  constructor(options) {
25721
25757
  this.instrumentsImpl = new FivePaisaInstruments;
25722
25758
  this.instruments = this.instrumentsImpl;
25723
25759
  this._iMaster = new InstrumentMaster(options);
25760
+ this.egressIp = options?.egressIp;
25761
+ this.dispatcher = egressDispatcher(options?.egressIp);
25762
+ this.instrumentsImpl.setDispatcher(this.dispatcher);
25724
25763
  }
25725
25764
  async authenticate(creds) {
25726
- const result = creds.accessToken ? await authenticateWithToken(creds) : await authenticate4(creds);
25765
+ const opts = { dispatcher: this.dispatcher };
25766
+ const result = creds.accessToken ? await authenticateWithToken(creds, opts) : await authenticate4(creds, opts);
25727
25767
  if (!result.ok)
25728
25768
  return result;
25729
25769
  this.credentials = creds;
@@ -25779,7 +25819,10 @@ class FivePaisaBroker {
25779
25819
  const brokerOid = res.BrokerOrderID ?? 0;
25780
25820
  const isRejected = (res.Status ?? 0) !== 0 || (res.RMSResponseCode ?? 0) < 0 || (res.Message ?? "").toLowerCase().includes("rejected");
25781
25821
  if (isRejected) {
25782
- return Err(new Error(res.Message ?? `Order rejected (Status=${res.Status}, RMS=${res.RMSResponseCode})`));
25822
+ const err = new Error(res.Message ?? `Order rejected (Status=${res.Status}, RMS=${res.RMSResponseCode})`);
25823
+ if (brokerOid > 0)
25824
+ err.brokerOrderId = String(brokerOid);
25825
+ return Err(err);
25783
25826
  }
25784
25827
  if (brokerOid === 0) {
25785
25828
  return Err(new Error(`Order placement failed: ${res.Message ?? "No BrokerOrderID returned"}`));
@@ -26060,7 +26103,8 @@ class FivePaisaBroker {
26060
26103
  headers: {
26061
26104
  "Content-Type": "application/json",
26062
26105
  Authorization: `bearer ${token}`
26063
- }
26106
+ },
26107
+ dispatcher: this.dispatcher
26064
26108
  });
26065
26109
  const text = await res.text();
26066
26110
  let json;
@@ -26232,7 +26276,8 @@ class FivePaisaBroker {
26232
26276
  "Content-Type": "application/json",
26233
26277
  Authorization: `Bearer ${this.session.accessToken}`
26234
26278
  },
26235
- body: JSON.stringify(payload)
26279
+ body: JSON.stringify(payload),
26280
+ dispatcher: this.dispatcher
26236
26281
  });
26237
26282
  const text = await response.text();
26238
26283
  let json;
@@ -26255,7 +26300,7 @@ class FivePaisaBroker {
26255
26300
  }
26256
26301
  return;
26257
26302
  }
26258
- this.socket = new FivePaisaSocket(this.session.userId, this.session.accessToken);
26303
+ this.socket = new FivePaisaSocket(this.session.userId, this.session.accessToken, this.egressIp);
26259
26304
  this.socket.connect();
26260
26305
  }
26261
26306
  }