@pear-protocol/hyperliquid-sdk 0.0.11 → 0.0.12

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.js CHANGED
@@ -1,3930 +1,22 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var axios = require('axios');
6
- var require$$0 = require('react');
7
- var require$$1 = require('react-dom');
8
-
9
- /**
10
- * Main SDK client for Pear Protocol Hyperliquid API integration
11
- */
12
- class PearHyperliquidClient {
13
- constructor(config) {
14
- this.baseUrl = config.baseUrl.replace(/\/$/, ''); // Remove trailing slash
15
- this.httpClient = axios.create({
16
- baseURL: this.baseUrl,
17
- timeout: config.timeout || 30000,
18
- headers: {
19
- 'Content-Type': 'application/json',
20
- ...config.headers,
21
- },
22
- });
23
- // Add response interceptor for error handling
24
- this.httpClient.interceptors.response.use((response) => response, (error) => {
25
- var _a, _b, _c, _d, _e;
26
- const apiError = {
27
- statusCode: ((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) || 500,
28
- message: ((_c = (_b = error.response) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.message) || error.message,
29
- error: (_e = (_d = error.response) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.error,
30
- };
31
- return Promise.reject(apiError);
32
- });
33
- }
34
- /**
35
- * Get the configured base URL
36
- */
37
- getBaseUrl() {
38
- return this.baseUrl;
39
- }
40
- /**
41
- * Update request headers
42
- */
43
- setHeaders(headers) {
44
- this.httpClient.defaults.headers = {
45
- ...this.httpClient.defaults.headers,
46
- ...headers,
47
- };
48
- }
49
- /**
50
- * Set authorization header
51
- */
52
- setAuthToken(token) {
53
- this.setHeaders({ Authorization: `Bearer ${token}` });
54
- }
55
- /**
56
- * Make a generic HTTP request
57
- */
58
- async makeRequest(method, endpoint, data) {
59
- const response = await this.httpClient.request({
60
- method,
61
- url: endpoint,
62
- data,
63
- });
64
- return {
65
- data: response.data,
66
- status: response.status,
67
- headers: response.headers,
68
- };
69
- }
70
- /**
71
- * Sync trade history data from old database structure to new database format
72
- * @param payload - Trade history data with user address
73
- * @returns Promise with sync result
74
- */
75
- async syncTradeHistory(payload) {
76
- return this.makeRequest('POST', '/syncer/trade-histories', payload);
77
- }
78
- /**
79
- * Sync open positions data from old database structure to new database format
80
- * @param payload - Open positions data with user address
81
- * @returns Promise with sync result
82
- */
83
- async syncOpenPositions(payload) {
84
- return this.makeRequest('POST', '/syncer/open-positions', payload);
85
- }
86
- /**
87
- * Sync open orders data from old database structure to new database format
88
- * @param payload - Open orders data with user address
89
- * @returns Promise with sync result
90
- */
91
- async syncOpenOrders(payload) {
92
- return this.makeRequest('POST', '/syncer/open-orders', payload);
93
- }
94
- }
95
-
96
- /**
97
- * Main Migration SDK Class - Simple request/response pattern
98
- */
99
- class PearMigrationSDK {
100
- constructor(client) {
101
- this.isTradeHistorySyncRunning = false;
102
- this.isOpenPositionsSyncRunning = false;
103
- this.isOpenOrdersSyncRunning = false;
104
- this.client = client;
105
- }
106
- /**
107
- * Sync trade history data - can only run one at a time
108
- * If called while already running, returns immediately without making request
109
- */
110
- async syncTradeHistory(payload) {
111
- // If sync is already running, return immediately
112
- if (this.isTradeHistorySyncRunning) {
113
- return null;
114
- }
115
- try {
116
- this.isTradeHistorySyncRunning = true;
117
- const response = await this.client.syncTradeHistory(payload);
118
- return response;
119
- }
120
- finally {
121
- this.isTradeHistorySyncRunning = false;
122
- }
123
- }
124
- /**
125
- * Sync open positions data - can only run one at a time
126
- * If called while already running, returns immediately without making request
127
- */
128
- async syncOpenPositions(payload) {
129
- // If sync is already running, return immediately
130
- if (this.isOpenPositionsSyncRunning) {
131
- return null;
132
- }
133
- try {
134
- this.isOpenPositionsSyncRunning = true;
135
- const response = await this.client.syncOpenPositions(payload);
136
- return response;
137
- }
138
- finally {
139
- this.isOpenPositionsSyncRunning = false;
140
- }
141
- }
142
- /**
143
- * Sync open orders data - can only run one at a time
144
- * If called while already running, returns immediately without making request
145
- */
146
- async syncOpenOrders(payload) {
147
- // If sync is already running, return immediately
148
- if (this.isOpenOrdersSyncRunning) {
149
- return null;
150
- }
151
- try {
152
- this.isOpenOrdersSyncRunning = true;
153
- const response = await this.client.syncOpenOrders(payload);
154
- return response;
155
- }
156
- finally {
157
- this.isOpenOrdersSyncRunning = false;
158
- }
159
- }
160
- /**
161
- * Check if any sync is currently running
162
- */
163
- isSyncInProgress() {
164
- return this.isTradeHistorySyncRunning || this.isOpenPositionsSyncRunning || this.isOpenOrdersSyncRunning;
165
- }
166
- /**
167
- * Check if trade history sync is currently running
168
- */
169
- isTradeHistorySyncInProgress() {
170
- return this.isTradeHistorySyncRunning;
171
- }
172
- /**
173
- * Check if open positions sync is currently running
174
- */
175
- isOpenPositionsSyncInProgress() {
176
- return this.isOpenPositionsSyncRunning;
177
- }
178
- /**
179
- * Check if open orders sync is currently running
180
- */
181
- isOpenOrdersSyncInProgress() {
182
- return this.isOpenOrdersSyncRunning;
183
- }
184
- /**
185
- * Get the underlying client instance
186
- */
187
- getClient() {
188
- return this.client;
189
- }
190
- /**
191
- * Set authorization token on the client
192
- */
193
- setAuthToken(token) {
194
- this.client.setAuthToken(token);
195
- }
196
- /**
197
- * Set custom headers on the client
198
- */
199
- setHeaders(headers) {
200
- this.client.setHeaders(headers);
201
- }
202
- /**
203
- * Get base URL from client
204
- */
205
- getBaseUrl() {
206
- return this.client.getBaseUrl();
207
- }
208
- }
209
-
210
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
211
-
212
- function getDefaultExportFromCjs (x) {
213
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
214
- }
215
-
216
- var jsxRuntime = {exports: {}};
217
-
218
- var reactJsxRuntime_production_min = {};
219
-
220
- /**
1
+ var et=Object.defineProperty;var d=(t,e)=>et(t,"name",{value:e,configurable:!0});import tt from"axios";import ve,{useState as B,useEffect as ce,useRef as nt,createContext as rt,useMemo as D,useContext as ee,useCallback as z}from"react";import ot from"react-dom";class Me{static{d(this,"PearHyperliquidClient")}constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.httpClient=tt.create({baseURL:this.baseUrl,timeout:e.timeout||3e4,headers:{"Content-Type":"application/json",...e.headers}}),this.httpClient.interceptors.response.use(n=>n,n=>{var a,r,o,s,f;const c={statusCode:((a=n.response)===null||a===void 0?void 0:a.status)||500,message:((o=(r=n.response)===null||r===void 0?void 0:r.data)===null||o===void 0?void 0:o.message)||n.message,error:(f=(s=n.response)===null||s===void 0?void 0:s.data)===null||f===void 0?void 0:f.error};return Promise.reject(c)})}getBaseUrl(){return this.baseUrl}setHeaders(e){this.httpClient.defaults.headers={...this.httpClient.defaults.headers,...e}}setAuthToken(e){this.setHeaders({Authorization:`Bearer ${e}`})}async makeRequest(e,n,a){const r=await this.httpClient.request({method:e,url:n,data:a});return{data:r.data,status:r.status,headers:r.headers}}async syncTradeHistory(e){return this.makeRequest("POST","/syncer/trade-histories",e)}async syncOpenPositions(e){return this.makeRequest("POST","/syncer/open-positions",e)}async syncOpenOrders(e){return this.makeRequest("POST","/syncer/open-orders",e)}}class je{static{d(this,"PearMigrationSDK")}constructor(e){this.isTradeHistorySyncRunning=!1,this.isOpenPositionsSyncRunning=!1,this.isOpenOrdersSyncRunning=!1,this.client=e}async syncTradeHistory(e){if(this.isTradeHistorySyncRunning)return null;try{return this.isTradeHistorySyncRunning=!0,await this.client.syncTradeHistory(e)}finally{this.isTradeHistorySyncRunning=!1}}async syncOpenPositions(e){if(this.isOpenPositionsSyncRunning)return null;try{return this.isOpenPositionsSyncRunning=!0,await this.client.syncOpenPositions(e)}finally{this.isOpenPositionsSyncRunning=!1}}async syncOpenOrders(e){if(this.isOpenOrdersSyncRunning)return null;try{return this.isOpenOrdersSyncRunning=!0,await this.client.syncOpenOrders(e)}finally{this.isOpenOrdersSyncRunning=!1}}isSyncInProgress(){return this.isTradeHistorySyncRunning||this.isOpenPositionsSyncRunning||this.isOpenOrdersSyncRunning}isTradeHistorySyncInProgress(){return this.isTradeHistorySyncRunning}isOpenPositionsSyncInProgress(){return this.isOpenPositionsSyncRunning}isOpenOrdersSyncInProgress(){return this.isOpenOrdersSyncRunning}getClient(){return this.client}setAuthToken(e){this.client.setAuthToken(e)}setHeaders(e){this.client.setHeaders(e)}getBaseUrl(){return this.client.getBaseUrl()}}var A=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function at(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}d(at,"getDefaultExportFromCjs");var Re={exports:{}},ue={};/**
221
2
  * @license React
222
- * react-jsx-runtime.production.min.js
3
+ * react-jsx-runtime.production.js
223
4
  *
224
- * Copyright (c) Facebook, Inc. and its affiliates.
5
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
225
6
  *
226
7
  * This source code is licensed under the MIT license found in the
227
8
  * LICENSE file in the root directory of this source tree.
228
- */
229
-
230
- var hasRequiredReactJsxRuntime_production_min;
231
-
232
- function requireReactJsxRuntime_production_min () {
233
- if (hasRequiredReactJsxRuntime_production_min) return reactJsxRuntime_production_min;
234
- hasRequiredReactJsxRuntime_production_min = 1;
235
- var f=require$$0,k=Symbol.for("react.element"),l=Symbol.for("react.fragment"),m=Object.prototype.hasOwnProperty,n=f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,p={key:!0,ref:!0,__self:!0,__source:!0};
236
- function q(c,a,g){var b,d={},e=null,h=null;void 0!==g&&(e=""+g);void 0!==a.key&&(e=""+a.key);void 0!==a.ref&&(h=a.ref);for(b in a)m.call(a,b)&&!p.hasOwnProperty(b)&&(d[b]=a[b]);if(c&&c.defaultProps)for(b in a=c.defaultProps,a)void 0===d[b]&&(d[b]=a[b]);return {$$typeof:k,type:c,key:e,ref:h,props:d,_owner:n.current}}reactJsxRuntime_production_min.Fragment=l;reactJsxRuntime_production_min.jsx=q;reactJsxRuntime_production_min.jsxs=q;
237
- return reactJsxRuntime_production_min;
238
- }
239
-
240
- var reactJsxRuntime_development = {};
241
-
242
- /**
9
+ */var Fe;function st(){if(Fe)return ue;Fe=1;var t=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(a,r,o){var s=null;if(o!==void 0&&(s=""+o),r.key!==void 0&&(s=""+r.key),"key"in r){o={};for(var f in r)f!=="key"&&(o[f]=r[f])}else o=r;return r=o.ref,{$$typeof:t,type:a,key:s,ref:r!==void 0?r:null,props:o}}return d(n,"jsxProd"),ue.Fragment=e,ue.jsx=n,ue.jsxs=n,ue}d(st,"requireReactJsxRuntime_production");var le={};/**
243
10
  * @license React
244
11
  * react-jsx-runtime.development.js
245
12
  *
246
- * Copyright (c) Facebook, Inc. and its affiliates.
13
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
247
14
  *
248
15
  * This source code is licensed under the MIT license found in the
249
16
  * LICENSE file in the root directory of this source tree.
250
- */
251
-
252
- var hasRequiredReactJsxRuntime_development;
253
-
254
- function requireReactJsxRuntime_development () {
255
- if (hasRequiredReactJsxRuntime_development) return reactJsxRuntime_development;
256
- hasRequiredReactJsxRuntime_development = 1;
257
-
258
- if (process.env.NODE_ENV !== "production") {
259
- (function() {
260
-
261
- var React = require$$0;
262
-
263
- // ATTENTION
264
- // When adding new symbols to this file,
265
- // Please consider also adding to 'react-devtools-shared/src/backend/ReactSymbols'
266
- // The Symbol used to tag the ReactElement-like types.
267
- var REACT_ELEMENT_TYPE = Symbol.for('react.element');
268
- var REACT_PORTAL_TYPE = Symbol.for('react.portal');
269
- var REACT_FRAGMENT_TYPE = Symbol.for('react.fragment');
270
- var REACT_STRICT_MODE_TYPE = Symbol.for('react.strict_mode');
271
- var REACT_PROFILER_TYPE = Symbol.for('react.profiler');
272
- var REACT_PROVIDER_TYPE = Symbol.for('react.provider');
273
- var REACT_CONTEXT_TYPE = Symbol.for('react.context');
274
- var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
275
- var REACT_SUSPENSE_TYPE = Symbol.for('react.suspense');
276
- var REACT_SUSPENSE_LIST_TYPE = Symbol.for('react.suspense_list');
277
- var REACT_MEMO_TYPE = Symbol.for('react.memo');
278
- var REACT_LAZY_TYPE = Symbol.for('react.lazy');
279
- var REACT_OFFSCREEN_TYPE = Symbol.for('react.offscreen');
280
- var MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
281
- var FAUX_ITERATOR_SYMBOL = '@@iterator';
282
- function getIteratorFn(maybeIterable) {
283
- if (maybeIterable === null || typeof maybeIterable !== 'object') {
284
- return null;
285
- }
286
-
287
- var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL];
288
-
289
- if (typeof maybeIterator === 'function') {
290
- return maybeIterator;
291
- }
292
-
293
- return null;
294
- }
295
-
296
- var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
297
-
298
- function error(format) {
299
- {
300
- {
301
- for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
302
- args[_key2 - 1] = arguments[_key2];
303
- }
304
-
305
- printWarning('error', format, args);
306
- }
307
- }
308
- }
309
-
310
- function printWarning(level, format, args) {
311
- // When changing this logic, you might want to also
312
- // update consoleWithStackDev.www.js as well.
313
- {
314
- var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
315
- var stack = ReactDebugCurrentFrame.getStackAddendum();
316
-
317
- if (stack !== '') {
318
- format += '%s';
319
- args = args.concat([stack]);
320
- } // eslint-disable-next-line react-internal/safe-string-coercion
321
-
322
-
323
- var argsWithFormat = args.map(function (item) {
324
- return String(item);
325
- }); // Careful: RN currently depends on this prefix
326
-
327
- argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
328
- // breaks IE9: https://github.com/facebook/react/issues/13610
329
- // eslint-disable-next-line react-internal/no-production-logging
330
-
331
- Function.prototype.apply.call(console[level], console, argsWithFormat);
332
- }
333
- }
334
-
335
- // -----------------------------------------------------------------------------
336
-
337
- var enableScopeAPI = false; // Experimental Create Event Handle API.
338
- var enableCacheElement = false;
339
- var enableTransitionTracing = false; // No known bugs, but needs performance testing
340
-
341
- var enableLegacyHidden = false; // Enables unstable_avoidThisFallback feature in Fiber
342
- // stuff. Intended to enable React core members to more easily debug scheduling
343
- // issues in DEV builds.
344
-
345
- var enableDebugTracing = false; // Track which Fiber(s) schedule render work.
346
-
347
- var REACT_MODULE_REFERENCE;
348
-
349
- {
350
- REACT_MODULE_REFERENCE = Symbol.for('react.module.reference');
351
- }
352
-
353
- function isValidElementType(type) {
354
- if (typeof type === 'string' || typeof type === 'function') {
355
- return true;
356
- } // Note: typeof might be other than 'symbol' or 'number' (e.g. if it's a polyfill).
357
-
358
-
359
- if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing ) {
360
- return true;
361
- }
362
-
363
- if (typeof type === 'object' && type !== null) {
364
- if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object
365
- // types supported by any Flight configuration anywhere since
366
- // we don't know which Flight build this will end up being used
367
- // with.
368
- type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) {
369
- return true;
370
- }
371
- }
372
-
373
- return false;
374
- }
375
-
376
- function getWrappedName(outerType, innerType, wrapperName) {
377
- var displayName = outerType.displayName;
378
-
379
- if (displayName) {
380
- return displayName;
381
- }
382
-
383
- var functionName = innerType.displayName || innerType.name || '';
384
- return functionName !== '' ? wrapperName + "(" + functionName + ")" : wrapperName;
385
- } // Keep in sync with react-reconciler/getComponentNameFromFiber
386
-
387
-
388
- function getContextName(type) {
389
- return type.displayName || 'Context';
390
- } // Note that the reconciler package should generally prefer to use getComponentNameFromFiber() instead.
391
-
392
-
393
- function getComponentNameFromType(type) {
394
- if (type == null) {
395
- // Host root, text node or just invalid type.
396
- return null;
397
- }
398
-
399
- {
400
- if (typeof type.tag === 'number') {
401
- error('Received an unexpected object in getComponentNameFromType(). ' + 'This is likely a bug in React. Please file an issue.');
402
- }
403
- }
404
-
405
- if (typeof type === 'function') {
406
- return type.displayName || type.name || null;
407
- }
408
-
409
- if (typeof type === 'string') {
410
- return type;
411
- }
412
-
413
- switch (type) {
414
- case REACT_FRAGMENT_TYPE:
415
- return 'Fragment';
416
-
417
- case REACT_PORTAL_TYPE:
418
- return 'Portal';
419
-
420
- case REACT_PROFILER_TYPE:
421
- return 'Profiler';
422
-
423
- case REACT_STRICT_MODE_TYPE:
424
- return 'StrictMode';
425
-
426
- case REACT_SUSPENSE_TYPE:
427
- return 'Suspense';
428
-
429
- case REACT_SUSPENSE_LIST_TYPE:
430
- return 'SuspenseList';
431
-
432
- }
433
-
434
- if (typeof type === 'object') {
435
- switch (type.$$typeof) {
436
- case REACT_CONTEXT_TYPE:
437
- var context = type;
438
- return getContextName(context) + '.Consumer';
439
-
440
- case REACT_PROVIDER_TYPE:
441
- var provider = type;
442
- return getContextName(provider._context) + '.Provider';
443
-
444
- case REACT_FORWARD_REF_TYPE:
445
- return getWrappedName(type, type.render, 'ForwardRef');
446
-
447
- case REACT_MEMO_TYPE:
448
- var outerName = type.displayName || null;
449
-
450
- if (outerName !== null) {
451
- return outerName;
452
- }
453
-
454
- return getComponentNameFromType(type.type) || 'Memo';
455
-
456
- case REACT_LAZY_TYPE:
457
- {
458
- var lazyComponent = type;
459
- var payload = lazyComponent._payload;
460
- var init = lazyComponent._init;
461
-
462
- try {
463
- return getComponentNameFromType(init(payload));
464
- } catch (x) {
465
- return null;
466
- }
467
- }
468
-
469
- // eslint-disable-next-line no-fallthrough
470
- }
471
- }
472
-
473
- return null;
474
- }
475
-
476
- var assign = Object.assign;
477
-
478
- // Helpers to patch console.logs to avoid logging during side-effect free
479
- // replaying on render function. This currently only patches the object
480
- // lazily which won't cover if the log function was extracted eagerly.
481
- // We could also eagerly patch the method.
482
- var disabledDepth = 0;
483
- var prevLog;
484
- var prevInfo;
485
- var prevWarn;
486
- var prevError;
487
- var prevGroup;
488
- var prevGroupCollapsed;
489
- var prevGroupEnd;
490
-
491
- function disabledLog() {}
492
-
493
- disabledLog.__reactDisabledLog = true;
494
- function disableLogs() {
495
- {
496
- if (disabledDepth === 0) {
497
- /* eslint-disable react-internal/no-production-logging */
498
- prevLog = console.log;
499
- prevInfo = console.info;
500
- prevWarn = console.warn;
501
- prevError = console.error;
502
- prevGroup = console.group;
503
- prevGroupCollapsed = console.groupCollapsed;
504
- prevGroupEnd = console.groupEnd; // https://github.com/facebook/react/issues/19099
505
-
506
- var props = {
507
- configurable: true,
508
- enumerable: true,
509
- value: disabledLog,
510
- writable: true
511
- }; // $FlowFixMe Flow thinks console is immutable.
512
-
513
- Object.defineProperties(console, {
514
- info: props,
515
- log: props,
516
- warn: props,
517
- error: props,
518
- group: props,
519
- groupCollapsed: props,
520
- groupEnd: props
521
- });
522
- /* eslint-enable react-internal/no-production-logging */
523
- }
524
-
525
- disabledDepth++;
526
- }
527
- }
528
- function reenableLogs() {
529
- {
530
- disabledDepth--;
531
-
532
- if (disabledDepth === 0) {
533
- /* eslint-disable react-internal/no-production-logging */
534
- var props = {
535
- configurable: true,
536
- enumerable: true,
537
- writable: true
538
- }; // $FlowFixMe Flow thinks console is immutable.
539
-
540
- Object.defineProperties(console, {
541
- log: assign({}, props, {
542
- value: prevLog
543
- }),
544
- info: assign({}, props, {
545
- value: prevInfo
546
- }),
547
- warn: assign({}, props, {
548
- value: prevWarn
549
- }),
550
- error: assign({}, props, {
551
- value: prevError
552
- }),
553
- group: assign({}, props, {
554
- value: prevGroup
555
- }),
556
- groupCollapsed: assign({}, props, {
557
- value: prevGroupCollapsed
558
- }),
559
- groupEnd: assign({}, props, {
560
- value: prevGroupEnd
561
- })
562
- });
563
- /* eslint-enable react-internal/no-production-logging */
564
- }
565
-
566
- if (disabledDepth < 0) {
567
- error('disabledDepth fell below zero. ' + 'This is a bug in React. Please file an issue.');
568
- }
569
- }
570
- }
571
-
572
- var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
573
- var prefix;
574
- function describeBuiltInComponentFrame(name, source, ownerFn) {
575
- {
576
- if (prefix === undefined) {
577
- // Extract the VM specific prefix used by each line.
578
- try {
579
- throw Error();
580
- } catch (x) {
581
- var match = x.stack.trim().match(/\n( *(at )?)/);
582
- prefix = match && match[1] || '';
583
- }
584
- } // We use the prefix to ensure our stacks line up with native stack frames.
585
-
586
-
587
- return '\n' + prefix + name;
588
- }
589
- }
590
- var reentry = false;
591
- var componentFrameCache;
592
-
593
- {
594
- var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
595
- componentFrameCache = new PossiblyWeakMap();
596
- }
597
-
598
- function describeNativeComponentFrame(fn, construct) {
599
- // If something asked for a stack inside a fake render, it should get ignored.
600
- if ( !fn || reentry) {
601
- return '';
602
- }
603
-
604
- {
605
- var frame = componentFrameCache.get(fn);
606
-
607
- if (frame !== undefined) {
608
- return frame;
609
- }
610
- }
611
-
612
- var control;
613
- reentry = true;
614
- var previousPrepareStackTrace = Error.prepareStackTrace; // $FlowFixMe It does accept undefined.
615
-
616
- Error.prepareStackTrace = undefined;
617
- var previousDispatcher;
618
-
619
- {
620
- previousDispatcher = ReactCurrentDispatcher.current; // Set the dispatcher in DEV because this might be call in the render function
621
- // for warnings.
622
-
623
- ReactCurrentDispatcher.current = null;
624
- disableLogs();
625
- }
626
-
627
- try {
628
- // This should throw.
629
- if (construct) {
630
- // Something should be setting the props in the constructor.
631
- var Fake = function () {
632
- throw Error();
633
- }; // $FlowFixMe
634
-
635
-
636
- Object.defineProperty(Fake.prototype, 'props', {
637
- set: function () {
638
- // We use a throwing setter instead of frozen or non-writable props
639
- // because that won't throw in a non-strict mode function.
640
- throw Error();
641
- }
642
- });
643
-
644
- if (typeof Reflect === 'object' && Reflect.construct) {
645
- // We construct a different control for this case to include any extra
646
- // frames added by the construct call.
647
- try {
648
- Reflect.construct(Fake, []);
649
- } catch (x) {
650
- control = x;
651
- }
652
-
653
- Reflect.construct(fn, [], Fake);
654
- } else {
655
- try {
656
- Fake.call();
657
- } catch (x) {
658
- control = x;
659
- }
660
-
661
- fn.call(Fake.prototype);
662
- }
663
- } else {
664
- try {
665
- throw Error();
666
- } catch (x) {
667
- control = x;
668
- }
669
-
670
- fn();
671
- }
672
- } catch (sample) {
673
- // This is inlined manually because closure doesn't do it for us.
674
- if (sample && control && typeof sample.stack === 'string') {
675
- // This extracts the first frame from the sample that isn't also in the control.
676
- // Skipping one frame that we assume is the frame that calls the two.
677
- var sampleLines = sample.stack.split('\n');
678
- var controlLines = control.stack.split('\n');
679
- var s = sampleLines.length - 1;
680
- var c = controlLines.length - 1;
681
-
682
- while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) {
683
- // We expect at least one stack frame to be shared.
684
- // Typically this will be the root most one. However, stack frames may be
685
- // cut off due to maximum stack limits. In this case, one maybe cut off
686
- // earlier than the other. We assume that the sample is longer or the same
687
- // and there for cut off earlier. So we should find the root most frame in
688
- // the sample somewhere in the control.
689
- c--;
690
- }
691
-
692
- for (; s >= 1 && c >= 0; s--, c--) {
693
- // Next we find the first one that isn't the same which should be the
694
- // frame that called our sample function and the control.
695
- if (sampleLines[s] !== controlLines[c]) {
696
- // In V8, the first line is describing the message but other VMs don't.
697
- // If we're about to return the first line, and the control is also on the same
698
- // line, that's a pretty good indicator that our sample threw at same line as
699
- // the control. I.e. before we entered the sample frame. So we ignore this result.
700
- // This can happen if you passed a class to function component, or non-function.
701
- if (s !== 1 || c !== 1) {
702
- do {
703
- s--;
704
- c--; // We may still have similar intermediate frames from the construct call.
705
- // The next one that isn't the same should be our match though.
706
-
707
- if (c < 0 || sampleLines[s] !== controlLines[c]) {
708
- // V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
709
- var _frame = '\n' + sampleLines[s].replace(' at new ', ' at '); // If our component frame is labeled "<anonymous>"
710
- // but we have a user-provided "displayName"
711
- // splice it in to make the stack more readable.
712
-
713
-
714
- if (fn.displayName && _frame.includes('<anonymous>')) {
715
- _frame = _frame.replace('<anonymous>', fn.displayName);
716
- }
717
-
718
- {
719
- if (typeof fn === 'function') {
720
- componentFrameCache.set(fn, _frame);
721
- }
722
- } // Return the line we found.
723
-
724
-
725
- return _frame;
726
- }
727
- } while (s >= 1 && c >= 0);
728
- }
729
-
730
- break;
731
- }
732
- }
733
- }
734
- } finally {
735
- reentry = false;
736
-
737
- {
738
- ReactCurrentDispatcher.current = previousDispatcher;
739
- reenableLogs();
740
- }
741
-
742
- Error.prepareStackTrace = previousPrepareStackTrace;
743
- } // Fallback to just using the name if we couldn't make it throw.
744
-
745
-
746
- var name = fn ? fn.displayName || fn.name : '';
747
- var syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
748
-
749
- {
750
- if (typeof fn === 'function') {
751
- componentFrameCache.set(fn, syntheticFrame);
752
- }
753
- }
754
-
755
- return syntheticFrame;
756
- }
757
- function describeFunctionComponentFrame(fn, source, ownerFn) {
758
- {
759
- return describeNativeComponentFrame(fn, false);
760
- }
761
- }
762
-
763
- function shouldConstruct(Component) {
764
- var prototype = Component.prototype;
765
- return !!(prototype && prototype.isReactComponent);
766
- }
767
-
768
- function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) {
769
-
770
- if (type == null) {
771
- return '';
772
- }
773
-
774
- if (typeof type === 'function') {
775
- {
776
- return describeNativeComponentFrame(type, shouldConstruct(type));
777
- }
778
- }
779
-
780
- if (typeof type === 'string') {
781
- return describeBuiltInComponentFrame(type);
782
- }
783
-
784
- switch (type) {
785
- case REACT_SUSPENSE_TYPE:
786
- return describeBuiltInComponentFrame('Suspense');
787
-
788
- case REACT_SUSPENSE_LIST_TYPE:
789
- return describeBuiltInComponentFrame('SuspenseList');
790
- }
791
-
792
- if (typeof type === 'object') {
793
- switch (type.$$typeof) {
794
- case REACT_FORWARD_REF_TYPE:
795
- return describeFunctionComponentFrame(type.render);
796
-
797
- case REACT_MEMO_TYPE:
798
- // Memo may contain any component type so we recursively resolve it.
799
- return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn);
800
-
801
- case REACT_LAZY_TYPE:
802
- {
803
- var lazyComponent = type;
804
- var payload = lazyComponent._payload;
805
- var init = lazyComponent._init;
806
-
807
- try {
808
- // Lazy may contain any component type so we recursively resolve it.
809
- return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn);
810
- } catch (x) {}
811
- }
812
- }
813
- }
814
-
815
- return '';
816
- }
817
-
818
- var hasOwnProperty = Object.prototype.hasOwnProperty;
819
-
820
- var loggedTypeFailures = {};
821
- var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
822
-
823
- function setCurrentlyValidatingElement(element) {
824
- {
825
- if (element) {
826
- var owner = element._owner;
827
- var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
828
- ReactDebugCurrentFrame.setExtraStackFrame(stack);
829
- } else {
830
- ReactDebugCurrentFrame.setExtraStackFrame(null);
831
- }
832
- }
833
- }
834
-
835
- function checkPropTypes(typeSpecs, values, location, componentName, element) {
836
- {
837
- // $FlowFixMe This is okay but Flow doesn't know it.
838
- var has = Function.call.bind(hasOwnProperty);
839
-
840
- for (var typeSpecName in typeSpecs) {
841
- if (has(typeSpecs, typeSpecName)) {
842
- var error$1 = void 0; // Prop type validation may throw. In case they do, we don't want to
843
- // fail the render phase where it didn't fail before. So we log it.
844
- // After these have been cleaned up, we'll let them throw.
845
-
846
- try {
847
- // This is intentionally an invariant that gets caught. It's the same
848
- // behavior as without this statement except with a better message.
849
- if (typeof typeSpecs[typeSpecName] !== 'function') {
850
- // eslint-disable-next-line react-internal/prod-error-codes
851
- var err = Error((componentName || 'React class') + ': ' + location + ' type `' + typeSpecName + '` is invalid; ' + 'it must be a function, usually from the `prop-types` package, but received `' + typeof typeSpecs[typeSpecName] + '`.' + 'This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.');
852
- err.name = 'Invariant Violation';
853
- throw err;
854
- }
855
-
856
- error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED');
857
- } catch (ex) {
858
- error$1 = ex;
859
- }
860
-
861
- if (error$1 && !(error$1 instanceof Error)) {
862
- setCurrentlyValidatingElement(element);
863
-
864
- error('%s: type specification of %s' + ' `%s` is invalid; the type checker ' + 'function must return `null` or an `Error` but returned a %s. ' + 'You may have forgotten to pass an argument to the type checker ' + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).', componentName || 'React class', location, typeSpecName, typeof error$1);
865
-
866
- setCurrentlyValidatingElement(null);
867
- }
868
-
869
- if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) {
870
- // Only monitor this failure once because there tends to be a lot of the
871
- // same error.
872
- loggedTypeFailures[error$1.message] = true;
873
- setCurrentlyValidatingElement(element);
874
-
875
- error('Failed %s type: %s', location, error$1.message);
876
-
877
- setCurrentlyValidatingElement(null);
878
- }
879
- }
880
- }
881
- }
882
- }
883
-
884
- var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
885
-
886
- function isArray(a) {
887
- return isArrayImpl(a);
888
- }
889
-
890
- /*
891
- * The `'' + value` pattern (used in in perf-sensitive code) throws for Symbol
892
- * and Temporal.* types. See https://github.com/facebook/react/pull/22064.
893
- *
894
- * The functions in this module will throw an easier-to-understand,
895
- * easier-to-debug exception with a clear errors message message explaining the
896
- * problem. (Instead of a confusing exception thrown inside the implementation
897
- * of the `value` object).
898
- */
899
- // $FlowFixMe only called in DEV, so void return is not possible.
900
- function typeName(value) {
901
- {
902
- // toStringTag is needed for namespaced types like Temporal.Instant
903
- var hasToStringTag = typeof Symbol === 'function' && Symbol.toStringTag;
904
- var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || 'Object';
905
- return type;
906
- }
907
- } // $FlowFixMe only called in DEV, so void return is not possible.
908
-
909
-
910
- function willCoercionThrow(value) {
911
- {
912
- try {
913
- testStringCoercion(value);
914
- return false;
915
- } catch (e) {
916
- return true;
917
- }
918
- }
919
- }
920
-
921
- function testStringCoercion(value) {
922
- // If you ended up here by following an exception call stack, here's what's
923
- // happened: you supplied an object or symbol value to React (as a prop, key,
924
- // DOM attribute, CSS property, string ref, etc.) and when React tried to
925
- // coerce it to a string using `'' + value`, an exception was thrown.
926
- //
927
- // The most common types that will cause this exception are `Symbol` instances
928
- // and Temporal objects like `Temporal.Instant`. But any object that has a
929
- // `valueOf` or `[Symbol.toPrimitive]` method that throws will also cause this
930
- // exception. (Library authors do this to prevent users from using built-in
931
- // numeric operators like `+` or comparison operators like `>=` because custom
932
- // methods are needed to perform accurate arithmetic or comparison.)
933
- //
934
- // To fix the problem, coerce this object or symbol value to a string before
935
- // passing it to React. The most reliable way is usually `String(value)`.
936
- //
937
- // To find which value is throwing, check the browser or debugger console.
938
- // Before this exception was thrown, there should be `console.error` output
939
- // that shows the type (Symbol, Temporal.PlainDate, etc.) that caused the
940
- // problem and how that type was used: key, atrribute, input value prop, etc.
941
- // In most cases, this console output also shows the component and its
942
- // ancestor components where the exception happened.
943
- //
944
- // eslint-disable-next-line react-internal/safe-string-coercion
945
- return '' + value;
946
- }
947
- function checkKeyStringCoercion(value) {
948
- {
949
- if (willCoercionThrow(value)) {
950
- error('The provided key is an unsupported type %s.' + ' This value must be coerced to a string before before using it here.', typeName(value));
951
-
952
- return testStringCoercion(value); // throw (to help callers find troubleshooting comments)
953
- }
954
- }
955
- }
956
-
957
- var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
958
- var RESERVED_PROPS = {
959
- key: true,
960
- ref: true,
961
- __self: true,
962
- __source: true
963
- };
964
- var specialPropKeyWarningShown;
965
- var specialPropRefWarningShown;
966
- var didWarnAboutStringRefs;
967
-
968
- {
969
- didWarnAboutStringRefs = {};
970
- }
971
-
972
- function hasValidRef(config) {
973
- {
974
- if (hasOwnProperty.call(config, 'ref')) {
975
- var getter = Object.getOwnPropertyDescriptor(config, 'ref').get;
976
-
977
- if (getter && getter.isReactWarning) {
978
- return false;
979
- }
980
- }
981
- }
982
-
983
- return config.ref !== undefined;
984
- }
985
-
986
- function hasValidKey(config) {
987
- {
988
- if (hasOwnProperty.call(config, 'key')) {
989
- var getter = Object.getOwnPropertyDescriptor(config, 'key').get;
990
-
991
- if (getter && getter.isReactWarning) {
992
- return false;
993
- }
994
- }
995
- }
996
-
997
- return config.key !== undefined;
998
- }
999
-
1000
- function warnIfStringRefCannotBeAutoConverted(config, self) {
1001
- {
1002
- if (typeof config.ref === 'string' && ReactCurrentOwner.current && self && ReactCurrentOwner.current.stateNode !== self) {
1003
- var componentName = getComponentNameFromType(ReactCurrentOwner.current.type);
1004
-
1005
- if (!didWarnAboutStringRefs[componentName]) {
1006
- error('Component "%s" contains the string ref "%s". ' + 'Support for string refs will be removed in a future major release. ' + 'This case cannot be automatically converted to an arrow function. ' + 'We ask you to manually fix this case by using useRef() or createRef() instead. ' + 'Learn more about using refs safely here: ' + 'https://reactjs.org/link/strict-mode-string-ref', getComponentNameFromType(ReactCurrentOwner.current.type), config.ref);
1007
-
1008
- didWarnAboutStringRefs[componentName] = true;
1009
- }
1010
- }
1011
- }
1012
- }
1013
-
1014
- function defineKeyPropWarningGetter(props, displayName) {
1015
- {
1016
- var warnAboutAccessingKey = function () {
1017
- if (!specialPropKeyWarningShown) {
1018
- specialPropKeyWarningShown = true;
1019
-
1020
- error('%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
1021
- }
1022
- };
1023
-
1024
- warnAboutAccessingKey.isReactWarning = true;
1025
- Object.defineProperty(props, 'key', {
1026
- get: warnAboutAccessingKey,
1027
- configurable: true
1028
- });
1029
- }
1030
- }
1031
-
1032
- function defineRefPropWarningGetter(props, displayName) {
1033
- {
1034
- var warnAboutAccessingRef = function () {
1035
- if (!specialPropRefWarningShown) {
1036
- specialPropRefWarningShown = true;
1037
-
1038
- error('%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://reactjs.org/link/special-props)', displayName);
1039
- }
1040
- };
1041
-
1042
- warnAboutAccessingRef.isReactWarning = true;
1043
- Object.defineProperty(props, 'ref', {
1044
- get: warnAboutAccessingRef,
1045
- configurable: true
1046
- });
1047
- }
1048
- }
1049
- /**
1050
- * Factory method to create a new React element. This no longer adheres to
1051
- * the class pattern, so do not use new to call it. Also, instanceof check
1052
- * will not work. Instead test $$typeof field against Symbol.for('react.element') to check
1053
- * if something is a React Element.
1054
- *
1055
- * @param {*} type
1056
- * @param {*} props
1057
- * @param {*} key
1058
- * @param {string|object} ref
1059
- * @param {*} owner
1060
- * @param {*} self A *temporary* helper to detect places where `this` is
1061
- * different from the `owner` when React.createElement is called, so that we
1062
- * can warn. We want to get rid of owner and replace string `ref`s with arrow
1063
- * functions, and as long as `this` and owner are the same, there will be no
1064
- * change in behavior.
1065
- * @param {*} source An annotation object (added by a transpiler or otherwise)
1066
- * indicating filename, line number, and/or other information.
1067
- * @internal
1068
- */
1069
-
1070
-
1071
- var ReactElement = function (type, key, ref, self, source, owner, props) {
1072
- var element = {
1073
- // This tag allows us to uniquely identify this as a React Element
1074
- $$typeof: REACT_ELEMENT_TYPE,
1075
- // Built-in properties that belong on the element
1076
- type: type,
1077
- key: key,
1078
- ref: ref,
1079
- props: props,
1080
- // Record the component responsible for creating this element.
1081
- _owner: owner
1082
- };
1083
-
1084
- {
1085
- // The validation flag is currently mutative. We put it on
1086
- // an external backing store so that we can freeze the whole object.
1087
- // This can be replaced with a WeakMap once they are implemented in
1088
- // commonly used development environments.
1089
- element._store = {}; // To make comparing ReactElements easier for testing purposes, we make
1090
- // the validation flag non-enumerable (where possible, which should
1091
- // include every environment we run tests in), so the test framework
1092
- // ignores it.
1093
-
1094
- Object.defineProperty(element._store, 'validated', {
1095
- configurable: false,
1096
- enumerable: false,
1097
- writable: true,
1098
- value: false
1099
- }); // self and source are DEV only properties.
1100
-
1101
- Object.defineProperty(element, '_self', {
1102
- configurable: false,
1103
- enumerable: false,
1104
- writable: false,
1105
- value: self
1106
- }); // Two elements created in two different places should be considered
1107
- // equal for testing purposes and therefore we hide it from enumeration.
1108
-
1109
- Object.defineProperty(element, '_source', {
1110
- configurable: false,
1111
- enumerable: false,
1112
- writable: false,
1113
- value: source
1114
- });
1115
-
1116
- if (Object.freeze) {
1117
- Object.freeze(element.props);
1118
- Object.freeze(element);
1119
- }
1120
- }
1121
-
1122
- return element;
1123
- };
1124
- /**
1125
- * https://github.com/reactjs/rfcs/pull/107
1126
- * @param {*} type
1127
- * @param {object} props
1128
- * @param {string} key
1129
- */
1130
-
1131
- function jsxDEV(type, config, maybeKey, source, self) {
1132
- {
1133
- var propName; // Reserved names are extracted
1134
-
1135
- var props = {};
1136
- var key = null;
1137
- var ref = null; // Currently, key can be spread in as a prop. This causes a potential
1138
- // issue if key is also explicitly declared (ie. <div {...props} key="Hi" />
1139
- // or <div key="Hi" {...props} /> ). We want to deprecate key spread,
1140
- // but as an intermediary step, we will use jsxDEV for everything except
1141
- // <div {...props} key="Hi" />, because we aren't currently able to tell if
1142
- // key is explicitly declared to be undefined or not.
1143
-
1144
- if (maybeKey !== undefined) {
1145
- {
1146
- checkKeyStringCoercion(maybeKey);
1147
- }
1148
-
1149
- key = '' + maybeKey;
1150
- }
1151
-
1152
- if (hasValidKey(config)) {
1153
- {
1154
- checkKeyStringCoercion(config.key);
1155
- }
1156
-
1157
- key = '' + config.key;
1158
- }
1159
-
1160
- if (hasValidRef(config)) {
1161
- ref = config.ref;
1162
- warnIfStringRefCannotBeAutoConverted(config, self);
1163
- } // Remaining properties are added to a new props object
1164
-
1165
-
1166
- for (propName in config) {
1167
- if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) {
1168
- props[propName] = config[propName];
1169
- }
1170
- } // Resolve default props
1171
-
1172
-
1173
- if (type && type.defaultProps) {
1174
- var defaultProps = type.defaultProps;
1175
-
1176
- for (propName in defaultProps) {
1177
- if (props[propName] === undefined) {
1178
- props[propName] = defaultProps[propName];
1179
- }
1180
- }
1181
- }
1182
-
1183
- if (key || ref) {
1184
- var displayName = typeof type === 'function' ? type.displayName || type.name || 'Unknown' : type;
1185
-
1186
- if (key) {
1187
- defineKeyPropWarningGetter(props, displayName);
1188
- }
1189
-
1190
- if (ref) {
1191
- defineRefPropWarningGetter(props, displayName);
1192
- }
1193
- }
1194
-
1195
- return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props);
1196
- }
1197
- }
1198
-
1199
- var ReactCurrentOwner$1 = ReactSharedInternals.ReactCurrentOwner;
1200
- var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame;
1201
-
1202
- function setCurrentlyValidatingElement$1(element) {
1203
- {
1204
- if (element) {
1205
- var owner = element._owner;
1206
- var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null);
1207
- ReactDebugCurrentFrame$1.setExtraStackFrame(stack);
1208
- } else {
1209
- ReactDebugCurrentFrame$1.setExtraStackFrame(null);
1210
- }
1211
- }
1212
- }
1213
-
1214
- var propTypesMisspellWarningShown;
1215
-
1216
- {
1217
- propTypesMisspellWarningShown = false;
1218
- }
1219
- /**
1220
- * Verifies the object is a ReactElement.
1221
- * See https://reactjs.org/docs/react-api.html#isvalidelement
1222
- * @param {?object} object
1223
- * @return {boolean} True if `object` is a ReactElement.
1224
- * @final
1225
- */
1226
-
1227
-
1228
- function isValidElement(object) {
1229
- {
1230
- return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE;
1231
- }
1232
- }
1233
-
1234
- function getDeclarationErrorAddendum() {
1235
- {
1236
- if (ReactCurrentOwner$1.current) {
1237
- var name = getComponentNameFromType(ReactCurrentOwner$1.current.type);
1238
-
1239
- if (name) {
1240
- return '\n\nCheck the render method of `' + name + '`.';
1241
- }
1242
- }
1243
-
1244
- return '';
1245
- }
1246
- }
1247
-
1248
- function getSourceInfoErrorAddendum(source) {
1249
- {
1250
- if (source !== undefined) {
1251
- var fileName = source.fileName.replace(/^.*[\\\/]/, '');
1252
- var lineNumber = source.lineNumber;
1253
- return '\n\nCheck your code at ' + fileName + ':' + lineNumber + '.';
1254
- }
1255
-
1256
- return '';
1257
- }
1258
- }
1259
- /**
1260
- * Warn if there's no key explicitly set on dynamic arrays of children or
1261
- * object keys are not valid. This allows us to keep track of children between
1262
- * updates.
1263
- */
1264
-
1265
-
1266
- var ownerHasKeyUseWarning = {};
1267
-
1268
- function getCurrentComponentErrorInfo(parentType) {
1269
- {
1270
- var info = getDeclarationErrorAddendum();
1271
-
1272
- if (!info) {
1273
- var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name;
1274
-
1275
- if (parentName) {
1276
- info = "\n\nCheck the top-level render call using <" + parentName + ">.";
1277
- }
1278
- }
1279
-
1280
- return info;
1281
- }
1282
- }
1283
- /**
1284
- * Warn if the element doesn't have an explicit key assigned to it.
1285
- * This element is in an array. The array could grow and shrink or be
1286
- * reordered. All children that haven't already been validated are required to
1287
- * have a "key" property assigned to it. Error statuses are cached so a warning
1288
- * will only be shown once.
1289
- *
1290
- * @internal
1291
- * @param {ReactElement} element Element that requires a key.
1292
- * @param {*} parentType element's parent's type.
1293
- */
1294
-
1295
-
1296
- function validateExplicitKey(element, parentType) {
1297
- {
1298
- if (!element._store || element._store.validated || element.key != null) {
1299
- return;
1300
- }
1301
-
1302
- element._store.validated = true;
1303
- var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType);
1304
-
1305
- if (ownerHasKeyUseWarning[currentComponentErrorInfo]) {
1306
- return;
1307
- }
1308
-
1309
- ownerHasKeyUseWarning[currentComponentErrorInfo] = true; // Usually the current owner is the offender, but if it accepts children as a
1310
- // property, it may be the creator of the child that's responsible for
1311
- // assigning it a key.
1312
-
1313
- var childOwner = '';
1314
-
1315
- if (element && element._owner && element._owner !== ReactCurrentOwner$1.current) {
1316
- // Give the component that originally created this child.
1317
- childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + ".";
1318
- }
1319
-
1320
- setCurrentlyValidatingElement$1(element);
1321
-
1322
- error('Each child in a list should have a unique "key" prop.' + '%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner);
1323
-
1324
- setCurrentlyValidatingElement$1(null);
1325
- }
1326
- }
1327
- /**
1328
- * Ensure that every element either is passed in a static location, in an
1329
- * array with an explicit keys property defined, or in an object literal
1330
- * with valid key property.
1331
- *
1332
- * @internal
1333
- * @param {ReactNode} node Statically passed child of any type.
1334
- * @param {*} parentType node's parent's type.
1335
- */
1336
-
1337
-
1338
- function validateChildKeys(node, parentType) {
1339
- {
1340
- if (typeof node !== 'object') {
1341
- return;
1342
- }
1343
-
1344
- if (isArray(node)) {
1345
- for (var i = 0; i < node.length; i++) {
1346
- var child = node[i];
1347
-
1348
- if (isValidElement(child)) {
1349
- validateExplicitKey(child, parentType);
1350
- }
1351
- }
1352
- } else if (isValidElement(node)) {
1353
- // This element was passed in a valid location.
1354
- if (node._store) {
1355
- node._store.validated = true;
1356
- }
1357
- } else if (node) {
1358
- var iteratorFn = getIteratorFn(node);
1359
-
1360
- if (typeof iteratorFn === 'function') {
1361
- // Entry iterators used to provide implicit keys,
1362
- // but now we print a separate warning for them later.
1363
- if (iteratorFn !== node.entries) {
1364
- var iterator = iteratorFn.call(node);
1365
- var step;
1366
-
1367
- while (!(step = iterator.next()).done) {
1368
- if (isValidElement(step.value)) {
1369
- validateExplicitKey(step.value, parentType);
1370
- }
1371
- }
1372
- }
1373
- }
1374
- }
1375
- }
1376
- }
1377
- /**
1378
- * Given an element, validate that its props follow the propTypes definition,
1379
- * provided by the type.
1380
- *
1381
- * @param {ReactElement} element
1382
- */
1383
-
1384
-
1385
- function validatePropTypes(element) {
1386
- {
1387
- var type = element.type;
1388
-
1389
- if (type === null || type === undefined || typeof type === 'string') {
1390
- return;
1391
- }
1392
-
1393
- var propTypes;
1394
-
1395
- if (typeof type === 'function') {
1396
- propTypes = type.propTypes;
1397
- } else if (typeof type === 'object' && (type.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here.
1398
- // Inner props are checked in the reconciler.
1399
- type.$$typeof === REACT_MEMO_TYPE)) {
1400
- propTypes = type.propTypes;
1401
- } else {
1402
- return;
1403
- }
1404
-
1405
- if (propTypes) {
1406
- // Intentionally inside to avoid triggering lazy initializers:
1407
- var name = getComponentNameFromType(type);
1408
- checkPropTypes(propTypes, element.props, 'prop', name, element);
1409
- } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) {
1410
- propTypesMisspellWarningShown = true; // Intentionally inside to avoid triggering lazy initializers:
1411
-
1412
- var _name = getComponentNameFromType(type);
1413
-
1414
- error('Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?', _name || 'Unknown');
1415
- }
1416
-
1417
- if (typeof type.getDefaultProps === 'function' && !type.getDefaultProps.isReactClassApproved) {
1418
- error('getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.');
1419
- }
1420
- }
1421
- }
1422
- /**
1423
- * Given a fragment, validate that it can only be provided with fragment props
1424
- * @param {ReactElement} fragment
1425
- */
1426
-
1427
-
1428
- function validateFragmentProps(fragment) {
1429
- {
1430
- var keys = Object.keys(fragment.props);
1431
-
1432
- for (var i = 0; i < keys.length; i++) {
1433
- var key = keys[i];
1434
-
1435
- if (key !== 'children' && key !== 'key') {
1436
- setCurrentlyValidatingElement$1(fragment);
1437
-
1438
- error('Invalid prop `%s` supplied to `React.Fragment`. ' + 'React.Fragment can only have `key` and `children` props.', key);
1439
-
1440
- setCurrentlyValidatingElement$1(null);
1441
- break;
1442
- }
1443
- }
1444
-
1445
- if (fragment.ref !== null) {
1446
- setCurrentlyValidatingElement$1(fragment);
1447
-
1448
- error('Invalid attribute `ref` supplied to `React.Fragment`.');
1449
-
1450
- setCurrentlyValidatingElement$1(null);
1451
- }
1452
- }
1453
- }
1454
-
1455
- var didWarnAboutKeySpread = {};
1456
- function jsxWithValidation(type, props, key, isStaticChildren, source, self) {
1457
- {
1458
- var validType = isValidElementType(type); // We warn in this case but don't throw. We expect the element creation to
1459
- // succeed and there will likely be errors in render.
1460
-
1461
- if (!validType) {
1462
- var info = '';
1463
-
1464
- if (type === undefined || typeof type === 'object' && type !== null && Object.keys(type).length === 0) {
1465
- info += ' You likely forgot to export your component from the file ' + "it's defined in, or you might have mixed up default and named imports.";
1466
- }
1467
-
1468
- var sourceInfo = getSourceInfoErrorAddendum(source);
1469
-
1470
- if (sourceInfo) {
1471
- info += sourceInfo;
1472
- } else {
1473
- info += getDeclarationErrorAddendum();
1474
- }
1475
-
1476
- var typeString;
1477
-
1478
- if (type === null) {
1479
- typeString = 'null';
1480
- } else if (isArray(type)) {
1481
- typeString = 'array';
1482
- } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) {
1483
- typeString = "<" + (getComponentNameFromType(type.type) || 'Unknown') + " />";
1484
- info = ' Did you accidentally export a JSX literal instead of a component?';
1485
- } else {
1486
- typeString = typeof type;
1487
- }
1488
-
1489
- error('React.jsx: type is invalid -- expected a string (for ' + 'built-in components) or a class/function (for composite ' + 'components) but got: %s.%s', typeString, info);
1490
- }
1491
-
1492
- var element = jsxDEV(type, props, key, source, self); // The result can be nullish if a mock or a custom function is used.
1493
- // TODO: Drop this when these are no longer allowed as the type argument.
1494
-
1495
- if (element == null) {
1496
- return element;
1497
- } // Skip key warning if the type isn't valid since our key validation logic
1498
- // doesn't expect a non-string/function type and can throw confusing errors.
1499
- // We don't want exception behavior to differ between dev and prod.
1500
- // (Rendering will throw with a helpful message and as soon as the type is
1501
- // fixed, the key warnings will appear.)
1502
-
1503
-
1504
- if (validType) {
1505
- var children = props.children;
1506
-
1507
- if (children !== undefined) {
1508
- if (isStaticChildren) {
1509
- if (isArray(children)) {
1510
- for (var i = 0; i < children.length; i++) {
1511
- validateChildKeys(children[i], type);
1512
- }
1513
-
1514
- if (Object.freeze) {
1515
- Object.freeze(children);
1516
- }
1517
- } else {
1518
- error('React.jsx: Static children should always be an array. ' + 'You are likely explicitly calling React.jsxs or React.jsxDEV. ' + 'Use the Babel transform instead.');
1519
- }
1520
- } else {
1521
- validateChildKeys(children, type);
1522
- }
1523
- }
1524
- }
1525
-
1526
- {
1527
- if (hasOwnProperty.call(props, 'key')) {
1528
- var componentName = getComponentNameFromType(type);
1529
- var keys = Object.keys(props).filter(function (k) {
1530
- return k !== 'key';
1531
- });
1532
- var beforeExample = keys.length > 0 ? '{key: someKey, ' + keys.join(': ..., ') + ': ...}' : '{key: someKey}';
1533
-
1534
- if (!didWarnAboutKeySpread[componentName + beforeExample]) {
1535
- var afterExample = keys.length > 0 ? '{' + keys.join(': ..., ') + ': ...}' : '{}';
1536
-
1537
- error('A props object containing a "key" prop is being spread into JSX:\n' + ' let props = %s;\n' + ' <%s {...props} />\n' + 'React keys must be passed directly to JSX without using spread:\n' + ' let props = %s;\n' + ' <%s key={someKey} {...props} />', beforeExample, componentName, afterExample, componentName);
1538
-
1539
- didWarnAboutKeySpread[componentName + beforeExample] = true;
1540
- }
1541
- }
1542
- }
1543
-
1544
- if (type === REACT_FRAGMENT_TYPE) {
1545
- validateFragmentProps(element);
1546
- } else {
1547
- validatePropTypes(element);
1548
- }
1549
-
1550
- return element;
1551
- }
1552
- } // These two functions exist to still get child warnings in dev
1553
- // even with the prod transform. This means that jsxDEV is purely
1554
- // opt-in behavior for better messages but that we won't stop
1555
- // giving you warnings if you use production apis.
1556
-
1557
- function jsxWithValidationStatic(type, props, key) {
1558
- {
1559
- return jsxWithValidation(type, props, key, true);
1560
- }
1561
- }
1562
- function jsxWithValidationDynamic(type, props, key) {
1563
- {
1564
- return jsxWithValidation(type, props, key, false);
1565
- }
1566
- }
1567
-
1568
- var jsx = jsxWithValidationDynamic ; // we may want to special case jsxs internally to take advantage of static children.
1569
- // for now we can ship identical prod functions
1570
-
1571
- var jsxs = jsxWithValidationStatic ;
1572
-
1573
- reactJsxRuntime_development.Fragment = REACT_FRAGMENT_TYPE;
1574
- reactJsxRuntime_development.jsx = jsx;
1575
- reactJsxRuntime_development.jsxs = jsxs;
1576
- })();
1577
- }
1578
- return reactJsxRuntime_development;
1579
- }
1580
-
1581
- if (process.env.NODE_ENV === 'production') {
1582
- jsxRuntime.exports = requireReactJsxRuntime_production_min();
1583
- } else {
1584
- jsxRuntime.exports = requireReactJsxRuntime_development();
1585
- }
1586
-
1587
- var jsxRuntimeExports = jsxRuntime.exports;
1588
-
1589
- var dist = {};
1590
-
1591
- var useWebsocket = {};
1592
-
1593
- var constants = {};
1594
-
1595
- (function (exports) {
1596
- Object.defineProperty(exports, "__esModule", { value: true });
1597
- exports.isEventSourceSupported = exports.isReactNative = exports.ReadyState = exports.DEFAULT_HEARTBEAT = exports.UNPARSABLE_JSON_OBJECT = exports.DEFAULT_RECONNECT_INTERVAL_MS = exports.DEFAULT_RECONNECT_LIMIT = exports.SOCKET_IO_PING_CODE = exports.SOCKET_IO_PATH = exports.SOCKET_IO_PING_INTERVAL = exports.DEFAULT_EVENT_SOURCE_OPTIONS = exports.EMPTY_EVENT_HANDLERS = exports.DEFAULT_OPTIONS = void 0;
1598
- var MILLISECONDS = 1;
1599
- var SECONDS = 1000 * MILLISECONDS;
1600
- exports.DEFAULT_OPTIONS = {};
1601
- exports.EMPTY_EVENT_HANDLERS = {};
1602
- exports.DEFAULT_EVENT_SOURCE_OPTIONS = {
1603
- withCredentials: false,
1604
- events: exports.EMPTY_EVENT_HANDLERS,
1605
- };
1606
- exports.SOCKET_IO_PING_INTERVAL = 25 * SECONDS;
1607
- exports.SOCKET_IO_PATH = '/socket.io/?EIO=3&transport=websocket';
1608
- exports.SOCKET_IO_PING_CODE = '2';
1609
- exports.DEFAULT_RECONNECT_LIMIT = 20;
1610
- exports.DEFAULT_RECONNECT_INTERVAL_MS = 5000;
1611
- exports.UNPARSABLE_JSON_OBJECT = {};
1612
- exports.DEFAULT_HEARTBEAT = {
1613
- message: 'ping',
1614
- timeout: 60000,
1615
- interval: 25000,
1616
- };
1617
- var ReadyState;
1618
- (function (ReadyState) {
1619
- ReadyState[ReadyState["UNINSTANTIATED"] = -1] = "UNINSTANTIATED";
1620
- ReadyState[ReadyState["CONNECTING"] = 0] = "CONNECTING";
1621
- ReadyState[ReadyState["OPEN"] = 1] = "OPEN";
1622
- ReadyState[ReadyState["CLOSING"] = 2] = "CLOSING";
1623
- ReadyState[ReadyState["CLOSED"] = 3] = "CLOSED";
1624
- })(ReadyState || (exports.ReadyState = ReadyState = {}));
1625
- var eventSourceSupported = function () {
1626
- try {
1627
- return 'EventSource' in globalThis;
1628
- }
1629
- catch (e) {
1630
- return false;
1631
- }
1632
- };
1633
- exports.isReactNative = typeof navigator !== 'undefined' && navigator.product === 'ReactNative';
1634
- exports.isEventSourceSupported = !exports.isReactNative && eventSourceSupported();
1635
-
1636
- } (constants));
1637
-
1638
- var createOrJoin = {};
1639
-
1640
- var globals = {};
1641
-
1642
- (function (exports) {
1643
- Object.defineProperty(exports, "__esModule", { value: true });
1644
- exports.resetWebSockets = exports.sharedWebSockets = void 0;
1645
- exports.sharedWebSockets = {};
1646
- var resetWebSockets = function (url) {
1647
- if (url && exports.sharedWebSockets.hasOwnProperty(url)) {
1648
- delete exports.sharedWebSockets[url];
1649
- }
1650
- else {
1651
- for (var url_1 in exports.sharedWebSockets) {
1652
- if (exports.sharedWebSockets.hasOwnProperty(url_1)) {
1653
- delete exports.sharedWebSockets[url_1];
1654
- }
1655
- }
1656
- }
1657
- };
1658
- exports.resetWebSockets = resetWebSockets;
1659
-
1660
- } (globals));
1661
-
1662
- var attachListener = {};
1663
-
1664
- var socketIo = {};
1665
-
1666
- Object.defineProperty(socketIo, "__esModule", { value: true });
1667
- socketIo.setUpSocketIOPing = socketIo.appendQueryParams = socketIo.parseSocketIOUrl = void 0;
1668
- var constants_1$7 = constants;
1669
- var parseSocketIOUrl = function (url) {
1670
- if (url) {
1671
- var isSecure = /^https|wss/.test(url);
1672
- var strippedProtocol = url.replace(/^(https?|wss?)(:\/\/)?/, '');
1673
- var removedFinalBackSlack = strippedProtocol.replace(/\/$/, '');
1674
- var protocol = isSecure ? 'wss' : 'ws';
1675
- return "".concat(protocol, "://").concat(removedFinalBackSlack).concat(constants_1$7.SOCKET_IO_PATH);
1676
- }
1677
- else if (url === '') {
1678
- var isSecure = /^https/.test(window.location.protocol);
1679
- var protocol = isSecure ? 'wss' : 'ws';
1680
- var port = window.location.port ? ":".concat(window.location.port) : '';
1681
- return "".concat(protocol, "://").concat(window.location.hostname).concat(port).concat(constants_1$7.SOCKET_IO_PATH);
1682
- }
1683
- return url;
1684
- };
1685
- socketIo.parseSocketIOUrl = parseSocketIOUrl;
1686
- var appendQueryParams = function (url, params) {
1687
- if (params === void 0) { params = {}; }
1688
- var hasParamsRegex = /\?([\w]+=[\w]+)/;
1689
- var alreadyHasParams = hasParamsRegex.test(url);
1690
- var stringified = "".concat(Object.entries(params).reduce(function (next, _a) {
1691
- var key = _a[0], value = _a[1];
1692
- return next + "".concat(key, "=").concat(value, "&");
1693
- }, '').slice(0, -1));
1694
- return "".concat(url).concat(alreadyHasParams ? '&' : '?').concat(stringified);
1695
- };
1696
- socketIo.appendQueryParams = appendQueryParams;
1697
- var setUpSocketIOPing = function (sendMessage, interval) {
1698
- if (interval === void 0) { interval = constants_1$7.SOCKET_IO_PING_INTERVAL; }
1699
- var ping = function () { return sendMessage(constants_1$7.SOCKET_IO_PING_CODE); };
1700
- return window.setInterval(ping, interval);
1701
- };
1702
- socketIo.setUpSocketIOPing = setUpSocketIOPing;
1703
-
1704
- var heartbeat$1 = {};
1705
-
1706
- Object.defineProperty(heartbeat$1, "__esModule", { value: true });
1707
- heartbeat$1.heartbeat = heartbeat;
1708
- var constants_1$6 = constants;
1709
- function getLastMessageTime(lastMessageTime) {
1710
- if (Array.isArray(lastMessageTime)) {
1711
- return lastMessageTime.reduce(function (p, c) { return (p.current > c.current) ? p : c; }).current;
1712
- }
1713
- return lastMessageTime.current;
1714
- }
1715
- function heartbeat(ws, lastMessageTime, options) {
1716
- var _a = options || {}, _b = _a.interval, interval = _b === void 0 ? constants_1$6.DEFAULT_HEARTBEAT.interval : _b, _c = _a.timeout, timeout = _c === void 0 ? constants_1$6.DEFAULT_HEARTBEAT.timeout : _c, _d = _a.message, message = _d === void 0 ? constants_1$6.DEFAULT_HEARTBEAT.message : _d;
1717
- // how often check interval between ping messages
1718
- // minimum is 100ms
1719
- // maximum is ${interval / 10}ms
1720
- var intervalCheck = Math.max(100, interval / 10);
1721
- var lastPingSentAt = Date.now();
1722
- var heartbeatInterval = setInterval(function () {
1723
- var timeNow = Date.now();
1724
- var lastMessageReceivedAt = getLastMessageTime(lastMessageTime);
1725
- if (lastMessageReceivedAt + timeout <= timeNow) {
1726
- console.warn("Heartbeat timed out, closing connection, last message received ".concat(timeNow - lastMessageReceivedAt, "ms ago, last ping sent ").concat(timeNow - lastPingSentAt, "ms ago"));
1727
- ws.close();
1728
- }
1729
- else {
1730
- if (lastMessageReceivedAt + interval <= timeNow && lastPingSentAt + interval <= timeNow) {
1731
- try {
1732
- if (typeof message === 'function') {
1733
- ws.send(message());
1734
- }
1735
- else {
1736
- ws.send(message);
1737
- }
1738
- lastPingSentAt = timeNow;
1739
- }
1740
- catch (err) {
1741
- console.error("Heartbeat failed, closing connection", err instanceof Error ? err.message : err);
1742
- ws.close();
1743
- }
1744
- }
1745
- }
1746
- }, intervalCheck);
1747
- ws.addEventListener("close", function () {
1748
- clearInterval(heartbeatInterval);
1749
- });
1750
- return function () { };
1751
- }
1752
-
1753
- var util = {};
1754
-
1755
- var manageSubscribers = {};
1756
-
1757
- (function (exports) {
1758
- Object.defineProperty(exports, "__esModule", { value: true });
1759
- exports.resetSubscribers = exports.removeSubscriber = exports.addSubscriber = exports.hasSubscribers = exports.getSubscribers = void 0;
1760
- var subscribers = {};
1761
- var EMPTY_LIST = [];
1762
- var getSubscribers = function (url) {
1763
- if ((0, exports.hasSubscribers)(url)) {
1764
- return Array.from(subscribers[url]);
1765
- }
1766
- return EMPTY_LIST;
1767
- };
1768
- exports.getSubscribers = getSubscribers;
1769
- var hasSubscribers = function (url) {
1770
- var _a;
1771
- return ((_a = subscribers[url]) === null || _a === void 0 ? void 0 : _a.size) > 0;
1772
- };
1773
- exports.hasSubscribers = hasSubscribers;
1774
- var addSubscriber = function (url, subscriber) {
1775
- subscribers[url] = subscribers[url] || new Set();
1776
- subscribers[url].add(subscriber);
1777
- };
1778
- exports.addSubscriber = addSubscriber;
1779
- var removeSubscriber = function (url, subscriber) {
1780
- subscribers[url].delete(subscriber);
1781
- };
1782
- exports.removeSubscriber = removeSubscriber;
1783
- var resetSubscribers = function (url) {
1784
- if (url && subscribers.hasOwnProperty(url)) {
1785
- delete subscribers[url];
1786
- }
1787
- else {
1788
- for (var url_1 in subscribers) {
1789
- if (subscribers.hasOwnProperty(url_1)) {
1790
- delete subscribers[url_1];
1791
- }
1792
- }
1793
- }
1794
- };
1795
- exports.resetSubscribers = resetSubscribers;
1796
-
1797
- } (manageSubscribers));
1798
-
1799
- Object.defineProperty(util, "__esModule", { value: true });
1800
- util.assertIsWebSocket = assertIsWebSocket;
1801
- util.resetGlobalState = resetGlobalState;
1802
- var globals_1$2 = globals;
1803
- var manage_subscribers_1$2 = manageSubscribers;
1804
- function assertIsWebSocket(webSocketInstance, skip) {
1805
- if (!skip && webSocketInstance instanceof WebSocket === false)
1806
- throw new Error('');
1807
- }
1808
- function resetGlobalState(url) {
1809
- (0, manage_subscribers_1$2.resetSubscribers)(url);
1810
- (0, globals_1$2.resetWebSockets)(url);
1811
- }
1812
-
1813
- var __assign$4 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
1814
- __assign$4 = Object.assign || function(t) {
1815
- for (var s, i = 1, n = arguments.length; i < n; i++) {
1816
- s = arguments[i];
1817
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
1818
- t[p] = s[p];
1819
- }
1820
- return t;
1821
- };
1822
- return __assign$4.apply(this, arguments);
1823
- };
1824
- Object.defineProperty(attachListener, "__esModule", { value: true });
1825
- attachListener.attachListeners = void 0;
1826
- var socket_io_1$1 = socketIo;
1827
- var heartbeat_1$1 = heartbeat$1;
1828
- var constants_1$5 = constants;
1829
- var util_1$1 = util;
1830
- var bindMessageHandler$1 = function (webSocketInstance, optionsRef, setLastMessage, lastMessageTime) {
1831
- webSocketInstance.onmessage = function (message) {
1832
- var _a;
1833
- optionsRef.current.onMessage && optionsRef.current.onMessage(message);
1834
- if (typeof (lastMessageTime === null || lastMessageTime === void 0 ? void 0 : lastMessageTime.current) === 'number') {
1835
- lastMessageTime.current = Date.now();
1836
- }
1837
- if (typeof optionsRef.current.filter === 'function' && optionsRef.current.filter(message) !== true) {
1838
- return;
1839
- }
1840
- if (optionsRef.current.heartbeat &&
1841
- typeof optionsRef.current.heartbeat !== "boolean" &&
1842
- ((_a = optionsRef.current.heartbeat) === null || _a === void 0 ? void 0 : _a.returnMessage) === message.data) {
1843
- return;
1844
- }
1845
- setLastMessage(message);
1846
- };
1847
- };
1848
- var bindOpenHandler$1 = function (webSocketInstance, optionsRef, setReadyState, reconnectCount, lastMessageTime) {
1849
- webSocketInstance.onopen = function (event) {
1850
- optionsRef.current.onOpen && optionsRef.current.onOpen(event);
1851
- reconnectCount.current = 0;
1852
- setReadyState(constants_1$5.ReadyState.OPEN);
1853
- //start heart beat here
1854
- if (optionsRef.current.heartbeat && webSocketInstance instanceof WebSocket) {
1855
- var heartbeatOptions = typeof optionsRef.current.heartbeat === "boolean"
1856
- ? undefined
1857
- : optionsRef.current.heartbeat;
1858
- lastMessageTime.current = Date.now();
1859
- (0, heartbeat_1$1.heartbeat)(webSocketInstance, lastMessageTime, heartbeatOptions);
1860
- }
1861
- };
1862
- };
1863
- var bindCloseHandler$1 = function (webSocketInstance, optionsRef, setReadyState, reconnect, reconnectCount) {
1864
- if (constants_1$5.isEventSourceSupported && webSocketInstance instanceof EventSource) {
1865
- return function () { };
1866
- }
1867
- (0, util_1$1.assertIsWebSocket)(webSocketInstance, optionsRef.current.skipAssert);
1868
- var reconnectTimeout;
1869
- webSocketInstance.onclose = function (event) {
1870
- var _a;
1871
- optionsRef.current.onClose && optionsRef.current.onClose(event);
1872
- setReadyState(constants_1$5.ReadyState.CLOSED);
1873
- if (optionsRef.current.shouldReconnect && optionsRef.current.shouldReconnect(event)) {
1874
- var reconnectAttempts = (_a = optionsRef.current.reconnectAttempts) !== null && _a !== void 0 ? _a : constants_1$5.DEFAULT_RECONNECT_LIMIT;
1875
- if (reconnectCount.current < reconnectAttempts) {
1876
- var nextReconnectInterval = typeof optionsRef.current.reconnectInterval === 'function' ?
1877
- optionsRef.current.reconnectInterval(reconnectCount.current) :
1878
- optionsRef.current.reconnectInterval;
1879
- reconnectTimeout = window.setTimeout(function () {
1880
- reconnectCount.current++;
1881
- reconnect();
1882
- }, nextReconnectInterval !== null && nextReconnectInterval !== void 0 ? nextReconnectInterval : constants_1$5.DEFAULT_RECONNECT_INTERVAL_MS);
1883
- }
1884
- else {
1885
- optionsRef.current.onReconnectStop && optionsRef.current.onReconnectStop(reconnectAttempts);
1886
- console.warn("Max reconnect attempts of ".concat(reconnectAttempts, " exceeded"));
1887
- }
1888
- }
1889
- };
1890
- return function () { return reconnectTimeout && window.clearTimeout(reconnectTimeout); };
1891
- };
1892
- var bindErrorHandler$1 = function (webSocketInstance, optionsRef, setReadyState, reconnect, reconnectCount) {
1893
- var reconnectTimeout;
1894
- webSocketInstance.onerror = function (error) {
1895
- var _a;
1896
- optionsRef.current.onError && optionsRef.current.onError(error);
1897
- if (constants_1$5.isEventSourceSupported && webSocketInstance instanceof EventSource) {
1898
- optionsRef.current.onClose && optionsRef.current.onClose(__assign$4(__assign$4({}, error), { code: 1006, reason: "An error occurred with the EventSource: ".concat(error), wasClean: false }));
1899
- setReadyState(constants_1$5.ReadyState.CLOSED);
1900
- webSocketInstance.close();
1901
- }
1902
- if (optionsRef.current.retryOnError) {
1903
- if (reconnectCount.current < ((_a = optionsRef.current.reconnectAttempts) !== null && _a !== void 0 ? _a : constants_1$5.DEFAULT_RECONNECT_LIMIT)) {
1904
- var nextReconnectInterval = typeof optionsRef.current.reconnectInterval === 'function' ?
1905
- optionsRef.current.reconnectInterval(reconnectCount.current) :
1906
- optionsRef.current.reconnectInterval;
1907
- reconnectTimeout = window.setTimeout(function () {
1908
- reconnectCount.current++;
1909
- reconnect();
1910
- }, nextReconnectInterval !== null && nextReconnectInterval !== void 0 ? nextReconnectInterval : constants_1$5.DEFAULT_RECONNECT_INTERVAL_MS);
1911
- }
1912
- else {
1913
- optionsRef.current.onReconnectStop && optionsRef.current.onReconnectStop(optionsRef.current.reconnectAttempts);
1914
- console.warn("Max reconnect attempts of ".concat(optionsRef.current.reconnectAttempts, " exceeded"));
1915
- }
1916
- }
1917
- };
1918
- return function () { return reconnectTimeout && window.clearTimeout(reconnectTimeout); };
1919
- };
1920
- var attachListeners = function (webSocketInstance, setters, optionsRef, reconnect, reconnectCount, lastMessageTime, sendMessage) {
1921
- var setLastMessage = setters.setLastMessage, setReadyState = setters.setReadyState;
1922
- var interval;
1923
- var cancelReconnectOnClose;
1924
- var cancelReconnectOnError;
1925
- if (optionsRef.current.fromSocketIO) {
1926
- interval = (0, socket_io_1$1.setUpSocketIOPing)(sendMessage);
1927
- }
1928
- bindMessageHandler$1(webSocketInstance, optionsRef, setLastMessage, lastMessageTime);
1929
- bindOpenHandler$1(webSocketInstance, optionsRef, setReadyState, reconnectCount, lastMessageTime);
1930
- cancelReconnectOnClose = bindCloseHandler$1(webSocketInstance, optionsRef, setReadyState, reconnect, reconnectCount);
1931
- cancelReconnectOnError = bindErrorHandler$1(webSocketInstance, optionsRef, setReadyState, reconnect, reconnectCount);
1932
- return function () {
1933
- setReadyState(constants_1$5.ReadyState.CLOSING);
1934
- cancelReconnectOnClose();
1935
- cancelReconnectOnError();
1936
- webSocketInstance.close();
1937
- if (interval)
1938
- clearInterval(interval);
1939
- };
1940
- };
1941
- attachListener.attachListeners = attachListeners;
1942
-
1943
- var attachSharedListeners$1 = {};
1944
-
1945
- var __assign$3 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
1946
- __assign$3 = Object.assign || function(t) {
1947
- for (var s, i = 1, n = arguments.length; i < n; i++) {
1948
- s = arguments[i];
1949
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
1950
- t[p] = s[p];
1951
- }
1952
- return t;
1953
- };
1954
- return __assign$3.apply(this, arguments);
1955
- };
1956
- Object.defineProperty(attachSharedListeners$1, "__esModule", { value: true });
1957
- attachSharedListeners$1.attachSharedListeners = void 0;
1958
- var globals_1$1 = globals;
1959
- var constants_1$4 = constants;
1960
- var manage_subscribers_1$1 = manageSubscribers;
1961
- var socket_io_1 = socketIo;
1962
- var heartbeat_1 = heartbeat$1;
1963
- var bindMessageHandler = function (webSocketInstance, url, heartbeatOptions) {
1964
- webSocketInstance.onmessage = function (message) {
1965
- (0, manage_subscribers_1$1.getSubscribers)(url).forEach(function (subscriber) {
1966
- var _a;
1967
- if (subscriber.optionsRef.current.onMessage) {
1968
- subscriber.optionsRef.current.onMessage(message);
1969
- }
1970
- if (typeof ((_a = subscriber === null || subscriber === void 0 ? void 0 : subscriber.lastMessageTime) === null || _a === void 0 ? void 0 : _a.current) === 'number') {
1971
- subscriber.lastMessageTime.current = Date.now();
1972
- }
1973
- if (typeof subscriber.optionsRef.current.filter === 'function' &&
1974
- subscriber.optionsRef.current.filter(message) !== true) {
1975
- return;
1976
- }
1977
- if (heartbeatOptions &&
1978
- typeof heartbeatOptions !== "boolean" &&
1979
- (heartbeatOptions === null || heartbeatOptions === void 0 ? void 0 : heartbeatOptions.returnMessage) === message.data)
1980
- return;
1981
- subscriber.setLastMessage(message);
1982
- });
1983
- };
1984
- };
1985
- var bindOpenHandler = function (webSocketInstance, url, heartbeatOptions) {
1986
- webSocketInstance.onopen = function (event) {
1987
- var subscribers = (0, manage_subscribers_1$1.getSubscribers)(url);
1988
- subscribers.forEach(function (subscriber) {
1989
- subscriber.reconnectCount.current = 0;
1990
- if (subscriber.optionsRef.current.onOpen) {
1991
- subscriber.optionsRef.current.onOpen(event);
1992
- }
1993
- subscriber.setReadyState(constants_1$4.ReadyState.OPEN);
1994
- if (heartbeatOptions && webSocketInstance instanceof WebSocket) {
1995
- subscriber.lastMessageTime.current = Date.now();
1996
- }
1997
- });
1998
- if (heartbeatOptions && webSocketInstance instanceof WebSocket) {
1999
- (0, heartbeat_1.heartbeat)(webSocketInstance, subscribers.map(function (subscriber) { return subscriber.lastMessageTime; }), typeof heartbeatOptions === 'boolean' ? undefined : heartbeatOptions);
2000
- }
2001
- };
2002
- };
2003
- var bindCloseHandler = function (webSocketInstance, url) {
2004
- if (webSocketInstance instanceof WebSocket) {
2005
- webSocketInstance.onclose = function (event) {
2006
- (0, manage_subscribers_1$1.getSubscribers)(url).forEach(function (subscriber) {
2007
- if (subscriber.optionsRef.current.onClose) {
2008
- subscriber.optionsRef.current.onClose(event);
2009
- }
2010
- subscriber.setReadyState(constants_1$4.ReadyState.CLOSED);
2011
- });
2012
- delete globals_1$1.sharedWebSockets[url];
2013
- (0, manage_subscribers_1$1.getSubscribers)(url).forEach(function (subscriber) {
2014
- var _a;
2015
- if (subscriber.optionsRef.current.shouldReconnect &&
2016
- subscriber.optionsRef.current.shouldReconnect(event)) {
2017
- var reconnectAttempts = (_a = subscriber.optionsRef.current.reconnectAttempts) !== null && _a !== void 0 ? _a : constants_1$4.DEFAULT_RECONNECT_LIMIT;
2018
- if (subscriber.reconnectCount.current < reconnectAttempts) {
2019
- var nextReconnectInterval = typeof subscriber.optionsRef.current.reconnectInterval === 'function' ?
2020
- subscriber.optionsRef.current.reconnectInterval(subscriber.reconnectCount.current) :
2021
- subscriber.optionsRef.current.reconnectInterval;
2022
- setTimeout(function () {
2023
- subscriber.reconnectCount.current++;
2024
- subscriber.reconnect.current();
2025
- }, nextReconnectInterval !== null && nextReconnectInterval !== void 0 ? nextReconnectInterval : constants_1$4.DEFAULT_RECONNECT_INTERVAL_MS);
2026
- }
2027
- else {
2028
- subscriber.optionsRef.current.onReconnectStop && subscriber.optionsRef.current.onReconnectStop(subscriber.optionsRef.current.reconnectAttempts);
2029
- console.warn("Max reconnect attempts of ".concat(reconnectAttempts, " exceeded"));
2030
- }
2031
- }
2032
- });
2033
- };
2034
- }
2035
- };
2036
- var bindErrorHandler = function (webSocketInstance, url) {
2037
- webSocketInstance.onerror = function (error) {
2038
- (0, manage_subscribers_1$1.getSubscribers)(url).forEach(function (subscriber) {
2039
- if (subscriber.optionsRef.current.onError) {
2040
- subscriber.optionsRef.current.onError(error);
2041
- }
2042
- if (constants_1$4.isEventSourceSupported && webSocketInstance instanceof EventSource) {
2043
- subscriber.optionsRef.current.onClose && subscriber.optionsRef.current.onClose(__assign$3(__assign$3({}, error), { code: 1006, reason: "An error occurred with the EventSource: ".concat(error), wasClean: false }));
2044
- subscriber.setReadyState(constants_1$4.ReadyState.CLOSED);
2045
- }
2046
- });
2047
- if (constants_1$4.isEventSourceSupported && webSocketInstance instanceof EventSource) {
2048
- webSocketInstance.close();
2049
- }
2050
- };
2051
- };
2052
- var attachSharedListeners = function (webSocketInstance, url, optionsRef, sendMessage) {
2053
- var interval;
2054
- if (optionsRef.current.fromSocketIO) {
2055
- interval = (0, socket_io_1.setUpSocketIOPing)(sendMessage);
2056
- }
2057
- bindMessageHandler(webSocketInstance, url, optionsRef.current.heartbeat);
2058
- bindCloseHandler(webSocketInstance, url);
2059
- bindOpenHandler(webSocketInstance, url, optionsRef.current.heartbeat);
2060
- bindErrorHandler(webSocketInstance, url);
2061
- return function () {
2062
- if (interval)
2063
- clearInterval(interval);
2064
- };
2065
- };
2066
- attachSharedListeners$1.attachSharedListeners = attachSharedListeners;
2067
-
2068
- Object.defineProperty(createOrJoin, "__esModule", { value: true });
2069
- createOrJoin.createOrJoinSocket = void 0;
2070
- var globals_1 = globals;
2071
- var constants_1$3 = constants;
2072
- var attach_listener_1 = attachListener;
2073
- var attach_shared_listeners_1 = attachSharedListeners$1;
2074
- var manage_subscribers_1 = manageSubscribers;
2075
- //TODO ensure that all onClose callbacks are called
2076
- var cleanSubscribers = function (url, subscriber, optionsRef, setReadyState, clearSocketIoPingInterval) {
2077
- return function () {
2078
- (0, manage_subscribers_1.removeSubscriber)(url, subscriber);
2079
- if (!(0, manage_subscribers_1.hasSubscribers)(url)) {
2080
- try {
2081
- var socketLike = globals_1.sharedWebSockets[url];
2082
- if (socketLike instanceof WebSocket) {
2083
- socketLike.onclose = function (event) {
2084
- if (optionsRef.current.onClose) {
2085
- optionsRef.current.onClose(event);
2086
- }
2087
- setReadyState(constants_1$3.ReadyState.CLOSED);
2088
- };
2089
- }
2090
- socketLike.close();
2091
- }
2092
- catch (e) {
2093
- }
2094
- if (clearSocketIoPingInterval)
2095
- clearSocketIoPingInterval();
2096
- delete globals_1.sharedWebSockets[url];
2097
- }
2098
- };
2099
- };
2100
- var createOrJoinSocket = function (webSocketRef, url, setReadyState, optionsRef, setLastMessage, startRef, reconnectCount, lastMessageTime, sendMessage) {
2101
- if (!constants_1$3.isEventSourceSupported && optionsRef.current.eventSourceOptions) {
2102
- if (constants_1$3.isReactNative) {
2103
- throw new Error('EventSource is not supported in ReactNative');
2104
- }
2105
- else {
2106
- throw new Error('EventSource is not supported');
2107
- }
2108
- }
2109
- if (optionsRef.current.share) {
2110
- var clearSocketIoPingInterval = null;
2111
- if (globals_1.sharedWebSockets[url] === undefined) {
2112
- globals_1.sharedWebSockets[url] = optionsRef.current.eventSourceOptions ?
2113
- new EventSource(url, optionsRef.current.eventSourceOptions) :
2114
- new WebSocket(url, optionsRef.current.protocols);
2115
- webSocketRef.current = globals_1.sharedWebSockets[url];
2116
- setReadyState(constants_1$3.ReadyState.CONNECTING);
2117
- clearSocketIoPingInterval = (0, attach_shared_listeners_1.attachSharedListeners)(globals_1.sharedWebSockets[url], url, optionsRef, sendMessage);
2118
- }
2119
- else {
2120
- webSocketRef.current = globals_1.sharedWebSockets[url];
2121
- setReadyState(globals_1.sharedWebSockets[url].readyState);
2122
- }
2123
- var subscriber = {
2124
- setLastMessage: setLastMessage,
2125
- setReadyState: setReadyState,
2126
- optionsRef: optionsRef,
2127
- reconnectCount: reconnectCount,
2128
- lastMessageTime: lastMessageTime,
2129
- reconnect: startRef,
2130
- };
2131
- (0, manage_subscribers_1.addSubscriber)(url, subscriber);
2132
- return cleanSubscribers(url, subscriber, optionsRef, setReadyState, clearSocketIoPingInterval);
2133
- }
2134
- else {
2135
- webSocketRef.current = optionsRef.current.eventSourceOptions ?
2136
- new EventSource(url, optionsRef.current.eventSourceOptions) :
2137
- new WebSocket(url, optionsRef.current.protocols);
2138
- setReadyState(constants_1$3.ReadyState.CONNECTING);
2139
- if (!webSocketRef.current) {
2140
- throw new Error('WebSocket failed to be created');
2141
- }
2142
- return (0, attach_listener_1.attachListeners)(webSocketRef.current, {
2143
- setLastMessage: setLastMessage,
2144
- setReadyState: setReadyState
2145
- }, optionsRef, startRef.current, reconnectCount, lastMessageTime, sendMessage);
2146
- }
2147
- };
2148
- createOrJoin.createOrJoinSocket = createOrJoinSocket;
2149
-
2150
- var getUrl = {};
2151
-
2152
- (function (exports) {
2153
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
2154
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
2155
- return new (P || (P = Promise))(function (resolve, reject) {
2156
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
2157
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
2158
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
2159
- step((generator = generator.apply(thisArg, _arguments || [])).next());
2160
- });
2161
- };
2162
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
2163
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
2164
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
2165
- function verb(n) { return function (v) { return step([n, v]); }; }
2166
- function step(op) {
2167
- if (f) throw new TypeError("Generator is already executing.");
2168
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
2169
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
2170
- if (y = 0, t) op = [op[0] & 2, t.value];
2171
- switch (op[0]) {
2172
- case 0: case 1: t = op; break;
2173
- case 4: _.label++; return { value: op[1], done: false };
2174
- case 5: _.label++; y = op[1]; op = [0]; continue;
2175
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
2176
- default:
2177
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
2178
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
2179
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
2180
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
2181
- if (t[2]) _.ops.pop();
2182
- _.trys.pop(); continue;
2183
- }
2184
- op = body.call(thisArg, _);
2185
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
2186
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
2187
- }
2188
- };
2189
- var __spreadArray = (commonjsGlobal && commonjsGlobal.__spreadArray) || function (to, from, pack) {
2190
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
2191
- if (ar || !(i in from)) {
2192
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
2193
- ar[i] = from[i];
2194
- }
2195
- }
2196
- return to.concat(ar || Array.prototype.slice.call(from));
2197
- };
2198
- Object.defineProperty(exports, "__esModule", { value: true });
2199
- exports.getUrl = void 0;
2200
- var socket_io_1 = socketIo;
2201
- var constants_1 = constants;
2202
- var waitFor = function (duration) { return new Promise(function (resolve) { return window.setTimeout(resolve, duration); }); };
2203
- var getUrl = function (url_1, optionsRef_1) {
2204
- var args_1 = [];
2205
- for (var _i = 2; _i < arguments.length; _i++) {
2206
- args_1[_i - 2] = arguments[_i];
2207
- }
2208
- return __awaiter(void 0, __spreadArray([url_1, optionsRef_1], args_1, true), void 0, function (url, optionsRef, retriedAttempts) {
2209
- var convertedUrl, reconnectLimit, nextReconnectInterval, parsedUrl, parsedWithQueryParams;
2210
- var _a, _b, _c;
2211
- if (retriedAttempts === void 0) { retriedAttempts = 0; }
2212
- return __generator(this, function (_d) {
2213
- switch (_d.label) {
2214
- case 0:
2215
- if (!(typeof url === 'function')) return [3 /*break*/, 10];
2216
- _d.label = 1;
2217
- case 1:
2218
- _d.trys.push([1, 3, , 9]);
2219
- return [4 /*yield*/, url()];
2220
- case 2:
2221
- convertedUrl = _d.sent();
2222
- return [3 /*break*/, 9];
2223
- case 3:
2224
- _d.sent();
2225
- if (!optionsRef.current.retryOnError) return [3 /*break*/, 7];
2226
- reconnectLimit = (_a = optionsRef.current.reconnectAttempts) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_RECONNECT_LIMIT;
2227
- if (!(retriedAttempts < reconnectLimit)) return [3 /*break*/, 5];
2228
- nextReconnectInterval = typeof optionsRef.current.reconnectInterval === 'function' ?
2229
- optionsRef.current.reconnectInterval(retriedAttempts) :
2230
- optionsRef.current.reconnectInterval;
2231
- return [4 /*yield*/, waitFor(nextReconnectInterval !== null && nextReconnectInterval !== void 0 ? nextReconnectInterval : constants_1.DEFAULT_RECONNECT_INTERVAL_MS)];
2232
- case 4:
2233
- _d.sent();
2234
- return [2 /*return*/, (0, exports.getUrl)(url, optionsRef, retriedAttempts + 1)];
2235
- case 5:
2236
- (_c = (_b = optionsRef.current).onReconnectStop) === null || _c === void 0 ? void 0 : _c.call(_b, retriedAttempts);
2237
- return [2 /*return*/, null];
2238
- case 6: return [3 /*break*/, 8];
2239
- case 7: return [2 /*return*/, null];
2240
- case 8: return [3 /*break*/, 9];
2241
- case 9: return [3 /*break*/, 11];
2242
- case 10:
2243
- convertedUrl = url;
2244
- _d.label = 11;
2245
- case 11:
2246
- parsedUrl = optionsRef.current.fromSocketIO ?
2247
- (0, socket_io_1.parseSocketIOUrl)(convertedUrl) :
2248
- convertedUrl;
2249
- parsedWithQueryParams = optionsRef.current.queryParams ?
2250
- (0, socket_io_1.appendQueryParams)(parsedUrl, optionsRef.current.queryParams) :
2251
- parsedUrl;
2252
- return [2 /*return*/, parsedWithQueryParams];
2253
- }
2254
- });
2255
- });
2256
- };
2257
- exports.getUrl = getUrl;
2258
-
2259
- } (getUrl));
2260
-
2261
- var proxy = {};
2262
-
2263
- (function (exports) {
2264
- Object.defineProperty(exports, "__esModule", { value: true });
2265
- exports.websocketWrapper = void 0;
2266
- var websocketWrapper = function (webSocket, start) {
2267
- return new Proxy(webSocket, {
2268
- get: function (obj, key) {
2269
- var val = obj[key];
2270
- if (key === 'reconnect')
2271
- return start;
2272
- if (typeof val === 'function') {
2273
- console.error('Calling methods directly on the websocket is not supported at this moment. You must use the methods returned by useWebSocket.');
2274
- //Prevent error thrown by invoking a non-function
2275
- return function () { };
2276
- }
2277
- else {
2278
- return val;
2279
- }
2280
- },
2281
- set: function (obj, key, val) {
2282
- if (/^on/.test(key)) {
2283
- console.warn('The websocket\'s event handlers should be defined through the options object passed into useWebSocket.');
2284
- return false;
2285
- }
2286
- else {
2287
- obj[key] = val;
2288
- return true;
2289
- }
2290
- },
2291
- });
2292
- };
2293
- exports.websocketWrapper = websocketWrapper;
2294
- exports.default = exports.websocketWrapper;
2295
-
2296
- } (proxy));
2297
-
2298
- var __assign$2 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
2299
- __assign$2 = Object.assign || function(t) {
2300
- for (var s, i = 1, n = arguments.length; i < n; i++) {
2301
- s = arguments[i];
2302
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
2303
- t[p] = s[p];
2304
- }
2305
- return t;
2306
- };
2307
- return __assign$2.apply(this, arguments);
2308
- };
2309
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
2310
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
2311
- return new (P || (P = Promise))(function (resolve, reject) {
2312
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
2313
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
2314
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
2315
- step((generator = generator.apply(thisArg, _arguments || [])).next());
2316
- });
2317
- };
2318
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
2319
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
2320
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
2321
- function verb(n) { return function (v) { return step([n, v]); }; }
2322
- function step(op) {
2323
- if (f) throw new TypeError("Generator is already executing.");
2324
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
2325
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
2326
- if (y = 0, t) op = [op[0] & 2, t.value];
2327
- switch (op[0]) {
2328
- case 0: case 1: t = op; break;
2329
- case 4: _.label++; return { value: op[1], done: false };
2330
- case 5: _.label++; y = op[1]; op = [0]; continue;
2331
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
2332
- default:
2333
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
2334
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
2335
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
2336
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
2337
- if (t[2]) _.ops.pop();
2338
- _.trys.pop(); continue;
2339
- }
2340
- op = body.call(thisArg, _);
2341
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
2342
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
2343
- }
2344
- };
2345
- var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
2346
- return (mod && mod.__esModule) ? mod : { "default": mod };
2347
- };
2348
- Object.defineProperty(useWebsocket, "__esModule", { value: true });
2349
- useWebsocket.useWebSocket = void 0;
2350
- var react_1$2 = require$$0;
2351
- var react_dom_1 = require$$1;
2352
- var constants_1$2 = constants;
2353
- var create_or_join_1 = createOrJoin;
2354
- var get_url_1 = getUrl;
2355
- var proxy_1 = __importDefault(proxy);
2356
- var util_1 = util;
2357
- var useWebSocket$1 = function (url, options, connect) {
2358
- if (options === void 0) { options = constants_1$2.DEFAULT_OPTIONS; }
2359
- if (connect === void 0) { connect = true; }
2360
- var _a = (0, react_1$2.useState)(null), lastMessage = _a[0], setLastMessage = _a[1];
2361
- var _b = (0, react_1$2.useState)({}), readyState = _b[0], setReadyState = _b[1];
2362
- var lastJsonMessage = (0, react_1$2.useMemo)(function () {
2363
- if (!options.disableJson && lastMessage) {
2364
- try {
2365
- return JSON.parse(lastMessage.data);
2366
- }
2367
- catch (e) {
2368
- return constants_1$2.UNPARSABLE_JSON_OBJECT;
2369
- }
2370
- }
2371
- return null;
2372
- }, [lastMessage, options.disableJson]);
2373
- var convertedUrl = (0, react_1$2.useRef)(null);
2374
- var webSocketRef = (0, react_1$2.useRef)(null);
2375
- var startRef = (0, react_1$2.useRef)(function () { return void 0; });
2376
- var reconnectCount = (0, react_1$2.useRef)(0);
2377
- var lastMessageTime = (0, react_1$2.useRef)(Date.now());
2378
- var messageQueue = (0, react_1$2.useRef)([]);
2379
- var webSocketProxy = (0, react_1$2.useRef)(null);
2380
- var optionsCache = (0, react_1$2.useRef)(options);
2381
- optionsCache.current = options;
2382
- var readyStateFromUrl = convertedUrl.current && readyState[convertedUrl.current] !== undefined ?
2383
- readyState[convertedUrl.current] :
2384
- url !== null && connect === true ?
2385
- constants_1$2.ReadyState.CONNECTING :
2386
- constants_1$2.ReadyState.UNINSTANTIATED;
2387
- var stringifiedQueryParams = options.queryParams ? JSON.stringify(options.queryParams) : null;
2388
- var sendMessage = (0, react_1$2.useCallback)(function (message, keep) {
2389
- var _a;
2390
- if (keep === void 0) { keep = true; }
2391
- if (constants_1$2.isEventSourceSupported && webSocketRef.current instanceof EventSource) {
2392
- console.warn('Unable to send a message from an eventSource');
2393
- return;
2394
- }
2395
- if (((_a = webSocketRef.current) === null || _a === void 0 ? void 0 : _a.readyState) === constants_1$2.ReadyState.OPEN) {
2396
- (0, util_1.assertIsWebSocket)(webSocketRef.current, optionsCache.current.skipAssert);
2397
- webSocketRef.current.send(message);
2398
- }
2399
- else if (keep) {
2400
- messageQueue.current.push(message);
2401
- }
2402
- }, []);
2403
- var sendJsonMessage = (0, react_1$2.useCallback)(function (message, keep) {
2404
- if (keep === void 0) { keep = true; }
2405
- sendMessage(JSON.stringify(message), keep);
2406
- }, [sendMessage]);
2407
- var getWebSocket = (0, react_1$2.useCallback)(function () {
2408
- if (optionsCache.current.share !== true || (constants_1$2.isEventSourceSupported && webSocketRef.current instanceof EventSource)) {
2409
- return webSocketRef.current;
2410
- }
2411
- if (webSocketProxy.current === null && webSocketRef.current) {
2412
- (0, util_1.assertIsWebSocket)(webSocketRef.current, optionsCache.current.skipAssert);
2413
- webSocketProxy.current = (0, proxy_1.default)(webSocketRef.current, startRef);
2414
- }
2415
- return webSocketProxy.current;
2416
- }, []);
2417
- (0, react_1$2.useEffect)(function () {
2418
- if (url !== null && connect === true) {
2419
- var removeListeners_1;
2420
- var expectClose_1 = false;
2421
- var createOrJoin_1 = true;
2422
- var start_1 = function () { return __awaiter(void 0, void 0, void 0, function () {
2423
- var _a, protectedSetLastMessage, protectedSetReadyState;
2424
- return __generator(this, function (_b) {
2425
- switch (_b.label) {
2426
- case 0:
2427
- _a = convertedUrl;
2428
- return [4 /*yield*/, (0, get_url_1.getUrl)(url, optionsCache)];
2429
- case 1:
2430
- _a.current = _b.sent();
2431
- if (convertedUrl.current === null) {
2432
- console.error('Failed to get a valid URL. WebSocket connection aborted.');
2433
- convertedUrl.current = 'ABORTED';
2434
- (0, react_dom_1.flushSync)(function () { return setReadyState(function (prev) { return (__assign$2(__assign$2({}, prev), { ABORTED: constants_1$2.ReadyState.CLOSED })); }); });
2435
- return [2 /*return*/];
2436
- }
2437
- protectedSetLastMessage = function (message) {
2438
- if (!expectClose_1) {
2439
- (0, react_dom_1.flushSync)(function () { return setLastMessage(message); });
2440
- }
2441
- };
2442
- protectedSetReadyState = function (state) {
2443
- if (!expectClose_1) {
2444
- (0, react_dom_1.flushSync)(function () { return setReadyState(function (prev) {
2445
- var _a;
2446
- return (__assign$2(__assign$2({}, prev), (convertedUrl.current && (_a = {}, _a[convertedUrl.current] = state, _a))));
2447
- }); });
2448
- }
2449
- };
2450
- if (createOrJoin_1) {
2451
- removeListeners_1 = (0, create_or_join_1.createOrJoinSocket)(webSocketRef, convertedUrl.current, protectedSetReadyState, optionsCache, protectedSetLastMessage, startRef, reconnectCount, lastMessageTime, sendMessage);
2452
- }
2453
- return [2 /*return*/];
2454
- }
2455
- });
2456
- }); };
2457
- startRef.current = function () {
2458
- if (!expectClose_1) {
2459
- if (webSocketProxy.current)
2460
- webSocketProxy.current = null;
2461
- removeListeners_1 === null || removeListeners_1 === void 0 ? void 0 : removeListeners_1();
2462
- start_1();
2463
- }
2464
- };
2465
- start_1();
2466
- return function () {
2467
- expectClose_1 = true;
2468
- createOrJoin_1 = false;
2469
- if (webSocketProxy.current)
2470
- webSocketProxy.current = null;
2471
- removeListeners_1 === null || removeListeners_1 === void 0 ? void 0 : removeListeners_1();
2472
- setLastMessage(null);
2473
- };
2474
- }
2475
- else if (url === null || connect === false) {
2476
- reconnectCount.current = 0; // reset reconnection attempts
2477
- setReadyState(function (prev) {
2478
- var _a;
2479
- return (__assign$2(__assign$2({}, prev), (convertedUrl.current && (_a = {}, _a[convertedUrl.current] = constants_1$2.ReadyState.CLOSED, _a))));
2480
- });
2481
- }
2482
- }, [url, connect, stringifiedQueryParams, sendMessage]);
2483
- (0, react_1$2.useEffect)(function () {
2484
- if (readyStateFromUrl === constants_1$2.ReadyState.OPEN) {
2485
- messageQueue.current.splice(0).forEach(function (message) {
2486
- sendMessage(message);
2487
- });
2488
- }
2489
- }, [readyStateFromUrl]);
2490
- return {
2491
- sendMessage: sendMessage,
2492
- sendJsonMessage: sendJsonMessage,
2493
- lastMessage: lastMessage,
2494
- lastJsonMessage: lastJsonMessage,
2495
- readyState: readyStateFromUrl,
2496
- getWebSocket: getWebSocket,
2497
- };
2498
- };
2499
- useWebsocket.useWebSocket = useWebSocket$1;
2500
-
2501
- var useSocketIo = {};
2502
-
2503
- var __assign$1 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
2504
- __assign$1 = Object.assign || function(t) {
2505
- for (var s, i = 1, n = arguments.length; i < n; i++) {
2506
- s = arguments[i];
2507
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
2508
- t[p] = s[p];
2509
- }
2510
- return t;
2511
- };
2512
- return __assign$1.apply(this, arguments);
2513
- };
2514
- Object.defineProperty(useSocketIo, "__esModule", { value: true });
2515
- useSocketIo.useSocketIO = void 0;
2516
- var react_1$1 = require$$0;
2517
- var use_websocket_1$1 = useWebsocket;
2518
- var constants_1$1 = constants;
2519
- var emptyEvent = {
2520
- type: 'empty',
2521
- payload: null,
2522
- };
2523
- var getSocketData = function (event) {
2524
- if (!event || !event.data) {
2525
- return emptyEvent;
2526
- }
2527
- var match = event.data.match(/\[.*]/);
2528
- if (!match) {
2529
- return emptyEvent;
2530
- }
2531
- var data = JSON.parse(match);
2532
- if (!Array.isArray(data) || !data[1]) {
2533
- return emptyEvent;
2534
- }
2535
- return {
2536
- type: data[0],
2537
- payload: data[1],
2538
- };
2539
- };
2540
- var useSocketIO = function (url, options, connect) {
2541
- if (options === void 0) { options = constants_1$1.DEFAULT_OPTIONS; }
2542
- if (connect === void 0) { connect = true; }
2543
- var optionsWithSocketIO = (0, react_1$1.useMemo)(function () { return (__assign$1(__assign$1({}, options), { fromSocketIO: true })); }, []);
2544
- var _a = (0, use_websocket_1$1.useWebSocket)(url, optionsWithSocketIO, connect), sendMessage = _a.sendMessage, sendJsonMessage = _a.sendJsonMessage, lastMessage = _a.lastMessage, readyState = _a.readyState, getWebSocket = _a.getWebSocket;
2545
- var socketIOLastMessage = (0, react_1$1.useMemo)(function () {
2546
- return getSocketData(lastMessage);
2547
- }, [lastMessage]);
2548
- return {
2549
- sendMessage: sendMessage,
2550
- sendJsonMessage: sendJsonMessage,
2551
- lastMessage: socketIOLastMessage,
2552
- lastJsonMessage: socketIOLastMessage,
2553
- readyState: readyState,
2554
- getWebSocket: getWebSocket,
2555
- };
2556
- };
2557
- useSocketIo.useSocketIO = useSocketIO;
2558
-
2559
- var useEventSource$1 = {};
2560
-
2561
- var __assign = (commonjsGlobal && commonjsGlobal.__assign) || function () {
2562
- __assign = Object.assign || function(t) {
2563
- for (var s, i = 1, n = arguments.length; i < n; i++) {
2564
- s = arguments[i];
2565
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
2566
- t[p] = s[p];
2567
- }
2568
- return t;
2569
- };
2570
- return __assign.apply(this, arguments);
2571
- };
2572
- var __rest = (commonjsGlobal && commonjsGlobal.__rest) || function (s, e) {
2573
- var t = {};
2574
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
2575
- t[p] = s[p];
2576
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
2577
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
2578
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
2579
- t[p[i]] = s[p[i]];
2580
- }
2581
- return t;
2582
- };
2583
- Object.defineProperty(useEventSource$1, "__esModule", { value: true });
2584
- useEventSource$1.useEventSource = void 0;
2585
- var react_1 = require$$0;
2586
- var use_websocket_1 = useWebsocket;
2587
- var constants_1 = constants;
2588
- var useEventSource = function (url, _a, connect) {
2589
- if (_a === void 0) { _a = constants_1.DEFAULT_EVENT_SOURCE_OPTIONS; }
2590
- var withCredentials = _a.withCredentials, events = _a.events, options = __rest(_a, ["withCredentials", "events"]);
2591
- if (connect === void 0) { connect = true; }
2592
- var optionsWithEventSource = __assign(__assign({}, options), { eventSourceOptions: {
2593
- withCredentials: withCredentials,
2594
- } });
2595
- var eventsRef = (0, react_1.useRef)(constants_1.EMPTY_EVENT_HANDLERS);
2596
- if (events) {
2597
- eventsRef.current = events;
2598
- }
2599
- var _b = (0, use_websocket_1.useWebSocket)(url, optionsWithEventSource, connect), lastMessage = _b.lastMessage, readyState = _b.readyState, getWebSocket = _b.getWebSocket;
2600
- (0, react_1.useEffect)(function () {
2601
- if (lastMessage === null || lastMessage === void 0 ? void 0 : lastMessage.type) {
2602
- Object.entries(eventsRef.current).forEach(function (_a) {
2603
- var type = _a[0], handler = _a[1];
2604
- if (type === lastMessage.type) {
2605
- handler(lastMessage);
2606
- }
2607
- });
2608
- }
2609
- }, [lastMessage]);
2610
- return {
2611
- lastEvent: lastMessage,
2612
- readyState: readyState,
2613
- getEventSource: getWebSocket,
2614
- };
2615
- };
2616
- useEventSource$1.useEventSource = useEventSource;
2617
-
2618
- (function (exports) {
2619
- Object.defineProperty(exports, "__esModule", { value: true });
2620
- exports.resetGlobalState = exports.useEventSource = exports.ReadyState = exports.useSocketIO = exports.default = void 0;
2621
- var use_websocket_1 = useWebsocket;
2622
- Object.defineProperty(exports, "default", { enumerable: true, get: function () { return use_websocket_1.useWebSocket; } });
2623
- var use_socket_io_1 = useSocketIo;
2624
- Object.defineProperty(exports, "useSocketIO", { enumerable: true, get: function () { return use_socket_io_1.useSocketIO; } });
2625
- var constants_1 = constants;
2626
- Object.defineProperty(exports, "ReadyState", { enumerable: true, get: function () { return constants_1.ReadyState; } });
2627
- var use_event_source_1 = useEventSource$1;
2628
- Object.defineProperty(exports, "useEventSource", { enumerable: true, get: function () { return use_event_source_1.useEventSource; } });
2629
- var util_1 = util;
2630
- Object.defineProperty(exports, "resetGlobalState", { enumerable: true, get: function () { return util_1.resetGlobalState; } });
2631
-
2632
- } (dist));
2633
-
2634
- var useWebSocket = /*@__PURE__*/getDefaultExportFromCjs(dist);
2635
-
2636
- const useHyperliquidWebSocket = ({ wsUrl, address }) => {
2637
- // WebSocket data state
2638
- const [data, setData] = require$$0.useState({
2639
- tradeHistories: null,
2640
- openPositions: null,
2641
- openOrders: null,
2642
- accountSummary: null,
2643
- });
2644
- const [lastError, setLastError] = require$$0.useState(null);
2645
- const [lastSubscribedAddress, setLastSubscribedAddress] = require$$0.useState(null);
2646
- // WebSocket connection
2647
- const { readyState, sendMessage } = useWebSocket(wsUrl, {
2648
- shouldReconnect: () => true,
2649
- reconnectAttempts: 5,
2650
- reconnectInterval: 3000,
2651
- onMessage: (event) => {
2652
- try {
2653
- const message = JSON.parse(event.data);
2654
- // Handle subscription responses (only if they don't have channel data)
2655
- if (('success' in message || 'error' in message) && !('channel' in message)) {
2656
- if (message.error) {
2657
- setLastError(message.error);
2658
- }
2659
- else {
2660
- setLastError(null);
2661
- }
2662
- return;
2663
- }
2664
- // Handle channel data messages
2665
- if ('channel' in message && 'data' in message) {
2666
- const dataMessage = message;
2667
- // Validate data exists and is not null/undefined
2668
- if (dataMessage.data === null || dataMessage.data === undefined) {
2669
- return;
2670
- }
2671
- switch (dataMessage.channel) {
2672
- case 'trade-histories':
2673
- if (Array.isArray(dataMessage.data)) {
2674
- setData(prev => ({
2675
- ...prev,
2676
- tradeHistories: dataMessage.data
2677
- }));
2678
- }
2679
- break;
2680
- case 'open-positions':
2681
- if (Array.isArray(dataMessage.data)) {
2682
- setData(prev => ({
2683
- ...prev,
2684
- openPositions: dataMessage.data
2685
- }));
2686
- }
2687
- break;
2688
- case 'open-orders':
2689
- if (Array.isArray(dataMessage.data)) {
2690
- setData(prev => ({
2691
- ...prev,
2692
- openOrders: dataMessage.data
2693
- }));
2694
- }
2695
- break;
2696
- case 'account-summary':
2697
- if (typeof dataMessage.data === 'object' && dataMessage.data !== null) {
2698
- setData(prev => ({
2699
- ...prev,
2700
- accountSummary: dataMessage.data
2701
- }));
2702
- }
2703
- break;
2704
- }
2705
- }
2706
- }
2707
- catch (error) {
2708
- setLastError(`Failed to parse message: ${error instanceof Error ? error.message : String(error)}`);
2709
- }
2710
- }
2711
- });
2712
- const isConnected = readyState === dist.ReadyState.OPEN;
2713
- // Handle subscription management
2714
- require$$0.useEffect(() => {
2715
- if (isConnected && address && address !== lastSubscribedAddress) {
2716
- // Unsubscribe from previous address if exists
2717
- if (lastSubscribedAddress) {
2718
- sendMessage(JSON.stringify({
2719
- action: 'unsubscribe',
2720
- address: lastSubscribedAddress
2721
- }));
2722
- }
2723
- // Subscribe to new address
2724
- sendMessage(JSON.stringify({
2725
- action: 'subscribe',
2726
- address: address
2727
- }));
2728
- setLastSubscribedAddress(address);
2729
- setLastError(null);
2730
- }
2731
- else if (isConnected && !address && lastSubscribedAddress) {
2732
- // Send unsubscribe action when address is removed
2733
- sendMessage(JSON.stringify({
2734
- action: 'unsubscribe',
2735
- address: lastSubscribedAddress
2736
- }));
2737
- setLastSubscribedAddress(null);
2738
- }
2739
- }, [isConnected, address, lastSubscribedAddress, sendMessage]);
2740
- // Clear data when address changes
2741
- require$$0.useEffect(() => {
2742
- if (address !== lastSubscribedAddress) {
2743
- setData({
2744
- tradeHistories: null,
2745
- openPositions: null,
2746
- openOrders: null,
2747
- accountSummary: null,
2748
- });
2749
- setLastError(null);
2750
- }
2751
- }, [address, lastSubscribedAddress]);
2752
- return {
2753
- data,
2754
- connectionStatus: readyState,
2755
- isConnected,
2756
- lastError,
2757
- };
2758
- };
2759
-
2760
- const useHyperliquidNativeWebSocket = ({ address }) => {
2761
- const [webData2, setWebData2] = require$$0.useState(null);
2762
- const [allMids, setAllMids] = require$$0.useState(null);
2763
- const [lastError, setLastError] = require$$0.useState(null);
2764
- const [subscribedAddress, setSubscribedAddress] = require$$0.useState(null);
2765
- const pingIntervalRef = require$$0.useRef(null);
2766
- // WebSocket connection to HyperLiquid native API
2767
- const { readyState, sendJsonMessage } = useWebSocket('wss://api.hyperliquid.xyz/ws', {
2768
- shouldReconnect: () => true,
2769
- reconnectAttempts: 5,
2770
- reconnectInterval: 3000,
2771
- onOpen: () => { },
2772
- onClose: () => { },
2773
- onError: (event) => console.error('[HyperLiquid WS] Connection error:', event),
2774
- onReconnectStop: () => console.error('[HyperLiquid WS] Reconnection stopped after 5 attempts'),
2775
- onMessage: (event) => {
2776
- try {
2777
- const message = JSON.parse(event.data);
2778
- // Handle subscription responses
2779
- if ('success' in message || 'error' in message) {
2780
- if (message.error) {
2781
- console.error('[HyperLiquid WS] Subscription error:', message.error);
2782
- setLastError(message.error);
2783
- }
2784
- else {
2785
- setLastError(null);
2786
- }
2787
- return;
2788
- }
2789
- // Handle channel data messages
2790
- if ('channel' in message && 'data' in message) {
2791
- const response = message;
2792
- switch (response.channel) {
2793
- case 'webData2':
2794
- setWebData2(response.data);
2795
- break;
2796
- case 'allMids':
2797
- setAllMids(response.data);
2798
- break;
2799
- default:
2800
- console.warn(`[HyperLiquid WS] Unknown channel: ${response.channel}`);
2801
- }
2802
- }
2803
- }
2804
- catch (error) {
2805
- const errorMessage = `Failed to parse message: ${error instanceof Error ? error.message : String(error)}`;
2806
- console.error('[HyperLiquid WS] Parse error:', errorMessage, 'Raw message:', event.data);
2807
- setLastError(errorMessage);
2808
- }
2809
- }
2810
- });
2811
- const isConnected = readyState === dist.ReadyState.OPEN;
2812
- // Setup ping mechanism
2813
- require$$0.useEffect(() => {
2814
- if (isConnected) {
2815
- // Send ping every 30 seconds
2816
- pingIntervalRef.current = setInterval(() => {
2817
- sendJsonMessage({ method: 'ping' });
2818
- }, 30000);
2819
- }
2820
- else {
2821
- if (pingIntervalRef.current) {
2822
- clearInterval(pingIntervalRef.current);
2823
- pingIntervalRef.current = null;
2824
- }
2825
- }
2826
- return () => {
2827
- if (pingIntervalRef.current) {
2828
- clearInterval(pingIntervalRef.current);
2829
- pingIntervalRef.current = null;
2830
- }
2831
- };
2832
- }, [isConnected, sendJsonMessage]);
2833
- // Handle address subscription changes
2834
- require$$0.useEffect(() => {
2835
- if (!isConnected)
2836
- return;
2837
- const DEFAULT_ADDRESS = '0x0000000000000000000000000000000000000000';
2838
- const userAddress = address || DEFAULT_ADDRESS;
2839
- if (subscribedAddress === userAddress)
2840
- return;
2841
- // Unsubscribe from previous address if exists
2842
- if (subscribedAddress) {
2843
- const unsubscribeMessage = {
2844
- method: 'unsubscribe',
2845
- subscription: {
2846
- type: 'webData2',
2847
- user: subscribedAddress,
2848
- },
2849
- };
2850
- sendJsonMessage(unsubscribeMessage);
2851
- }
2852
- // Subscribe to webData2 with new address
2853
- const subscribeWebData2 = {
2854
- method: 'subscribe',
2855
- subscription: {
2856
- type: 'webData2',
2857
- user: userAddress,
2858
- },
2859
- };
2860
- // Subscribe to allMids
2861
- const subscribeAllMids = {
2862
- method: 'subscribe',
2863
- subscription: {
2864
- type: 'allMids',
2865
- },
2866
- };
2867
- sendJsonMessage(subscribeWebData2);
2868
- sendJsonMessage(subscribeAllMids);
2869
- setSubscribedAddress(userAddress);
2870
- // Clear previous data when address changes
2871
- if (subscribedAddress && subscribedAddress !== userAddress) {
2872
- setWebData2(null);
2873
- }
2874
- }, [isConnected, address, subscribedAddress, sendJsonMessage]);
2875
- return {
2876
- webData2,
2877
- allMids,
2878
- connectionStatus: readyState,
2879
- isConnected,
2880
- lastError,
2881
- };
2882
- };
2883
-
2884
- const DEFAULT_TOKEN_SELECTION_STATE = {
2885
- longTokens: [
2886
- { symbol: 'HYPE', weight: 25 },
2887
- { symbol: 'BTC', weight: 25 }
2888
- ],
2889
- shortTokens: [
2890
- { symbol: 'AVAX', weight: 10 },
2891
- { symbol: 'SEI', weight: 10 },
2892
- { symbol: 'ADA', weight: 10 },
2893
- { symbol: 'TRUMP', weight: 10 },
2894
- { symbol: 'SUI', weight: 10 }
2895
- ],
2896
- openTokenSelector: false,
2897
- selectorConfig: null,
2898
- openConflictModal: false,
2899
- conflicts: [],
2900
- };
2901
- const PearHyperliquidContext = require$$0.createContext(undefined);
2902
- /**
2903
- * React Provider for PearHyperliquidClient
2904
- */
2905
- const PearHyperliquidProvider = ({ config, wsUrl = 'wss://hl-v2.pearprotocol.io/ws', children, }) => {
2906
- const client = require$$0.useMemo(() => new PearHyperliquidClient(config), [config]);
2907
- const migrationSDK = require$$0.useMemo(() => new PearMigrationSDK(client), [client]);
2908
- // Address state
2909
- const [address, setAddress] = require$$0.useState(null);
2910
- // Token selection state
2911
- const [tokenSelection, setTokenSelection] = require$$0.useState(DEFAULT_TOKEN_SELECTION_STATE);
2912
- // WebSocket connection and data (Pear API)
2913
- const { data, connectionStatus, isConnected, lastError } = useHyperliquidWebSocket({
2914
- wsUrl,
2915
- address,
2916
- });
2917
- // HyperLiquid native WebSocket connection
2918
- const { webData2, allMids, connectionStatus: nativeConnectionStatus, isConnected: nativeIsConnected, lastError: nativeLastError } = useHyperliquidNativeWebSocket({
2919
- address,
2920
- });
2921
- const contextValue = require$$0.useMemo(() => ({
2922
- // Existing clients
2923
- client,
2924
- migrationSDK,
2925
- // Address management
2926
- address,
2927
- setAddress,
2928
- // WebSocket state (Pear API)
2929
- connectionStatus,
2930
- isConnected,
2931
- // WebSocket data (Pear API)
2932
- data,
2933
- lastError,
2934
- // HyperLiquid native WebSocket state
2935
- nativeConnectionStatus,
2936
- nativeIsConnected,
2937
- nativeLastError,
2938
- // HyperLiquid native WebSocket data
2939
- webData2,
2940
- allMids,
2941
- // Token selection state
2942
- tokenSelection,
2943
- setTokenSelection,
2944
- }), [client, migrationSDK, address, connectionStatus, isConnected, data, lastError, nativeConnectionStatus, nativeIsConnected, nativeLastError, webData2, allMids, tokenSelection, setTokenSelection]);
2945
- return (jsxRuntimeExports.jsx(PearHyperliquidContext.Provider, { value: contextValue, children: children }));
2946
- };
2947
- /**
2948
- * Hook to use PearHyperliquidClient from context
2949
- */
2950
- const usePearHyperliquidClient = () => {
2951
- const context = require$$0.useContext(PearHyperliquidContext);
2952
- if (!context) {
2953
- throw new Error('usePearHyperliquidClient must be used within a PearHyperliquidProvider');
2954
- }
2955
- return context.client;
2956
- };
2957
- /**
2958
- * Hook to use migration SDK from context
2959
- */
2960
- const useMigrationSDK = () => {
2961
- const context = require$$0.useContext(PearHyperliquidContext);
2962
- if (!context) {
2963
- throw new Error('useMigrationSDK must be used within a PearHyperliquidProvider');
2964
- }
2965
- return context.migrationSDK;
2966
- };
2967
-
2968
- /**
2969
- * Hook to manage address (login/logout functionality)
2970
- */
2971
- const useAddress = () => {
2972
- const context = require$$0.useContext(PearHyperliquidContext);
2973
- if (!context) {
2974
- throw new Error('useAddress must be used within a PearHyperliquidProvider');
2975
- }
2976
- return {
2977
- address: context.address,
2978
- setAddress: context.setAddress,
2979
- clearAddress: () => context.setAddress(null),
2980
- isLoggedIn: !!context.address,
2981
- };
2982
- };
2983
-
2984
- var PositionSide;
2985
- (function (PositionSide) {
2986
- PositionSide["LONG"] = "LONG";
2987
- PositionSide["SHORT"] = "SHORT";
2988
- })(PositionSide || (PositionSide = {}));
2989
- class PositionProcessor {
2990
- constructor(webData2, allMids) {
2991
- this.webData2 = webData2;
2992
- this.allMids = allMids;
2993
- }
2994
- execute(rawPositions) {
2995
- if (!rawPositions || rawPositions.length === 0) {
2996
- return [];
2997
- }
2998
- const userHyperliquidPositions = this.getUserPositions();
2999
- const platformTotalsByAsset = this.calculatePlatformTotalsByAsset(rawPositions);
3000
- const hlPositionsMap = new Map();
3001
- (userHyperliquidPositions || []).forEach(assetPos => {
3002
- var _a;
3003
- if ((_a = assetPos.position) === null || _a === void 0 ? void 0 : _a.coin) {
3004
- hlPositionsMap.set(assetPos.position.coin, assetPos);
3005
- }
3006
- });
3007
- const openPositionDtos = [];
3008
- for (const position of rawPositions) {
3009
- const syncedPositionDto = this.syncPositionWithAggregateData(position, hlPositionsMap, platformTotalsByAsset);
3010
- openPositionDtos.push(syncedPositionDto);
3011
- }
3012
- return openPositionDtos;
3013
- }
3014
- getUserPositions() {
3015
- var _a, _b;
3016
- return ((_b = (_a = this.webData2) === null || _a === void 0 ? void 0 : _a.clearinghouseState) === null || _b === void 0 ? void 0 : _b.assetPositions) || [];
3017
- }
3018
- getMarketPrice(coin) {
3019
- var _a;
3020
- if (!((_a = this.allMids) === null || _a === void 0 ? void 0 : _a.mids))
3021
- return 0;
3022
- const exactPrice = this.allMids.mids[coin];
3023
- if (exactPrice) {
3024
- return Number(exactPrice);
3025
- }
3026
- const baseCurrency = this.extractBaseCurrency(coin);
3027
- const basePrice = this.allMids.mids[baseCurrency];
3028
- if (basePrice) {
3029
- return Number(basePrice);
3030
- }
3031
- return 0;
3032
- }
3033
- calculatePlatformTotalsByAsset(positions) {
3034
- const totalsMap = new Map();
3035
- for (const position of positions) {
3036
- for (const asset of position.longAssets || []) {
3037
- const baseCurrency = this.extractBaseCurrency(asset.coin);
3038
- if (!totalsMap.has(baseCurrency)) {
3039
- totalsMap.set(baseCurrency, {
3040
- totalSize: 0,
3041
- positions: []
3042
- });
3043
- }
3044
- const totals = totalsMap.get(baseCurrency);
3045
- const assetSize = Number(asset.size || 0);
3046
- totals.totalSize += assetSize;
3047
- totals.positions.push({
3048
- positionId: position.positionId,
3049
- asset: asset,
3050
- size: assetSize
3051
- });
3052
- }
3053
- for (const asset of position.shortAssets || []) {
3054
- const baseCurrency = this.extractBaseCurrency(asset.coin);
3055
- if (!totalsMap.has(baseCurrency)) {
3056
- totalsMap.set(baseCurrency, {
3057
- totalSize: 0,
3058
- positions: []
3059
- });
3060
- }
3061
- const totals = totalsMap.get(baseCurrency);
3062
- const assetSize = Number(asset.size || 0);
3063
- totals.totalSize += assetSize;
3064
- totals.positions.push({
3065
- positionId: position.positionId,
3066
- asset: asset,
3067
- size: assetSize
3068
- });
3069
- }
3070
- }
3071
- return totalsMap;
3072
- }
3073
- extractBaseCurrency(assetName) {
3074
- return assetName.split('/')[0] || assetName;
3075
- }
3076
- syncPositionWithAggregateData(position, hlPositionsMap, platformTotalsByAsset) {
3077
- const syncResults = [];
3078
- let hasExternalModification = false;
3079
- let allAssetsClosed = true;
3080
- let longAssetStatuses = { total: 0, closed: 0 };
3081
- let shortAssetStatuses = { total: 0, closed: 0 };
3082
- // Process long assets
3083
- for (const asset of position.longAssets || []) {
3084
- const baseCurrency = this.extractBaseCurrency(asset.coin);
3085
- const hlPosition = hlPositionsMap.get(baseCurrency);
3086
- const platformTotals = platformTotalsByAsset.get(baseCurrency);
3087
- const syncResult = this.syncAssetWithAggregateData({ ...asset, side: PositionSide.LONG }, hlPosition, (platformTotals === null || platformTotals === void 0 ? void 0 : platformTotals.totalSize) || 0);
3088
- syncResults.push(syncResult);
3089
- longAssetStatuses.total++;
3090
- if (syncResult.actualSize === 0) {
3091
- longAssetStatuses.closed++;
3092
- }
3093
- if (syncResult.isExternallyModified) {
3094
- hasExternalModification = true;
3095
- }
3096
- if (syncResult.actualSize !== 0) {
3097
- allAssetsClosed = false;
3098
- }
3099
- }
3100
- // Process short assets
3101
- for (const asset of position.shortAssets || []) {
3102
- const baseCurrency = this.extractBaseCurrency(asset.coin);
3103
- const hlPosition = hlPositionsMap.get(baseCurrency);
3104
- const platformTotals = platformTotalsByAsset.get(baseCurrency);
3105
- const syncResult = this.syncAssetWithAggregateData({ ...asset, side: PositionSide.SHORT }, hlPosition, (platformTotals === null || platformTotals === void 0 ? void 0 : platformTotals.totalSize) || 0);
3106
- syncResults.push(syncResult);
3107
- shortAssetStatuses.total++;
3108
- if (syncResult.actualSize === 0) {
3109
- shortAssetStatuses.closed++;
3110
- }
3111
- if (syncResult.isExternallyModified) {
3112
- hasExternalModification = true;
3113
- }
3114
- if (syncResult.actualSize !== 0) {
3115
- allAssetsClosed = false;
3116
- }
3117
- }
3118
- const syncStatus = this.determineSyncStatus(hasExternalModification, allAssetsClosed, longAssetStatuses, shortAssetStatuses);
3119
- return this.mapPositionToDtoWithSyncData(position, syncResults, syncStatus);
3120
- }
3121
- determineSyncStatus(hasExternalModification, allAssetsClosed, longAssetStatuses, shortAssetStatuses) {
3122
- if (allAssetsClosed) {
3123
- return 'EXTERNALLY_CLOSED';
3124
- }
3125
- const allLongsClosed = longAssetStatuses.total > 0 &&
3126
- longAssetStatuses.closed === longAssetStatuses.total;
3127
- const allShortsClosed = shortAssetStatuses.total > 0 &&
3128
- shortAssetStatuses.closed === shortAssetStatuses.total;
3129
- if ((allLongsClosed && !allShortsClosed) || (!allLongsClosed && allShortsClosed)) {
3130
- return 'PAIR_BROKEN';
3131
- }
3132
- if (hasExternalModification) {
3133
- return 'EXTERNALLY_MODIFIED';
3134
- }
3135
- return 'SYNCED';
3136
- }
3137
- syncAssetWithAggregateData(asset, hlPosition, platformTotal) {
3138
- const platformSize = Number(asset.size || 0);
3139
- if (!hlPosition || !hlPosition.position || !hlPosition.position.szi) {
3140
- return {
3141
- asset,
3142
- actualSize: 0,
3143
- isExternallyModified: true,
3144
- cumFunding: { allTime: 0, sinceChange: 0, sinceOpen: 0 },
3145
- unrealizedPnl: 0,
3146
- liquidationPrice: 0
3147
- };
3148
- }
3149
- const hlTotalSize = Math.abs(Number(hlPosition.position.szi || 0));
3150
- const totalDifference = Math.abs(hlTotalSize - platformTotal);
3151
- const tolerance = platformTotal * 0.001;
3152
- const isExternallyModified = totalDifference > tolerance;
3153
- const proportion = platformTotal > 0 ? platformSize / platformTotal : 0;
3154
- const actualSize = hlTotalSize * proportion;
3155
- // Get cumFunding from hlPosition.position.cumFunding
3156
- const rawCumFunding = hlPosition.position.cumFunding;
3157
- const cumFunding = {
3158
- allTime: Number((rawCumFunding === null || rawCumFunding === void 0 ? void 0 : rawCumFunding.allTime) || 0),
3159
- sinceChange: Number((rawCumFunding === null || rawCumFunding === void 0 ? void 0 : rawCumFunding.sinceChange) || 0) * proportion,
3160
- sinceOpen: Number((rawCumFunding === null || rawCumFunding === void 0 ? void 0 : rawCumFunding.sinceOpen) || 0) * proportion
3161
- };
3162
- const unrealizedPnl = Number(hlPosition.position.unrealizedPnl || 0) * proportion;
3163
- const liquidationPrice = Number(hlPosition.position.liquidationPx || 0);
3164
- return {
3165
- asset,
3166
- actualSize,
3167
- isExternallyModified,
3168
- cumFunding,
3169
- unrealizedPnl,
3170
- liquidationPrice
3171
- };
3172
- }
3173
- mapPositionToDtoWithSyncData(position, syncResults, syncStatus) {
3174
- var _a, _b;
3175
- const longAssets = ((_a = position.longAssets) === null || _a === void 0 ? void 0 : _a.filter(asset => asset)) || [];
3176
- const shortAssets = ((_b = position.shortAssets) === null || _b === void 0 ? void 0 : _b.filter(asset => asset)) || [];
3177
- const syncResultsMap = new Map();
3178
- syncResults.forEach(result => {
3179
- syncResultsMap.set(`${result.asset.coin}-${result.asset.side}`, result);
3180
- });
3181
- const currentTotalPositionValue = this.calculateCurrentTotalPositionValue(syncResults);
3182
- const entryTotalPositionValue = this.calculateEntryTotalPositionValue(syncResults);
3183
- const totalMarginUsed = entryTotalPositionValue / position.leverage;
3184
- return {
3185
- syncStatus: syncStatus,
3186
- positionId: position.positionId,
3187
- address: position.address,
3188
- leverage: position.leverage,
3189
- stopLoss: position.stopLoss,
3190
- takeProfit: position.takeProfit,
3191
- entryRatio: this.calculateEntryRatio(syncResults),
3192
- markRatio: this.calculateMarkRatio(syncResults),
3193
- netFunding: this.calculateNetFundingFromSyncResults(syncResults),
3194
- positionValue: currentTotalPositionValue,
3195
- marginUsed: totalMarginUsed,
3196
- unrealizedPnl: this.calculateTotalUnrealizedPnlFromSyncResults(syncResults),
3197
- lastSyncAt: new Date().toISOString(),
3198
- longAssets: longAssets.map(asset => this.mapAssetToDetailDto(asset, syncResultsMap.get(`${asset.coin}-LONG`))),
3199
- shortAssets: shortAssets.map(asset => this.mapAssetToDetailDto(asset, syncResultsMap.get(`${asset.coin}-SHORT`))),
3200
- createdAt: position.createdAt,
3201
- updatedAt: position.updatedAt
3202
- };
3203
- }
3204
- mapAssetToDetailDto(asset, syncData) {
3205
- const currentPrice = this.getMarketPrice(asset.coin);
3206
- const actualSize = (syncData === null || syncData === void 0 ? void 0 : syncData.actualSize) || Number(asset.size || 0);
3207
- const positionValue = actualSize * currentPrice;
3208
- const entryValue = Number(asset.size || 0) * Number(asset.entryPrice || 0);
3209
- return {
3210
- coin: asset.coin,
3211
- entryPrice: Number(asset.entryPrice || 0),
3212
- platformSize: Number(asset.size || 0),
3213
- actualSize: actualSize,
3214
- isExternallyModified: (syncData === null || syncData === void 0 ? void 0 : syncData.isExternallyModified) || false,
3215
- cumFunding: (syncData === null || syncData === void 0 ? void 0 : syncData.cumFunding) || {
3216
- allTime: 0,
3217
- sinceChange: 0,
3218
- sinceOpen: 0
3219
- },
3220
- marginUsed: entryValue,
3221
- positionValue: positionValue,
3222
- unrealizedPnl: (syncData === null || syncData === void 0 ? void 0 : syncData.unrealizedPnl) || 0,
3223
- liquidationPrice: (syncData === null || syncData === void 0 ? void 0 : syncData.liquidationPrice) || 0
3224
- };
3225
- }
3226
- calculateEntryRatio(syncResults) {
3227
- var _a, _b;
3228
- const longResults = syncResults.filter(result => result.asset.side === PositionSide.LONG);
3229
- const shortResults = syncResults.filter(result => result.asset.side === PositionSide.SHORT);
3230
- if (longResults.length === 0 || shortResults.length === 0)
3231
- return 0;
3232
- const longEntryPrice = ((_a = longResults[0]) === null || _a === void 0 ? void 0 : _a.asset.entryPrice) ? Number(longResults[0].asset.entryPrice) : 0;
3233
- const shortEntryPrice = ((_b = shortResults[0]) === null || _b === void 0 ? void 0 : _b.asset.entryPrice) ? Number(shortResults[0].asset.entryPrice) : 0;
3234
- return shortEntryPrice > 0 ? longEntryPrice / shortEntryPrice : 0;
3235
- }
3236
- calculateMarkRatio(syncResults) {
3237
- var _a, _b;
3238
- const longResults = syncResults.filter(result => result.asset.side === PositionSide.LONG);
3239
- const shortResults = syncResults.filter(result => result.asset.side === PositionSide.SHORT);
3240
- if (longResults.length === 0 || shortResults.length === 0)
3241
- return 0;
3242
- const longMarkPrice = ((_a = longResults[0]) === null || _a === void 0 ? void 0 : _a.asset.coin) ? this.getMarketPrice(longResults[0].asset.coin) : 0;
3243
- const shortMarkPrice = ((_b = shortResults[0]) === null || _b === void 0 ? void 0 : _b.asset.coin) ? this.getMarketPrice(shortResults[0].asset.coin) : 0;
3244
- return shortMarkPrice > 0 ? longMarkPrice / shortMarkPrice : 0;
3245
- }
3246
- calculateNetFundingFromSyncResults(syncResults) {
3247
- const netFunding = syncResults.reduce((sum, result) => {
3248
- const funding = result.cumFunding.sinceOpen;
3249
- return sum + funding;
3250
- }, 0);
3251
- return netFunding;
3252
- }
3253
- calculateTotalUnrealizedPnlFromSyncResults(syncResults) {
3254
- return syncResults.reduce((sum, result) => sum + result.unrealizedPnl, 0);
3255
- }
3256
- calculateCurrentTotalPositionValue(syncResults) {
3257
- return syncResults.reduce((sum, result) => {
3258
- const currentPrice = this.getMarketPrice(result.asset.coin);
3259
- return sum + (result.actualSize * currentPrice);
3260
- }, 0);
3261
- }
3262
- calculateEntryTotalPositionValue(syncResults) {
3263
- return syncResults.reduce((sum, result) => {
3264
- return sum + (Number(result.asset.size || 0) * Number(result.asset.entryPrice || 0));
3265
- }, 0);
3266
- }
3267
- }
3268
-
3269
- /**
3270
- * Hook that calculates open positions by syncing platform positions with HyperLiquid real-time data
3271
- */
3272
- const useCalculatedOpenPositions = (platformPositions, webData2, allMids) => {
3273
- const calculatedPositions = require$$0.useMemo(() => {
3274
- // Return null if we don't have platform positions yet
3275
- if (!platformPositions) {
3276
- return null;
3277
- }
3278
- // If we don't have real-time data yet, we can't calculate properly, return null
3279
- if (!webData2 || !allMids) {
3280
- return null;
3281
- }
3282
- // Create processor and compute positions
3283
- const processor = new PositionProcessor(webData2, allMids);
3284
- const processed = processor.execute(platformPositions);
3285
- return processed;
3286
- }, [platformPositions, webData2, allMids]);
3287
- return calculatedPositions;
3288
- };
3289
-
3290
- /**
3291
- * Account summary calculation utility class
3292
- */
3293
- class AccountSummaryCalculator {
3294
- constructor(webData2) {
3295
- this.webData2 = webData2;
3296
- }
3297
- /**
3298
- * Calculate account summary from webData2 and platform orders
3299
- */
3300
- calculateAccountSummary(platformAccountSummary, platformOpenOrders, agentWalletAddress, agentWalletStatus) {
3301
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
3302
- // If we don't have webData2, return platform data as-is
3303
- if (!((_a = this.webData2) === null || _a === void 0 ? void 0 : _a.clearinghouseState)) {
3304
- return platformAccountSummary;
3305
- }
3306
- const clearinghouseState = this.webData2.clearinghouseState;
3307
- // Calculate total limit order value from platform orders
3308
- const totalLimitOrderValue = this.calculateTotalLimitOrderValue(platformOpenOrders || []);
3309
- // Use real-time data from webData2 clearinghouseState
3310
- const withdrawableAmount = parseFloat(clearinghouseState.withdrawable || '0');
3311
- const adjustedWithdrawable = Math.max(0, withdrawableAmount - totalLimitOrderValue);
3312
- const accountSummary = {
3313
- balanceSummary: {
3314
- crossMaintenanceMarginUsed: clearinghouseState.crossMaintenanceMarginUsed || '0',
3315
- crossMarginSummary: {
3316
- accountValue: ((_b = clearinghouseState.crossMarginSummary) === null || _b === void 0 ? void 0 : _b.accountValue) || '0',
3317
- totalMarginUsed: ((_c = clearinghouseState.crossMarginSummary) === null || _c === void 0 ? void 0 : _c.totalMarginUsed) || '0',
3318
- totalNtlPos: ((_d = clearinghouseState.crossMarginSummary) === null || _d === void 0 ? void 0 : _d.totalNtlPos) || '0',
3319
- totalRawUsd: ((_e = clearinghouseState.crossMarginSummary) === null || _e === void 0 ? void 0 : _e.totalRawUsd) || '0'
3320
- },
3321
- marginSummary: {
3322
- accountValue: ((_f = clearinghouseState.marginSummary) === null || _f === void 0 ? void 0 : _f.accountValue) || '0',
3323
- totalMarginUsed: ((_g = clearinghouseState.marginSummary) === null || _g === void 0 ? void 0 : _g.totalMarginUsed) || '0',
3324
- totalNtlPos: ((_h = clearinghouseState.marginSummary) === null || _h === void 0 ? void 0 : _h.totalNtlPos) || '0',
3325
- totalRawUsd: ((_j = clearinghouseState.marginSummary) === null || _j === void 0 ? void 0 : _j.totalRawUsd) || '0'
3326
- },
3327
- time: clearinghouseState.time || Date.now(),
3328
- withdrawable: adjustedWithdrawable.toString()
3329
- },
3330
- agentWallet: {
3331
- address: agentWalletAddress || ((_k = platformAccountSummary === null || platformAccountSummary === void 0 ? void 0 : platformAccountSummary.agentWallet) === null || _k === void 0 ? void 0 : _k.address) || '',
3332
- status: agentWalletStatus || ((_l = platformAccountSummary === null || platformAccountSummary === void 0 ? void 0 : platformAccountSummary.agentWallet) === null || _l === void 0 ? void 0 : _l.status) || 'UNKNOWN'
3333
- }
3334
- };
3335
- return accountSummary;
3336
- }
3337
- /**
3338
- * Calculate total USD value of open limit orders
3339
- */
3340
- calculateTotalLimitOrderValue(openOrders) {
3341
- if (!(openOrders === null || openOrders === void 0 ? void 0 : openOrders.length)) {
3342
- return 0;
3343
- }
3344
- const totalValue = openOrders
3345
- .filter(order => order.status === 'OPEN' || order.status === 'PROCESSING')
3346
- .reduce((sum, order) => sum + order.usdValue, 0);
3347
- return totalValue;
3348
- }
3349
- /**
3350
- * Get real-time clearinghouse state from webData2
3351
- */
3352
- getClearinghouseState() {
3353
- var _a;
3354
- return ((_a = this.webData2) === null || _a === void 0 ? void 0 : _a.clearinghouseState) || null;
3355
- }
3356
- /**
3357
- * Check if real-time data is available
3358
- */
3359
- hasRealTimeData() {
3360
- var _a;
3361
- return !!((_a = this.webData2) === null || _a === void 0 ? void 0 : _a.clearinghouseState);
3362
- }
3363
- }
3364
-
3365
- /**
3366
- * Hook that calculates account summary by syncing platform data with HyperLiquid real-time data
3367
- */
3368
- const useCalculatedAccountSummary = (platformAccountSummary, platformOpenOrders, webData2, agentWalletAddress, agentWalletStatus) => {
3369
- const calculatedAccountSummary = require$$0.useMemo(() => {
3370
- // Return null if we don't have platform account summary yet
3371
- if (!platformAccountSummary) {
3372
- return null;
3373
- }
3374
- // If we don't have real-time data yet, return platform summary as-is
3375
- if (!(webData2 === null || webData2 === void 0 ? void 0 : webData2.clearinghouseState)) {
3376
- return platformAccountSummary;
3377
- }
3378
- // Create calculator and compute account summary
3379
- const calculator = new AccountSummaryCalculator(webData2);
3380
- const calculated = calculator.calculateAccountSummary(platformAccountSummary, platformOpenOrders, agentWalletAddress, agentWalletStatus);
3381
- return calculated;
3382
- }, [platformAccountSummary, platformOpenOrders, webData2, agentWalletAddress, agentWalletStatus]);
3383
- return calculatedAccountSummary;
3384
- };
3385
-
3386
- /**
3387
- * Hook to access trade histories with loading state
3388
- */
3389
- const useTradeHistories = () => {
3390
- const context = require$$0.useContext(PearHyperliquidContext);
3391
- if (!context) {
3392
- throw new Error('useTradeHistories must be used within a PearHyperliquidProvider');
3393
- }
3394
- const isLoading = require$$0.useMemo(() => {
3395
- // Loading is true initially and becomes false once we get the first data
3396
- return context.data.tradeHistories === null && context.isConnected;
3397
- }, [context.data.tradeHistories, context.isConnected]);
3398
- return {
3399
- data: context.data.tradeHistories,
3400
- isLoading
3401
- };
3402
- };
3403
- /**
3404
- * Hook to access open positions with real-time calculations and loading state
3405
- */
3406
- const useOpenPositions = () => {
3407
- const context = require$$0.useContext(PearHyperliquidContext);
3408
- if (!context) {
3409
- throw new Error('useOpenPositions must be used within a PearHyperliquidProvider');
3410
- }
3411
- // Use calculated positions that sync platform data with HyperLiquid real-time data
3412
- const calculatedPositions = useCalculatedOpenPositions(context.data.openPositions, context.webData2, context.allMids);
3413
- const isLoading = require$$0.useMemo(() => {
3414
- // Loading is true initially and becomes false only when:
3415
- // 1. WebSocket has open-positions data
3416
- // 2. webData2 and allMids are ready (required for calculations)
3417
- // 3. Connection is established
3418
- return (context.isConnected &&
3419
- (context.data.openPositions === null || !context.webData2 || !context.allMids));
3420
- }, [context.data.openPositions, context.webData2, context.allMids, context.isConnected]);
3421
- return {
3422
- data: calculatedPositions,
3423
- isLoading
3424
- };
3425
- };
3426
- /**
3427
- * Hook to access open orders with loading state
3428
- */
3429
- const useOpenOrders = () => {
3430
- const context = require$$0.useContext(PearHyperliquidContext);
3431
- if (!context) {
3432
- throw new Error('useOpenOrders must be used within a PearHyperliquidProvider');
3433
- }
3434
- const isLoading = require$$0.useMemo(() => {
3435
- // Loading is true initially and becomes false once we get the first data
3436
- return context.data.openOrders === null && context.isConnected;
3437
- }, [context.data.openOrders, context.isConnected]);
3438
- return {
3439
- data: context.data.openOrders,
3440
- isLoading
3441
- };
3442
- };
3443
- /**
3444
- * Hook to access account summary with real-time calculations and loading state
3445
- */
3446
- const useAccountSummary = () => {
3447
- var _a, _b, _c, _d;
3448
- const context = require$$0.useContext(PearHyperliquidContext);
3449
- if (!context) {
3450
- throw new Error('useAccountSummary must be used within a PearHyperliquidProvider');
3451
- }
3452
- // Use calculated account summary that syncs platform data with HyperLiquid real-time data
3453
- const calculatedAccountSummary = useCalculatedAccountSummary(context.data.accountSummary, context.data.openOrders, context.webData2, (_b = (_a = context.data.accountSummary) === null || _a === void 0 ? void 0 : _a.agentWallet) === null || _b === void 0 ? void 0 : _b.address, (_d = (_c = context.data.accountSummary) === null || _c === void 0 ? void 0 : _c.agentWallet) === null || _d === void 0 ? void 0 : _d.status);
3454
- const isLoading = require$$0.useMemo(() => {
3455
- // Loading is true initially and becomes false once we get the first data
3456
- return context.data.accountSummary === null && context.isConnected;
3457
- }, [context.data.accountSummary, context.isConnected]);
3458
- return {
3459
- data: calculatedAccountSummary,
3460
- isLoading
3461
- };
3462
- };
3463
-
3464
- /**
3465
- * Extracts token metadata from WebData2 and AllMids data
3466
- */
3467
- class TokenMetadataExtractor {
3468
- /**
3469
- * Extracts comprehensive token metadata
3470
- * @param symbol - Token symbol
3471
- * @param webData2 - WebData2 response containing asset context and universe data
3472
- * @param allMids - AllMids data containing current prices
3473
- * @returns TokenMetadata or null if token not found
3474
- */
3475
- static extractTokenMetadata(symbol, webData2, allMids) {
3476
- if (!webData2 || !allMids) {
3477
- return null;
3478
- }
3479
- // Find token index in universe
3480
- const universeIndex = webData2.meta.universe.findIndex(asset => asset.name === symbol);
3481
- if (universeIndex === -1) {
3482
- return null;
3483
- }
3484
- const universeAsset = webData2.meta.universe[universeIndex];
3485
- const assetCtx = webData2.assetCtxs[universeIndex];
3486
- if (!assetCtx) {
3487
- return null;
3488
- }
3489
- // Get current price from allMids
3490
- const currentPriceStr = allMids.mids[symbol];
3491
- const currentPrice = currentPriceStr ? parseFloat(currentPriceStr) : 0;
3492
- // Get previous day price
3493
- const prevDayPrice = parseFloat(assetCtx.prevDayPx);
3494
- // Calculate 24h price change
3495
- const priceChange24h = currentPrice - prevDayPrice;
3496
- const priceChange24hPercent = prevDayPrice !== 0 ? (priceChange24h / prevDayPrice) * 100 : 0;
3497
- // Parse other metadata
3498
- const netFunding = parseFloat(assetCtx.funding);
3499
- const markPrice = parseFloat(assetCtx.markPx);
3500
- const oraclePrice = parseFloat(assetCtx.oraclePx);
3501
- return {
3502
- currentPrice,
3503
- prevDayPrice,
3504
- priceChange24h,
3505
- priceChange24hPercent,
3506
- netFunding,
3507
- maxLeverage: universeAsset.maxLeverage,
3508
- markPrice,
3509
- oraclePrice,
3510
- openInterest: assetCtx.openInterest,
3511
- dayVolume: assetCtx.dayNtlVlm,
3512
- };
3513
- }
3514
- /**
3515
- * Extracts metadata for multiple tokens
3516
- * @param symbols - Array of token symbols
3517
- * @param webData2 - WebData2 response
3518
- * @param allMids - AllMids data
3519
- * @returns Record of symbol to TokenMetadata
3520
- */
3521
- static extractMultipleTokensMetadata(symbols, webData2, allMids) {
3522
- const result = {};
3523
- for (const symbol of symbols) {
3524
- result[symbol] = this.extractTokenMetadata(symbol, webData2, allMids);
3525
- }
3526
- return result;
3527
- }
3528
- /**
3529
- * Checks if token data is available in WebData2
3530
- * @param symbol - Token symbol
3531
- * @param webData2 - WebData2 response
3532
- * @returns boolean indicating if token exists in universe
3533
- */
3534
- static isTokenAvailable(symbol, webData2) {
3535
- if (!webData2)
3536
- return false;
3537
- return webData2.meta.universe.some(asset => asset.name === symbol);
3538
- }
3539
- }
3540
-
3541
- /**
3542
- * Hook to access token selection state using provider's WebSocket data
3543
- */
3544
- const useTokenSelection = () => {
3545
- var _a;
3546
- const context = require$$0.useContext(PearHyperliquidContext);
3547
- if (!context) {
3548
- throw new Error('useTokenSelection must be used within PearHyperliquidProvider');
3549
- }
3550
- const { webData2, allMids, tokenSelection, setTokenSelection } = context;
3551
- // Loading states
3552
- const isPriceDataReady = require$$0.useMemo(() => {
3553
- return !!(webData2 && allMids);
3554
- }, [webData2, allMids]);
3555
- const isLoading = require$$0.useMemo(() => {
3556
- // Check if any tokens have missing metadata when price data is available
3557
- if (!isPriceDataReady)
3558
- return true;
3559
- const allTokens = [...tokenSelection.longTokens, ...tokenSelection.shortTokens];
3560
- if (allTokens.length === 0)
3561
- return false;
3562
- // Loading if any token is missing metadata
3563
- return allTokens.some(token => !token.metadata);
3564
- }, [isPriceDataReady, tokenSelection.longTokens, tokenSelection.shortTokens]);
3565
- // Auto-update token metadata when WebSocket data changes
3566
- require$$0.useEffect(() => {
3567
- if (!webData2 || !allMids)
3568
- return;
3569
- const allTokenSymbols = [...tokenSelection.longTokens, ...tokenSelection.shortTokens].map(t => t.symbol);
3570
- if (allTokenSymbols.length === 0)
3571
- return;
3572
- const metadataMap = TokenMetadataExtractor.extractMultipleTokensMetadata(allTokenSymbols, webData2, allMids);
3573
- setTokenSelection(prev => ({
3574
- ...prev,
3575
- longTokens: prev.longTokens.map(token => ({
3576
- ...token,
3577
- metadata: metadataMap[token.symbol] || undefined
3578
- })),
3579
- shortTokens: prev.shortTokens.map(token => ({
3580
- ...token,
3581
- metadata: metadataMap[token.symbol] || undefined
3582
- }))
3583
- }));
3584
- }, [webData2, allMids, setTokenSelection]);
3585
- // Calculate weighted ratio: LONG^WEIGHT * SHORT^-WEIGHT
3586
- const weightedRatio = require$$0.useMemo(() => {
3587
- let longProduct = 1;
3588
- let shortProduct = 1;
3589
- // Calculate long side product: PRICE^(WEIGHT/100)
3590
- tokenSelection.longTokens.forEach(token => {
3591
- var _a;
3592
- if (((_a = token.metadata) === null || _a === void 0 ? void 0 : _a.currentPrice) && token.weight > 0) {
3593
- const weightFactor = token.weight / 100;
3594
- longProduct *= Math.pow(token.metadata.currentPrice, weightFactor);
3595
- }
3596
- });
3597
- // Calculate short side product: PRICE^-(WEIGHT/100)
3598
- tokenSelection.shortTokens.forEach(token => {
3599
- var _a;
3600
- if (((_a = token.metadata) === null || _a === void 0 ? void 0 : _a.currentPrice) && token.weight > 0) {
3601
- const weightFactor = token.weight / 100;
3602
- shortProduct *= Math.pow(token.metadata.currentPrice, -weightFactor);
3603
- }
3604
- });
3605
- return longProduct * shortProduct;
3606
- }, [tokenSelection.longTokens, tokenSelection.shortTokens]);
3607
- // Calculate 24h weighted ratio using previous day prices
3608
- const weightedRatio24h = require$$0.useMemo(() => {
3609
- let longProduct = 1;
3610
- let shortProduct = 1;
3611
- // Calculate long side product: PREV_PRICE^(WEIGHT/100)
3612
- tokenSelection.longTokens.forEach(token => {
3613
- var _a;
3614
- if (((_a = token.metadata) === null || _a === void 0 ? void 0 : _a.prevDayPrice) && token.weight > 0) {
3615
- const weightFactor = token.weight / 100;
3616
- longProduct *= Math.pow(token.metadata.prevDayPrice, weightFactor);
3617
- }
3618
- });
3619
- // Calculate short side product: PREV_PRICE^-(WEIGHT/100)
3620
- tokenSelection.shortTokens.forEach(token => {
3621
- var _a;
3622
- if (((_a = token.metadata) === null || _a === void 0 ? void 0 : _a.prevDayPrice) && token.weight > 0) {
3623
- const weightFactor = token.weight / 100;
3624
- shortProduct *= Math.pow(token.metadata.prevDayPrice, -weightFactor);
3625
- }
3626
- });
3627
- return longProduct * shortProduct;
3628
- }, [tokenSelection.longTokens, tokenSelection.shortTokens]);
3629
- // Calculate sum of weighted net funding
3630
- const sumNetFunding = require$$0.useMemo(() => {
3631
- let totalFunding = 0;
3632
- // Add long funding weighted by allocation
3633
- tokenSelection.longTokens.forEach(token => {
3634
- var _a;
3635
- if (((_a = token.metadata) === null || _a === void 0 ? void 0 : _a.netFunding) && token.weight > 0) {
3636
- const weightFactor = token.weight / 100;
3637
- totalFunding += token.metadata.netFunding * weightFactor;
3638
- }
3639
- });
3640
- // Subtract short funding weighted by allocation (since we're short)
3641
- tokenSelection.shortTokens.forEach(token => {
3642
- var _a;
3643
- if (((_a = token.metadata) === null || _a === void 0 ? void 0 : _a.netFunding) && token.weight > 0) {
3644
- const weightFactor = token.weight / 100;
3645
- totalFunding -= token.metadata.netFunding * weightFactor;
3646
- }
3647
- });
3648
- return totalFunding;
3649
- }, [tokenSelection.longTokens, tokenSelection.shortTokens]);
3650
- // Calculate max leverage (minimum of all token maxLeverages)
3651
- const maxLeverage = require$$0.useMemo(() => {
3652
- var _a;
3653
- if (!((_a = webData2 === null || webData2 === void 0 ? void 0 : webData2.meta) === null || _a === void 0 ? void 0 : _a.universe))
3654
- return 0;
3655
- const allTokenSymbols = [...tokenSelection.longTokens, ...tokenSelection.shortTokens].map(t => t.symbol);
3656
- if (allTokenSymbols.length === 0)
3657
- return 0;
3658
- let minLeverage = Infinity;
3659
- allTokenSymbols.forEach(symbol => {
3660
- const tokenUniverse = webData2.meta.universe.find(u => u.name === symbol);
3661
- if (tokenUniverse === null || tokenUniverse === void 0 ? void 0 : tokenUniverse.maxLeverage) {
3662
- minLeverage = Math.min(minLeverage, tokenUniverse.maxLeverage);
3663
- }
3664
- });
3665
- return minLeverage === Infinity ? 0 : minLeverage;
3666
- }, [(_a = webData2 === null || webData2 === void 0 ? void 0 : webData2.meta) === null || _a === void 0 ? void 0 : _a.universe, tokenSelection.longTokens, tokenSelection.shortTokens]);
3667
- // Calculate minimum margin (10 * total number of tokens)
3668
- const minMargin = require$$0.useMemo(() => {
3669
- const totalTokenCount = tokenSelection.longTokens.length + tokenSelection.shortTokens.length;
3670
- return 10 * totalTokenCount;
3671
- }, [tokenSelection.longTokens.length, tokenSelection.shortTokens.length]);
3672
- // Actions
3673
- const setLongTokens = require$$0.useCallback((tokens) => {
3674
- setTokenSelection(prev => ({ ...prev, longTokens: tokens }));
3675
- }, [setTokenSelection]);
3676
- const setShortTokens = require$$0.useCallback((tokens) => {
3677
- setTokenSelection(prev => ({ ...prev, shortTokens: tokens }));
3678
- }, [setTokenSelection]);
3679
- const updateTokenWeight = require$$0.useCallback((isLong, index, newWeight) => {
3680
- const clampedWeight = Math.max(1, Math.min(100, newWeight));
3681
- setTokenSelection(prev => {
3682
- var _a, _b;
3683
- const currentLongTotal = prev.longTokens.reduce((sum, token) => sum + token.weight, 0);
3684
- const currentShortTotal = prev.shortTokens.reduce((sum, token) => sum + token.weight, 0);
3685
- if (isLong) {
3686
- const oldWeight = ((_a = prev.longTokens[index]) === null || _a === void 0 ? void 0 : _a.weight) || 0;
3687
- const weightDiff = clampedWeight - oldWeight;
3688
- const newLongTotal = currentLongTotal + weightDiff;
3689
- if (newLongTotal + currentShortTotal > 100) {
3690
- const maxAllowedWeight = Math.max(1, 100 - currentShortTotal - (currentLongTotal - oldWeight));
3691
- const updated = [...prev.longTokens];
3692
- updated[index] = { ...updated[index], weight: maxAllowedWeight };
3693
- return { ...prev, longTokens: updated };
3694
- }
3695
- else {
3696
- const updated = [...prev.longTokens];
3697
- updated[index] = { ...updated[index], weight: clampedWeight };
3698
- return { ...prev, longTokens: updated };
3699
- }
3700
- }
3701
- else {
3702
- const oldWeight = ((_b = prev.shortTokens[index]) === null || _b === void 0 ? void 0 : _b.weight) || 0;
3703
- const weightDiff = clampedWeight - oldWeight;
3704
- const newShortTotal = currentShortTotal + weightDiff;
3705
- if (currentLongTotal + newShortTotal > 100) {
3706
- const maxAllowedWeight = Math.max(1, 100 - currentLongTotal - (currentShortTotal - oldWeight));
3707
- const updated = [...prev.shortTokens];
3708
- updated[index] = { ...updated[index], weight: maxAllowedWeight };
3709
- return { ...prev, shortTokens: updated };
3710
- }
3711
- else {
3712
- const updated = [...prev.shortTokens];
3713
- updated[index] = { ...updated[index], weight: clampedWeight };
3714
- return { ...prev, shortTokens: updated };
3715
- }
3716
- }
3717
- });
3718
- }, [setTokenSelection]);
3719
- const addToken = require$$0.useCallback((isLong) => {
3720
- const currentTokens = isLong ? tokenSelection.longTokens : tokenSelection.shortTokens;
3721
- const newIndex = currentTokens.length;
3722
- setTokenSelection(prev => ({
3723
- ...prev,
3724
- selectorConfig: { isLong, index: newIndex },
3725
- openTokenSelector: true,
3726
- }));
3727
- }, [tokenSelection.longTokens, tokenSelection.shortTokens, setTokenSelection]);
3728
- const removeToken = require$$0.useCallback((isLong, index) => {
3729
- setTokenSelection(prev => {
3730
- if (isLong) {
3731
- const updated = prev.longTokens.filter((_, i) => i !== index);
3732
- return { ...prev, longTokens: updated };
3733
- }
3734
- else {
3735
- const updated = prev.shortTokens.filter((_, i) => i !== index);
3736
- return { ...prev, shortTokens: updated };
3737
- }
3738
- });
3739
- }, [setTokenSelection]);
3740
- const setOpenTokenSelector = require$$0.useCallback((open) => {
3741
- setTokenSelection(prev => ({ ...prev, openTokenSelector: open }));
3742
- }, [setTokenSelection]);
3743
- const setSelectorConfig = require$$0.useCallback((config) => {
3744
- setTokenSelection(prev => ({ ...prev, selectorConfig: config }));
3745
- }, [setTokenSelection]);
3746
- const setOpenConflictModal = require$$0.useCallback((open) => {
3747
- setTokenSelection(prev => ({ ...prev, openConflictModal: open }));
3748
- }, [setTokenSelection]);
3749
- const setConflicts = require$$0.useCallback((conflicts) => {
3750
- setTokenSelection(prev => ({ ...prev, conflicts }));
3751
- }, [setTokenSelection]);
3752
- const resetToDefaults = require$$0.useCallback(() => {
3753
- setTokenSelection(prev => ({
3754
- ...prev,
3755
- longTokens: [
3756
- { symbol: 'HYPE', weight: 25 },
3757
- { symbol: 'BTC', weight: 25 }
3758
- ],
3759
- shortTokens: [
3760
- { symbol: 'AVAX', weight: 10 },
3761
- { symbol: 'SEI', weight: 10 },
3762
- { symbol: 'ADA', weight: 10 },
3763
- { symbol: 'TRUMP', weight: 10 },
3764
- { symbol: 'SUI', weight: 10 }
3765
- ],
3766
- openTokenSelector: false,
3767
- selectorConfig: null,
3768
- openConflictModal: false,
3769
- }));
3770
- }, [setTokenSelection]);
3771
- const handleTokenSelect = require$$0.useCallback((selectedToken) => {
3772
- if (!tokenSelection.selectorConfig)
3773
- return;
3774
- const { isLong, index } = tokenSelection.selectorConfig;
3775
- const existingTokens = isLong ? tokenSelection.longTokens : tokenSelection.shortTokens;
3776
- // Check if token already exists
3777
- if (existingTokens.some(t => t.symbol === selectedToken))
3778
- return;
3779
- // Get metadata for new token
3780
- const metadata = TokenMetadataExtractor.extractTokenMetadata(selectedToken, webData2, allMids);
3781
- setTokenSelection(prev => {
3782
- if (index >= existingTokens.length) {
3783
- // Adding new token - calculate safe weight
3784
- const currentLongTotal = prev.longTokens.reduce((sum, token) => sum + token.weight, 0);
3785
- const currentShortTotal = prev.shortTokens.reduce((sum, token) => sum + token.weight, 0);
3786
- const currentTotal = currentLongTotal + currentShortTotal;
3787
- const maxAvailableWeight = Math.max(1, 100 - currentTotal);
3788
- const safeWeight = Math.min(20, maxAvailableWeight);
3789
- const newToken = {
3790
- symbol: selectedToken,
3791
- weight: safeWeight,
3792
- metadata: metadata || undefined
3793
- };
3794
- if (isLong) {
3795
- return { ...prev, longTokens: [...prev.longTokens, newToken] };
3796
- }
3797
- else {
3798
- return { ...prev, shortTokens: [...prev.shortTokens, newToken] };
3799
- }
3800
- }
3801
- else {
3802
- // Replacing existing token
3803
- if (isLong) {
3804
- const updated = [...prev.longTokens];
3805
- updated[index] = {
3806
- ...updated[index],
3807
- symbol: selectedToken,
3808
- metadata: metadata || undefined
3809
- };
3810
- return { ...prev, longTokens: updated };
3811
- }
3812
- else {
3813
- const updated = [...prev.shortTokens];
3814
- updated[index] = {
3815
- ...updated[index],
3816
- symbol: selectedToken,
3817
- metadata: metadata || undefined
3818
- };
3819
- return { ...prev, shortTokens: updated };
3820
- }
3821
- }
3822
- });
3823
- }, [tokenSelection.selectorConfig, tokenSelection.longTokens, tokenSelection.shortTokens, webData2, allMids, setTokenSelection]);
3824
- // updateTokenMetadata is now handled automatically by the useEffect above
3825
- return {
3826
- // State
3827
- longTokens: tokenSelection.longTokens,
3828
- shortTokens: tokenSelection.shortTokens,
3829
- openTokenSelector: tokenSelection.openTokenSelector,
3830
- selectorConfig: tokenSelection.selectorConfig,
3831
- openConflictModal: tokenSelection.openConflictModal,
3832
- conflicts: tokenSelection.conflicts,
3833
- // Loading states
3834
- isLoading,
3835
- isPriceDataReady,
3836
- // Calculated values
3837
- weightedRatio,
3838
- weightedRatio24h,
3839
- sumNetFunding,
3840
- maxLeverage,
3841
- minMargin,
3842
- // Actions
3843
- setLongTokens,
3844
- setShortTokens,
3845
- updateTokenWeight,
3846
- addToken,
3847
- removeToken,
3848
- handleTokenSelect,
3849
- setOpenTokenSelector,
3850
- setSelectorConfig,
3851
- setOpenConflictModal,
3852
- setConflicts,
3853
- resetToDefaults,
3854
- };
3855
- };
3856
-
3857
- /**
3858
- * Detects conflicts between selected tokens and existing positions
3859
- */
3860
- class ConflictDetector {
3861
- /**
3862
- * Detects conflicts between token selections and open positions
3863
- * @param longTokens - Selected long tokens
3864
- * @param shortTokens - Selected short tokens
3865
- * @param openPositions - Current open positions from API
3866
- * @returns Array of detected conflicts
3867
- */
3868
- static detectConflicts(longTokens, shortTokens, openPositions) {
3869
- const detectedConflicts = [];
3870
- if (!openPositions) {
3871
- return detectedConflicts;
3872
- }
3873
- // Check long tokens against existing short positions
3874
- longTokens.forEach((token) => {
3875
- const existingShortPosition = openPositions.find((pos) => {
3876
- var _a;
3877
- // Check multiple possible property names and side values
3878
- const symbol = pos.coin || pos.symbol || pos.asset;
3879
- const side = (_a = pos.side) === null || _a === void 0 ? void 0 : _a.toLowerCase();
3880
- return symbol === token.symbol && (side === 'short' || side === 'sell');
3881
- });
3882
- if (existingShortPosition) {
3883
- detectedConflicts.push({
3884
- symbol: token.symbol,
3885
- conflictType: 'short',
3886
- conflictMessage: `${token.symbol} Long conflicts with existing ${token.symbol} Short position`
3887
- });
3888
- }
3889
- });
3890
- // Check short tokens against existing long positions
3891
- shortTokens.forEach((token) => {
3892
- const existingLongPosition = openPositions.find((pos) => {
3893
- var _a;
3894
- // Check multiple possible property names and side values
3895
- const symbol = pos.coin || pos.symbol || pos.asset;
3896
- const side = (_a = pos.side) === null || _a === void 0 ? void 0 : _a.toLowerCase();
3897
- return symbol === token.symbol && (side === 'long' || side === 'buy');
3898
- });
3899
- if (existingLongPosition) {
3900
- detectedConflicts.push({
3901
- symbol: token.symbol,
3902
- conflictType: 'long',
3903
- conflictMessage: `${token.symbol} Short conflicts with existing ${token.symbol} Long position`
3904
- });
3905
- }
3906
- });
3907
- return detectedConflicts;
3908
- }
3909
- }
3910
-
3911
- exports.AccountSummaryCalculator = AccountSummaryCalculator;
3912
- exports.ConflictDetector = ConflictDetector;
3913
- exports.PearHyperliquidClient = PearHyperliquidClient;
3914
- exports.PearHyperliquidProvider = PearHyperliquidProvider;
3915
- exports.PearMigrationSDK = PearMigrationSDK;
3916
- exports.TokenMetadataExtractor = TokenMetadataExtractor;
3917
- exports.default = PearHyperliquidClient;
3918
- exports.useAccountSummary = useAccountSummary;
3919
- exports.useAddress = useAddress;
3920
- exports.useCalculatedAccountSummary = useCalculatedAccountSummary;
3921
- exports.useCalculatedOpenPositions = useCalculatedOpenPositions;
3922
- exports.useHyperliquidNativeWebSocket = useHyperliquidNativeWebSocket;
3923
- exports.useHyperliquidWebSocket = useHyperliquidWebSocket;
3924
- exports.useMigrationSDK = useMigrationSDK;
3925
- exports.useOpenOrders = useOpenOrders;
3926
- exports.useOpenPositions = useOpenPositions;
3927
- exports.usePearHyperliquidClient = usePearHyperliquidClient;
3928
- exports.useTokenSelection = useTokenSelection;
3929
- exports.useTradeHistories = useTradeHistories;
3930
- //# sourceMappingURL=index.js.map
17
+ */var He;function it(){return He||(He=1,process.env.NODE_ENV!=="production"&&(function(){function t(l){if(l==null)return null;if(typeof l=="function")return l.$$typeof===b?null:l.displayName||l.name||null;if(typeof l=="string")return l;switch(l){case O:return"Fragment";case T:return"Profiler";case w:return"StrictMode";case X:return"Suspense";case Y:return"SuspenseList";case m:return"Activity"}if(typeof l=="object")switch(typeof l.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),l.$$typeof){case S:return"Portal";case F:return(l.displayName||"Context")+".Provider";case P:return(l._context.displayName||"Context")+".Consumer";case W:var _=l.render;return l=l.displayName,l||(l=_.displayName||_.name||"",l=l!==""?"ForwardRef("+l+")":"ForwardRef"),l;case k:return _=l.displayName||null,_!==null?_:t(l.type)||"Memo";case y:_=l._payload,l=l._init;try{return t(l(_))}catch{}}return null}d(t,"getComponentNameFromType");function e(l){return""+l}d(e,"testStringCoercion");function n(l){try{e(l);var _=!1}catch{_=!0}if(_){_=console;var N=_.error,L=typeof Symbol=="function"&&Symbol.toStringTag&&l[Symbol.toStringTag]||l.constructor.name||"Object";return N.call(_,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",L),e(l)}}d(n,"checkKeyStringCoercion");function a(l){if(l===O)return"<>";if(typeof l=="object"&&l!==null&&l.$$typeof===y)return"<...>";try{var _=t(l);return _?"<"+_+">":"<...>"}catch{return"<...>"}}d(a,"getTaskName");function r(){var l=E.A;return l===null?null:l.getOwner()}d(r,"getOwner");function o(){return Error("react-stack-top-frame")}d(o,"UnknownOwner");function s(l){if(p.call(l,"key")){var _=Object.getOwnPropertyDescriptor(l,"key").get;if(_&&_.isReactWarning)return!1}return l.key!==void 0}d(s,"hasValidKey");function f(l,_){function N(){j||(j=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",_))}d(N,"warnAboutAccessingKey"),N.isReactWarning=!0,Object.defineProperty(l,"key",{get:N,configurable:!0})}d(f,"defineKeyPropWarningGetter");function c(){var l=t(this.type);return $[l]||($[l]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),l=this.props.ref,l!==void 0?l:null}d(c,"elementRefGetterWithDeprecationWarning");function i(l,_,N,L,Z,q,Ce,Ae){return N=q.ref,l={$$typeof:u,type:l,key:_,props:q,_owner:Z},(N!==void 0?N:null)!==null?Object.defineProperty(l,"ref",{enumerable:!1,get:c}):Object.defineProperty(l,"ref",{enumerable:!1,value:null}),l._store={},Object.defineProperty(l._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(l,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(l,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:Ce}),Object.defineProperty(l,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:Ae}),Object.freeze&&(Object.freeze(l.props),Object.freeze(l)),l}d(i,"ReactElement");function v(l,_,N,L,Z,q,Ce,Ae){var I=_.children;if(I!==void 0)if(L)if(C(I)){for(L=0;L<I.length;L++)h(I[L]);Object.freeze&&Object.freeze(I)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else h(I);if(p.call(_,"key")){I=t(l);var ae=Object.keys(_).filter(function(Ze){return Ze!=="key"});L=0<ae.length?"{key: someKey, "+ae.join(": ..., ")+": ...}":"{key: someKey}",Q[I+L]||(ae=0<ae.length?"{"+ae.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
18
+ let props = %s;
19
+ <%s {...props} />
20
+ React keys must be passed directly to JSX without using spread:
21
+ let props = %s;
22
+ <%s key={someKey} {...props} />`,L,I,ae,I),Q[I+L]=!0)}if(I=null,N!==void 0&&(n(N),I=""+N),s(_)&&(n(_.key),I=""+_.key),"key"in _){N={};for(var Ne in _)Ne!=="key"&&(N[Ne]=_[Ne])}else N=_;return I&&f(N,typeof l=="function"?l.displayName||l.name||"Unknown":l),i(l,I,q,Z,r(),N,Ce,Ae)}d(v,"jsxDEVImpl");function h(l){typeof l=="object"&&l!==null&&l.$$typeof===u&&l._store&&(l._store.validated=1)}d(h,"validateChildKeys");var g=ve,u=Symbol.for("react.transitional.element"),S=Symbol.for("react.portal"),O=Symbol.for("react.fragment"),w=Symbol.for("react.strict_mode"),T=Symbol.for("react.profiler"),P=Symbol.for("react.consumer"),F=Symbol.for("react.context"),W=Symbol.for("react.forward_ref"),X=Symbol.for("react.suspense"),Y=Symbol.for("react.suspense_list"),k=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),m=Symbol.for("react.activity"),b=Symbol.for("react.client.reference"),E=g.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,p=Object.prototype.hasOwnProperty,C=Array.isArray,M=console.createTask?console.createTask:function(){return null};g={react_stack_bottom_frame:d(function(l){return l()},"react_stack_bottom_frame")};var j,$={},R=g.react_stack_bottom_frame.bind(g,o)(),H=M(a(o)),Q={};le.Fragment=O,le.jsx=function(l,_,N,L,Z){var q=1e4>E.recentlyCreatedOwnerStacks++;return v(l,_,N,!1,L,Z,q?Error("react-stack-top-frame"):R,q?M(a(l)):H)},le.jsxs=function(l,_,N,L,Z){var q=1e4>E.recentlyCreatedOwnerStacks++;return v(l,_,N,!0,L,Z,q?Error("react-stack-top-frame"):R,q?M(a(l)):H)}})()),le}d(it,"requireReactJsxRuntime_development"),process.env.NODE_ENV==="production"?Re.exports=st():Re.exports=it();var ct=Re.exports,he={},se={},V={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.isEventSourceSupported=t.isReactNative=t.ReadyState=t.DEFAULT_HEARTBEAT=t.UNPARSABLE_JSON_OBJECT=t.DEFAULT_RECONNECT_INTERVAL_MS=t.DEFAULT_RECONNECT_LIMIT=t.SOCKET_IO_PING_CODE=t.SOCKET_IO_PATH=t.SOCKET_IO_PING_INTERVAL=t.DEFAULT_EVENT_SOURCE_OPTIONS=t.EMPTY_EVENT_HANDLERS=t.DEFAULT_OPTIONS=void 0;var e=1,n=1e3*e;t.DEFAULT_OPTIONS={},t.EMPTY_EVENT_HANDLERS={},t.DEFAULT_EVENT_SOURCE_OPTIONS={withCredentials:!1,events:t.EMPTY_EVENT_HANDLERS},t.SOCKET_IO_PING_INTERVAL=25*n,t.SOCKET_IO_PATH="/socket.io/?EIO=3&transport=websocket",t.SOCKET_IO_PING_CODE="2",t.DEFAULT_RECONNECT_LIMIT=20,t.DEFAULT_RECONNECT_INTERVAL_MS=5e3,t.UNPARSABLE_JSON_OBJECT={},t.DEFAULT_HEARTBEAT={message:"ping",timeout:6e4,interval:25e3};var a;(function(o){o[o.UNINSTANTIATED=-1]="UNINSTANTIATED",o[o.CONNECTING=0]="CONNECTING",o[o.OPEN=1]="OPEN",o[o.CLOSING=2]="CLOSING",o[o.CLOSED=3]="CLOSED"})(a||(t.ReadyState=a={}));var r=d(function(){try{return"EventSource"in globalThis}catch{return!1}},"eventSourceSupported");t.isReactNative=typeof navigator<"u"&&navigator.product==="ReactNative",t.isEventSourceSupported=!t.isReactNative&&r()})(V);var ge={},Se={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.resetWebSockets=t.sharedWebSockets=void 0,t.sharedWebSockets={};var e=d(function(n){if(n&&t.sharedWebSockets.hasOwnProperty(n))delete t.sharedWebSockets[n];else for(var a in t.sharedWebSockets)t.sharedWebSockets.hasOwnProperty(a)&&delete t.sharedWebSockets[a]},"resetWebSockets");t.resetWebSockets=e})(Se);var ye={},x={};Object.defineProperty(x,"__esModule",{value:!0}),x.setUpSocketIOPing=x.appendQueryParams=x.parseSocketIOUrl=void 0;var me=V,ut=d(function(t){if(t){var e=/^https|wss/.test(t),n=t.replace(/^(https?|wss?)(:\/\/)?/,""),a=n.replace(/\/$/,""),r=e?"wss":"ws";return"".concat(r,"://").concat(a).concat(me.SOCKET_IO_PATH)}else if(t===""){var e=/^https/.test(window.location.protocol),r=e?"wss":"ws",o=window.location.port?":".concat(window.location.port):"";return"".concat(r,"://").concat(window.location.hostname).concat(o).concat(me.SOCKET_IO_PATH)}return t},"parseSocketIOUrl");x.parseSocketIOUrl=ut;var lt=d(function(t,e){e===void 0&&(e={});var n=/\?([\w]+=[\w]+)/,a=n.test(t),r="".concat(Object.entries(e).reduce(function(o,s){var f=s[0],c=s[1];return o+"".concat(f,"=").concat(c,"&")},"").slice(0,-1));return"".concat(t).concat(a?"&":"?").concat(r)},"appendQueryParams");x.appendQueryParams=lt;var dt=d(function(t,e){e===void 0&&(e=me.SOCKET_IO_PING_INTERVAL);var n=d(function(){return t(me.SOCKET_IO_PING_CODE)},"ping");return window.setInterval(n,e)},"setUpSocketIOPing");x.setUpSocketIOPing=dt;var be={};Object.defineProperty(be,"__esModule",{value:!0}),be.heartbeat=vt;var Le=V;function ft(t){return Array.isArray(t)?t.reduce(function(e,n){return e.current>n.current?e:n}).current:t.current}d(ft,"getLastMessageTime");function vt(t,e,n){var a=n||{},r=a.interval,o=r===void 0?Le.DEFAULT_HEARTBEAT.interval:r,s=a.timeout,f=s===void 0?Le.DEFAULT_HEARTBEAT.timeout:s,c=a.message,i=c===void 0?Le.DEFAULT_HEARTBEAT.message:c,v=Math.max(100,o/10),h=Date.now(),g=setInterval(function(){var u=Date.now(),S=ft(e);if(S+f<=u)console.warn("Heartbeat timed out, closing connection, last message received ".concat(u-S,"ms ago, last ping sent ").concat(u-h,"ms ago")),t.close();else if(S+o<=u&&h+o<=u)try{typeof i=="function"?t.send(i()):t.send(i),h=u}catch(O){console.error("Heartbeat failed, closing connection",O instanceof Error?O.message:O),t.close()}},v);return t.addEventListener("close",function(){clearInterval(g)}),function(){}}d(vt,"heartbeat");var ie={},Te={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.resetSubscribers=t.removeSubscriber=t.addSubscriber=t.hasSubscribers=t.getSubscribers=void 0;var e={},n=[],a=d(function(c){return(0,t.hasSubscribers)(c)?Array.from(e[c]):n},"getSubscribers");t.getSubscribers=a;var r=d(function(c){var i;return((i=e[c])===null||i===void 0?void 0:i.size)>0},"hasSubscribers");t.hasSubscribers=r;var o=d(function(c,i){e[c]=e[c]||new Set,e[c].add(i)},"addSubscriber");t.addSubscriber=o;var s=d(function(c,i){e[c].delete(i)},"removeSubscriber");t.removeSubscriber=s;var f=d(function(c){if(c&&e.hasOwnProperty(c))delete e[c];else for(var i in e)e.hasOwnProperty(i)&&delete e[i]},"resetSubscribers");t.resetSubscribers=f})(Te),Object.defineProperty(ie,"__esModule",{value:!0}),ie.assertIsWebSocket=St,ie.resetGlobalState=yt;var ht=Se,gt=Te;function St(t,e){if(!e&&!(t instanceof WebSocket))throw new Error("")}d(St,"assertIsWebSocket");function yt(t){(0,gt.resetSubscribers)(t),(0,ht.resetWebSockets)(t)}d(yt,"resetGlobalState");var Ee=A&&A.__assign||function(){return Ee=Object.assign||function(t){for(var e,n=1,a=arguments.length;n<a;n++){e=arguments[n];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}return t},Ee.apply(this,arguments)};Object.defineProperty(ye,"__esModule",{value:!0}),ye.attachListeners=void 0;var mt=x,bt=be,J=V,Tt=ie,Et=d(function(t,e,n,a){t.onmessage=function(r){var o;e.current.onMessage&&e.current.onMessage(r),typeof a?.current=="number"&&(a.current=Date.now()),!(typeof e.current.filter=="function"&&e.current.filter(r)!==!0)&&(e.current.heartbeat&&typeof e.current.heartbeat!="boolean"&&((o=e.current.heartbeat)===null||o===void 0?void 0:o.returnMessage)===r.data||n(r))}},"bindMessageHandler$1"),_t=d(function(t,e,n,a,r){t.onopen=function(o){if(e.current.onOpen&&e.current.onOpen(o),a.current=0,n(J.ReadyState.OPEN),e.current.heartbeat&&t instanceof WebSocket){var s=typeof e.current.heartbeat=="boolean"?void 0:e.current.heartbeat;r.current=Date.now(),(0,bt.heartbeat)(t,r,s)}}},"bindOpenHandler$1"),Ot=d(function(t,e,n,a,r){if(J.isEventSourceSupported&&t instanceof EventSource)return function(){};(0,Tt.assertIsWebSocket)(t,e.current.skipAssert);var o;return t.onclose=function(s){var f;if(e.current.onClose&&e.current.onClose(s),n(J.ReadyState.CLOSED),e.current.shouldReconnect&&e.current.shouldReconnect(s)){var c=(f=e.current.reconnectAttempts)!==null&&f!==void 0?f:J.DEFAULT_RECONNECT_LIMIT;if(r.current<c){var i=typeof e.current.reconnectInterval=="function"?e.current.reconnectInterval(r.current):e.current.reconnectInterval;o=window.setTimeout(function(){r.current++,a()},i??J.DEFAULT_RECONNECT_INTERVAL_MS)}else e.current.onReconnectStop&&e.current.onReconnectStop(c),console.warn("Max reconnect attempts of ".concat(c," exceeded"))}},function(){return o&&window.clearTimeout(o)}},"bindCloseHandler$1"),pt=d(function(t,e,n,a,r){var o;return t.onerror=function(s){var f;if(e.current.onError&&e.current.onError(s),J.isEventSourceSupported&&t instanceof EventSource&&(e.current.onClose&&e.current.onClose(Ee(Ee({},s),{code:1006,reason:"An error occurred with the EventSource: ".concat(s),wasClean:!1})),n(J.ReadyState.CLOSED),t.close()),e.current.retryOnError)if(r.current<((f=e.current.reconnectAttempts)!==null&&f!==void 0?f:J.DEFAULT_RECONNECT_LIMIT)){var c=typeof e.current.reconnectInterval=="function"?e.current.reconnectInterval(r.current):e.current.reconnectInterval;o=window.setTimeout(function(){r.current++,a()},c??J.DEFAULT_RECONNECT_INTERVAL_MS)}else e.current.onReconnectStop&&e.current.onReconnectStop(e.current.reconnectAttempts),console.warn("Max reconnect attempts of ".concat(e.current.reconnectAttempts," exceeded"))},function(){return o&&window.clearTimeout(o)}},"bindErrorHandler$1"),wt=d(function(t,e,n,a,r,o,s){var f=e.setLastMessage,c=e.setReadyState,i,v,h;return n.current.fromSocketIO&&(i=(0,mt.setUpSocketIOPing)(s)),Et(t,n,f,o),_t(t,n,c,r,o),v=Ot(t,n,c,a,r),h=pt(t,n,c,a,r),function(){c(J.ReadyState.CLOSING),v(),h(),t.close(),i&&clearInterval(i)}},"attachListeners");ye.attachListeners=wt;var _e={},Oe=A&&A.__assign||function(){return Oe=Object.assign||function(t){for(var e,n=1,a=arguments.length;n<a;n++){e=arguments[n];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}return t},Oe.apply(this,arguments)};Object.defineProperty(_e,"__esModule",{value:!0}),_e.attachSharedListeners=void 0;var Pt=Se,oe=V,de=Te,kt=x,Ct=be,At=d(function(t,e,n){t.onmessage=function(a){(0,de.getSubscribers)(e).forEach(function(r){var o;r.optionsRef.current.onMessage&&r.optionsRef.current.onMessage(a),typeof((o=r?.lastMessageTime)===null||o===void 0?void 0:o.current)=="number"&&(r.lastMessageTime.current=Date.now()),!(typeof r.optionsRef.current.filter=="function"&&r.optionsRef.current.filter(a)!==!0)&&(n&&typeof n!="boolean"&&n?.returnMessage===a.data||r.setLastMessage(a))})}},"bindMessageHandler"),Nt=d(function(t,e,n){t.onopen=function(a){var r=(0,de.getSubscribers)(e);r.forEach(function(o){o.reconnectCount.current=0,o.optionsRef.current.onOpen&&o.optionsRef.current.onOpen(a),o.setReadyState(oe.ReadyState.OPEN),n&&t instanceof WebSocket&&(o.lastMessageTime.current=Date.now())}),n&&t instanceof WebSocket&&(0,Ct.heartbeat)(t,r.map(function(o){return o.lastMessageTime}),typeof n=="boolean"?void 0:n)}},"bindOpenHandler"),Mt=d(function(t,e){t instanceof WebSocket&&(t.onclose=function(n){(0,de.getSubscribers)(e).forEach(function(a){a.optionsRef.current.onClose&&a.optionsRef.current.onClose(n),a.setReadyState(oe.ReadyState.CLOSED)}),delete Pt.sharedWebSockets[e],(0,de.getSubscribers)(e).forEach(function(a){var r;if(a.optionsRef.current.shouldReconnect&&a.optionsRef.current.shouldReconnect(n)){var o=(r=a.optionsRef.current.reconnectAttempts)!==null&&r!==void 0?r:oe.DEFAULT_RECONNECT_LIMIT;if(a.reconnectCount.current<o){var s=typeof a.optionsRef.current.reconnectInterval=="function"?a.optionsRef.current.reconnectInterval(a.reconnectCount.current):a.optionsRef.current.reconnectInterval;setTimeout(function(){a.reconnectCount.current++,a.reconnect.current()},s??oe.DEFAULT_RECONNECT_INTERVAL_MS)}else a.optionsRef.current.onReconnectStop&&a.optionsRef.current.onReconnectStop(a.optionsRef.current.reconnectAttempts),console.warn("Max reconnect attempts of ".concat(o," exceeded"))}})})},"bindCloseHandler"),Rt=d(function(t,e){t.onerror=function(n){(0,de.getSubscribers)(e).forEach(function(a){a.optionsRef.current.onError&&a.optionsRef.current.onError(n),oe.isEventSourceSupported&&t instanceof EventSource&&(a.optionsRef.current.onClose&&a.optionsRef.current.onClose(Oe(Oe({},n),{code:1006,reason:"An error occurred with the EventSource: ".concat(n),wasClean:!1})),a.setReadyState(oe.ReadyState.CLOSED))}),oe.isEventSourceSupported&&t instanceof EventSource&&t.close()}},"bindErrorHandler"),Lt=d(function(t,e,n,a){var r;return n.current.fromSocketIO&&(r=(0,kt.setUpSocketIOPing)(a)),At(t,e,n.current.heartbeat),Mt(t,e),Nt(t,e,n.current.heartbeat),Rt(t,e),function(){r&&clearInterval(r)}},"attachSharedListeners");_e.attachSharedListeners=Lt,Object.defineProperty(ge,"__esModule",{value:!0}),ge.createOrJoinSocket=void 0;var te=Se,fe=V,It=ye,Dt=_e,Ie=Te,Ut=d(function(t,e,n,a,r){return function(){if((0,Ie.removeSubscriber)(t,e),!(0,Ie.hasSubscribers)(t)){try{var o=te.sharedWebSockets[t];o instanceof WebSocket&&(o.onclose=function(s){n.current.onClose&&n.current.onClose(s),a(fe.ReadyState.CLOSED)}),o.close()}catch{}r&&r(),delete te.sharedWebSockets[t]}}},"cleanSubscribers"),Wt=d(function(t,e,n,a,r,o,s,f,c){if(!fe.isEventSourceSupported&&a.current.eventSourceOptions)throw fe.isReactNative?new Error("EventSource is not supported in ReactNative"):new Error("EventSource is not supported");if(a.current.share){var i=null;te.sharedWebSockets[e]===void 0?(te.sharedWebSockets[e]=a.current.eventSourceOptions?new EventSource(e,a.current.eventSourceOptions):new WebSocket(e,a.current.protocols),t.current=te.sharedWebSockets[e],n(fe.ReadyState.CONNECTING),i=(0,Dt.attachSharedListeners)(te.sharedWebSockets[e],e,a,c)):(t.current=te.sharedWebSockets[e],n(te.sharedWebSockets[e].readyState));var v={setLastMessage:r,setReadyState:n,optionsRef:a,reconnectCount:s,lastMessageTime:f,reconnect:o};return(0,Ie.addSubscriber)(e,v),Ut(e,v,a,n,i)}else{if(t.current=a.current.eventSourceOptions?new EventSource(e,a.current.eventSourceOptions):new WebSocket(e,a.current.protocols),n(fe.ReadyState.CONNECTING),!t.current)throw new Error("WebSocket failed to be created");return(0,It.attachListeners)(t.current,{setLastMessage:r,setReadyState:n},a,o.current,s,f,c)}},"createOrJoinSocket");ge.createOrJoinSocket=Wt;var $e={};(function(t){var e=A&&A.__awaiter||function(c,i,v,h){function g(u){return u instanceof v?u:new v(function(S){S(u)})}return d(g,"adopt"),new(v||(v=Promise))(function(u,S){function O(P){try{T(h.next(P))}catch(F){S(F)}}d(O,"fulfilled");function w(P){try{T(h.throw(P))}catch(F){S(F)}}d(w,"rejected");function T(P){P.done?u(P.value):g(P.value).then(O,w)}d(T,"step"),T((h=h.apply(c,i||[])).next())})},n=A&&A.__generator||function(c,i){var v={label:0,sent:d(function(){if(u[0]&1)throw u[1];return u[1]},"sent"),trys:[],ops:[]},h,g,u,S=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return S.next=O(0),S.throw=O(1),S.return=O(2),typeof Symbol=="function"&&(S[Symbol.iterator]=function(){return this}),S;function O(T){return function(P){return w([T,P])}}function w(T){if(h)throw new TypeError("Generator is already executing.");for(;S&&(S=0,T[0]&&(v=0)),v;)try{if(h=1,g&&(u=T[0]&2?g.return:T[0]?g.throw||((u=g.return)&&u.call(g),0):g.next)&&!(u=u.call(g,T[1])).done)return u;switch(g=0,u&&(T=[T[0]&2,u.value]),T[0]){case 0:case 1:u=T;break;case 4:return v.label++,{value:T[1],done:!1};case 5:v.label++,g=T[1],T=[0];continue;case 7:T=v.ops.pop(),v.trys.pop();continue;default:if(u=v.trys,!(u=u.length>0&&u[u.length-1])&&(T[0]===6||T[0]===2)){v=0;continue}if(T[0]===3&&(!u||T[1]>u[0]&&T[1]<u[3])){v.label=T[1];break}if(T[0]===6&&v.label<u[1]){v.label=u[1],u=T;break}if(u&&v.label<u[2]){v.label=u[2],v.ops.push(T);break}u[2]&&v.ops.pop(),v.trys.pop();continue}T=i.call(c,v)}catch(P){T=[6,P],g=0}finally{h=u=0}if(T[0]&5)throw T[1];return{value:T[0]?T[1]:void 0,done:!0}}},a=A&&A.__spreadArray||function(c,i,v){if(v||arguments.length===2)for(var h=0,g=i.length,u;h<g;h++)(u||!(h in i))&&(u||(u=Array.prototype.slice.call(i,0,h)),u[h]=i[h]);return c.concat(u||Array.prototype.slice.call(i))};Object.defineProperty(t,"__esModule",{value:!0}),t.getUrl=void 0;var r=x,o=V,s=d(function(c){return new Promise(function(i){return window.setTimeout(i,c)})},"waitFor"),f=d(function(c,i){for(var v=[],h=2;h<arguments.length;h++)v[h-2]=arguments[h];return e(void 0,a([c,i],v,!0),void 0,function(g,u,S){var O,w,T,P,F,W,X,Y;return S===void 0&&(S=0),n(this,function(k){switch(k.label){case 0:if(typeof g!="function")return[3,10];k.label=1;case 1:return k.trys.push([1,3,,9]),[4,g()];case 2:return O=k.sent(),[3,9];case 3:return k.sent(),u.current.retryOnError?(w=(W=u.current.reconnectAttempts)!==null&&W!==void 0?W:o.DEFAULT_RECONNECT_LIMIT,S<w?(T=typeof u.current.reconnectInterval=="function"?u.current.reconnectInterval(S):u.current.reconnectInterval,[4,s(T??o.DEFAULT_RECONNECT_INTERVAL_MS)]):[3,5]):[3,7];case 4:return k.sent(),[2,(0,t.getUrl)(g,u,S+1)];case 5:return(Y=(X=u.current).onReconnectStop)===null||Y===void 0||Y.call(X,S),[2,null];case 6:return[3,8];case 7:return[2,null];case 8:return[3,9];case 9:return[3,11];case 10:O=g,k.label=11;case 11:return P=u.current.fromSocketIO?(0,r.parseSocketIOUrl)(O):O,F=u.current.queryParams?(0,r.appendQueryParams)(P,u.current.queryParams):P,[2,F]}})})},"getUrl");t.getUrl=f})($e);var ze={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.websocketWrapper=void 0;var e=d(function(n,a){return new Proxy(n,{get:d(function(r,o){var s=r[o];return o==="reconnect"?a:typeof s=="function"?(console.error("Calling methods directly on the websocket is not supported at this moment. You must use the methods returned by useWebSocket."),function(){}):s},"get"),set:d(function(r,o,s){return/^on/.test(o)?(console.warn("The websocket's event handlers should be defined through the options object passed into useWebSocket."),!1):(r[o]=s,!0)},"set")})},"websocketWrapper");t.websocketWrapper=e,t.default=t.websocketWrapper})(ze);var ne=A&&A.__assign||function(){return ne=Object.assign||function(t){for(var e,n=1,a=arguments.length;n<a;n++){e=arguments[n];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}return t},ne.apply(this,arguments)},jt=A&&A.__awaiter||function(t,e,n,a){function r(o){return o instanceof n?o:new n(function(s){s(o)})}return d(r,"adopt"),new(n||(n=Promise))(function(o,s){function f(v){try{i(a.next(v))}catch(h){s(h)}}d(f,"fulfilled");function c(v){try{i(a.throw(v))}catch(h){s(h)}}d(c,"rejected");function i(v){v.done?o(v.value):r(v.value).then(f,c)}d(i,"step"),i((a=a.apply(t,e||[])).next())})},Ft=A&&A.__generator||function(t,e){var n={label:0,sent:d(function(){if(o[0]&1)throw o[1];return o[1]},"sent"),trys:[],ops:[]},a,r,o,s=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return s.next=f(0),s.throw=f(1),s.return=f(2),typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function f(i){return function(v){return c([i,v])}}function c(i){if(a)throw new TypeError("Generator is already executing.");for(;s&&(s=0,i[0]&&(n=0)),n;)try{if(a=1,r&&(o=i[0]&2?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[i[0]&2,o.value]),i[0]){case 0:case 1:o=i;break;case 4:return n.label++,{value:i[1],done:!1};case 5:n.label++,r=i[1],i=[0];continue;case 7:i=n.ops.pop(),n.trys.pop();continue;default:if(o=n.trys,!(o=o.length>0&&o[o.length-1])&&(i[0]===6||i[0]===2)){n=0;continue}if(i[0]===3&&(!o||i[1]>o[0]&&i[1]<o[3])){n.label=i[1];break}if(i[0]===6&&n.label<o[1]){n.label=o[1],o=i;break}if(o&&n.label<o[2]){n.label=o[2],n.ops.push(i);break}o[2]&&n.ops.pop(),n.trys.pop();continue}i=e.call(t,n)}catch(v){i=[6,v],r=0}finally{a=o=0}if(i[0]&5)throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}},Ht=A&&A.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(se,"__esModule",{value:!0}),se.useWebSocket=void 0;var U=ve,De=ot,G=V,$t=ge,zt=$e,Vt=Ht(ze),Ve=ie,qt=d(function(t,e,n){e===void 0&&(e=G.DEFAULT_OPTIONS),n===void 0&&(n=!0);var a=(0,U.useState)(null),r=a[0],o=a[1],s=(0,U.useState)({}),f=s[0],c=s[1],i=(0,U.useMemo)(function(){if(!e.disableJson&&r)try{return JSON.parse(r.data)}catch{return G.UNPARSABLE_JSON_OBJECT}return null},[r,e.disableJson]),v=(0,U.useRef)(null),h=(0,U.useRef)(null),g=(0,U.useRef)(function(){}),u=(0,U.useRef)(0),S=(0,U.useRef)(Date.now()),O=(0,U.useRef)([]),w=(0,U.useRef)(null),T=(0,U.useRef)(e);T.current=e;var P=v.current&&f[v.current]!==void 0?f[v.current]:t!==null&&n===!0?G.ReadyState.CONNECTING:G.ReadyState.UNINSTANTIATED,F=e.queryParams?JSON.stringify(e.queryParams):null,W=(0,U.useCallback)(function(k,y){var m;if(y===void 0&&(y=!0),G.isEventSourceSupported&&h.current instanceof EventSource){console.warn("Unable to send a message from an eventSource");return}((m=h.current)===null||m===void 0?void 0:m.readyState)===G.ReadyState.OPEN?((0,Ve.assertIsWebSocket)(h.current,T.current.skipAssert),h.current.send(k)):y&&O.current.push(k)},[]),X=(0,U.useCallback)(function(k,y){y===void 0&&(y=!0),W(JSON.stringify(k),y)},[W]),Y=(0,U.useCallback)(function(){return T.current.share!==!0||G.isEventSourceSupported&&h.current instanceof EventSource?h.current:(w.current===null&&h.current&&((0,Ve.assertIsWebSocket)(h.current,T.current.skipAssert),w.current=(0,Vt.default)(h.current,g)),w.current)},[]);return(0,U.useEffect)(function(){if(t!==null&&n===!0){var k,y=!1,m=!0,b=d(function(){return jt(void 0,void 0,void 0,function(){var E,p,C;return Ft(this,function(M){switch(M.label){case 0:return E=v,[4,(0,zt.getUrl)(t,T)];case 1:return E.current=M.sent(),v.current===null?(console.error("Failed to get a valid URL. WebSocket connection aborted."),v.current="ABORTED",(0,De.flushSync)(function(){return c(function(j){return ne(ne({},j),{ABORTED:G.ReadyState.CLOSED})})}),[2]):(p=d(function(j){y||(0,De.flushSync)(function(){return o(j)})},"protectedSetLastMessage"),C=d(function(j){y||(0,De.flushSync)(function(){return c(function($){var R;return ne(ne({},$),v.current&&(R={},R[v.current]=j,R))})})},"protectedSetReadyState"),m&&(k=(0,$t.createOrJoinSocket)(h,v.current,C,T,p,g,u,S,W)),[2])}})})},"start_1");return g.current=function(){y||(w.current&&(w.current=null),k?.(),b())},b(),function(){y=!0,m=!1,w.current&&(w.current=null),k?.(),o(null)}}else(t===null||n===!1)&&(u.current=0,c(function(E){var p;return ne(ne({},E),v.current&&(p={},p[v.current]=G.ReadyState.CLOSED,p))}))},[t,n,F,W]),(0,U.useEffect)(function(){P===G.ReadyState.OPEN&&O.current.splice(0).forEach(function(k){W(k)})},[P]),{sendMessage:W,sendJsonMessage:X,lastMessage:r,lastJsonMessage:i,readyState:P,getWebSocket:Y}},"useWebSocket$1");se.useWebSocket=qt;var pe={},we=A&&A.__assign||function(){return we=Object.assign||function(t){for(var e,n=1,a=arguments.length;n<a;n++){e=arguments[n];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}return t},we.apply(this,arguments)};Object.defineProperty(pe,"__esModule",{value:!0}),pe.useSocketIO=void 0;var qe=ve,xt=se,Jt=V,Ue={type:"empty",payload:null},Gt=d(function(t){if(!t||!t.data)return Ue;var e=t.data.match(/\[.*]/);if(!e)return Ue;var n=JSON.parse(e);return!Array.isArray(n)||!n[1]?Ue:{type:n[0],payload:n[1]}},"getSocketData"),Yt=d(function(t,e,n){e===void 0&&(e=Jt.DEFAULT_OPTIONS),n===void 0&&(n=!0);var a=(0,qe.useMemo)(function(){return we(we({},e),{fromSocketIO:!0})},[]),r=(0,xt.useWebSocket)(t,a,n),o=r.sendMessage,s=r.sendJsonMessage,f=r.lastMessage,c=r.readyState,i=r.getWebSocket,v=(0,qe.useMemo)(function(){return Gt(f)},[f]);return{sendMessage:o,sendJsonMessage:s,lastMessage:v,lastJsonMessage:v,readyState:c,getWebSocket:i}},"useSocketIO");pe.useSocketIO=Yt;var Pe={},ke=A&&A.__assign||function(){return ke=Object.assign||function(t){for(var e,n=1,a=arguments.length;n<a;n++){e=arguments[n];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])}return t},ke.apply(this,arguments)},Bt=A&&A.__rest||function(t,e){var n={};for(var a in t)Object.prototype.hasOwnProperty.call(t,a)&&e.indexOf(a)<0&&(n[a]=t[a]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,a=Object.getOwnPropertySymbols(t);r<a.length;r++)e.indexOf(a[r])<0&&Object.prototype.propertyIsEnumerable.call(t,a[r])&&(n[a[r]]=t[a[r]]);return n};Object.defineProperty(Pe,"__esModule",{value:!0}),Pe.useEventSource=void 0;var xe=ve,Kt=se,Je=V,Xt=d(function(t,e,n){e===void 0&&(e=Je.DEFAULT_EVENT_SOURCE_OPTIONS);var a=e.withCredentials,r=e.events,o=Bt(e,["withCredentials","events"]);n===void 0&&(n=!0);var s=ke(ke({},o),{eventSourceOptions:{withCredentials:a}}),f=(0,xe.useRef)(Je.EMPTY_EVENT_HANDLERS);r&&(f.current=r);var c=(0,Kt.useWebSocket)(t,s,n),i=c.lastMessage,v=c.readyState,h=c.getWebSocket;return(0,xe.useEffect)(function(){i?.type&&Object.entries(f.current).forEach(function(g){var u=g[0],S=g[1];u===i.type&&S(i)})},[i]),{lastEvent:i,readyState:v,getEventSource:h}},"useEventSource");Pe.useEventSource=Xt,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.resetGlobalState=t.useEventSource=t.ReadyState=t.useSocketIO=t.default=void 0;var e=se;Object.defineProperty(t,"default",{enumerable:!0,get:d(function(){return e.useWebSocket},"get")});var n=pe;Object.defineProperty(t,"useSocketIO",{enumerable:!0,get:d(function(){return n.useSocketIO},"get")});var a=V;Object.defineProperty(t,"ReadyState",{enumerable:!0,get:d(function(){return a.ReadyState},"get")});var r=Pe;Object.defineProperty(t,"useEventSource",{enumerable:!0,get:d(function(){return r.useEventSource},"get")});var o=ie;Object.defineProperty(t,"resetGlobalState",{enumerable:!0,get:d(function(){return o.resetGlobalState},"get")})})(he);var Ge=at(he);const Ye=d(({wsUrl:t,address:e})=>{const[n,a]=B({tradeHistories:null,openPositions:null,openOrders:null,accountSummary:null}),[r,o]=B(null),[s,f]=B(null),{readyState:c,sendMessage:i}=Ge(t,{shouldReconnect:d(()=>!0,"shouldReconnect"),reconnectAttempts:5,reconnectInterval:3e3,onMessage:d(h=>{try{const g=JSON.parse(h.data);if(("success"in g||"error"in g)&&!("channel"in g)){g.error?o(g.error):o(null);return}if("channel"in g&&"data"in g){const u=g;if(u.data===null||u.data===void 0)return;switch(u.channel){case"trade-histories":Array.isArray(u.data)&&a(S=>({...S,tradeHistories:u.data}));break;case"open-positions":Array.isArray(u.data)&&a(S=>({...S,openPositions:u.data}));break;case"open-orders":Array.isArray(u.data)&&a(S=>({...S,openOrders:u.data}));break;case"account-summary":typeof u.data=="object"&&u.data!==null&&a(S=>({...S,accountSummary:u.data}));break}}}catch(g){o(`Failed to parse message: ${g instanceof Error?g.message:String(g)}`)}},"onMessage")}),v=c===he.ReadyState.OPEN;return ce(()=>{v&&e&&e!==s?(s&&i(JSON.stringify({action:"unsubscribe",address:s})),i(JSON.stringify({action:"subscribe",address:e})),f(e),o(null)):v&&!e&&s&&(i(JSON.stringify({action:"unsubscribe",address:s})),f(null))},[v,e,s,i]),ce(()=>{e!==s&&(a({tradeHistories:null,openPositions:null,openOrders:null,accountSummary:null}),o(null))},[e,s]),{data:n,connectionStatus:c,isConnected:v,lastError:r}},"useHyperliquidWebSocket"),Be=d(({address:t})=>{const[e,n]=B(null),[a,r]=B(null),[o,s]=B(null),[f,c]=B(null),i=nt(null),{readyState:v,sendJsonMessage:h}=Ge("wss://api.hyperliquid.xyz/ws",{shouldReconnect:d(()=>!0,"shouldReconnect"),reconnectAttempts:5,reconnectInterval:3e3,onOpen:d(()=>{},"onOpen"),onClose:d(()=>{},"onClose"),onError:d(u=>console.error("[HyperLiquid WS] Connection error:",u),"onError"),onReconnectStop:d(()=>console.error("[HyperLiquid WS] Reconnection stopped after 5 attempts"),"onReconnectStop"),onMessage:d(u=>{try{const S=JSON.parse(u.data);if("success"in S||"error"in S){S.error?(console.error("[HyperLiquid WS] Subscription error:",S.error),s(S.error)):s(null);return}if("channel"in S&&"data"in S){const O=S;switch(O.channel){case"webData2":n(O.data);break;case"allMids":r(O.data);break;default:console.warn(`[HyperLiquid WS] Unknown channel: ${O.channel}`)}}}catch(S){const O=`Failed to parse message: ${S instanceof Error?S.message:String(S)}`;console.error("[HyperLiquid WS] Parse error:",O,"Raw message:",u.data),s(O)}},"onMessage")}),g=v===he.ReadyState.OPEN;return ce(()=>(g?i.current=setInterval(()=>{h({method:"ping"})},3e4):i.current&&(clearInterval(i.current),i.current=null),()=>{i.current&&(clearInterval(i.current),i.current=null)}),[g,h]),ce(()=>{if(!g)return;const S=t||"0x0000000000000000000000000000000000000000";if(f===S)return;f&&h({method:"unsubscribe",subscription:{type:"webData2",user:f}});const O={method:"subscribe",subscription:{type:"webData2",user:S}},w={method:"subscribe",subscription:{type:"allMids"}};h(O),h(w),c(S),f&&f!==S&&n(null)},[g,t,f,h]),{webData2:e,allMids:a,connectionStatus:v,isConnected:g,lastError:o}},"useHyperliquidNativeWebSocket"),Qt={longTokens:[{symbol:"HYPE",weight:25},{symbol:"BTC",weight:25}],shortTokens:[{symbol:"AVAX",weight:10},{symbol:"SEI",weight:10},{symbol:"ADA",weight:10},{symbol:"TRUMP",weight:10},{symbol:"SUI",weight:10}],openTokenSelector:!1,selectorConfig:null,openConflictModal:!1,conflicts:[]},K=rt(void 0),Zt=d(({config:t,wsUrl:e="wss://hl-v2.pearprotocol.io/ws",children:n})=>{const a=D(()=>new Me(t),[t]),r=D(()=>new je(a),[a]),[o,s]=B(null),[f,c]=B(Qt),{data:i,connectionStatus:v,isConnected:h,lastError:g}=Ye({wsUrl:e,address:o}),{webData2:u,allMids:S,connectionStatus:O,isConnected:w,lastError:T}=Be({address:o}),P=D(()=>({client:a,migrationSDK:r,address:o,setAddress:s,connectionStatus:v,isConnected:h,data:i,lastError:g,nativeConnectionStatus:O,nativeIsConnected:w,nativeLastError:T,webData2:u,allMids:S,tokenSelection:f,setTokenSelection:c}),[a,r,o,v,h,i,g,O,w,T,u,S,f,c]);return ct.jsx(K.Provider,{value:P,children:n})},"PearHyperliquidProvider"),en=d(()=>{const t=ee(K);if(!t)throw new Error("usePearHyperliquidClient must be used within a PearHyperliquidProvider");return t.client},"usePearHyperliquidClient"),tn=d(()=>{const t=ee(K);if(!t)throw new Error("useMigrationSDK must be used within a PearHyperliquidProvider");return t.migrationSDK},"useMigrationSDK"),nn=d(()=>{const t=ee(K);if(!t)throw new Error("useAddress must be used within a PearHyperliquidProvider");return{address:t.address,setAddress:t.setAddress,clearAddress:d(()=>t.setAddress(null),"clearAddress"),isLoggedIn:!!t.address}},"useAddress");var re;(function(t){t.LONG="LONG",t.SHORT="SHORT"})(re||(re={}));class rn{static{d(this,"PositionProcessor")}constructor(e,n){this.webData2=e,this.allMids=n}execute(e){if(!e||e.length===0)return[];const n=this.getUserPositions(),a=this.calculatePlatformTotalsByAsset(e),r=new Map;(n||[]).forEach(s=>{var f;!((f=s.position)===null||f===void 0)&&f.coin&&r.set(s.position.coin,s)});const o=[];for(const s of e){const f=this.syncPositionWithAggregateData(s,r,a);o.push(f)}return o}getUserPositions(){var e,n;return((n=(e=this.webData2)===null||e===void 0?void 0:e.clearinghouseState)===null||n===void 0?void 0:n.assetPositions)||[]}getMarketPrice(e){var n;if(!(!((n=this.allMids)===null||n===void 0)&&n.mids))return 0;const a=this.allMids.mids[e];if(a)return Number(a);const r=this.extractBaseCurrency(e),o=this.allMids.mids[r];return o?Number(o):0}calculatePlatformTotalsByAsset(e){const n=new Map;for(const a of e){for(const r of a.longAssets||[]){const o=this.extractBaseCurrency(r.coin);n.has(o)||n.set(o,{totalSize:0,positions:[]});const s=n.get(o),f=Number(r.size||0);s.totalSize+=f,s.positions.push({positionId:a.positionId,asset:r,size:f})}for(const r of a.shortAssets||[]){const o=this.extractBaseCurrency(r.coin);n.has(o)||n.set(o,{totalSize:0,positions:[]});const s=n.get(o),f=Number(r.size||0);s.totalSize+=f,s.positions.push({positionId:a.positionId,asset:r,size:f})}}return n}extractBaseCurrency(e){return e.split("/")[0]||e}syncPositionWithAggregateData(e,n,a){const r=[];let o=!1,s=!0,f={total:0,closed:0},c={total:0,closed:0};for(const v of e.longAssets||[]){const h=this.extractBaseCurrency(v.coin),g=n.get(h),u=a.get(h),S=this.syncAssetWithAggregateData({...v,side:re.LONG},g,u?.totalSize||0);r.push(S),f.total++,S.actualSize===0&&f.closed++,S.isExternallyModified&&(o=!0),S.actualSize!==0&&(s=!1)}for(const v of e.shortAssets||[]){const h=this.extractBaseCurrency(v.coin),g=n.get(h),u=a.get(h),S=this.syncAssetWithAggregateData({...v,side:re.SHORT},g,u?.totalSize||0);r.push(S),c.total++,S.actualSize===0&&c.closed++,S.isExternallyModified&&(o=!0),S.actualSize!==0&&(s=!1)}const i=this.determineSyncStatus(o,s,f,c);return this.mapPositionToDtoWithSyncData(e,r,i)}determineSyncStatus(e,n,a,r){if(n)return"EXTERNALLY_CLOSED";const o=a.total>0&&a.closed===a.total,s=r.total>0&&r.closed===r.total;return o&&!s||!o&&s?"PAIR_BROKEN":e?"EXTERNALLY_MODIFIED":"SYNCED"}syncAssetWithAggregateData(e,n,a){const r=Number(e.size||0);if(!n||!n.position||!n.position.szi)return{asset:e,actualSize:0,isExternallyModified:!0,cumFunding:{allTime:0,sinceChange:0,sinceOpen:0},unrealizedPnl:0,liquidationPrice:0};const o=Math.abs(Number(n.position.szi||0)),s=Math.abs(o-a),f=a*.001,c=s>f,i=a>0?r/a:0,v=o*i,h=n.position.cumFunding,g={allTime:Number(h?.allTime||0),sinceChange:Number(h?.sinceChange||0)*i,sinceOpen:Number(h?.sinceOpen||0)*i},u=Number(n.position.unrealizedPnl||0)*i,S=Number(n.position.liquidationPx||0);return{asset:e,actualSize:v,isExternallyModified:c,cumFunding:g,unrealizedPnl:u,liquidationPrice:S}}mapPositionToDtoWithSyncData(e,n,a){var r,o;const s=((r=e.longAssets)===null||r===void 0?void 0:r.filter(g=>g))||[],f=((o=e.shortAssets)===null||o===void 0?void 0:o.filter(g=>g))||[],c=new Map;n.forEach(g=>{c.set(`${g.asset.coin}-${g.asset.side}`,g)});const i=this.calculateCurrentTotalPositionValue(n),h=this.calculateEntryTotalPositionValue(n)/e.leverage;return{syncStatus:a,positionId:e.positionId,address:e.address,leverage:e.leverage,stopLoss:e.stopLoss,takeProfit:e.takeProfit,entryRatio:this.calculateEntryRatio(n),markRatio:this.calculateMarkRatio(n),netFunding:this.calculateNetFundingFromSyncResults(n),positionValue:i,marginUsed:h,unrealizedPnl:this.calculateTotalUnrealizedPnlFromSyncResults(n),lastSyncAt:new Date().toISOString(),longAssets:s.map(g=>this.mapAssetToDetailDto(g,c.get(`${g.coin}-LONG`))),shortAssets:f.map(g=>this.mapAssetToDetailDto(g,c.get(`${g.coin}-SHORT`))),createdAt:e.createdAt,updatedAt:e.updatedAt}}mapAssetToDetailDto(e,n){const a=this.getMarketPrice(e.coin),r=n?.actualSize||Number(e.size||0),o=r*a,s=Number(e.size||0)*Number(e.entryPrice||0);return{coin:e.coin,entryPrice:Number(e.entryPrice||0),platformSize:Number(e.size||0),actualSize:r,isExternallyModified:n?.isExternallyModified||!1,cumFunding:n?.cumFunding||{allTime:0,sinceChange:0,sinceOpen:0},marginUsed:s,positionValue:o,unrealizedPnl:n?.unrealizedPnl||0,liquidationPrice:n?.liquidationPrice||0}}calculateEntryRatio(e){var n,a;const r=e.filter(c=>c.asset.side===re.LONG),o=e.filter(c=>c.asset.side===re.SHORT);if(r.length===0||o.length===0)return 0;const s=!((n=r[0])===null||n===void 0)&&n.asset.entryPrice?Number(r[0].asset.entryPrice):0,f=!((a=o[0])===null||a===void 0)&&a.asset.entryPrice?Number(o[0].asset.entryPrice):0;return f>0?s/f:0}calculateMarkRatio(e){var n,a;const r=e.filter(c=>c.asset.side===re.LONG),o=e.filter(c=>c.asset.side===re.SHORT);if(r.length===0||o.length===0)return 0;const s=!((n=r[0])===null||n===void 0)&&n.asset.coin?this.getMarketPrice(r[0].asset.coin):0,f=!((a=o[0])===null||a===void 0)&&a.asset.coin?this.getMarketPrice(o[0].asset.coin):0;return f>0?s/f:0}calculateNetFundingFromSyncResults(e){return e.reduce((a,r)=>{const o=r.cumFunding.sinceOpen;return a+o},0)}calculateTotalUnrealizedPnlFromSyncResults(e){return e.reduce((n,a)=>n+a.unrealizedPnl,0)}calculateCurrentTotalPositionValue(e){return e.reduce((n,a)=>{const r=this.getMarketPrice(a.asset.coin);return n+a.actualSize*r},0)}calculateEntryTotalPositionValue(e){return e.reduce((n,a)=>n+Number(a.asset.size||0)*Number(a.asset.entryPrice||0),0)}}const Ke=d((t,e,n)=>D(()=>!t||!e||!n?null:new rn(e,n).execute(t),[t,e,n]),"useCalculatedOpenPositions");class Xe{static{d(this,"AccountSummaryCalculator")}constructor(e){this.webData2=e}calculateAccountSummary(e,n,a,r){var o,s,f,c,i,v,h,g,u,S,O;if(!(!((o=this.webData2)===null||o===void 0)&&o.clearinghouseState))return e;const w=this.webData2.clearinghouseState,T=this.calculateTotalLimitOrderValue(n||[]),P=parseFloat(w.withdrawable||"0"),F=Math.max(0,P-T);return{balanceSummary:{crossMaintenanceMarginUsed:w.crossMaintenanceMarginUsed||"0",crossMarginSummary:{accountValue:((s=w.crossMarginSummary)===null||s===void 0?void 0:s.accountValue)||"0",totalMarginUsed:((f=w.crossMarginSummary)===null||f===void 0?void 0:f.totalMarginUsed)||"0",totalNtlPos:((c=w.crossMarginSummary)===null||c===void 0?void 0:c.totalNtlPos)||"0",totalRawUsd:((i=w.crossMarginSummary)===null||i===void 0?void 0:i.totalRawUsd)||"0"},marginSummary:{accountValue:((v=w.marginSummary)===null||v===void 0?void 0:v.accountValue)||"0",totalMarginUsed:((h=w.marginSummary)===null||h===void 0?void 0:h.totalMarginUsed)||"0",totalNtlPos:((g=w.marginSummary)===null||g===void 0?void 0:g.totalNtlPos)||"0",totalRawUsd:((u=w.marginSummary)===null||u===void 0?void 0:u.totalRawUsd)||"0"},time:w.time||Date.now(),withdrawable:F.toString()},agentWallet:{address:a||((S=e?.agentWallet)===null||S===void 0?void 0:S.address)||"",status:r||((O=e?.agentWallet)===null||O===void 0?void 0:O.status)||"UNKNOWN"}}}calculateTotalLimitOrderValue(e){return e?.length?e.filter(a=>a.status==="OPEN"||a.status==="PROCESSING").reduce((a,r)=>a+r.usdValue,0):0}getClearinghouseState(){var e;return((e=this.webData2)===null||e===void 0?void 0:e.clearinghouseState)||null}hasRealTimeData(){var e;return!!(!((e=this.webData2)===null||e===void 0)&&e.clearinghouseState)}}const Qe=d((t,e,n,a,r)=>D(()=>t?n?.clearinghouseState?new Xe(n).calculateAccountSummary(t,e,a,r):t:null,[t,e,n,a,r]),"useCalculatedAccountSummary"),on=d(()=>{const t=ee(K);if(!t)throw new Error("useTradeHistories must be used within a PearHyperliquidProvider");const e=D(()=>t.data.tradeHistories===null&&t.isConnected,[t.data.tradeHistories,t.isConnected]);return{data:t.data.tradeHistories,isLoading:e}},"useTradeHistories"),an=d(()=>{const t=ee(K);if(!t)throw new Error("useOpenPositions must be used within a PearHyperliquidProvider");const e=Ke(t.data.openPositions,t.webData2,t.allMids),n=D(()=>t.isConnected&&(t.data.openPositions===null||!t.webData2||!t.allMids),[t.data.openPositions,t.webData2,t.allMids,t.isConnected]);return{data:e,isLoading:n}},"useOpenPositions"),sn=d(()=>{const t=ee(K);if(!t)throw new Error("useOpenOrders must be used within a PearHyperliquidProvider");const e=D(()=>t.data.openOrders===null&&t.isConnected,[t.data.openOrders,t.isConnected]);return{data:t.data.openOrders,isLoading:e}},"useOpenOrders"),cn=d(()=>{var t,e,n,a;const r=ee(K);if(!r)throw new Error("useAccountSummary must be used within a PearHyperliquidProvider");const o=Qe(r.data.accountSummary,r.data.openOrders,r.webData2,(e=(t=r.data.accountSummary)===null||t===void 0?void 0:t.agentWallet)===null||e===void 0?void 0:e.address,(a=(n=r.data.accountSummary)===null||n===void 0?void 0:n.agentWallet)===null||a===void 0?void 0:a.status),s=D(()=>r.data.accountSummary===null&&r.isConnected,[r.data.accountSummary,r.isConnected]);return{data:o,isLoading:s}},"useAccountSummary");class We{static{d(this,"TokenMetadataExtractor")}static extractTokenMetadata(e,n,a){if(!n||!a)return null;const r=n.meta.universe.findIndex(O=>O.name===e);if(r===-1)return null;const o=n.meta.universe[r],s=n.assetCtxs[r];if(!s)return null;const f=a.mids[e],c=f?parseFloat(f):0,i=parseFloat(s.prevDayPx),v=c-i,h=i!==0?v/i*100:0,g=parseFloat(s.funding)*100,u=parseFloat(s.markPx),S=parseFloat(s.oraclePx);return{currentPrice:c,prevDayPrice:i,priceChange24h:v,priceChange24hPercent:h,netFunding:g,maxLeverage:o.maxLeverage,markPrice:u,oraclePrice:S,openInterest:s.openInterest,dayVolume:s.dayNtlVlm}}static extractMultipleTokensMetadata(e,n,a){const r={};for(const o of e)r[o]=this.extractTokenMetadata(o,n,a);return r}static isTokenAvailable(e,n){return n?n.meta.universe.some(a=>a.name===e):!1}}const un=d(()=>{var t;const e=ee(K);if(!e)throw new Error("useTokenSelection must be used within PearHyperliquidProvider");const{webData2:n,allMids:a,tokenSelection:r,setTokenSelection:o}=e,s=D(()=>!!(n&&a),[n,a]),f=D(()=>{if(!s)return!0;const y=[...r.longTokens,...r.shortTokens];return y.length===0?!1:y.some(m=>!m.metadata)},[s,r.longTokens,r.shortTokens]);ce(()=>{if(!n||!a)return;const y=[...r.longTokens,...r.shortTokens].map(b=>b.symbol);if(y.length===0)return;const m=We.extractMultipleTokensMetadata(y,n,a);o(b=>({...b,longTokens:b.longTokens.map(E=>({...E,metadata:m[E.symbol]||void 0})),shortTokens:b.shortTokens.map(E=>({...E,metadata:m[E.symbol]||void 0}))}))},[n,a,o]);const c=D(()=>{let y=1,m=1;return r.longTokens.forEach(b=>{var E;if(!((E=b.metadata)===null||E===void 0)&&E.currentPrice&&b.weight>0){const p=b.weight/100;y*=Math.pow(b.metadata.currentPrice,p)}}),r.shortTokens.forEach(b=>{var E;if(!((E=b.metadata)===null||E===void 0)&&E.currentPrice&&b.weight>0){const p=b.weight/100;m*=Math.pow(b.metadata.currentPrice,-p)}}),y*m},[r.longTokens,r.shortTokens]),i=D(()=>{let y=1,m=1;return r.longTokens.forEach(b=>{var E;if(!((E=b.metadata)===null||E===void 0)&&E.prevDayPrice&&b.weight>0){const p=b.weight/100;y*=Math.pow(b.metadata.prevDayPrice,p)}}),r.shortTokens.forEach(b=>{var E;if(!((E=b.metadata)===null||E===void 0)&&E.prevDayPrice&&b.weight>0){const p=b.weight/100;m*=Math.pow(b.metadata.prevDayPrice,-p)}}),y*m},[r.longTokens,r.shortTokens]),v=D(()=>{let y=0;return r.longTokens.forEach(m=>{var b;if(!((b=m.metadata)===null||b===void 0)&&b.netFunding&&m.weight>0){const E=m.weight/100;y+=m.metadata.netFunding*E}}),r.shortTokens.forEach(m=>{var b;if(!((b=m.metadata)===null||b===void 0)&&b.netFunding&&m.weight>0){const E=m.weight/100;y-=m.metadata.netFunding*E}}),y*100},[r.longTokens,r.shortTokens]),h=D(()=>{var y;if(!(!((y=n?.meta)===null||y===void 0)&&y.universe))return 0;const m=[...r.longTokens,...r.shortTokens].map(E=>E.symbol);if(m.length===0)return 0;let b=1/0;return m.forEach(E=>{const p=n.meta.universe.find(C=>C.name===E);p?.maxLeverage&&(b=Math.min(b,p.maxLeverage))}),b===1/0?0:b},[(t=n?.meta)===null||t===void 0?void 0:t.universe,r.longTokens,r.shortTokens]),g=D(()=>10*(r.longTokens.length+r.shortTokens.length),[r.longTokens.length,r.shortTokens.length]),u=z(y=>{o(m=>({...m,longTokens:y}))},[o]),S=z(y=>{o(m=>({...m,shortTokens:y}))},[o]),O=z((y,m,b)=>{const E=Math.max(1,Math.min(100,b));o(p=>{var C,M;const j=p.longTokens.reduce((R,H)=>R+H.weight,0),$=p.shortTokens.reduce((R,H)=>R+H.weight,0);if(y){const R=((C=p.longTokens[m])===null||C===void 0?void 0:C.weight)||0,H=E-R;if(j+H+$>100){const l=Math.max(1,100-$-(j-R)),_=[...p.longTokens];return _[m]={..._[m],weight:l},{...p,longTokens:_}}else{const l=[...p.longTokens];return l[m]={...l[m],weight:E},{...p,longTokens:l}}}else{const R=((M=p.shortTokens[m])===null||M===void 0?void 0:M.weight)||0,H=E-R,Q=$+H;if(j+Q>100){const l=Math.max(1,100-j-($-R)),_=[...p.shortTokens];return _[m]={..._[m],weight:l},{...p,shortTokens:_}}else{const l=[...p.shortTokens];return l[m]={...l[m],weight:E},{...p,shortTokens:l}}}})},[o]),w=z(y=>{const b=(y?r.longTokens:r.shortTokens).length;o(E=>({...E,selectorConfig:{isLong:y,index:b},openTokenSelector:!0}))},[r.longTokens,r.shortTokens,o]),T=z((y,m)=>{o(b=>{if(y){const E=b.longTokens.filter((p,C)=>C!==m);return{...b,longTokens:E}}else{const E=b.shortTokens.filter((p,C)=>C!==m);return{...b,shortTokens:E}}})},[o]),P=z(y=>{o(m=>({...m,openTokenSelector:y}))},[o]),F=z(y=>{o(m=>({...m,selectorConfig:y}))},[o]),W=z(y=>{o(m=>({...m,openConflictModal:y}))},[o]),X=z(y=>{o(m=>({...m,conflicts:y}))},[o]),Y=z(()=>{o(y=>({...y,longTokens:[{symbol:"HYPE",weight:25},{symbol:"BTC",weight:25}],shortTokens:[{symbol:"AVAX",weight:10},{symbol:"SEI",weight:10},{symbol:"ADA",weight:10},{symbol:"TRUMP",weight:10},{symbol:"SUI",weight:10}],openTokenSelector:!1,selectorConfig:null,openConflictModal:!1}))},[o]),k=z(y=>{if(!r.selectorConfig)return;const{isLong:m,index:b}=r.selectorConfig,E=m?r.longTokens:r.shortTokens;if(E.some(C=>C.symbol===y))return;const p=We.extractTokenMetadata(y,n,a);o(C=>{if(b>=E.length){const M=C.longTokens.reduce((l,_)=>l+_.weight,0),j=C.shortTokens.reduce((l,_)=>l+_.weight,0),$=M+j,R=Math.max(1,100-$),H=Math.min(20,R),Q={symbol:y,weight:H,metadata:p||void 0};return m?{...C,longTokens:[...C.longTokens,Q]}:{...C,shortTokens:[...C.shortTokens,Q]}}else if(m){const M=[...C.longTokens];return M[b]={...M[b],symbol:y,metadata:p||void 0},{...C,longTokens:M}}else{const M=[...C.shortTokens];return M[b]={...M[b],symbol:y,metadata:p||void 0},{...C,shortTokens:M}}})},[r.selectorConfig,r.longTokens,r.shortTokens,n,a,o]);return{longTokens:r.longTokens,shortTokens:r.shortTokens,openTokenSelector:r.openTokenSelector,selectorConfig:r.selectorConfig,openConflictModal:r.openConflictModal,conflicts:r.conflicts,isLoading:f,isPriceDataReady:s,weightedRatio:c,weightedRatio24h:i,sumNetFunding:v,maxLeverage:h,minMargin:g,setLongTokens:u,setShortTokens:S,updateTokenWeight:O,addToken:w,removeToken:T,handleTokenSelect:k,setOpenTokenSelector:P,setSelectorConfig:F,setOpenConflictModal:W,setConflicts:X,resetToDefaults:Y}},"useTokenSelection");class ln{static{d(this,"ConflictDetector")}static detectConflicts(e,n,a){const r=[];return a&&(e.forEach(o=>{a.find(f=>{var c;const i=f.coin||f.symbol||f.asset,v=(c=f.side)===null||c===void 0?void 0:c.toLowerCase();return i===o.symbol&&(v==="short"||v==="sell")})&&r.push({symbol:o.symbol,conflictType:"short",conflictMessage:`${o.symbol} Long conflicts with existing ${o.symbol} Short position`})}),n.forEach(o=>{a.find(f=>{var c;const i=f.coin||f.symbol||f.asset,v=(c=f.side)===null||c===void 0?void 0:c.toLowerCase();return i===o.symbol&&(v==="long"||v==="buy")})&&r.push({symbol:o.symbol,conflictType:"long",conflictMessage:`${o.symbol} Short conflicts with existing ${o.symbol} Long position`})})),r}}export{Xe as AccountSummaryCalculator,ln as ConflictDetector,Me as PearHyperliquidClient,Zt as PearHyperliquidProvider,je as PearMigrationSDK,We as TokenMetadataExtractor,Me as default,cn as useAccountSummary,nn as useAddress,Qe as useCalculatedAccountSummary,Ke as useCalculatedOpenPositions,Be as useHyperliquidNativeWebSocket,Ye as useHyperliquidWebSocket,tn as useMigrationSDK,sn as useOpenOrders,an as useOpenPositions,en as usePearHyperliquidClient,un as useTokenSelection,on as useTradeHistories};