Edits history of script submission #24309 for ' Web Fetch (apify)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    import { ApifyClient } from 'apify-client@^2.19.0';
    
    type ApifyApiKey = {
      api_key: string;
    };
    
    type Apify = {
      token: string;
    };
    
    const createClient = (api_key?: ApifyApiKey, oauth_token?: Apify): ApifyClient => {
      const token = oauth_token?.token ?? api_key?.api_key;
      if (!token) {
        throw new Error('Missing Apify API key or OAuth token');
      }
    
      return new ApifyClient({
        token: token,
        requestInterceptors: [
          (request) => {
            if (!request.headers) {
              request.headers = {};
            }
            request.headers['x-apify-integration-platform'] = 'windmill';
            return request;
          },
        ],
      });
    };
    
    // constants
    // Standby endpoint of the apify/web-fetch Actor. It answers synchronously, so
    // unlike scrape_single_url there is no run to start and no pollRunStatus.
    const WEB_FETCH_STANDBY_URL = 'https://web-fetch.apify.actor/';
    
    type WebFetchFormat = 'markdown' | 'html' | 'text' | 'links' | 'raw';
    
    const WEB_FETCH_FORMATS: WebFetchFormat[] = ['markdown', 'html', 'text', 'links', 'raw'];
    
    // A standby cold-start plus a slow page can take far longer than the client's
    // 360s default, so the fetch gets the same 10 min budget as the n8n node.
    const WEB_FETCH_TIMEOUT_MS = 10 * 60 * 1000;
    
    // Retries cover only errors of the Apify platform in front of the Actor (429, 5xx). Web Fetch's
    // own errors are final, because the Actor already retries the fetch of the target URL.
    const MAX_RETRIES = 3;
    const RETRY_BACKOFF_MS = 200;
    
    const isValidHostname = (hostname: string): boolean =>
      /^(?=.{1,253}$)((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63}$/.test(hostname);
    
    // apify-client parses JSON by the Content-Type header, and some Web Fetch
    // responses (e.g. 401 for a missing token) have none, so the body stays a Buffer.
    function parseResponseBody(data: unknown): any {
      if (Buffer.isBuffer(data) || typeof data === 'string') {
        try {
          return JSON.parse(data.toString());
        } catch {
          return data;
        }
      }
      return data;
    }
    
    // Web Fetch errors arrive either flat ({ code, error }) or nested
    // ({ error: { message, type } }) for platform errors such as a bad token.
    function getWebFetchErrorMessage(status: number, body: any): string {
      if (body && typeof body === 'object') {
        if (typeof body.error === 'string') {
          return typeof body.code === 'string'
            ? `${body.error} (Web Fetch error code: ${body.code})`
            : body.error;
        }
        if (typeof body.error?.message === 'string') {
          return typeof body.error.type === 'string'
            ? `${body.error.message} (Web Fetch error type: ${body.error.type})`
            : body.error.message;
        }
      }
      return `Web Fetch responded with HTTP status ${status}`;
    }
    
    const isWebFetchError = (body: any): boolean =>
      !!body && typeof body === 'object' && typeof body.code === 'string' && typeof body.error === 'string';
    
    const isRetryable = (status: number, body: any): boolean =>
      (status === 429 || status >= 500) && !isWebFetchError(body);
    
    // -----------------------------------------------------------------------------
    // main logic
    export async function main(
      url: string,
      formats: WebFetchFormat[] = ['markdown'],
      headers?: Record<string, string>,
      api_key?: ApifyApiKey,
      oauth_token?: Apify,
    ) {
      // Reject bad URLs up front instead of leaving the validation to Web Fetch.
      let parsedUrl: URL | undefined;
      try {
        parsedUrl = new URL(url);
      } catch {
        // handled below
      }
      if (
        !parsedUrl ||
        (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') ||
        !isValidHostname(parsedUrl.hostname)
      ) {
        return {
          error: `Invalid URL: "${url}". Provide a full, valid URL including a domain name, e.g. https://example.com.`,
        };
      }
    
      // With no format selected, the formats field is left out and Web Fetch picks
      // one based on the content type.
      if (formats != null && !Array.isArray(formats)) {
        return { error: `Invalid formats. Allowed: ${WEB_FETCH_FORMATS.join(', ')}.` };
      }
      const requestedFormats = formats ?? [];
      const unknownFormats = requestedFormats.filter((format) => !WEB_FETCH_FORMATS.includes(format));
      if (unknownFormats.length > 0) {
        return {
          error: `Unknown format(s): ${unknownFormats.join(', ')}. Allowed: ${WEB_FETCH_FORMATS.join(', ')}.`,
        };
      }
    
      if (
        headers != null &&
        (typeof headers !== 'object' ||
          Array.isArray(headers) ||
          Object.values(headers).some((value) => typeof value !== 'string'))
      ) {
        return {
          error: 'Invalid headers. Provide an object of header names and string values, e.g. {"Accept-Language": "fr-FR"}.',
        };
      }
    
      // The Actor fails the whole fetch on a header without a name, so blank rows are dropped.
      const validHeaders = Object.fromEntries(
        Object.entries(headers ?? {}).filter(([name]) => name.trim()),
      );
    
      const client = createClient(api_key, oauth_token);
    
      try {
        // The client's axios instance carries the token and the integration-platform
        // interceptor, and it does not throw on non-2xx statuses, so Web Fetch's own
        // error body stays readable (ApifyApiError drops the flat { code, error } shape).
        // It skips the client's retry logic, so platform errors are retried here.
        const data = {
          url,
          ...(requestedFormats.length > 0 ? { formats: requestedFormats } : {}),
          ...(Object.keys(validHeaders).length > 0 ? { headers: validHeaders } : {}),
        };
        // All attempts share one time budget, so retries can't stretch the fetch past it.
        const deadline = Date.now() + WEB_FETCH_TIMEOUT_MS;
        let attempt = 0;
        let response;
        let body;
        while (true) {
          response = await client.httpClient.axios.request({
            url: WEB_FETCH_STANDBY_URL,
            method: 'POST',
            data,
            timeout: Math.max(deadline - Date.now(), 1000),
          });
          body = parseResponseBody(response.data);
    
          const backoff = RETRY_BACKOFF_MS * 2 ** attempt;
          if (
            response.status < 300 ||
            attempt >= MAX_RETRIES ||
            !isRetryable(response.status, body) ||
            Date.now() + backoff >= deadline
          ) {
            break;
          }
          await new Promise((resolve) => setTimeout(resolve, backoff));
          attempt += 1;
        }
    
        if (response.status >= 300) {
          return {
            error: `Failed to fetch URL. Reason: ${getWebFetchErrorMessage(response.status, body)}`,
          };
        }
    
        if (!body || typeof body !== 'object' || Array.isArray(body) || Buffer.isBuffer(body)) {
          return { error: 'Failed to fetch URL. Reason: Web Fetch returned an unexpected response.' };
        }
    
        // The envelope (url, fetch, metadata, one key per requested format) is
        // returned verbatim.
        return body;
      } catch (error: any) {
        if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') {
          return {
            error:
              `Fetching ${url} took more than ${WEB_FETCH_TIMEOUT_MS / 1000} seconds. ` +
              'The website may be slow or too large. Try again or use a different URL.',
          };
        }
        return {
          error: `Failed to fetch URL. Reason: ${error.message}`,
        };
      }
    }

    Submitted by jakub.drobnik222 3 hours ago