warframe-nexus-query 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,246 @@
1
+ /**
2
+ * HTTP client for Warframe Market API v2
3
+ */
4
+
5
+ import { API_BASE_URL, DEFAULT_TIMEOUT, PLATFORMS } from '../constants.js';
6
+
7
+ import { normalizeLanguage } from './i18n.js';
8
+
9
+ /**
10
+ * Make HTTP request with timeout
11
+ * @param {string} url - URL to fetch
12
+ * @param {Object} options - Fetch options
13
+ * @param {number} timeout - Timeout in milliseconds
14
+ * @returns {Promise<Response>}
15
+ */
16
+ async function fetchWithTimeout(url, options = {}, timeout = DEFAULT_TIMEOUT) {
17
+ const controller = new AbortController();
18
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
19
+
20
+ try {
21
+ const response = await fetch(url, {
22
+ ...options,
23
+ signal: controller.signal,
24
+ });
25
+ clearTimeout(timeoutId);
26
+ return response;
27
+ } catch (error) {
28
+ clearTimeout(timeoutId);
29
+ if (error.name === 'AbortError') {
30
+ throw new Error(`Request timeout after ${timeout}ms`);
31
+ }
32
+ throw error;
33
+ }
34
+ }
35
+
36
+ /**
37
+ * HTTP Client for Warframe Market API v2
38
+ */
39
+ export default class HttpClient {
40
+ #baseURL;
41
+ #timeout;
42
+ #locale;
43
+ #logger;
44
+
45
+ /**
46
+ * @param {Object} options - Client options
47
+ * @param {string} [options.baseURL] - Base URL for API
48
+ * @param {number} [options.timeout] - Request timeout in ms
49
+ * @param {string} [options.locale] - Default language
50
+ * @param {Object} [options.logger] - Logger instance
51
+ */
52
+ constructor(options = {}) {
53
+ // Ensure baseURL ends with /
54
+ let baseURL = options.baseURL || API_BASE_URL;
55
+ if (!baseURL.endsWith('/')) {
56
+ baseURL += '/';
57
+ }
58
+ this.#baseURL = baseURL;
59
+ this.#timeout = options.timeout || DEFAULT_TIMEOUT;
60
+ this.#locale = normalizeLanguage(options.locale || 'en');
61
+ this.#logger = options.logger || console;
62
+ }
63
+
64
+ /**
65
+ * Make GET request
66
+ * @param {string} path - API path
67
+ * @param {Object} options - Request options
68
+ * @param {string} [options.platform] - Platform header
69
+ * @param {string} [options.locale] - Language header
70
+ * @param {Object} [options.query] - Query parameters
71
+ * @returns {Promise<Object>}
72
+ */
73
+ async get(path, options = {}) {
74
+ const url = this.#buildUrl(path, options.query);
75
+ const headers = this.#buildHeaders(options);
76
+
77
+ this.#logger.debug(`[v2] GET ${url}`);
78
+
79
+ try {
80
+ const response = await fetchWithTimeout(url, { headers }, this.#timeout);
81
+
82
+ if (!response.ok) {
83
+ throw await this.#handleError(response);
84
+ }
85
+
86
+ const data = await response.json();
87
+ return this.#unwrapResponse(data);
88
+ } catch (error) {
89
+ this.#logger.error(`HTTP GET ${path} failed:`, error.message);
90
+ throw error;
91
+ }
92
+ }
93
+
94
+ /**
95
+ * Make POST request
96
+ * @param {string} path - API path
97
+ * @param {Object} body - Request body
98
+ * @param {Object} options - Request options
99
+ * @returns {Promise<Object>}
100
+ */
101
+ async post(path, body, options = {}) {
102
+ const url = this.#buildUrl(path);
103
+ const headers = {
104
+ ...this.#buildHeaders(options),
105
+ 'Content-Type': 'application/json',
106
+ };
107
+
108
+ try {
109
+ const response = await fetchWithTimeout(
110
+ url,
111
+ {
112
+ method: 'POST',
113
+ headers,
114
+ body: JSON.stringify(body),
115
+ },
116
+ this.#timeout
117
+ );
118
+
119
+ if (!response.ok) {
120
+ throw await this.#handleError(response);
121
+ }
122
+
123
+ const data = await response.json();
124
+ return this.#unwrapResponse(data);
125
+ } catch (error) {
126
+ this.#logger.error(`HTTP POST ${path} failed:`, error.message);
127
+ throw error;
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Build full URL with query parameters
133
+ * @param {string} path - API path
134
+ * @param {Object} [query] - Query parameters
135
+ * @returns {string}
136
+ * @private
137
+ */
138
+ #buildUrl(path, query) {
139
+ // Remove leading slash from path if present
140
+ const cleanPath = path.startsWith('/') ? path.substring(1) : path;
141
+ const url = new URL(cleanPath, this.#baseURL);
142
+
143
+ if (query) {
144
+ Object.entries(query).forEach(([key, value]) => {
145
+ if (value !== undefined && value !== null) {
146
+ url.searchParams.append(key, value);
147
+ }
148
+ });
149
+ }
150
+
151
+ return url.toString();
152
+ }
153
+
154
+ /**
155
+ * Build request headers
156
+ * @param {Object} options - Options
157
+ * @returns {Object}
158
+ * @private
159
+ */
160
+ #buildHeaders(options = {}) {
161
+ const headers = {
162
+ Accept: 'application/json',
163
+ };
164
+
165
+ // Add language header
166
+ const locale = options.locale || this.#locale;
167
+ if (locale) {
168
+ headers.Language = locale;
169
+ }
170
+
171
+ // Add platform header if provided
172
+ if (options.platform) {
173
+ const normalizedPlatform = PLATFORMS[options.platform.toLowerCase()] || options.platform;
174
+ headers.Platform = normalizedPlatform;
175
+ }
176
+
177
+ // Add authorization header if provided
178
+ if (options.token) {
179
+ headers.Authorization = `Bearer ${options.token}`;
180
+ }
181
+
182
+ // Add custom headers
183
+ if (options.headers) {
184
+ Object.assign(headers, options.headers);
185
+ }
186
+
187
+ return headers;
188
+ }
189
+
190
+ /**
191
+ * Handle HTTP error response
192
+ * @param {Response} response - Response object
193
+ * @returns {Promise<Error>}
194
+ * @private
195
+ */
196
+ async #handleError(response) {
197
+ let errorMessage = `HTTP ${response.status}: ${response.statusText}`;
198
+
199
+ try {
200
+ const data = await response.json();
201
+ if (data.error && data.error.message) {
202
+ errorMessage = data.error.message;
203
+ }
204
+ } catch {
205
+ // If JSON parsing fails, use default error message
206
+ }
207
+
208
+ const error = new Error(errorMessage);
209
+ error.status = response.status;
210
+ error.statusText = response.statusText;
211
+ return error;
212
+ }
213
+
214
+ /**
215
+ * Unwrap API response
216
+ * @param {Object} data - Response data
217
+ * @returns {*}
218
+ * @private
219
+ */
220
+ #unwrapResponse(data) {
221
+ // v2 API wraps responses in { apiVersion, data, error }
222
+ if (data.error) {
223
+ const error = new Error(data.error.message || 'API Error');
224
+ error.code = data.error.code;
225
+ throw error;
226
+ }
227
+
228
+ return data.data;
229
+ }
230
+
231
+ /**
232
+ * Set default locale
233
+ * @param {string} locale - Language code
234
+ */
235
+ setLocale(locale) {
236
+ this.#locale = normalizeLanguage(locale);
237
+ }
238
+
239
+ /**
240
+ * Set timeout
241
+ * @param {number} timeout - Timeout in milliseconds
242
+ */
243
+ setTimeout(timeout) {
244
+ this.#timeout = timeout;
245
+ }
246
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * i18n helper utilities
3
+ */
4
+
5
+ import { LANGUAGES } from '../constants.js';
6
+
7
+ /**
8
+ * Normalize language code
9
+ * @param {string} lang - Language code
10
+ * @returns {string} Normalized language code
11
+ */
12
+ export function normalizeLanguage(lang) {
13
+ if (!lang) return 'en';
14
+ const normalized = lang.toLowerCase().trim();
15
+ return LANGUAGES[normalized] || 'en';
16
+ }
17
+
18
+ /**
19
+ * Extract localized data from i18n object
20
+ * @param {Object} i18n - i18n object
21
+ * @param {string} locale - Preferred locale
22
+ * @returns {Object} Localized data
23
+ */
24
+ export function extractLocalized(i18n, locale = 'en') {
25
+ if (!i18n) return {};
26
+ return i18n[locale] || i18n.en || {};
27
+ }
28
+
29
+ /**
30
+ * Get field from i18n object with fallback
31
+ * @param {Object} i18n - i18n object
32
+ * @param {string} field - Field name
33
+ * @param {string} locale - Preferred locale
34
+ * @param {*} defaultValue - Default value if not found
35
+ * @returns {*}
36
+ */
37
+ export function getLocalizedField(i18n, field, locale = 'en', defaultValue = null) {
38
+ const localized = extractLocalized(i18n, locale);
39
+ return localized[field] ?? defaultValue;
40
+ }
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Statistics calculator for order data
3
+ * Replaces v1's pre-calculated statistics with client-side calculation
4
+ */
5
+
6
+ /**
7
+ * Calculate statistics from order list
8
+ * @param {Array<Order>} orders - Array of orders
9
+ * @param {Object} options - Calculation options
10
+ * @param {string} [options.type='sell'] - Order type ('buy' or 'sell')
11
+ * @param {boolean} [options.onlineOnly=true] - Only include online users
12
+ * @param {boolean} [options.includeOutliers=true] - Include price outliers
13
+ * @returns {Object} Statistics object
14
+ */
15
+ export function calculateStatistics(orders, options = {}) {
16
+ const { type = 'sell', onlineOnly = true, includeOutliers = true } = options;
17
+
18
+ // Filter orders
19
+ let filtered = orders.filter((o) => o.type === type);
20
+
21
+ // Filter online users only
22
+ if (onlineOnly) {
23
+ filtered = filtered.filter((o) => o.isUserOnline());
24
+ }
25
+
26
+ // Extract prices
27
+ let prices = filtered.map((o) => o.platinum).sort((a, b) => a - b);
28
+
29
+ // Remove outliers if requested (using IQR method)
30
+ if (!includeOutliers && prices.length > 4) {
31
+ prices = removeOutliers(prices);
32
+ }
33
+
34
+ // If no prices, return empty stats
35
+ if (prices.length === 0) {
36
+ return {
37
+ volume: 0,
38
+ orderCount: 0,
39
+ median: 0,
40
+ min: 0,
41
+ max: 0,
42
+ avg: 0,
43
+ q1: 0,
44
+ q3: 0,
45
+ };
46
+ }
47
+
48
+ // Calculate volume
49
+ const volume = filtered.reduce((sum, o) => sum + o.quantity, 0);
50
+
51
+ // Calculate statistics
52
+ const median = calculateMedian(prices);
53
+ const min = prices[0];
54
+ const max = prices[prices.length - 1];
55
+ const avg = prices.reduce((a, b) => a + b, 0) / prices.length;
56
+ const q1 = calculatePercentile(prices, 25);
57
+ const q3 = calculatePercentile(prices, 75);
58
+
59
+ return {
60
+ volume,
61
+ orderCount: filtered.length,
62
+ median: Math.round(median),
63
+ min,
64
+ max,
65
+ avg: Math.round(avg),
66
+ q1: Math.round(q1),
67
+ q3: Math.round(q3),
68
+ };
69
+ }
70
+
71
+ /**
72
+ * Calculate median of sorted array
73
+ * @param {number[]} sortedPrices - Sorted price array
74
+ * @returns {number}
75
+ */
76
+ function calculateMedian(sortedPrices) {
77
+ const len = sortedPrices.length;
78
+ if (len === 0) return 0;
79
+ if (len === 1) return sortedPrices[0];
80
+
81
+ const mid = Math.floor(len / 2);
82
+ if (len % 2 === 0) {
83
+ return (sortedPrices[mid - 1] + sortedPrices[mid]) / 2;
84
+ }
85
+ return sortedPrices[mid];
86
+ }
87
+
88
+ /**
89
+ * Calculate percentile of sorted array
90
+ * @param {number[]} sortedPrices - Sorted price array
91
+ * @param {number} percentile - Percentile (0-100)
92
+ * @returns {number}
93
+ */
94
+ function calculatePercentile(sortedPrices, percentile) {
95
+ if (sortedPrices.length === 0) return 0;
96
+ if (sortedPrices.length === 1) return sortedPrices[0];
97
+
98
+ const index = (percentile / 100) * (sortedPrices.length - 1);
99
+ const lower = Math.floor(index);
100
+ const upper = Math.ceil(index);
101
+ const weight = index - lower;
102
+
103
+ return sortedPrices[lower] * (1 - weight) + sortedPrices[upper] * weight;
104
+ }
105
+
106
+ /**
107
+ * Remove outliers using IQR method
108
+ * @param {number[]} sortedPrices - Sorted price array
109
+ * @returns {number[]}
110
+ */
111
+ function removeOutliers(sortedPrices) {
112
+ const q1 = calculatePercentile(sortedPrices, 25);
113
+ const q3 = calculatePercentile(sortedPrices, 75);
114
+ const iqr = q3 - q1;
115
+ const lowerBound = q1 - 1.5 * iqr;
116
+ const upperBound = q3 + 1.5 * iqr;
117
+
118
+ return sortedPrices.filter((price) => price >= lowerBound && price <= upperBound);
119
+ }
120
+
121
+ /**
122
+ * Get best orders (lowest sell / highest buy)
123
+ * @param {Array<Order>} orders - Array of orders
124
+ * @param {Object} options - Options
125
+ * @param {number} [options.limit=5] - Number of orders to return
126
+ * @param {boolean} [options.onlineOnly=true] - Only online users
127
+ * @returns {Object} { buy: Order[], sell: Order[] }
128
+ */
129
+ export function getBestOrders(orders, options = {}) {
130
+ const { limit = 5, onlineOnly = true } = options;
131
+
132
+ // Filter online if requested
133
+ let filtered = orders;
134
+ if (onlineOnly) {
135
+ filtered = orders.filter((o) => o.isUserOnline());
136
+ }
137
+
138
+ // Separate buy and sell orders
139
+ const buyOrders = filtered.filter((o) => o.isBuyOrder()).sort((a, b) => b.platinum - a.platinum);
140
+
141
+ const sellOrders = filtered.filter((o) => o.isSellOrder()).sort((a, b) => a.platinum - b.platinum);
142
+
143
+ return {
144
+ buy: buyOrders.slice(0, limit),
145
+ sell: sellOrders.slice(0, limit),
146
+ };
147
+ }
148
+
149
+ /**
150
+ * Format price range string
151
+ * @param {Object} stats - Statistics object
152
+ * @returns {string}
153
+ */
154
+ export function formatPriceRange(stats) {
155
+ if (stats.orderCount === 0) {
156
+ return 'No orders found';
157
+ }
158
+
159
+ if (stats.min === stats.max) {
160
+ return `${stats.min}p`;
161
+ }
162
+
163
+ return `${stats.min}p - ${stats.max}p (median: ${stats.median}p)`;
164
+ }
165
+
166
+ /**
167
+ * Format statistics for display
168
+ * @param {Object} stats - Statistics object
169
+ * @param {string} type - Order type ('buy' or 'sell')
170
+ * @returns {string}
171
+ */
172
+ export function formatStatistics(stats, type = 'sell') {
173
+ const action = type === 'sell' ? 'Sellers' : 'Buyers';
174
+
175
+ if (stats.orderCount === 0) {
176
+ return `No ${action.toLowerCase()} found`;
177
+ }
178
+
179
+ return [
180
+ `**${action}:** ${stats.orderCount} orders (${stats.volume} items)`,
181
+ `**Median:** ${stats.median}p`,
182
+ `**Range:** ${stats.min}p - ${stats.max}p`,
183
+ `**Average:** ${stats.avg}p`,
184
+ ].join('\n');
185
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "warframe-nexus-query",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Query prices form nexus-stats.com and warframe.market.",
5
5
  "keywords": [
6
6
  "warframe",
@@ -14,7 +14,7 @@
14
14
  },
15
15
  "repository": {
16
16
  "type": "git",
17
- "url": "https://github.com/WFCD/warframe-nexus-query.git"
17
+ "url": "git+https://github.com/WFCD/warframe-nexus-query.git"
18
18
  },
19
19
  "license": "Apache-2.0",
20
20
  "author": "tobitenno",
@@ -36,79 +36,6 @@
36
36
  "prepare": "husky && npx install-peerdeps @wfcd/eslint-config@latest -S",
37
37
  "test": "c8 mocha"
38
38
  },
39
- "commitlint": {
40
- "extends": [
41
- "@commitlint/config-conventional"
42
- ],
43
- "rules": {
44
- "body-max-line-length": [
45
- 0
46
- ]
47
- }
48
- },
49
- "lint-staged": {
50
- "*.js": [
51
- "eslint --cache --fix"
52
- ],
53
- "package*.json": [
54
- "prettier --write",
55
- "npm dedupe",
56
- "npx sort-package-json"
57
- ],
58
- "*.{json,yaml,yml},!package*.json": [
59
- "prettier --write"
60
- ]
61
- },
62
- "babel": {
63
- "plugins": [
64
- "@babel/plugin-transform-class-properties",
65
- "@babel/plugin-transform-private-methods"
66
- ],
67
- "presets": [
68
- "@babel/preset-env"
69
- ]
70
- },
71
- "prettier": "@wfcd/eslint-config/prettier",
72
- "eslintConfig": {
73
- "extends": "@wfcd/eslint-config/esm",
74
- "rules": {
75
- "no-underscore-dangle": [
76
- "error",
77
- {
78
- "allow": [
79
- "__basedir"
80
- ]
81
- }
82
- ]
83
- }
84
- },
85
- "eslintIgnore": [
86
- ".github/**",
87
- "docs/**",
88
- "resources/**",
89
- "types/**"
90
- ],
91
- "release": {
92
- "branch": "master"
93
- },
94
- "mocha": {
95
- "bail": true,
96
- "exit": true,
97
- "slow": 10000,
98
- "spec": "test/test.js",
99
- "timeout": 30000
100
- },
101
- "c8": {
102
- "exclude": [
103
- "test/*",
104
- "lib/nexus/*"
105
- ],
106
- "reporter": [
107
- "lcov",
108
- "text"
109
- ],
110
- "skip-full": true
111
- },
112
39
  "dependencies": {
113
40
  "get-image-colors": "^4.0.1",
114
41
  "image-downloader": "^4.0.2",
@@ -118,21 +45,24 @@
118
45
  "numeral": "^2.0.6"
119
46
  },
120
47
  "devDependencies": {
121
- "@commitlint/cli": "^19.2.1",
122
- "@commitlint/config-conventional": "^19.1.0",
48
+ "@commitlint/cli": "^20.0.0",
49
+ "@commitlint/config-conventional": "^20.0.0",
123
50
  "@types/json-query": "^2.2.0",
124
51
  "@wfcd/eslint-config": "^1.6.1",
125
52
  "c8": "^10.1.2",
126
- "chai": "^5.0.3",
53
+ "chai": "^6.0.1",
127
54
  "coveralls": "^3.1.1",
128
55
  "husky": "^9.0.11",
129
56
  "install-peerdeps": "^3.0.3",
130
- "lint-staged": "^15.2.2",
57
+ "lint-staged": "^16.0.0",
131
58
  "mocha": "^11.0.1",
132
59
  "prettier": "^3.2.5"
133
60
  },
134
61
  "engines": {
135
62
  "node": ">=18",
136
63
  "npm": ">=8.19"
64
+ },
65
+ "publishConfig": {
66
+ "provenance": true
137
67
  }
138
68
  }