1import { Actor, log } from 'apify';
2
3import { createCrawler } from './crawler.js';
4import { createRobotsChecker } from './robots.js';
5import { assertPublicHttpUrl, createSafeAgents } from './url-safety.js';
6
7
8await Actor.init();
9
10const input = (await Actor.getInput()) ?? {};
11
12
13const proxyConfiguration = input.proxyConfiguration
14 ? await Actor.createProxyConfiguration(input.proxyConfiguration)
15 : undefined;
16const agents = createSafeAgents({
17 httpAgent: proxyConfiguration?.newProxyAgent?.(),
18 httpsAgent: proxyConfiguration?.newProxyAgent?.(),
19});
20log.info(proxyConfiguration ? 'Using configured proxy' : 'No proxy configured');
21
22
23
24
25function intInRange(value, fallback, min, max, name) {
26 if (value === undefined) return fallback;
27 if (!Number.isInteger(value) || value < min || value > max) {
28 throw new Error(`${name} must be an integer between ${min} and ${max}`);
29 }
30 return value;
31}
32
33const { startUrl, respectRobotsTxt = true, useScope = false, includeSubdomains = false } = input;
34
35if (typeof startUrl !== 'string' || !startUrl) throw new Error('startUrl is required!');
36
37await assertPublicHttpUrl(startUrl);
38
39const maxCrawlDepth = intInRange(input.maxCrawlDepth, 1, 0, 5, 'maxCrawlDepth');
40const maxConcurrency = intInRange(input.maxConcurrency, 50, 1, 100, 'maxConcurrency');
41
42const userAgent = input.userAgent ?? 'Mozilla/5.0 (compatible; ApifyBot/1.0; +https://apify.com/bot)';
43if (typeof userAgent !== 'string' || !userAgent || userAgent.length > 512 || /[\r\n]/.test(userAgent)) {
44 throw new Error('userAgent must be a non-empty string without line breaks (max 512 chars)');
45}
46
47const rawExtensions = input.imageExtensions ?? ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg'];
48if (!Array.isArray(rawExtensions)) throw new Error('imageExtensions must be an array of strings');
49const imageExtensions = [
50 ...new Set(
51 rawExtensions.map((e) => {
52 if (typeof e !== 'string') throw new Error('imageExtensions must be an array of strings');
53 const ext = e.trim().toLowerCase().replace(/^\./, '');
54 if (!/^[a-z0-9]{1,10}$/.test(ext)) throw new Error(`Invalid image extension: ${e}`);
55 return ext;
56 }),
57 ),
58];
59if (!imageExtensions.length) throw new Error('imageExtensions must not be empty');
60
61const rawScope = input.scope ?? [];
62if (!Array.isArray(rawScope)) throw new Error('scope must be an array of domain strings');
63const scope = rawScope.map((d) => {
64 if (typeof d !== 'string') throw new Error('scope must be an array of domain strings');
65 const domain = d
66 .trim()
67 .toLowerCase()
68 .replace(/^https?:\/\//, '')
69 .replace(/\/.*$/, '');
70 if (!/^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(domain)) {
71 throw new Error(`Invalid scope domain: ${d}`);
72 }
73 return domain;
74});
75if (useScope && !scope.length) throw new Error('scope must list at least one domain when useScope is enabled');
76for (const [name, value] of [
77 ['respectRobotsTxt', respectRobotsTxt],
78 ['useScope', useScope],
79 ['includeSubdomains', includeSubdomains],
80]) {
81 if (typeof value !== 'boolean') throw new Error(`${name} must be a boolean`);
82}
83
84log.info('Starting Image URL Scraper', { startUrl, maxCrawlDepth, maxConcurrency });
85
86
87const imageExtensionsSet = new Set(imageExtensions);
88
89const robotsChecker = respectRobotsTxt
90 ? createRobotsChecker({ userAgent, agents })
91 : { getGuard: () => Promise.resolve(null) };
92
93const processedUrls = new Set();
94const requestQueue = await Actor.openRequestQueue();
95
96const { crawlPage } = createCrawler({
97 config: {
98 userAgent,
99 agents,
100 maxCrawlDepth,
101 imageExtensionsSet,
102 useScope,
103 scope,
104 includeSubdomains,
105 },
106 requestQueue,
107 processedUrls,
108 robotsChecker,
109});
110
111await requestQueue.addRequest({ url: startUrl, userData: { depth: 0 } });
112
113
114const workers = Array.from({ length: maxConcurrency }, () =>
115 (async () => {
116 while (true) {
117 const request = await requestQueue.fetchNextRequest();
118 if (!request) break;
119 try {
120 await crawlPage(request);
121 await requestQueue.markRequestHandled(request);
122 } catch (err) {
123 log.error(`Error crawling ${request.url}: ${err.message}`);
124 await requestQueue.markRequestFailed(request);
125 }
126 }
127 })(),
128);
129
130await Promise.all(workers);
131
132log.info('Crawl finished.');
133await Actor.exit();