/ clis / douyin / _shared / browser-fetch.js
browser-fetch.js
 1  import { CommandExecutionError } from '@jackwener/opencli/errors';
 2  /**
 3   * Execute a fetch() call inside the Chrome browser context via page.evaluate.
 4   * This ensures a_bogus signing and cookies are handled automatically by the browser.
 5   */
 6  export async function browserFetch(page, method, url, options = {}) {
 7      const js = `
 8      (async () => {
 9        const res = await fetch(${JSON.stringify(url)}, {
10          method: ${JSON.stringify(method)},
11          credentials: 'include',
12          headers: {
13            'Content-Type': 'application/json',
14            ...${JSON.stringify(options.headers ?? {})}
15          },
16          ${options.body ? `body: JSON.stringify(${JSON.stringify(options.body)}),` : ''}
17        });
18        return res.json();
19      })()
20    `;
21      const result = await page.evaluate(js);
22      if (result && typeof result === 'object' && 'status_code' in result) {
23          const code = result.status_code;
24          if (code !== 0) {
25              const msg = result.status_msg ?? 'unknown error';
26              throw new CommandExecutionError(`Douyin API error ${code}: ${msg}`);
27          }
28      }
29      return result;
30  }