warframe-nexus-query 2.1.1 → 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,418 @@
1
+ /**
2
+ * Warframe Market API v2 Client
3
+ * Main entry point for interacting with the Warframe Market API v2
4
+ */
5
+
6
+ import HttpClient from './utils/http.js';
7
+ import VersionedCache from './utils/cache.js';
8
+ import Item from './models/Item.js';
9
+ import Order from './models/Order.js';
10
+ import Summary from './models/Summary.js';
11
+ import { calculateStatistics, getBestOrders, formatPriceRange, formatStatistics } from './utils/statistics.js';
12
+ import { normalizeLanguage } from './utils/i18n.js';
13
+ import { PLATFORMS, SHORT_CACHE_TTL, API_BASE_URL } from './constants.js';
14
+
15
+ export default class MarketFetcherV2 {
16
+ // Private fields
17
+ #http;
18
+ #cache;
19
+ #ordersCache;
20
+ #ordersCacheMaxSize;
21
+
22
+ /**
23
+ * @param {Object} options - Fetcher options
24
+ * @param {string} [options.locale='en'] - Default language
25
+ * @param {number} [options.timeout=5000] - Request timeout in ms
26
+ * @param {Object} [options.logger] - Logger instance
27
+ * @param {number} [options.cacheSize=100] - Cache size
28
+ * @param {number} [options.cacheTTL] - Cache TTL in ms
29
+ */
30
+ constructor(options = {}) {
31
+ this.locale = normalizeLanguage(options.locale || 'en');
32
+ this.logger = options.logger || console;
33
+
34
+ this.#ordersCacheMaxSize = options.ordersCacheSize || 50;
35
+
36
+ this.#http = new HttpClient({
37
+ baseURL: options.baseURL || API_BASE_URL,
38
+ locale: this.locale,
39
+ timeout: options.timeout,
40
+ logger: this.logger,
41
+ });
42
+
43
+ this.#cache = new VersionedCache({
44
+ maxSize: options.cacheSize || 100,
45
+ ttl: options.cacheTTL,
46
+ });
47
+
48
+ // Short-lived cache for orders (1 minute)
49
+ this.#ordersCache = new Map();
50
+ }
51
+
52
+ // ==========================================================================
53
+ // ITEMS
54
+ // ==========================================================================
55
+
56
+ /**
57
+ * Get list of all tradable items
58
+ * @returns {Promise<Item[]>}
59
+ */
60
+ async getItems() {
61
+ return this.#cache.get('items', 'items', async () => {
62
+ const data = await this.#http.get('/items', { locale: this.locale });
63
+ return data.map((item) => new Item(item, this.locale));
64
+ });
65
+ }
66
+
67
+ /**
68
+ * Get item by slug
69
+ * @param {string} slug - Item slug
70
+ * @returns {Promise<Item>}
71
+ */
72
+ async getItemBySlug(slug) {
73
+ const cacheKey = `item_${slug}`;
74
+ return this.#cache.get(cacheKey, 'items', async () => {
75
+ const data = await this.#http.get(`/item/${slug}`, { locale: this.locale });
76
+ return new Item(data, this.locale);
77
+ });
78
+ }
79
+
80
+ /**
81
+ * Get all items in a set
82
+ * @param {string} slug - Item slug
83
+ * @returns {Promise<{id: string, items: Item[]}>}
84
+ */
85
+ async getItemSet(slug) {
86
+ const cacheKey = `item_set_${slug}`;
87
+ return this.#cache.get(cacheKey, 'items', async () => {
88
+ const data = await this.#http.get(`/item/${slug}/set`, { locale: this.locale });
89
+ return {
90
+ id: data.id,
91
+ items: data.items.map((item) => new Item(item, this.locale)),
92
+ };
93
+ });
94
+ }
95
+
96
+ // ==========================================================================
97
+ // ORDERS
98
+ // ==========================================================================
99
+
100
+ /**
101
+ * Get top orders for an item (RECOMMENDED for price checks)
102
+ * @param {string} slug - Item slug
103
+ * @param {Object} options - Options
104
+ * @param {string} options.platform - Platform (pc, ps4, xbox, switch)
105
+ * @param {number} [options.rank] - Filter by rank
106
+ * @param {number} [options.rankLt] - Filter by rank less than
107
+ * @param {number} [options.charges] - Filter by charges
108
+ * @param {number} [options.chargesLt] - Filter by charges less than
109
+ * @param {number} [options.amberStars] - Filter by amber stars
110
+ * @param {number} [options.amberStarsLt] - Filter by amber stars less than
111
+ * @param {number} [options.cyanStars] - Filter by cyan stars
112
+ * @param {number} [options.cyanStarsLt] - Filter by cyan stars less than
113
+ * @param {string} [options.subtype] - Filter by subtype
114
+ * @returns {Promise<{buy: Order[], sell: Order[]}>}
115
+ */
116
+ async getTopOrders(slug, options = {}) {
117
+ const { platform, ...filters } = options;
118
+
119
+ if (!platform) {
120
+ throw new Error('Platform is required');
121
+ }
122
+
123
+ const cacheKey = `top_orders_${slug}_${platform}_${this.#stableStringify(filters)}`;
124
+
125
+ // Check short-lived cache
126
+ const cached = this.#getOrdersFromCache(cacheKey);
127
+ if (cached) return cached;
128
+
129
+ const data = await this.#http.get(`/orders/item/${slug}/top`, {
130
+ platform,
131
+ query: filters,
132
+ });
133
+
134
+ const result = {
135
+ buy: data.buy.map((order) => new Order(order)),
136
+ sell: data.sell.map((order) => new Order(order)),
137
+ };
138
+
139
+ this.#setOrdersCache(cacheKey, result);
140
+ return result;
141
+ }
142
+
143
+ /**
144
+ * Get all orders for an item
145
+ * @param {string} slug - Item slug
146
+ * @param {string} platform - Platform (pc, ps4, xbox, switch)
147
+ * @returns {Promise<Order[]>}
148
+ */
149
+ async getAllOrders(slug, platform) {
150
+ if (!platform) {
151
+ throw new Error('Platform is required');
152
+ }
153
+
154
+ const cacheKey = `all_orders_${slug}_${platform}`;
155
+
156
+ // Check short-lived cache
157
+ const cached = this.#getOrdersFromCache(cacheKey);
158
+ if (cached) return cached;
159
+
160
+ const data = await this.#http.get(`/orders/item/${slug}`, { platform });
161
+ const result = data.map((order) => new Order(order));
162
+
163
+ this.#setOrdersCache(cacheKey, result);
164
+ return result;
165
+ }
166
+
167
+ /**
168
+ * Get recent orders (last 4 hours)
169
+ * @param {string} platform - Platform (pc, ps4, xbox, switch)
170
+ * @returns {Promise<Order[]>}
171
+ */
172
+ async getRecentOrders(platform) {
173
+ if (!platform) {
174
+ throw new Error('Platform is required');
175
+ }
176
+
177
+ const cacheKey = `recent_orders_${platform}`;
178
+
179
+ // Check short-lived cache
180
+ const cached = this.#getOrdersFromCache(cacheKey);
181
+ if (cached) return cached;
182
+
183
+ const data = await this.#http.get('/orders/recent', { platform });
184
+ const result = data.map((order) => new Order(order));
185
+
186
+ this.#setOrdersCache(cacheKey, result);
187
+ return result;
188
+ }
189
+
190
+ // ==========================================================================
191
+ // STATISTICS (Client-side calculation)
192
+ // ==========================================================================
193
+
194
+ /**
195
+ * Calculate statistics from orders
196
+ * @param {Order[]} orders - Orders array
197
+ * @param {Object} options - Calculation options
198
+ * @returns {Object} Statistics
199
+ */
200
+ calculateStatistics(orders, options = {}) {
201
+ return calculateStatistics(orders, options);
202
+ }
203
+
204
+ /**
205
+ * Get best orders (sorted)
206
+ * @param {Order[]} orders - Orders array
207
+ * @param {Object} options - Options
208
+ * @returns {{buy: Order[], sell: Order[]}}
209
+ */
210
+ getBestOrders(orders, options = {}) {
211
+ return getBestOrders(orders, options);
212
+ }
213
+
214
+ /**
215
+ * Format price range string
216
+ * @param {Object} stats - Statistics object
217
+ * @returns {string}
218
+ */
219
+ formatPriceRange(stats) {
220
+ return formatPriceRange(stats);
221
+ }
222
+
223
+ /**
224
+ * Format statistics for display
225
+ * @param {Object} stats - Statistics object
226
+ * @param {string} type - Order type
227
+ * @returns {string}
228
+ */
229
+ formatStatistics(stats, type) {
230
+ return formatStatistics(stats, type);
231
+ }
232
+
233
+ // ==========================================================================
234
+ // SEARCH / QUERY (v1 compatibility)
235
+ // ==========================================================================
236
+
237
+ /**
238
+ * Query market for item (fuzzy search)
239
+ * @param {string} query - Search query
240
+ * @param {Object} options - Options
241
+ * @param {string} options.platform - Platform
242
+ * @param {function} [options.successfulQuery] - Callback for successful query
243
+ * @returns {Promise<Object>} Query results with statistics
244
+ */
245
+ async queryMarket(query, options = {}) {
246
+ const { platform, successfulQuery } = options;
247
+
248
+ if (!platform) {
249
+ throw new Error('Platform is required');
250
+ }
251
+
252
+ // Search for item
253
+ const items = await this.getItems();
254
+ const normalizedQuery = query.toLowerCase().trim();
255
+
256
+ // Fuzzy search
257
+ const matches = items.filter((item) => {
258
+ const name = item.name.toLowerCase();
259
+ const slug = item.slug.toLowerCase();
260
+ return name.includes(normalizedQuery) || slug.includes(normalizedQuery);
261
+ });
262
+
263
+ if (matches.length === 0) {
264
+ throw new Error(`No items found for query: ${query}`);
265
+ }
266
+
267
+ // Use first match
268
+ const item = matches[0];
269
+
270
+ // Get top orders for the item
271
+ const topOrders = await this.getTopOrders(item.slug, { platform });
272
+
273
+ // Calculate statistics
274
+ const sellStats = this.calculateStatistics(topOrders.sell, {
275
+ type: 'sell',
276
+ onlineOnly: true,
277
+ });
278
+ const buyStats = this.calculateStatistics(topOrders.buy, {
279
+ type: 'buy',
280
+ onlineOnly: true,
281
+ });
282
+
283
+ // Call success callback if provided
284
+ if (successfulQuery && typeof successfulQuery === 'function') {
285
+ successfulQuery();
286
+ }
287
+
288
+ // Create Summary object for v1 compatibility
289
+ const summary = new Summary(item, topOrders, {
290
+ sell: sellStats,
291
+ buy: buyStats,
292
+ });
293
+
294
+ // Return array of summaries (v1 compatibility)
295
+ return [summary];
296
+ }
297
+
298
+ /**
299
+ * Price check query (v1 compatibility method)
300
+ * @param {string} query - Search query
301
+ * @param {string} platform - Platform
302
+ * @returns {Promise<Object>}
303
+ */
304
+ async priceCheckQuery(query, platform) {
305
+ return this.queryMarket(query, { platform });
306
+ }
307
+
308
+ // ==========================================================================
309
+ // CACHE MANAGEMENT
310
+ // ==========================================================================
311
+
312
+ /**
313
+ * Get from short-lived orders cache
314
+ * @param {string} key - Cache key
315
+ * @returns {*|null}
316
+ * @private
317
+ */
318
+ #getOrdersFromCache(key) {
319
+ const cached = this.#ordersCache.get(key);
320
+ if (!cached) return null;
321
+
322
+ // Check TTL (1 minute for orders)
323
+ if (Date.now() - cached.timestamp > SHORT_CACHE_TTL) {
324
+ this.#ordersCache.delete(key);
325
+ return null;
326
+ }
327
+
328
+ return cached.value;
329
+ }
330
+
331
+ /**
332
+ * Set short-lived orders cache
333
+ * @param {string} key - Cache key
334
+ * @param {*} value - Value to cache
335
+ * @private
336
+ */
337
+ #setOrdersCache(key, value) {
338
+ // Evict oldest entries if at capacity
339
+ if (this.#ordersCache.size >= this.#ordersCacheMaxSize) {
340
+ const oldestKey = this.#ordersCache.keys().next().value;
341
+ this.#ordersCache.delete(oldestKey);
342
+ }
343
+ this.#ordersCache.set(key, {
344
+ value,
345
+ timestamp: Date.now(),
346
+ });
347
+ }
348
+
349
+ /**
350
+ * Clear all caches
351
+ */
352
+ clearCache() {
353
+ this.#cache.clear();
354
+ this.#ordersCache.clear();
355
+ }
356
+
357
+ /**
358
+ * Check API versions
359
+ * @returns {Promise<Object>}
360
+ */
361
+ async checkVersions() {
362
+ return this.#cache.checkVersions();
363
+ }
364
+
365
+ /**
366
+ * Stable stringify for cache keys (sorts object keys recursively)
367
+ * @param {*} value - Value to stringify
368
+ * @returns {string} Deterministic JSON string
369
+ * @private
370
+ */
371
+ #stableStringify(value) {
372
+ if (value === null || value === undefined) {
373
+ return JSON.stringify(value);
374
+ }
375
+
376
+ if (typeof value !== 'object') {
377
+ return JSON.stringify(value);
378
+ }
379
+
380
+ if (Array.isArray(value)) {
381
+ return `[${value.map((item) => this.#stableStringify(item)).join(',')}]`;
382
+ }
383
+
384
+ // Sort object keys and recursively stringify
385
+ const sortedKeys = Object.keys(value).sort();
386
+ const pairs = sortedKeys.map((key) => `${JSON.stringify(key)}:${this.#stableStringify(value[key])}`);
387
+ return `{${pairs.join(',')}}`;
388
+ }
389
+
390
+ // ==========================================================================
391
+ // UTILITY
392
+ // ==========================================================================
393
+
394
+ /**
395
+ * Normalize platform
396
+ * @param {string} platform - Platform alias
397
+ * @returns {string} Normalized platform
398
+ */
399
+ normalizePlatform(platform) {
400
+ return PLATFORMS[platform?.toLowerCase()] || platform;
401
+ }
402
+
403
+ /**
404
+ * Set locale
405
+ * @param {string} locale - Language code
406
+ */
407
+ setLocale(locale) {
408
+ this.locale = normalizeLanguage(locale);
409
+ this.#http.setLocale(locale);
410
+ }
411
+
412
+ /**
413
+ * Stop and cleanup (clears all caches)
414
+ */
415
+ stop() {
416
+ this.clearCache();
417
+ }
418
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Constants for Warframe Market API v2
3
+ */
4
+
5
+ export const API_BASE_URL = process.env.MARKET_V2_URL_OVERRIDE || 'https://api.warframe.market/v2';
6
+ export const ASSETS_BASE_URL = process.env.MARKET_ASSETS_URL_OVERRIDE || 'https://warframe.market/static/assets/';
7
+
8
+ export const DEFAULT_TIMEOUT = parseInt(process.env.MARKET_TIMEOUT, 10) || 5000;
9
+ export const VERSION_CHECK_INTERVAL = 5 * 60 * 1000; // 5 minutes
10
+ export const CACHE_TTL = 60 * 60 * 1000; // 1 hour fallback TTL
11
+ export const SHORT_CACHE_TTL = 60 * 1000; // 1 minute for orders
12
+
13
+ export const PLATFORMS = {
14
+ pc: 'pc',
15
+ ps4: 'ps4',
16
+ playstation: 'ps4',
17
+ xb1: 'xbox',
18
+ xbone: 'xbox',
19
+ xbox: 'xbox',
20
+ switch: 'switch',
21
+ swi: 'switch',
22
+ ns: 'switch',
23
+ mobile: 'mobile',
24
+ };
25
+
26
+ export const LANGUAGES = {
27
+ en: 'en',
28
+ es: 'es',
29
+ fr: 'fr',
30
+ de: 'de',
31
+ it: 'it',
32
+ pl: 'pl',
33
+ pt: 'pt',
34
+ ru: 'ru',
35
+ ko: 'ko',
36
+ 'zh-hans': 'zh-hans',
37
+ 'zh-hant': 'zh-hant',
38
+ uk: 'uk',
39
+ };
40
+
41
+ export const USER_STATUS = {
42
+ INVISIBLE: 'invisible',
43
+ OFFLINE: 'offline',
44
+ ONLINE: 'online',
45
+ INGAME: 'ingame',
46
+ };
47
+
48
+ export const ACTIVITY_TYPE = {
49
+ UNKNOWN: 'UNKNOWN',
50
+ IDLE: 'IDLE',
51
+ ON_MISSION: 'ON_MISSION',
52
+ IN_DOJO: 'IN_DOJO',
53
+ IN_ORBITER: 'IN_ORBITER',
54
+ IN_RELAY: 'IN_RELAY',
55
+ };
56
+
57
+ export const ORDER_TYPE = {
58
+ BUY: 'buy',
59
+ SELL: 'sell',
60
+ };
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Warframe Market API v2 - Main exports
3
+ */
4
+
5
+ export { default as MarketFetcherV2 } from './MarketFetcherV2.js';
6
+ export { default as Item } from './models/Item.js';
7
+ export { default as Order, OrderUser } from './models/Order.js';
8
+ export { default as SummaryV2 } from './models/Summary.js';
9
+ export { default as VersionedCache } from './utils/cache.js';
10
+ export { default as HttpClient } from './utils/http.js';
11
+ export { calculateStatistics, getBestOrders, formatPriceRange, formatStatistics } from './utils/statistics.js';
12
+ export * from './constants.js';
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Item model for Warframe Market API v2
3
+ * Represents a tradable item with full metadata and i18n support
4
+ */
5
+ export default class Item {
6
+ /**
7
+ * @param {Object} data - Raw item data from API
8
+ * @param {string} locale - Language code for i18n
9
+ */
10
+ constructor(data, locale = 'en') {
11
+ this.id = data.id;
12
+ this.slug = data.slug;
13
+ this.gameRef = data.gameRef;
14
+ this.tags = data.tags || [];
15
+
16
+ // Set relationships
17
+ this.setRoot = data.setRoot;
18
+ this.setParts = data.setParts || [];
19
+ this.quantityInSet = data.quantityInSet;
20
+
21
+ // Trading properties
22
+ this.rarity = data.rarity;
23
+ this.bulkTradable = data.bulkTradable || false;
24
+ this.subtypes = data.subtypes || [];
25
+ this.tradable = data.tradable;
26
+ this.vaulted = data.vaulted;
27
+
28
+ // Progression
29
+ this.maxRank = data.maxRank;
30
+ this.maxCharges = data.maxCharges;
31
+ this.maxAmberStars = data.maxAmberStars;
32
+ this.maxCyanStars = data.maxCyanStars;
33
+
34
+ // Economy
35
+ this.ducats = data.ducats;
36
+ this.vosfor = data.vosfor;
37
+ this.tradingTax = data.tradingTax;
38
+ this.baseEndo = data.baseEndo;
39
+ this.endoMultiplier = data.endoMultiplier;
40
+ this.reqMasteryRank = data.reqMasteryRank;
41
+
42
+ // i18n data
43
+ this.i18n = data.i18n || {};
44
+ this.locale = locale;
45
+
46
+ // Extract localized fields for convenience
47
+ const localizedData = this.i18n[locale] || this.i18n.en || {};
48
+ this.name = localizedData.name || this.slug;
49
+ this.description = localizedData.description;
50
+ this.wikiLink = localizedData.wikiLink;
51
+ this.icon = localizedData.icon;
52
+ this.thumb = localizedData.thumb;
53
+ this.subIcon = localizedData.subIcon;
54
+
55
+ // Type marker
56
+ this.type = 'market-v2';
57
+ }
58
+
59
+ /**
60
+ * Get localized field
61
+ * @param {string} field - Field name
62
+ * @param {string} [lang] - Language code (defaults to instance locale)
63
+ * @returns {*} Localized value
64
+ */
65
+ getLocalized(field, lang) {
66
+ const locale = lang || this.locale;
67
+ return this.i18n[locale]?.[field] || this.i18n.en?.[field];
68
+ }
69
+
70
+ /**
71
+ * Get full icon URL
72
+ * @param {string} [baseUrl='https://warframe.market/static/assets/'] - Base URL for assets
73
+ * @returns {string}
74
+ */
75
+ getIconUrl(baseUrl = 'https://warframe.market/static/assets/') {
76
+ return this.icon ? `${baseUrl}${this.icon}` : null;
77
+ }
78
+
79
+ /**
80
+ * Get full thumbnail URL
81
+ * @param {string} [baseUrl='https://warframe.market/static/assets/'] - Base URL for assets
82
+ * @returns {string}
83
+ */
84
+ getThumbUrl(baseUrl = 'https://warframe.market/static/assets/') {
85
+ return this.thumb ? `${baseUrl}${this.thumb}` : null;
86
+ }
87
+
88
+ /**
89
+ * Check if item is part of a set
90
+ * @returns {boolean}
91
+ */
92
+ isPartOfSet() {
93
+ return this.setParts && this.setParts.length > 0;
94
+ }
95
+
96
+ /**
97
+ * Check if item is vaulted
98
+ * @returns {boolean}
99
+ */
100
+ isVaulted() {
101
+ return this.vaulted === true;
102
+ }
103
+
104
+ /**
105
+ * Convert to JSON
106
+ * @returns {Object}
107
+ */
108
+ toJSON() {
109
+ return {
110
+ id: this.id,
111
+ slug: this.slug,
112
+ name: this.name,
113
+ thumb: this.thumb,
114
+ icon: this.icon,
115
+ tradingTax: this.tradingTax,
116
+ ducats: this.ducats,
117
+ vosfor: this.vosfor,
118
+ masteryLevel: this.reqMasteryRank,
119
+ tradable: this.tradable,
120
+ vaulted: this.vaulted,
121
+ wikiUrl: this.wikiLink,
122
+ description: this.description,
123
+ tags: this.tags,
124
+ type: this.type,
125
+ };
126
+ }
127
+
128
+ /**
129
+ * Convert to string representation
130
+ * @returns {string}
131
+ */
132
+ toString() {
133
+ return `${this.name} [${this.slug}]`;
134
+ }
135
+ }