discogs-marketplace-api-nodejs 1.11.0 → 1.13.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,111 @@
1
+ export default interface ShopResultApi {
2
+ /** Items */
3
+ items?: Array<{
4
+ /** ItemId */
5
+ itemId?: number;
6
+ /** AllowsOffers */
7
+ allowsOffers?: boolean;
8
+ /** Comments */
9
+ comments?: string;
10
+ /** ImageUrl */
11
+ imageUrl?: string;
12
+ /** InCart */
13
+ inCart?: boolean;
14
+ /** ListedDate */
15
+ listedDate?: string;
16
+ /** MediaCondition */
17
+ mediaCondition?: string;
18
+ /** PreviousPrice */
19
+ previousPrice?: string;
20
+ /** Price */
21
+ price?: {
22
+ /** Amount */
23
+ amount?: number;
24
+ /** AmountUsd */
25
+ amountUsd?: number;
26
+ /** CurrencyCode */
27
+ currencyCode?: string;
28
+ /** BuyerItemPrice */
29
+ buyerItemPrice?: string;
30
+ /** BuyerCurrencyCode */
31
+ buyerCurrencyCode?: string;
32
+ };
33
+ /** Release */
34
+ release?: {
35
+ /** ReleaseId */
36
+ releaseId?: number;
37
+ /** Artists */
38
+ artists?: Array<{
39
+ /** ArtistId */
40
+ artistId?: number;
41
+ /** Name */
42
+ name?: string;
43
+ }>;
44
+ /** Country */
45
+ country?: string;
46
+ /** FormatNames */
47
+ formatNames?: Array<string>;
48
+ /** Genres */
49
+ genres?: Array<{
50
+ /** GenreId */
51
+ genreId?: number;
52
+ /** Name */
53
+ name?: string;
54
+ }>;
55
+ /** Labels */
56
+ labels?: Array<{
57
+ /** LabelId */
58
+ labelId?: number;
59
+ /** Name */
60
+ name?: string;
61
+ }>;
62
+ /** MajorFormat */
63
+ majorFormat?: string;
64
+ /** Rating */
65
+ rating?: number;
66
+ /** Title */
67
+ title?: string;
68
+ /** Year */
69
+ year?: number;
70
+ };
71
+ /** Seller */
72
+ seller?: {
73
+ /** Uid */
74
+ uid?: number;
75
+ /** Name */
76
+ name?: string;
77
+ /** Rating */
78
+ rating?: number;
79
+ /** RatingCount */
80
+ ratingCount?: number;
81
+ /** ShipsFrom */
82
+ shipsFrom?: string;
83
+ /** MinBuyerRating */
84
+ minBuyerRating?: number;
85
+ /** IndependentSeller */
86
+ independentSeller?: boolean;
87
+ };
88
+ /** Shipping */
89
+ shipping?: {
90
+ /** ShippingPrice */
91
+ shippingPrice?: number;
92
+ /** BuyerShippingPrice */
93
+ buyerShippingPrice?: number;
94
+ /** FreeShippingMin */
95
+ freeShippingMin?: number;
96
+ };
97
+ /** SleeveCondition */
98
+ sleeveCondition?: string;
99
+ }>;
100
+ /** TotalCount */
101
+ totalCount?: number;
102
+ /** CompleteLookup */
103
+ completeLookup?: {
104
+ /** Artists */
105
+ artists?: string;
106
+ /** Sellers */
107
+ sellers?: string;
108
+ /** Releases */
109
+ releases?: Record<string, string>;
110
+ };
111
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,115 +1,122 @@
1
- import type { Condition } from '../types/condition.type';
2
- import type { Currency } from '../types/currency.type';
3
- import type { FormatDescription } from '../types/format-description.type';
4
- import type { Format } from '../types/format.type';
5
- import type { From } from '../types/from.type';
6
- import type { Genre } from '../types/genre.type';
7
- import type { Lang } from '../types/lang.type';
8
- import type { Limit } from '../types/limit.type';
9
- import type { Search } from '../types/search-type.type';
10
- import type { Sort } from '../types/sort.type';
11
- import type { Style } from '../types/style.type';
1
+ import type { Condition } from '../types/condition.type.js';
2
+ import type { Currency } from '../types/currency.type.js';
3
+ import type { FormatDescription } from '../types/format-description.type.js';
4
+ import type { Format } from '../types/format.type.js';
5
+ import type { From } from '../types/from.type.js';
6
+ import type { Genre } from '../types/genre.type.js';
7
+ import type { Lang } from '../types/lang.type.js';
8
+ import type { Limit } from '../types/limit.type.js';
9
+ import type { Search } from '../types/search-type.type.js';
10
+ import type { Sort } from '../types/sort.type.js';
11
+ import type { Style } from '../types/style.type.js';
12
12
  /**
13
- * Search parameters for Discogs Marketplace
13
+ * Parameters used to search listings on the Discogs Marketplace.
14
14
  */
15
15
  export default interface SearchParams {
16
16
  /**
17
- * Type of elements to search.
18
- * | Name | Description |
19
- * |:---------: |:--------------------------:|
20
- * | q | Basic query search |
21
- * | master_id | Search in a master release |
22
- * | release_id | Search in a release |
23
- * | label_id | Search in a label |
24
- * | artist_id | Search in a artist |
25
- * | user | Search in user wantlist |
17
+ * The type of element to search.
18
+ * | Value | Description |
19
+ * |-------------|--------------------------------|
20
+ * | `q` | Basic query search |
21
+ * | `master_id` | Search within a master release |
22
+ * | `release_id`| Search within a release |
23
+ * | `label_id` | Search within a label |
24
+ * | `artist_id` | Search by artist |
25
+ * | `user` | Search a user's wantlist |
26
26
  * @default 'q'
27
27
  */
28
28
  searchType: Search;
29
29
  /**
30
- * Value to search corresponding to the search type
30
+ * The search value corresponding to the selected `searchType`.
31
31
  */
32
32
  searchValue?: string | number;
33
33
  /**
34
- * Currency
34
+ * Currency code for price filtering.
35
35
  * @example 'USD'
36
36
  */
37
37
  currency?: Currency;
38
38
  /**
39
- * Genre
39
+ * Genre filter.
40
40
  * @example 'Rock'
41
41
  */
42
42
  genre?: Genre;
43
43
  /**
44
- * Styles
44
+ * List of styles.
45
45
  * @example ['Death Metal', 'Heavy Metal']
46
46
  */
47
47
  style?: Array<Style>;
48
48
  /**
49
- * Formats
49
+ * List of formats.
50
50
  * @example ['Vinyl', 'CD']
51
51
  */
52
52
  format?: Array<Format>;
53
53
  /**
54
- * Format descriptions
54
+ * List of format descriptions.
55
55
  * @example ['Limited Edition', 'Numbered']
56
56
  */
57
57
  formatDescription?: Array<FormatDescription>;
58
58
  /**
59
- * Media conditions
59
+ * List of media conditions.
60
60
  * @example ['Mint (M)', 'Very Good Plus (VG+)']
61
61
  */
62
62
  condition?: Array<Condition>;
63
63
  /**
64
- * Year (Do not use it with `years`)
64
+ * Release year.
65
+ * Do not use together with `years`.
65
66
  */
66
67
  year?: number;
67
68
  /**
68
- * Interval of years (Do not use it with `year`)
69
+ * Range of years.
70
+ * Do not use together with `year`.
69
71
  */
70
72
  years?: {
71
- /** Min */
73
+ /** Minimum year */
72
74
  min: number;
73
- /** Max */
75
+ /** Maximum year */
74
76
  max: number;
75
77
  };
76
78
  /**
77
- * Is audio sample ?
78
- * @default false
79
- */
80
- isAudioSample?: boolean;
81
- /**
82
- * Is make an offer only ?
79
+ * If true, only listings that accept offers are returned.
83
80
  * @default false
84
81
  */
85
82
  isMakeAnOfferOnly?: boolean;
86
83
  /**
87
- * Expedition country
84
+ * Expedition country filter (2-letter country code).
88
85
  * @example 'US'
89
86
  */
90
87
  from?: From;
91
88
  /**
92
- * Seller name
89
+ * Seller's username filter.
93
90
  */
94
91
  seller?: string;
95
92
  /**
96
- * Sort elements by.
97
- * @default 'Listed Newest'
93
+ * Sort order for the results.
94
+ * @default 'listed,desc'
98
95
  */
99
96
  sort?: Sort;
100
97
  /**
101
- * Limit of elements to search (25 | 50 | 100 | 250).
98
+ * Number of results to return per page.
99
+ * Allowed values: 25, 50, 100, 250.
102
100
  * @default 25
103
101
  */
104
102
  limit?: Limit;
105
103
  /**
106
- * Page (Must be < 401 or discogs will return an error 404).
104
+ * Page number of results.
105
+ * Must be less than 401 to avoid Discogs 404 errors.
107
106
  * @default 1
108
107
  */
109
108
  page?: number;
110
109
  /**
111
- * Lang to use for Discogs.
110
+ * Language code for Discogs interface.
112
111
  * @default 'en'
113
112
  */
114
113
  lang?: Lang;
115
114
  }
115
+ export type SearchParamsDefaulted = SearchParams & {
116
+ searchType: NonNullable<SearchParams['searchType']>;
117
+ isMakeAnOfferOnly: NonNullable<SearchParams['isMakeAnOfferOnly']>;
118
+ sort: NonNullable<SearchParams['sort']>;
119
+ limit: NonNullable<SearchParams['limit']>;
120
+ page: NonNullable<SearchParams['page']>;
121
+ lang: NonNullable<SearchParams['lang']>;
122
+ };
@@ -1,118 +1,120 @@
1
- import type { CountryValues } from '../data/country.data';
2
- import type { CurrencyValues } from '../data/currency.data';
1
+ import type { CountryValues } from '../data/country.data.js';
2
+ import type { CurrencyValues } from '../data/currency.data.js';
3
3
  /**
4
- * Search result from Discogs Marketplace
4
+ * Result returned from a Discogs Marketplace search.
5
5
  */
6
6
  export default interface SearchResult {
7
- /** Items */
7
+ /** List of items matching the search query. */
8
8
  items: Array<{
9
- /** Id */
9
+ /** Unique identifier for the listing */
10
10
  id: number;
11
- /** Title */
11
+ /** Title details */
12
12
  title: {
13
- /** Original */
13
+ /** Full original title */
14
14
  original: string;
15
- /** Artist */
15
+ /** Artist name */
16
16
  artist: string;
17
- /** Item */
17
+ /** Item description */
18
18
  item: string;
19
- /** Formats */
19
+ /** Array of format names */
20
20
  formats: Array<string>;
21
21
  };
22
- /** Url */
22
+ /** URL to the listing on Discogs */
23
23
  url: string;
24
- /** Labels */
24
+ /** Date the item was listed */
25
+ listedAt: Date | null;
26
+ /** Array of label names */
25
27
  labels: Array<string>;
26
- /** Catnos */
28
+ /** Array of catalog numbers */
27
29
  catnos: Array<string>;
28
- /** ImageUrl */
30
+ /** URL to the item's image */
29
31
  imageUrl: string;
30
- /** Description */
32
+ /** Text description of the item */
31
33
  description: string;
32
- /** IsAcceptingOffer */
34
+ /** Indicates if offers are accepted */
33
35
  isAcceptingOffer: boolean;
34
- /** IsAvailable */
36
+ /** Availability status of the item */
35
37
  isAvailable: boolean;
36
- /** Condition */
38
+ /** Condition details */
37
39
  condition: {
38
- /** Media */
40
+ /** Media condition */
39
41
  media: {
40
- /** Full */
42
+ /** Full description */
41
43
  full: string;
42
- /** Short */
44
+ /** Short code */
43
45
  short: string;
44
46
  };
45
- /** Sleeve */
47
+ /** Sleeve condition */
46
48
  sleeve: {
47
- /** Full */
49
+ /** Full description */
48
50
  full: string;
49
- /** Short */
51
+ /** Short code */
50
52
  short: string;
51
53
  };
52
54
  };
53
- /** Seller */
55
+ /** Seller information */
54
56
  seller: {
55
- /** Name */
57
+ /** Seller's username */
56
58
  name: string;
57
- /** Url */
59
+ /** Seller's profile URL */
58
60
  url: string;
59
- /** Score */
61
+ /** Seller rating/score */
60
62
  score: string;
61
- /** Notes */
63
+ /** Number of notes/reviews */
62
64
  notes: number;
63
65
  };
64
- /** Price */
66
+ /** Pricing details */
65
67
  price: {
66
68
  /**
67
- * Base
69
+ * Base price as a string combining amount and currency.
68
70
  * @example '12.34 USD'
69
71
  */
70
72
  base: `${number} ${CurrencyValues}` | '';
71
73
  /**
72
- * Shipping
74
+ * Shipping cost as a string combining amount and currency.
73
75
  * @example '5.67 USD'
74
76
  */
75
77
  shipping: `${number} ${CurrencyValues}` | '';
76
78
  };
77
- /** From */
79
+ /** Shipping origin country */
78
80
  country: {
79
- /** Name */
81
+ /** Country name */
80
82
  name: string;
81
83
  /**
82
- * Iso code
84
+ * ISO country code
83
85
  * @example 'US'
84
86
  */
85
87
  code: CountryValues;
86
88
  };
87
- /** Community */
89
+ /** Community stats */
88
90
  community: {
89
- /** Have */
91
+ /** Number of users who have this item */
90
92
  have: number;
91
- /** Want */
93
+ /** Number of users who want this item */
92
94
  want: number;
93
95
  };
94
- /** Release */
96
+ /** Release details */
95
97
  release: {
96
- /** Id */
98
+ /** Release ID */
97
99
  id: number;
98
- /** Url */
100
+ /** Release URL */
99
101
  url: string;
100
102
  };
101
103
  }>;
102
- /** Page */
104
+ /** Pagination information */
103
105
  page: {
104
- /** Current */
106
+ /** Current page number */
105
107
  current: number;
106
- /** Total */
108
+ /** Total number of pages */
107
109
  total: number;
108
110
  };
109
- /** Result */
111
+ /** Overall search result metadata */
110
112
  result: {
111
- /** Total */
113
+ /** Total number of results found */
112
114
  total: number;
113
- /** PerPage */
115
+ /** Number of results per page */
114
116
  perPage: number;
115
117
  };
116
- /** UrlGenerated */
118
+ /** The generated URL used for the search */
117
119
  urlGenerated: string;
118
120
  }
@@ -0,0 +1,11 @@
1
+ import type SearchResult from '../interfaces/search-result.interface.js';
2
+ import type { SearchParamsDefaulted } from '../interfaces/search-params.interface.js';
3
+ /**
4
+ * Parses the page and returns the items found.
5
+ * @param url Url to scrape
6
+ * @returns Items found and total
7
+ */
8
+ export default function scrapeLegacy({ searchType, searchValue, currency, genre, style, format, formatDescription, condition, year, years, isMakeAnOfferOnly, from, seller, sort, limit, page, lang, }: SearchParamsDefaulted): Promise<Pick<SearchResult, 'items' | 'urlGenerated'> & {
9
+ /** Total items found */
10
+ total: SearchResult['result']['total'];
11
+ }>;
@@ -1,47 +1,121 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.default = scrape;
4
- // These variables are injected by the browser context when the page is loaded.
5
- const { Country, Currency } = globalThis;
6
+ exports.default = scrapeLegacy;
7
+ const linkedom_1 = require("linkedom");
8
+ const currency_data_1 = __importDefault(require("../data/currency.data.js"));
9
+ const country_data_1 = __importDefault(require("../data/country.data.js"));
6
10
  /**
7
- * Parses the page and returns the items found.
8
- * This function is called by the browser context when the page is loaded.
9
- * @returns Items found and total
11
+ * Generate URL to be parsed
12
+ * @returns Url
10
13
  */
11
- function scrape() {
12
- /**
13
- * Converts a currency string to a standardized format.
14
- * @param value String to clean
15
- * @returns Cleaned-up string
16
- */
17
- const convertCurrency = (value) => {
18
- if (!value) {
19
- return '';
20
- }
21
- const currencyFound = Object.keys(Currency).find(key => value.includes(key));
22
- if (!currencyFound) {
23
- return '';
14
+ function generateUrl({ searchType, seller, lang, }) {
15
+ const baseUrl = `https://www.discogs.com/${lang}`;
16
+ if (seller) {
17
+ const path = searchType === 'user' ? 'mywants' : 'profile';
18
+ return `${baseUrl}/seller/${seller}/${path}`;
19
+ }
20
+ else {
21
+ const path = searchType === 'user' ? 'mywants' : 'list';
22
+ return `${baseUrl}/sell/${path}`;
23
+ }
24
+ }
25
+ /**
26
+ * Serialize params URL
27
+ * @param params Object of GET parameters
28
+ * @returns Url
29
+ */
30
+ function serializeParams(params) {
31
+ return Object.entries(params)
32
+ .flatMap(([key, value]) => {
33
+ if (value === undefined || value === null) {
34
+ return [];
24
35
  }
25
- const currencyClean = Currency[currencyFound];
26
- const amount = value
27
- .replace(currencyClean !== 'JPY' ? /[.](?=.*[.])/g : /\./g, '') // Remove all dots but the last, except for JPY
28
- .replace(currencyFound, '') // Remove original currency
29
- .replace(/\s\s+/g, ''); // Remove spaces
30
- const amountParsed = Number.parseFloat(amount);
31
- if (Number.isNaN(amountParsed)) {
32
- return '';
36
+ if (Array.isArray(value)) {
37
+ return value.map(v => `${key}=${encodeURIComponent(v)}`);
33
38
  }
34
- return `${amountParsed} ${currencyClean}`;
35
- };
36
- /**
37
- * Safely parses a number from a string.
38
- * @param value String to parse
39
- * @returns Parsed number or 0 if invalid
40
- */
41
- const safeParseInt = (value) => {
42
- const parsed = Number.parseInt(value ?? '', 10);
43
- return Number.isNaN(parsed) ? 0 : parsed;
44
- };
39
+ return [`${key}=${encodeURIComponent(value)}`];
40
+ })
41
+ .join('&');
42
+ }
43
+ /**
44
+ * Converts a currency string to a standardized format.
45
+ * @param value String to clean
46
+ * @returns Cleaned-up string
47
+ */
48
+ function convertCurrency(value) {
49
+ if (!value) {
50
+ return '';
51
+ }
52
+ const currencyFound = Object.keys(currency_data_1.default).find(key => value.includes(key));
53
+ if (!currencyFound) {
54
+ return '';
55
+ }
56
+ const currencyClean = currency_data_1.default[currencyFound];
57
+ const amount = value
58
+ .replace(currencyClean !== 'JPY' ? /[.](?=.*[.])/g : /\./g, '') // Remove all dots but the last, except for JPY
59
+ .replace(currencyFound, '') // Remove original currency
60
+ .replace(/\s\s+/g, ''); // Remove spaces
61
+ const amountParsed = Number.parseFloat(amount);
62
+ if (Number.isNaN(amountParsed)) {
63
+ return '';
64
+ }
65
+ return `${amountParsed} ${currencyClean}`;
66
+ }
67
+ /**
68
+ * Safely parses a number from a string.
69
+ * @param value String to parse
70
+ * @returns Parsed number or 0 if invalid
71
+ */
72
+ function safeParseInt(value) {
73
+ const parsed = Number.parseInt(value ?? '', 10);
74
+ return Number.isNaN(parsed) ? 0 : parsed;
75
+ }
76
+ /**
77
+ * Parses the page and returns the items found.
78
+ * @param url Url to scrape
79
+ * @returns Items found and total
80
+ */
81
+ async function scrapeLegacy({ searchType, searchValue, currency, genre, style, format, formatDescription, condition, year, years, isMakeAnOfferOnly, from, seller, sort, limit, page, lang, }) {
82
+ /** Url to be called by the browser */
83
+ const urlGenerated = [
84
+ generateUrl({ searchType, seller, lang }),
85
+ serializeParams({
86
+ [searchType]: searchValue,
87
+ currency,
88
+ genre,
89
+ style: style?.length ? style : null,
90
+ format: format?.length ? format : null,
91
+ format_desc: formatDescription?.length ? formatDescription : null,
92
+ condition: condition?.length ? condition : null,
93
+ year: year && !years ? year : null,
94
+ year1: years?.min && !year ? years.min : null,
95
+ year2: years?.max && !year ? years.max : null,
96
+ offers: isMakeAnOfferOnly ? 1 : null,
97
+ ships_from: from,
98
+ limit,
99
+ page,
100
+ sort,
101
+ }),
102
+ ].join('?');
103
+ const response = await globalThis.fetch(urlGenerated, {
104
+ headers: {
105
+ 'User-Agent': 'Discogs',
106
+ 'Content-Type': 'application/json',
107
+ 'X-PJAX': 'true',
108
+ },
109
+ referrer: 'https://discogs.com',
110
+ });
111
+ const content = await response.text();
112
+ const { document } = (0, linkedom_1.parseHTML)(content);
113
+ // If error status, reject
114
+ if (response.status >= 400) {
115
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
116
+ const errorMessage = document.querySelector('h1 + p')?.innerHTML.trim() || `An error ${response.status} occurred.`;
117
+ throw new Error(errorMessage);
118
+ }
45
119
  /**
46
120
  * Extracts and cleans text content from an element.
47
121
  * @param selector CSS selector
@@ -76,6 +150,7 @@ function scrape() {
76
150
  : [],
77
151
  },
78
152
  url: `https://www.discogs.com${itemHref}`,
153
+ listedAt: null,
79
154
  labels: [...el.querySelectorAll(".label_and_cat a[href^='https://www.discogs.com/']")]
80
155
  .map(x => x.textContent?.trim() ?? '')
81
156
  .filter((value, index, self) => self.indexOf(value) === index),
@@ -110,7 +185,7 @@ function scrape() {
110
185
  },
111
186
  country: {
112
187
  name: countryName,
113
- code: Country[countryName],
188
+ code: country_data_1.default[countryName],
114
189
  },
115
190
  community: {
116
191
  have: safeParseInt(getTextContent('.community_summary .community_result:nth-child(1) .community_number', el)),
@@ -122,5 +197,5 @@ function scrape() {
122
197
  },
123
198
  };
124
199
  });
125
- return { total, items };
200
+ return { total, items, urlGenerated };
126
201
  }
@@ -0,0 +1,14 @@
1
+ import type SearchResult from '../interfaces/search-result.interface.js';
2
+ import type { SearchParamsDefaulted } from '../interfaces/search-params.interface.js';
3
+ /**
4
+ * Parses the page and returns the items found.
5
+ * @param SearchParams Search parameters
6
+ * @returns Items found and total
7
+ */
8
+ export default function scrape({ currency, genre, format, formatDescription, condition, years, isMakeAnOfferOnly, from, sort, limit, page, releases, }: SearchParamsDefaulted & {
9
+ /** Releases */
10
+ releases?: Array<number>;
11
+ }): Promise<Pick<SearchResult, 'items' | 'urlGenerated'> & {
12
+ /** Total items found */
13
+ total: SearchResult['result']['total'];
14
+ }>;