discogs-marketplace-api-nodejs 1.17.0 → 1.17.1

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.
@@ -1,7 +1,8 @@
1
1
  import type { Browser, BrowserContext } from 'patchright';
2
2
  /**
3
3
  * Run a function in a headless browser context suited to call Discogs, closing what it opened afterwards.
4
- * JavaScript is disabled and the User-Agent is the one of the Discogs apps, which Cloudflare lets through.
4
+ * It looks like a regular Chrome with JavaScript enabled, which Cloudflare lets through more often than the User-Agent
5
+ * of the Discogs apps without JavaScript, especially from datacenter IPs.
5
6
  * @param browserInstance Browser to use, launched and closed here when not provided
6
7
  * @param fn Function to run
7
8
  * @returns Result of the function
@@ -2,9 +2,30 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.default = withBrowserContext;
4
4
  const patchright_1 = require("patchright");
5
+ /**
6
+ * Get the browser options of a regular Chrome of the same version as the browser, as its default User-Agent and
7
+ * `sec-ch-ua` header give away the headless mode ("HeadlessChrome").
8
+ * @param browser Browser
9
+ * @returns User-Agent, in the reduced form of Chrome ("Chrome/153.0.0.0"), and `sec-ch-ua` header
10
+ */
11
+ async function getChromeIdentity(browser) {
12
+ const session = await browser.newBrowserCDPSession();
13
+ try {
14
+ const { userAgent } = await session.send('Browser.getVersion');
15
+ const [major] = browser.version().split('.');
16
+ return {
17
+ userAgent: userAgent.replace(/HeadlessChrome\/[\d.]+/, `Chrome/${major ?? ''}.0.0.0`),
18
+ extraHTTPHeaders: { 'sec-ch-ua': `"Google Chrome";v="${major ?? ''}", "Not_A Brand";v="8", "Chromium";v="${major ?? ''}"` },
19
+ };
20
+ }
21
+ finally {
22
+ await session.detach();
23
+ }
24
+ }
5
25
  /**
6
26
  * Run a function in a headless browser context suited to call Discogs, closing what it opened afterwards.
7
- * JavaScript is disabled and the User-Agent is the one of the Discogs apps, which Cloudflare lets through.
27
+ * It looks like a regular Chrome with JavaScript enabled, which Cloudflare lets through more often than the User-Agent
28
+ * of the Discogs apps without JavaScript, especially from datacenter IPs.
8
29
  * @param browserInstance Browser to use, launched and closed here when not provided
9
30
  * @param fn Function to run
10
31
  * @returns Result of the function
@@ -12,7 +33,7 @@ const patchright_1 = require("patchright");
12
33
  async function withBrowserContext(browserInstance, fn) {
13
34
  const browser = browserInstance ?? (await patchright_1.chromium.launch({ headless: true, chromiumSandbox: false }));
14
35
  try {
15
- const browserContext = await browser.newContext({ javaScriptEnabled: false, userAgent: 'Discogs' });
36
+ const browserContext = await browser.newContext(await getChromeIdentity(browser));
16
37
  try {
17
38
  return await fn(browserContext);
18
39
  }
@@ -57,15 +57,23 @@ const CONDITIONS = {
57
57
  * @returns Response
58
58
  */
59
59
  async function queryGraphql(page, operationName, variables) {
60
- const { status, json } = await page.evaluate(async (body) => {
60
+ const { status, cfMitigated, cfRay, json } = await page.evaluate(async (body) => {
61
61
  const res = await fetch('/graphql', {
62
62
  method: 'POST',
63
63
  headers: { 'Content-Type': 'application/json' },
64
64
  body: JSON.stringify(body),
65
65
  });
66
- return { status: res.status, json: (await res.json().catch(() => null)) };
66
+ return {
67
+ status: res.status,
68
+ cfMitigated: res.headers.get('cf-mitigated'),
69
+ cfRay: res.headers.get('cf-ray'),
70
+ json: (await res.json().catch(() => null)),
71
+ };
67
72
  }, { operationName, variables, extensions: { persistedQuery: { version: 1, sha256Hash: HASHES[operationName] } } });
68
73
  const result = json;
74
+ if (cfMitigated) {
75
+ throw new Error(`An error ${status} occurred: blocked by Cloudflare (${cfMitigated}, cf-ray ${cfRay ?? '?'}).`);
76
+ }
69
77
  if (!result?.data) {
70
78
  // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
71
79
  throw new Error(result?.errors?.map(x => x.message).join(', ') || `An error ${status} occurred.`);
package/dist/wantlist.js CHANGED
@@ -71,7 +71,11 @@ function scrapeWantlist(username, browserContext) {
71
71
  return { ids: [], pages: 0 };
72
72
  }
73
73
  if (!response?.ok()) {
74
- throw new Error(`An error ${response?.status() ?? '?'} occurred.`);
74
+ const status = response?.status() ?? '?';
75
+ const { 'cf-mitigated': cfMitigated, 'cf-ray': cfRay = '?' } = response?.headers() ?? {};
76
+ throw new Error(cfMitigated
77
+ ? `An error ${status} occurred: blocked by Cloudflare (${cfMitigated}, cf-ray ${cfRay}).`
78
+ : `An error ${status} occurred.`);
75
79
  }
76
80
  const { total, ids } = await browserPage.evaluate(() => ({
77
81
  total: +(document.querySelector('.pagination_total')?.textContent.split(' of ').pop()?.replace(/,/g, '') ?? '0'),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "discogs-marketplace-api-nodejs",
3
- "version": "1.17.0",
3
+ "version": "1.17.1",
4
4
  "description": "Another (better ?) NodeJs library to fetch data from Discogs marketplace",
5
5
  "keywords": [
6
6
  "discogs",