@skinpricer/sdk 0.1.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.
package/dist/index.cjs ADDED
@@ -0,0 +1,1103 @@
1
+ 'use strict';
2
+
3
+ // src/errors/base.ts
4
+ var SkinpricerError = class _SkinpricerError extends Error {
5
+ status;
6
+ code;
7
+ requestId;
8
+ responseBody;
9
+ rateLimit;
10
+ constructor(message, options = {}) {
11
+ super(
12
+ message,
13
+ options.cause !== void 0 ? { cause: options.cause } : void 0
14
+ );
15
+ this.name = new.target.name;
16
+ this.status = options.status;
17
+ this.code = options.code;
18
+ this.requestId = options.requestId ?? null;
19
+ this.responseBody = options.responseBody;
20
+ this.rateLimit = options.rateLimit;
21
+ Object.setPrototypeOf(this, new.target.prototype);
22
+ }
23
+ static isSkinpricerError(value) {
24
+ return value instanceof _SkinpricerError;
25
+ }
26
+ };
27
+
28
+ // src/errors/network-errors.ts
29
+ var NetworkError = class extends SkinpricerError {
30
+ };
31
+ var TimeoutError = class extends NetworkError {
32
+ };
33
+ var ConfigurationError = class extends SkinpricerError {
34
+ };
35
+ var ParseError = class extends SkinpricerError {
36
+ };
37
+
38
+ // src/version.ts
39
+ var VERSION = "0.1.0";
40
+
41
+ // src/config.ts
42
+ var DEFAULT_BASE_URL = "https://pricing.skinpricer.com/v1";
43
+ var DEFAULT_TIMEOUT_MS = 3e4;
44
+ var DEFAULT_RETRY = {
45
+ maxRetries: 2,
46
+ baseDelayMs: 250,
47
+ maxDelayMs: 8e3,
48
+ retryOnMethods: ["GET"],
49
+ respectRetryAfter: true
50
+ };
51
+ function resolveFetch(custom) {
52
+ if (custom) return custom;
53
+ const globalFetch = globalThis.fetch;
54
+ if (typeof globalFetch === "function") {
55
+ return globalFetch.bind(globalThis);
56
+ }
57
+ throw new ConfigurationError(
58
+ "No global `fetch` is available. Provide a `fetch` implementation in the client config (required on Node < 18 or non-fetch runtimes)."
59
+ );
60
+ }
61
+ function resolveRetry(retry) {
62
+ if (retry === false) return null;
63
+ if (retry === void 0) return DEFAULT_RETRY;
64
+ return { ...DEFAULT_RETRY, ...retry };
65
+ }
66
+ function normalizeBaseUrl(baseUrl) {
67
+ const trimmed = baseUrl.replace(/\/+$/, "");
68
+ let parsed;
69
+ try {
70
+ parsed = new URL(trimmed);
71
+ } catch {
72
+ throw new ConfigurationError(
73
+ `\`baseUrl\` is not a valid URL: "${baseUrl}"`
74
+ );
75
+ }
76
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
77
+ throw new ConfigurationError(
78
+ `\`baseUrl\` must use http: or https: (got "${parsed.protocol}").`
79
+ );
80
+ }
81
+ return trimmed;
82
+ }
83
+ function resolveConfig(config) {
84
+ if (typeof config.apiKey !== "string" || config.apiKey.trim().length === 0) {
85
+ throw new ConfigurationError(
86
+ "A non-empty `apiKey` is required to construct SkinpricerClient."
87
+ );
88
+ }
89
+ return {
90
+ apiKey: config.apiKey,
91
+ baseUrl: normalizeBaseUrl(config.baseUrl ?? DEFAULT_BASE_URL),
92
+ fetch: resolveFetch(config.fetch),
93
+ timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,
94
+ retry: resolveRetry(config.retry),
95
+ headers: { ...config.headers },
96
+ authScheme: config.authScheme ?? "Bearer",
97
+ userAgent: config.userAgent ?? `skinpricer-sdk/${VERSION}`,
98
+ autoThrottle: config.autoThrottle ?? false,
99
+ hooks: config.hooks ?? {}
100
+ };
101
+ }
102
+
103
+ // src/errors/http-errors.ts
104
+ var APIError = class extends SkinpricerError {
105
+ };
106
+ var ValidationError = class extends APIError {
107
+ messages;
108
+ constructor(message, options = {}) {
109
+ super(message, options);
110
+ this.messages = options.messages ?? [];
111
+ }
112
+ };
113
+ var AuthenticationError = class extends APIError {
114
+ };
115
+ var PermissionError = class extends APIError {
116
+ };
117
+ var FeatureNotAvailableError = class extends PermissionError {
118
+ };
119
+ var NotFoundError = class extends APIError {
120
+ };
121
+ var RateLimitError = class extends APIError {
122
+ /** Seconds to wait before retrying (`Retry-After`). */
123
+ retryAfterSeconds;
124
+ limit;
125
+ remaining;
126
+ resetSeconds;
127
+ constructor(message, options = {}) {
128
+ super(message, options);
129
+ this.retryAfterSeconds = options.retryAfterSeconds ?? null;
130
+ this.limit = options.limit ?? null;
131
+ this.remaining = options.remaining ?? null;
132
+ this.resetSeconds = options.resetSeconds ?? null;
133
+ }
134
+ };
135
+ var ServerError = class extends APIError {
136
+ };
137
+
138
+ // src/hooks.ts
139
+ async function runHook(hook, ctx) {
140
+ if (!hook) return;
141
+ try {
142
+ await hook(ctx);
143
+ } catch {
144
+ }
145
+ }
146
+
147
+ // src/utils/abort.ts
148
+ function abortError(signal) {
149
+ const reason = signal?.reason;
150
+ if (reason instanceof Error) return reason;
151
+ return new DOMException("The operation was aborted.", "AbortError");
152
+ }
153
+
154
+ // src/utils/sleep.ts
155
+ function sleep(ms, signal) {
156
+ return new Promise((resolve, reject) => {
157
+ if (signal?.aborted) {
158
+ reject(abortError(signal));
159
+ return;
160
+ }
161
+ function cleanup() {
162
+ clearTimeout(timer);
163
+ signal?.removeEventListener("abort", onAbort);
164
+ }
165
+ function onAbort() {
166
+ cleanup();
167
+ reject(abortError(signal));
168
+ }
169
+ const timer = setTimeout(() => {
170
+ cleanup();
171
+ resolve();
172
+ }, ms);
173
+ signal?.addEventListener("abort", onAbort, { once: true });
174
+ });
175
+ }
176
+
177
+ // src/errors/from-response.ts
178
+ function defaultMessage(status) {
179
+ return `Request failed with status ${status}`;
180
+ }
181
+ function truncate(value, max) {
182
+ return value.length > max ? `${value.slice(0, max)}\u2026` : value;
183
+ }
184
+ function isRecord(value) {
185
+ return typeof value === "object" && value !== null;
186
+ }
187
+ function extractErrorFields(body, status) {
188
+ if (isRecord(body)) {
189
+ if (body.success === false && isRecord(body.error)) {
190
+ const err = body.error;
191
+ const message = typeof err.message === "string" ? err.message : defaultMessage(status);
192
+ const result = { message };
193
+ if (typeof err.code === "string") result.code = err.code;
194
+ return result;
195
+ }
196
+ const rawMessage = body.message;
197
+ if (Array.isArray(rawMessage)) {
198
+ const messages = rawMessage.filter(
199
+ (entry) => typeof entry === "string"
200
+ );
201
+ return {
202
+ message: messages.length > 0 ? messages.join(", ") : defaultMessage(status),
203
+ messages
204
+ };
205
+ }
206
+ if (typeof rawMessage === "string") {
207
+ return { message: rawMessage };
208
+ }
209
+ if (typeof body.error === "string") {
210
+ return { message: body.error };
211
+ }
212
+ }
213
+ if (typeof body === "string" && body.trim().length > 0) {
214
+ return { message: truncate(body, 500) };
215
+ }
216
+ return { message: defaultMessage(status) };
217
+ }
218
+ function looksLikeFeatureError(message) {
219
+ return /feature|does not include|plan/i.test(message);
220
+ }
221
+ function errorFromResponse(input) {
222
+ const { status, body, meta } = input;
223
+ const { code, message, messages } = extractErrorFields(body, status);
224
+ const base = {
225
+ status,
226
+ code,
227
+ requestId: meta.requestId,
228
+ responseBody: body,
229
+ rateLimit: meta.rateLimit
230
+ };
231
+ switch (status) {
232
+ case 400:
233
+ return new ValidationError(message, { ...base, messages });
234
+ case 401:
235
+ return new AuthenticationError(message, base);
236
+ case 403:
237
+ return code === "FEATURE_NOT_AVAILABLE" || looksLikeFeatureError(message) ? new FeatureNotAvailableError(message, base) : new PermissionError(message, base);
238
+ case 404:
239
+ return new NotFoundError(message, base);
240
+ case 429:
241
+ return new RateLimitError(message, {
242
+ ...base,
243
+ retryAfterSeconds: meta.rateLimit.retryAfterSeconds,
244
+ limit: meta.rateLimit.limit,
245
+ remaining: meta.rateLimit.remaining,
246
+ resetSeconds: meta.rateLimit.resetSeconds
247
+ });
248
+ default:
249
+ if (status >= 500) return new ServerError(message, base);
250
+ return new APIError(message, base);
251
+ }
252
+ }
253
+
254
+ // src/http/rate-limit.ts
255
+ function readInt(headers, name) {
256
+ const raw = headers.get(name);
257
+ if (raw === null) return null;
258
+ const value = Number.parseInt(raw, 10);
259
+ return Number.isFinite(value) ? value : null;
260
+ }
261
+ function parseRateLimit(headers) {
262
+ return {
263
+ limit: readInt(headers, "x-ratelimit-limit"),
264
+ remaining: readInt(headers, "x-ratelimit-remaining"),
265
+ resetSeconds: readInt(headers, "x-ratelimit-reset"),
266
+ month: {
267
+ limit: readInt(headers, "x-ratelimit-limit-month"),
268
+ remaining: readInt(headers, "x-ratelimit-remaining-month"),
269
+ resetSeconds: readInt(headers, "x-ratelimit-reset-month")
270
+ },
271
+ retryAfterSeconds: readInt(headers, "retry-after")
272
+ };
273
+ }
274
+
275
+ // src/http/parse-response.ts
276
+ function buildMeta(response) {
277
+ return {
278
+ status: response.status,
279
+ requestId: response.headers.get("x-request-id"),
280
+ rateLimit: parseRateLimit(response.headers),
281
+ headers: response.headers
282
+ };
283
+ }
284
+ function tryJsonParse(text) {
285
+ try {
286
+ return JSON.parse(text);
287
+ } catch {
288
+ return void 0;
289
+ }
290
+ }
291
+ async function parseResponse(response) {
292
+ const meta = buildMeta(response);
293
+ const text = await response.text();
294
+ if (response.ok) {
295
+ if (text.length === 0) {
296
+ return { data: {}, meta };
297
+ }
298
+ try {
299
+ return { data: JSON.parse(text), meta };
300
+ } catch (cause) {
301
+ throw new ParseError("Failed to parse response body as JSON.", {
302
+ status: response.status,
303
+ responseBody: text,
304
+ cause,
305
+ rateLimit: meta.rateLimit,
306
+ requestId: meta.requestId
307
+ });
308
+ }
309
+ }
310
+ const parsed = text.length > 0 ? tryJsonParse(text) : void 0;
311
+ const body = parsed !== void 0 ? parsed : text.length > 0 ? text : void 0;
312
+ throw errorFromResponse({ status: response.status, body, meta });
313
+ }
314
+
315
+ // src/utils/url.ts
316
+ function encodePathSegment(segment) {
317
+ return encodeURIComponent(segment);
318
+ }
319
+ function joinUrl(baseUrl, path) {
320
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
321
+ return `${baseUrl}${normalizedPath}`;
322
+ }
323
+
324
+ // src/http/query.ts
325
+ function serializeQuery(params) {
326
+ const search = new URLSearchParams();
327
+ for (const [key, value] of Object.entries(params)) {
328
+ if (value === void 0 || value === null) continue;
329
+ if (value instanceof Date) {
330
+ search.append(key, value.toISOString());
331
+ continue;
332
+ }
333
+ if (Array.isArray(value)) {
334
+ if (value.length === 0) continue;
335
+ search.append(key, value.map((entry) => String(entry)).join(","));
336
+ continue;
337
+ }
338
+ search.append(key, String(value));
339
+ }
340
+ const serialized = search.toString();
341
+ return serialized.length > 0 ? `?${serialized}` : "";
342
+ }
343
+
344
+ // src/http/request-builder.ts
345
+ function buildRequest(config, input) {
346
+ const queryString = input.query ? serializeQuery(input.query) : "";
347
+ const url = joinUrl(config.baseUrl, input.path) + queryString;
348
+ const headers = {
349
+ Accept: "application/json",
350
+ "User-Agent": config.userAgent,
351
+ "X-Skinpricer-Client": config.userAgent,
352
+ ...config.headers
353
+ };
354
+ let body;
355
+ if (input.body !== void 0) {
356
+ body = JSON.stringify(input.body);
357
+ headers["Content-Type"] = "application/json";
358
+ }
359
+ headers["Authorization"] = `${config.authScheme} ${config.apiKey}`;
360
+ const prepared = { url, method: input.method, headers };
361
+ if (body !== void 0) prepared.body = body;
362
+ return prepared;
363
+ }
364
+
365
+ // src/http/retry.ts
366
+ function isRetryableStatus(status) {
367
+ return status === 429 || status >= 500;
368
+ }
369
+ function shouldRetry(input) {
370
+ const { method, attempt, retry, status } = input;
371
+ if (attempt >= retry.maxRetries) return false;
372
+ if (!retry.retryOnMethods.includes(method)) return false;
373
+ if (status === null) return true;
374
+ return isRetryableStatus(status);
375
+ }
376
+ function backoffDelayMs(attempt, retry, rng = Math.random) {
377
+ const ceiling = Math.min(retry.baseDelayMs * 2 ** attempt, retry.maxDelayMs);
378
+ return Math.floor(rng() * ceiling);
379
+ }
380
+ function retryDelayMs(input) {
381
+ const { attempt, retry, retryAfterSeconds, rng } = input;
382
+ if (retry.respectRetryAfter && retryAfterSeconds !== null && retryAfterSeconds >= 0) {
383
+ return Math.min(retryAfterSeconds * 1e3, retry.maxDelayMs);
384
+ }
385
+ return backoffDelayMs(attempt, retry, rng);
386
+ }
387
+
388
+ // src/http/timeout.ts
389
+ function withTimeout(timeoutMs, external) {
390
+ const controller = new AbortController();
391
+ let timedOut = false;
392
+ let timer;
393
+ function onExternalAbort() {
394
+ controller.abort(external ? abortError(external) : void 0);
395
+ }
396
+ if (external) {
397
+ if (external.aborted) {
398
+ controller.abort(abortError(external));
399
+ } else {
400
+ external.addEventListener("abort", onExternalAbort, { once: true });
401
+ }
402
+ }
403
+ if (timeoutMs > 0 && !controller.signal.aborted) {
404
+ timer = setTimeout(() => {
405
+ timedOut = true;
406
+ controller.abort(
407
+ new DOMException(
408
+ `Request timed out after ${timeoutMs}ms`,
409
+ "TimeoutError"
410
+ )
411
+ );
412
+ }, timeoutMs);
413
+ }
414
+ return {
415
+ signal: controller.signal,
416
+ cleanup() {
417
+ if (timer !== void 0) clearTimeout(timer);
418
+ external?.removeEventListener("abort", onExternalAbort);
419
+ },
420
+ didTimeout() {
421
+ return timedOut;
422
+ }
423
+ };
424
+ }
425
+
426
+ // src/http/http-client.ts
427
+ var MAX_THROTTLE_WAIT_MS = 6e4;
428
+ function resolveRequestRetry(base, override) {
429
+ if (override === false) return null;
430
+ if (override === void 0) return base;
431
+ return { ...base ?? DEFAULT_RETRY, ...override };
432
+ }
433
+ function networkMessage(error) {
434
+ return error instanceof Error ? error.message : "Network request failed.";
435
+ }
436
+ var HttpClient = class {
437
+ constructor(config) {
438
+ this.config = config;
439
+ }
440
+ config;
441
+ throttleUntil = 0;
442
+ async request(input, options = {}) {
443
+ const prepared = buildRequest(this.config, input);
444
+ const retry = resolveRequestRetry(this.config.retry, options.retry);
445
+ const timeoutMs = options.timeoutMs ?? this.config.timeoutMs;
446
+ const callerSignal = options.signal;
447
+ const { hooks } = this.config;
448
+ await this.awaitThrottle(callerSignal);
449
+ let attempt = 0;
450
+ for (; ; ) {
451
+ const handle = withTimeout(timeoutMs, callerSignal);
452
+ await runHook(hooks.onRequest, {
453
+ method: input.method,
454
+ url: prepared.url,
455
+ attempt
456
+ });
457
+ let response;
458
+ try {
459
+ response = await this.config.fetch(prepared.url, {
460
+ method: prepared.method,
461
+ headers: prepared.headers,
462
+ body: prepared.body,
463
+ signal: handle.signal
464
+ });
465
+ } catch (error) {
466
+ handle.cleanup();
467
+ if (callerSignal?.aborted && !handle.didTimeout()) {
468
+ throw abortError(callerSignal);
469
+ }
470
+ if (retry && shouldRetry({ method: input.method, attempt, retry, status: null })) {
471
+ const delayMs = retryDelayMs({
472
+ attempt,
473
+ retry,
474
+ retryAfterSeconds: null
475
+ });
476
+ await runHook(hooks.onRetry, {
477
+ method: input.method,
478
+ url: prepared.url,
479
+ attempt,
480
+ delayMs,
481
+ status: null
482
+ });
483
+ await sleep(delayMs, callerSignal);
484
+ attempt += 1;
485
+ continue;
486
+ }
487
+ if (handle.didTimeout()) {
488
+ throw new TimeoutError(`Request timed out after ${timeoutMs}ms`, {
489
+ cause: error
490
+ });
491
+ }
492
+ throw new NetworkError(networkMessage(error), { cause: error });
493
+ }
494
+ handle.cleanup();
495
+ try {
496
+ const parsed = await parseResponse(response);
497
+ this.recordRateLimit(parsed.meta.rateLimit);
498
+ await runHook(hooks.onResponse, {
499
+ method: input.method,
500
+ url: prepared.url,
501
+ attempt,
502
+ status: parsed.meta.status,
503
+ rateLimit: parsed.meta.rateLimit
504
+ });
505
+ return parsed;
506
+ } catch (error) {
507
+ if (error instanceof RateLimitError) {
508
+ this.recordRateLimit(error.rateLimit, error.retryAfterSeconds);
509
+ }
510
+ if (error instanceof SkinpricerError && error.status !== void 0 && retry && shouldRetry({
511
+ method: input.method,
512
+ attempt,
513
+ retry,
514
+ status: error.status
515
+ })) {
516
+ const retryAfterSeconds = error instanceof RateLimitError ? error.retryAfterSeconds : error.rateLimit?.retryAfterSeconds ?? null;
517
+ const delayMs = retryDelayMs({ attempt, retry, retryAfterSeconds });
518
+ await runHook(hooks.onRetry, {
519
+ method: input.method,
520
+ url: prepared.url,
521
+ attempt,
522
+ delayMs,
523
+ status: error.status,
524
+ error
525
+ });
526
+ await sleep(delayMs, callerSignal);
527
+ attempt += 1;
528
+ continue;
529
+ }
530
+ throw error;
531
+ }
532
+ }
533
+ }
534
+ recordRateLimit(rateLimit, retryAfterSeconds) {
535
+ if (!this.config.autoThrottle || !rateLimit) return;
536
+ const waitSeconds = retryAfterSeconds ?? (rateLimit.remaining === 0 ? rateLimit.resetSeconds : null);
537
+ if (waitSeconds === null || waitSeconds <= 0) return;
538
+ const waitMs = Math.min(waitSeconds * 1e3, MAX_THROTTLE_WAIT_MS);
539
+ this.throttleUntil = Math.max(this.throttleUntil, Date.now() + waitMs);
540
+ }
541
+ async awaitThrottle(signal) {
542
+ if (!this.config.autoThrottle) return;
543
+ const waitMs = this.throttleUntil - Date.now();
544
+ if (waitMs > 0) {
545
+ await sleep(waitMs, signal);
546
+ }
547
+ }
548
+ };
549
+
550
+ // src/utils/batch.ts
551
+ function chunk(items, size) {
552
+ if (size <= 0) throw new RangeError("chunk size must be greater than 0");
553
+ const out = [];
554
+ for (let i = 0; i < items.length; i += size) {
555
+ out.push(items.slice(i, i + size));
556
+ }
557
+ return out;
558
+ }
559
+ async function mapWithConcurrency(items, limit, fn) {
560
+ if (limit <= 0)
561
+ throw new RangeError("concurrency limit must be greater than 0");
562
+ const results = new Array(items.length);
563
+ let cursor = 0;
564
+ async function worker() {
565
+ for (; ; ) {
566
+ const index = cursor++;
567
+ if (index >= items.length) return;
568
+ results[index] = await fn(items[index], index);
569
+ }
570
+ }
571
+ const poolSize = Math.min(limit, items.length);
572
+ await Promise.all(Array.from({ length: poolSize }, () => worker()));
573
+ return results;
574
+ }
575
+
576
+ // src/meta.ts
577
+ var RESPONSE_META = /* @__PURE__ */ Symbol("skinpricer.responseMeta");
578
+ function attachMeta(data, meta) {
579
+ if (data !== null && typeof data === "object") {
580
+ Object.defineProperty(data, RESPONSE_META, {
581
+ value: meta,
582
+ enumerable: false,
583
+ writable: false,
584
+ configurable: true
585
+ });
586
+ }
587
+ return data;
588
+ }
589
+ function getMeta(value) {
590
+ if (value !== null && typeof value === "object") {
591
+ return value[RESPONSE_META];
592
+ }
593
+ return void 0;
594
+ }
595
+
596
+ // src/resources/resource.ts
597
+ var BaseResource = class {
598
+ constructor(http) {
599
+ this.http = http;
600
+ }
601
+ http;
602
+ /** Performs a request and returns the data with {@link ResponseMeta} attached. */
603
+ async call(input, options) {
604
+ const { data, meta } = await this.http.request(input, options);
605
+ return attachMeta(data, meta);
606
+ }
607
+ };
608
+
609
+ // src/resources/aggregations.ts
610
+ var MAX_IDS_PER_REQUEST = 100;
611
+ var DEFAULT_BATCH_CONCURRENCY = 5;
612
+ var AggregationsResource = class extends BaseResource {
613
+ /** GET /v1/aggregations/min-prices — minimum sell price per market (max 100 ids). */
614
+ minPrices(params, options) {
615
+ return this.call(
616
+ {
617
+ method: "GET",
618
+ path: "/aggregations/min-prices",
619
+ query: { ids: params.ids, markets: params.markets }
620
+ },
621
+ options
622
+ );
623
+ }
624
+ /** GET /v1/aggregations/max-orders — maximum buy order per market (max 100 ids). */
625
+ maxOrders(params, options) {
626
+ return this.call(
627
+ {
628
+ method: "GET",
629
+ path: "/aggregations/max-orders",
630
+ query: { ids: params.ids, markets: params.markets }
631
+ },
632
+ options
633
+ );
634
+ }
635
+ /** Like `minPrices` but splits more than 100 ids into batches and merges them. */
636
+ async minPricesAll(ids, params = {}, options) {
637
+ const items = await this.runBatched(
638
+ ids,
639
+ params,
640
+ (chunkIds) => this.minPrices(
641
+ { ids: chunkIds, markets: params.markets },
642
+ options
643
+ ).then((res) => res.items)
644
+ );
645
+ return { items };
646
+ }
647
+ /** Like `maxOrders` but splits more than 100 ids into batches and merges them. */
648
+ async maxOrdersAll(ids, params = {}, options) {
649
+ const items = await this.runBatched(
650
+ ids,
651
+ params,
652
+ (chunkIds) => this.maxOrders(
653
+ { ids: chunkIds, markets: params.markets },
654
+ options
655
+ ).then((res) => res.items)
656
+ );
657
+ return { items };
658
+ }
659
+ async runBatched(ids, params, fetchChunk) {
660
+ if (ids.length === 0) return [];
661
+ const chunks = chunk(ids, MAX_IDS_PER_REQUEST);
662
+ const concurrency = params.concurrency ?? DEFAULT_BATCH_CONCURRENCY;
663
+ const batches = await mapWithConcurrency(chunks, concurrency, fetchChunk);
664
+ return batches.flat();
665
+ }
666
+ };
667
+
668
+ // src/resources/arbitrage.ts
669
+ var ArbitrageResource = class extends BaseResource {
670
+ /** `GET /v1/arbitrage/opportunities` — ranked cross-market opportunities. */
671
+ opportunities(params = {}, options) {
672
+ return this.call(
673
+ {
674
+ method: "GET",
675
+ path: "/arbitrage/opportunities",
676
+ query: {
677
+ limit: params.limit,
678
+ minSpreadBps: params.minSpreadBps,
679
+ minNotionalCents: params.minNotionalCents,
680
+ minNotional: params.minNotional,
681
+ sort: params.sort,
682
+ markets: params.markets,
683
+ candidateLimit: params.candidateLimit
684
+ }
685
+ },
686
+ options
687
+ );
688
+ }
689
+ };
690
+
691
+ // src/resources/attribute-prices.ts
692
+ var AttributePricesResource = class extends BaseResource {
693
+ /** GET /v1/attribute-prices/latest — latest attribute buckets across markets. */
694
+ latest(params = {}, options) {
695
+ return this.call(
696
+ {
697
+ method: "GET",
698
+ path: "/attribute-prices/latest",
699
+ query: {
700
+ canonicalItemId: params.canonicalItemId,
701
+ marketHashName: params.marketHashName,
702
+ attributes: params.attributes,
703
+ limit: params.limit,
704
+ cursor: params.cursor,
705
+ markets: params.markets
706
+ }
707
+ },
708
+ options
709
+ );
710
+ }
711
+ /** GET /v1/attribute-prices/history — OHLC attribute bucket history. */
712
+ history(params = {}, options) {
713
+ return this.call(
714
+ {
715
+ method: "GET",
716
+ path: "/attribute-prices/history",
717
+ query: {
718
+ canonicalItemId: params.canonicalItemId,
719
+ marketHashName: params.marketHashName,
720
+ bucketId: params.bucketId,
721
+ bucketIds: params.bucketIds,
722
+ attributes: params.attributes,
723
+ from: params.from,
724
+ to: params.to,
725
+ granularity: params.granularity,
726
+ limit: params.limit,
727
+ markets: params.markets
728
+ }
729
+ },
730
+ options
731
+ );
732
+ }
733
+ /** Async iterator over every latest attribute item, following `nextCursor`. */
734
+ async *latestEach(params = {}, options) {
735
+ let cursor = params.cursor;
736
+ for (; ; ) {
737
+ const res = await this.latest({ ...params, cursor }, options);
738
+ for (const item of res.items) {
739
+ yield item;
740
+ }
741
+ const next = res.nextCursor;
742
+ if (next === null || next === cursor) return;
743
+ cursor = next;
744
+ }
745
+ }
746
+ };
747
+
748
+ // src/resources/buff163.ts
749
+ var Buff163Resource = class extends BaseResource {
750
+ /** GET /v1/markets/buff163/latest — latest Buff163 attribute buckets. */
751
+ latest(params = {}, options) {
752
+ return this.call(
753
+ {
754
+ method: "GET",
755
+ path: "/markets/buff163/latest",
756
+ query: {
757
+ canonicalItemId: params.canonicalItemId,
758
+ marketHashName: params.marketHashName,
759
+ attributes: params.attributes,
760
+ limit: params.limit,
761
+ cursor: params.cursor
762
+ }
763
+ },
764
+ options
765
+ );
766
+ }
767
+ /** GET /v1/markets/buff163/history — OHLC Buff163 attribute bucket history. */
768
+ history(params = {}, options) {
769
+ return this.call(
770
+ {
771
+ method: "GET",
772
+ path: "/markets/buff163/history",
773
+ query: {
774
+ canonicalItemId: params.canonicalItemId,
775
+ marketHashName: params.marketHashName,
776
+ bucketId: params.bucketId,
777
+ bucketIds: params.bucketIds,
778
+ attributes: params.attributes,
779
+ from: params.from,
780
+ to: params.to,
781
+ granularity: params.granularity,
782
+ limit: params.limit
783
+ }
784
+ },
785
+ options
786
+ );
787
+ }
788
+ /** Async iterator over every latest Buff163 attribute item, following `nextCursor`. */
789
+ async *latestEach(params = {}, options) {
790
+ let cursor = params.cursor;
791
+ for (; ; ) {
792
+ const res = await this.latest({ ...params, cursor }, options);
793
+ for (const item of res.items) {
794
+ yield item;
795
+ }
796
+ const next = res.nextCursor;
797
+ if (next === null || next === cursor) return;
798
+ cursor = next;
799
+ }
800
+ }
801
+ };
802
+
803
+ // src/resources/history.ts
804
+ function historyQuery(params) {
805
+ return {
806
+ from: params.from,
807
+ to: params.to,
808
+ markets: params.markets,
809
+ listingType: params.listingType,
810
+ salesWindow: params.salesWindow,
811
+ interval: params.interval
812
+ };
813
+ }
814
+ var HistoryResource = class extends BaseResource {
815
+ /** `GET /v1/pricing/:marketHashName/history` — aggregated time series. */
816
+ get(marketHashName, params = {}, options) {
817
+ return this.call(
818
+ {
819
+ method: "GET",
820
+ path: `/pricing/${encodePathSegment(marketHashName)}/history`,
821
+ query: historyQuery(params)
822
+ },
823
+ options
824
+ );
825
+ }
826
+ /** `GET /v1/pricing/:marketHashName/history/markets` — per-market series. */
827
+ byMarket(marketHashName, params = {}, options) {
828
+ return this.call(
829
+ {
830
+ method: "GET",
831
+ path: `/pricing/${encodePathSegment(marketHashName)}/history/markets`,
832
+ query: historyQuery(params)
833
+ },
834
+ options
835
+ );
836
+ }
837
+ };
838
+
839
+ // src/resources/items.ts
840
+ var ItemsResource = class extends BaseResource {
841
+ /** GET /v1/items — paginated item search with current pricing. */
842
+ search(params = {}, options) {
843
+ return this.call(
844
+ {
845
+ method: "GET",
846
+ path: "/items",
847
+ query: {
848
+ search: params.search,
849
+ markets: params.markets,
850
+ page: params.page,
851
+ perPage: params.perPage
852
+ }
853
+ },
854
+ options
855
+ );
856
+ }
857
+ /** GET /v1/items/all — every tracked item with latest prices (capped, unpaginated). */
858
+ all(options) {
859
+ return this.call(
860
+ { method: "GET", path: "/items/all" },
861
+ options
862
+ );
863
+ }
864
+ /** Async iterator over every matching item, walking pages. */
865
+ async *searchEach(params = {}, options) {
866
+ let page = params.page ?? 1;
867
+ for (; ; ) {
868
+ const res = await this.search({ ...params, page }, options);
869
+ for (const item of res.data) {
870
+ yield item;
871
+ }
872
+ const next = res.pagination.nextPage;
873
+ if (next === null || next <= page) return;
874
+ page = next;
875
+ }
876
+ }
877
+ };
878
+
879
+ // src/resources/market-analytics.ts
880
+ var MarketAnalyticsResource = class extends BaseResource {
881
+ /** `GET /v1/market-analytics/:marketHashName` — per-market analytics rows. */
882
+ get(marketHashName, params = {}, options) {
883
+ return this.call(
884
+ {
885
+ method: "GET",
886
+ path: `/market-analytics/${encodePathSegment(marketHashName)}`,
887
+ query: { markets: params.markets, windowHours: params.windowHours }
888
+ },
889
+ options
890
+ );
891
+ }
892
+ };
893
+
894
+ // src/resources/nbbo.ts
895
+ var NbboResource = class extends BaseResource {
896
+ /** `GET /v1/nbbo` — best bid/ask across markets. Pass `id` or `marketHashName`. */
897
+ get(params, options) {
898
+ return this.call(
899
+ {
900
+ method: "GET",
901
+ path: "/nbbo",
902
+ query: {
903
+ id: params.id,
904
+ market_hash_name: params.marketHashName,
905
+ markets: params.markets
906
+ }
907
+ },
908
+ options
909
+ );
910
+ }
911
+ /** `GET /v1/nbbo/depth` — aggregated order-book depth per side. */
912
+ depth(params, options) {
913
+ return this.call(
914
+ {
915
+ method: "GET",
916
+ path: "/nbbo/depth",
917
+ query: {
918
+ id: params.id,
919
+ market_hash_name: params.marketHashName,
920
+ markets: params.markets,
921
+ depth: params.depth
922
+ }
923
+ },
924
+ options
925
+ );
926
+ }
927
+ };
928
+
929
+ // src/resources/pricing.ts
930
+ var PricingResource = class extends BaseResource {
931
+ /** `GET /v1/pricing/:marketHashName` — full cross-market pricing snapshot. */
932
+ get(marketHashName, params = {}, options) {
933
+ return this.call(
934
+ {
935
+ method: "GET",
936
+ path: `/pricing/${encodePathSegment(marketHashName)}`,
937
+ query: { markets: params.markets }
938
+ },
939
+ options
940
+ );
941
+ }
942
+ /** `GET /v1/pricing/:marketHashName/listings` — individual listing samples. */
943
+ listings(marketHashName, params = {}, options) {
944
+ return this.call(
945
+ {
946
+ method: "GET",
947
+ path: `/pricing/${encodePathSegment(marketHashName)}/listings`,
948
+ query: { limit: params.limit, markets: params.markets }
949
+ },
950
+ options
951
+ );
952
+ }
953
+ };
954
+
955
+ // src/resources/recommendations.ts
956
+ var RecommendationsResource = class extends BaseResource {
957
+ /** `GET /v1/recommendations/:marketHashName` — suggested price + confidence. */
958
+ get(marketHashName, params = {}, options) {
959
+ return this.call(
960
+ {
961
+ method: "GET",
962
+ path: `/recommendations/${encodePathSegment(marketHashName)}`,
963
+ query: { markets: params.markets }
964
+ },
965
+ options
966
+ );
967
+ }
968
+ };
969
+
970
+ // src/resources/status.ts
971
+ var StatusResource = class extends BaseResource {
972
+ /** `GET /v1/status/freshness` — per-market data freshness and overall health. */
973
+ freshness(options) {
974
+ return this.call(
975
+ { method: "GET", path: "/status/freshness" },
976
+ options
977
+ );
978
+ }
979
+ /** `GET /v1/status/market-latency` — fetch-to-ingest latency metrics per market. */
980
+ marketLatency(options) {
981
+ return this.call(
982
+ { method: "GET", path: "/status/market-latency" },
983
+ options
984
+ );
985
+ }
986
+ };
987
+
988
+ // src/client.ts
989
+ var SkinpricerClient = class {
990
+ pricing;
991
+ history;
992
+ nbbo;
993
+ aggregations;
994
+ items;
995
+ status;
996
+ arbitrage;
997
+ recommendations;
998
+ marketAnalytics;
999
+ attributePrices;
1000
+ buff163;
1001
+ httpClient;
1002
+ constructor(config) {
1003
+ this.httpClient = new HttpClient(resolveConfig(config));
1004
+ this.pricing = new PricingResource(this.httpClient);
1005
+ this.history = new HistoryResource(this.httpClient);
1006
+ this.nbbo = new NbboResource(this.httpClient);
1007
+ this.aggregations = new AggregationsResource(this.httpClient);
1008
+ this.items = new ItemsResource(this.httpClient);
1009
+ this.status = new StatusResource(this.httpClient);
1010
+ this.arbitrage = new ArbitrageResource(this.httpClient);
1011
+ this.recommendations = new RecommendationsResource(this.httpClient);
1012
+ this.marketAnalytics = new MarketAnalyticsResource(this.httpClient);
1013
+ this.attributePrices = new AttributePricesResource(this.httpClient);
1014
+ this.buff163 = new Buff163Resource(this.httpClient);
1015
+ }
1016
+ };
1017
+
1018
+ // src/types/markets.ts
1019
+ var KNOWN_MARKETS = [
1020
+ "skinport",
1021
+ "skindeck",
1022
+ "buff163",
1023
+ "csfloat",
1024
+ "marketcsgo",
1025
+ "cstrade",
1026
+ "dmarket",
1027
+ "itrade",
1028
+ "lis-skins",
1029
+ "swapgg",
1030
+ "whitemarket",
1031
+ "waxpeer",
1032
+ "lootfarm",
1033
+ "tradeit-store",
1034
+ "tradeit-trade",
1035
+ "steamcommunity"
1036
+ ];
1037
+ var ATTRIBUTE_MARKETS = [
1038
+ "buff163",
1039
+ "steamcommunity",
1040
+ "marketcsgo",
1041
+ "csfloat",
1042
+ "dmarket"
1043
+ ];
1044
+
1045
+ // src/utils/money.ts
1046
+ function centsToUsd(cents) {
1047
+ return cents / 100;
1048
+ }
1049
+ function formatUsd(cents, options = {}) {
1050
+ const { currency = "USD", locale = "en-US" } = options;
1051
+ return new Intl.NumberFormat(locale, { style: "currency", currency }).format(
1052
+ cents / 100
1053
+ );
1054
+ }
1055
+
1056
+ // src/utils/dates.ts
1057
+ function parseIsoDate(value) {
1058
+ return new Date(value);
1059
+ }
1060
+
1061
+ exports.APIError = APIError;
1062
+ exports.ATTRIBUTE_MARKETS = ATTRIBUTE_MARKETS;
1063
+ exports.AggregationsResource = AggregationsResource;
1064
+ exports.ArbitrageResource = ArbitrageResource;
1065
+ exports.AttributePricesResource = AttributePricesResource;
1066
+ exports.AuthenticationError = AuthenticationError;
1067
+ exports.BaseResource = BaseResource;
1068
+ exports.Buff163Resource = Buff163Resource;
1069
+ exports.ConfigurationError = ConfigurationError;
1070
+ exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
1071
+ exports.DEFAULT_RETRY = DEFAULT_RETRY;
1072
+ exports.DEFAULT_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;
1073
+ exports.FeatureNotAvailableError = FeatureNotAvailableError;
1074
+ exports.HistoryResource = HistoryResource;
1075
+ exports.ItemsResource = ItemsResource;
1076
+ exports.KNOWN_MARKETS = KNOWN_MARKETS;
1077
+ exports.MarketAnalyticsResource = MarketAnalyticsResource;
1078
+ exports.NbboResource = NbboResource;
1079
+ exports.NetworkError = NetworkError;
1080
+ exports.NotFoundError = NotFoundError;
1081
+ exports.ParseError = ParseError;
1082
+ exports.PermissionError = PermissionError;
1083
+ exports.PricingResource = PricingResource;
1084
+ exports.RESPONSE_META = RESPONSE_META;
1085
+ exports.RateLimitError = RateLimitError;
1086
+ exports.RecommendationsResource = RecommendationsResource;
1087
+ exports.ServerError = ServerError;
1088
+ exports.SkinpricerClient = SkinpricerClient;
1089
+ exports.SkinpricerError = SkinpricerError;
1090
+ exports.StatusResource = StatusResource;
1091
+ exports.TimeoutError = TimeoutError;
1092
+ exports.VERSION = VERSION;
1093
+ exports.ValidationError = ValidationError;
1094
+ exports.centsToUsd = centsToUsd;
1095
+ exports.chunk = chunk;
1096
+ exports.errorFromResponse = errorFromResponse;
1097
+ exports.formatUsd = formatUsd;
1098
+ exports.getMeta = getMeta;
1099
+ exports.mapWithConcurrency = mapWithConcurrency;
1100
+ exports.parseIsoDate = parseIsoDate;
1101
+ exports.resolveConfig = resolveConfig;
1102
+ //# sourceMappingURL=index.cjs.map
1103
+ //# sourceMappingURL=index.cjs.map