@ever-works/scrapfly-plugin 1.0.0 → 1.0.3
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.
- package/dist/index.cjs +313 -0
- package/dist/index.d.cts +31 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.js +308 -0
- package/package.json +90 -77
- package/LICENSE +0 -661
- package/src/__tests__/scrapfly.plugin.spec.ts +0 -288
- package/src/index.ts +0 -2
- package/src/scrapfly.plugin.ts +0 -324
- package/tsconfig.json +0 -22
- package/tsup.config.ts +0 -12
|
@@ -1,288 +0,0 @@
|
|
|
1
|
-
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
|
2
|
-
import type { PluginContext, ScreenshotOptions, ContentExtractionOptions } from '@ever-works/plugin';
|
|
3
|
-
|
|
4
|
-
const { scrapeMock, ClientCtorMock, ScrapeConfigCtorMock } = vi.hoisted(() => {
|
|
5
|
-
const scrape = vi.fn();
|
|
6
|
-
const client = vi.fn().mockImplementation(function () {
|
|
7
|
-
return { scrape };
|
|
8
|
-
});
|
|
9
|
-
const scrapeConfig = vi.fn().mockImplementation(function (cfg: unknown) {
|
|
10
|
-
return { __cfg: cfg };
|
|
11
|
-
});
|
|
12
|
-
return { scrapeMock: scrape, ClientCtorMock: client, ScrapeConfigCtorMock: scrapeConfig };
|
|
13
|
-
});
|
|
14
|
-
|
|
15
|
-
vi.mock('scrapfly-sdk', () => ({
|
|
16
|
-
ScrapflyClient: ClientCtorMock,
|
|
17
|
-
ScrapeConfig: ScrapeConfigCtorMock
|
|
18
|
-
}));
|
|
19
|
-
|
|
20
|
-
const { ScrapflyPlugin } = await import('../scrapfly.plugin.js');
|
|
21
|
-
|
|
22
|
-
const buildContext = (settings: Record<string, unknown> = {}): PluginContext =>
|
|
23
|
-
({
|
|
24
|
-
pluginId: 'scrapfly',
|
|
25
|
-
logger: {
|
|
26
|
-
log: vi.fn(),
|
|
27
|
-
debug: vi.fn(),
|
|
28
|
-
warn: vi.fn(),
|
|
29
|
-
error: vi.fn()
|
|
30
|
-
},
|
|
31
|
-
getSettings: vi.fn().mockResolvedValue(settings)
|
|
32
|
-
}) as unknown as PluginContext;
|
|
33
|
-
|
|
34
|
-
describe('ScrapflyPlugin', () => {
|
|
35
|
-
let plugin: ScrapflyPlugin;
|
|
36
|
-
let fetchMock: ReturnType<typeof vi.fn>;
|
|
37
|
-
const originalFetch = globalThis.fetch;
|
|
38
|
-
|
|
39
|
-
beforeEach(() => {
|
|
40
|
-
vi.clearAllMocks();
|
|
41
|
-
plugin = new ScrapflyPlugin();
|
|
42
|
-
fetchMock = vi.fn();
|
|
43
|
-
globalThis.fetch = fetchMock as unknown as typeof fetch;
|
|
44
|
-
});
|
|
45
|
-
|
|
46
|
-
afterEach(() => {
|
|
47
|
-
globalThis.fetch = originalFetch;
|
|
48
|
-
});
|
|
49
|
-
|
|
50
|
-
describe('metadata', () => {
|
|
51
|
-
it('exposes stable identity fields', () => {
|
|
52
|
-
expect(plugin.id).toBe('scrapfly');
|
|
53
|
-
expect(plugin.name).toBe('Scrapfly');
|
|
54
|
-
expect(plugin.version).toBe('1.0.0');
|
|
55
|
-
expect(plugin.category).toBe('content-extractor');
|
|
56
|
-
expect(plugin.providerName).toBe('Scrapfly');
|
|
57
|
-
});
|
|
58
|
-
|
|
59
|
-
it('declares screenshot and content-extractor capabilities', () => {
|
|
60
|
-
expect(plugin.capabilities).toEqual(['screenshot', 'content-extractor']);
|
|
61
|
-
});
|
|
62
|
-
});
|
|
63
|
-
|
|
64
|
-
describe('settingsSchema', () => {
|
|
65
|
-
it('requires apiKey and marks it as user-scoped secret', () => {
|
|
66
|
-
expect(plugin.settingsSchema.required).toContain('apiKey');
|
|
67
|
-
const props = plugin.settingsSchema.properties as Record<string, Record<string, unknown>>;
|
|
68
|
-
expect(props.apiKey['x-secret']).toBe(true);
|
|
69
|
-
expect(props.apiKey['x-envVar']).toBe('PLUGIN_SCRAPFLY_API_KEY');
|
|
70
|
-
});
|
|
71
|
-
});
|
|
72
|
-
|
|
73
|
-
describe('capture (screenshot)', () => {
|
|
74
|
-
const opts = (overrides: Partial<ScreenshotOptions> = {}): ScreenshotOptions => ({
|
|
75
|
-
url: 'https://example.com',
|
|
76
|
-
settings: { apiKey: 'k' },
|
|
77
|
-
...overrides
|
|
78
|
-
});
|
|
79
|
-
|
|
80
|
-
it('rejects when apiKey is missing (getApiKey runs before try/catch)', async () => {
|
|
81
|
-
await expect(plugin.capture({ url: 'https://example.com', settings: {} })).rejects.toThrow(
|
|
82
|
-
/API key not configured/i
|
|
83
|
-
);
|
|
84
|
-
expect(ClientCtorMock).not.toHaveBeenCalled();
|
|
85
|
-
});
|
|
86
|
-
|
|
87
|
-
it('returns success with imageUrl, dimensions, and fileSize', async () => {
|
|
88
|
-
scrapeMock.mockResolvedValueOnce({
|
|
89
|
-
result: {
|
|
90
|
-
screenshots: {
|
|
91
|
-
main: { url: 'https://shot.example/main.png', size: 1234 }
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
});
|
|
95
|
-
const r = await plugin.capture(opts({ viewportWidth: 1920, viewportHeight: 1080 }));
|
|
96
|
-
expect(ClientCtorMock).toHaveBeenCalledWith({ key: 'k' });
|
|
97
|
-
expect(r).toMatchObject({
|
|
98
|
-
success: true,
|
|
99
|
-
imageUrl: 'https://shot.example/main.png',
|
|
100
|
-
width: 1920,
|
|
101
|
-
height: 1080,
|
|
102
|
-
fileSize: 1234
|
|
103
|
-
});
|
|
104
|
-
});
|
|
105
|
-
|
|
106
|
-
it('returns failure when no screenshot data is returned', async () => {
|
|
107
|
-
scrapeMock.mockResolvedValueOnce({ result: { screenshots: {} } });
|
|
108
|
-
const r = await plugin.capture(opts());
|
|
109
|
-
expect(r.success).toBe(false);
|
|
110
|
-
expect(r.error).toMatch(/No screenshot data/);
|
|
111
|
-
});
|
|
112
|
-
|
|
113
|
-
it('returns failure and logs when SDK throws', async () => {
|
|
114
|
-
const ctx = buildContext();
|
|
115
|
-
await plugin.onLoad(ctx);
|
|
116
|
-
scrapeMock.mockRejectedValueOnce(new Error('shot failed'));
|
|
117
|
-
const r = await plugin.capture(opts());
|
|
118
|
-
expect(r.success).toBe(false);
|
|
119
|
-
expect(r.error).toMatch(/shot failed/);
|
|
120
|
-
expect(ctx.logger.error).toHaveBeenCalled();
|
|
121
|
-
});
|
|
122
|
-
});
|
|
123
|
-
|
|
124
|
-
describe('getScreenshotUrl', () => {
|
|
125
|
-
it('returns the imageUrl from a successful capture', async () => {
|
|
126
|
-
scrapeMock.mockResolvedValueOnce({
|
|
127
|
-
result: { screenshots: { main: { url: 'https://shot.example/main.png' } } }
|
|
128
|
-
});
|
|
129
|
-
const url = await plugin.getScreenshotUrl({
|
|
130
|
-
url: 'https://example.com',
|
|
131
|
-
settings: { apiKey: 'k' }
|
|
132
|
-
});
|
|
133
|
-
expect(url).toBe('https://shot.example/main.png');
|
|
134
|
-
});
|
|
135
|
-
|
|
136
|
-
it('returns null when capture fails', async () => {
|
|
137
|
-
scrapeMock.mockResolvedValueOnce({ result: { screenshots: {} } });
|
|
138
|
-
const url = await plugin.getScreenshotUrl({
|
|
139
|
-
url: 'https://example.com',
|
|
140
|
-
settings: { apiKey: 'k' }
|
|
141
|
-
});
|
|
142
|
-
expect(url).toBeNull();
|
|
143
|
-
});
|
|
144
|
-
});
|
|
145
|
-
|
|
146
|
-
describe('isAvailable', () => {
|
|
147
|
-
it('returns false without context', async () => {
|
|
148
|
-
expect(await plugin.isAvailable()).toBe(false);
|
|
149
|
-
});
|
|
150
|
-
|
|
151
|
-
it('reflects whether settings has an apiKey', async () => {
|
|
152
|
-
await plugin.onLoad(buildContext({ apiKey: 'k' }));
|
|
153
|
-
expect(await plugin.isAvailable()).toBe(true);
|
|
154
|
-
|
|
155
|
-
await plugin.onLoad(buildContext({}));
|
|
156
|
-
expect(await plugin.isAvailable()).toBe(false);
|
|
157
|
-
});
|
|
158
|
-
});
|
|
159
|
-
|
|
160
|
-
describe('validateConnection', () => {
|
|
161
|
-
it('fails fast without apiKey', async () => {
|
|
162
|
-
const r = await plugin.validateConnection({});
|
|
163
|
-
expect(r.success).toBe(false);
|
|
164
|
-
expect(r.message).toMatch(/not configured/i);
|
|
165
|
-
expect(fetchMock).not.toHaveBeenCalled();
|
|
166
|
-
});
|
|
167
|
-
|
|
168
|
-
it('returns success on a 200 response', async () => {
|
|
169
|
-
fetchMock.mockResolvedValueOnce({ ok: true, status: 200, statusText: 'OK' } as Response);
|
|
170
|
-
const r = await plugin.validateConnection({ apiKey: 'k' });
|
|
171
|
-
expect(r.success).toBe(true);
|
|
172
|
-
const url = fetchMock.mock.calls[0][0] as string;
|
|
173
|
-
expect(url).toContain('https://api.scrapfly.io/account?key=k');
|
|
174
|
-
});
|
|
175
|
-
|
|
176
|
-
it('returns failure on a non-OK response', async () => {
|
|
177
|
-
fetchMock.mockResolvedValueOnce({
|
|
178
|
-
ok: false,
|
|
179
|
-
status: 401,
|
|
180
|
-
statusText: 'Unauthorized'
|
|
181
|
-
} as Response);
|
|
182
|
-
const r = await plugin.validateConnection({ apiKey: 'k' });
|
|
183
|
-
expect(r.success).toBe(false);
|
|
184
|
-
expect(r.message).toMatch(/401/);
|
|
185
|
-
});
|
|
186
|
-
|
|
187
|
-
it('returns failure when fetch throws', async () => {
|
|
188
|
-
fetchMock.mockRejectedValueOnce(new Error('boom'));
|
|
189
|
-
const r = await plugin.validateConnection({ apiKey: 'k' });
|
|
190
|
-
expect(r.success).toBe(false);
|
|
191
|
-
expect(r.message).toMatch(/boom/);
|
|
192
|
-
});
|
|
193
|
-
});
|
|
194
|
-
|
|
195
|
-
describe('getMaxDimensions', () => {
|
|
196
|
-
it('returns 4K dimensions', () => {
|
|
197
|
-
const d = plugin.getMaxDimensions();
|
|
198
|
-
expect(d).toEqual({ width: 3840, height: 2160 });
|
|
199
|
-
});
|
|
200
|
-
});
|
|
201
|
-
|
|
202
|
-
describe('extract', () => {
|
|
203
|
-
const opts = (overrides: Partial<ContentExtractionOptions> = {}): ContentExtractionOptions => ({
|
|
204
|
-
url: 'https://example.com/post',
|
|
205
|
-
settings: { apiKey: 'k' },
|
|
206
|
-
...overrides
|
|
207
|
-
});
|
|
208
|
-
|
|
209
|
-
it('rejects when apiKey is missing (getApiKey runs before try/catch)', async () => {
|
|
210
|
-
await expect(plugin.extract({ url: 'https://example.com', settings: {} })).rejects.toThrow(
|
|
211
|
-
/API key not configured/i
|
|
212
|
-
);
|
|
213
|
-
});
|
|
214
|
-
|
|
215
|
-
it('returns success with markdown, wordCount, readingTime', async () => {
|
|
216
|
-
scrapeMock.mockResolvedValueOnce({ result: { content: 'one two three four' } });
|
|
217
|
-
const r = await plugin.extract(opts());
|
|
218
|
-
expect(r.success).toBe(true);
|
|
219
|
-
expect(r.markdown).toBe('one two three four');
|
|
220
|
-
expect(r.wordCount).toBe(4);
|
|
221
|
-
expect(r.readingTime).toBe(1);
|
|
222
|
-
});
|
|
223
|
-
|
|
224
|
-
it('returns failure when content is empty', async () => {
|
|
225
|
-
scrapeMock.mockResolvedValueOnce({ result: { content: '' } });
|
|
226
|
-
const r = await plugin.extract(opts());
|
|
227
|
-
expect(r.success).toBe(false);
|
|
228
|
-
expect(r.error).toMatch(/No content/);
|
|
229
|
-
});
|
|
230
|
-
|
|
231
|
-
it('returns failure when SDK throws', async () => {
|
|
232
|
-
scrapeMock.mockRejectedValueOnce(new Error('extract failed'));
|
|
233
|
-
const r = await plugin.extract(opts());
|
|
234
|
-
expect(r.success).toBe(false);
|
|
235
|
-
expect(r.error).toMatch(/extract failed/);
|
|
236
|
-
});
|
|
237
|
-
});
|
|
238
|
-
|
|
239
|
-
describe('extractBatch', () => {
|
|
240
|
-
it('chunks URLs into batches of 5', async () => {
|
|
241
|
-
const urls = Array.from({ length: 6 }, (_, i) => `https://example.com/${i}`);
|
|
242
|
-
for (let i = 0; i < urls.length; i++) {
|
|
243
|
-
scrapeMock.mockResolvedValueOnce({ result: { content: 'a b' } });
|
|
244
|
-
}
|
|
245
|
-
const r = await plugin.extractBatch(urls, { settings: { apiKey: 'k' } });
|
|
246
|
-
expect(r).toHaveLength(6);
|
|
247
|
-
expect(r.every((x) => x.success === true)).toBe(true);
|
|
248
|
-
expect(scrapeMock).toHaveBeenCalledTimes(6);
|
|
249
|
-
});
|
|
250
|
-
});
|
|
251
|
-
|
|
252
|
-
describe('canExtract', () => {
|
|
253
|
-
it('accepts http and https URLs', async () => {
|
|
254
|
-
expect(await plugin.canExtract('https://example.com')).toBe(true);
|
|
255
|
-
expect(await plugin.canExtract('http://example.com')).toBe(true);
|
|
256
|
-
});
|
|
257
|
-
|
|
258
|
-
it('rejects non-http schemes and invalid URLs', async () => {
|
|
259
|
-
expect(await plugin.canExtract('ftp://example.com')).toBe(false);
|
|
260
|
-
expect(await plugin.canExtract('garbage')).toBe(false);
|
|
261
|
-
});
|
|
262
|
-
});
|
|
263
|
-
|
|
264
|
-
describe('lifecycle', () => {
|
|
265
|
-
it('logs on load and clears context on unload', async () => {
|
|
266
|
-
const ctx = buildContext();
|
|
267
|
-
await plugin.onLoad(ctx);
|
|
268
|
-
expect(ctx.logger.log).toHaveBeenCalledWith('Scrapfly Plugin loaded');
|
|
269
|
-
await plugin.onUnload();
|
|
270
|
-
expect(await plugin.isAvailable()).toBe(false);
|
|
271
|
-
});
|
|
272
|
-
});
|
|
273
|
-
|
|
274
|
-
describe('healthCheck + manifest', () => {
|
|
275
|
-
it('reports healthy', async () => {
|
|
276
|
-
const h = await plugin.healthCheck();
|
|
277
|
-
expect(h.status).toBe('healthy');
|
|
278
|
-
});
|
|
279
|
-
|
|
280
|
-
it('returns a manifest aligned with plugin metadata', () => {
|
|
281
|
-
const m = plugin.getManifest();
|
|
282
|
-
expect(m.id).toBe('scrapfly');
|
|
283
|
-
expect(m.category).toBe('content-extractor');
|
|
284
|
-
expect(m.capabilities).toEqual(['screenshot', 'content-extractor']);
|
|
285
|
-
expect(m.builtIn).toBe(true);
|
|
286
|
-
});
|
|
287
|
-
});
|
|
288
|
-
});
|
package/src/index.ts
DELETED
package/src/scrapfly.plugin.ts
DELETED
|
@@ -1,324 +0,0 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
IPlugin,
|
|
3
|
-
IScreenshotPlugin,
|
|
4
|
-
IContentExtractorPlugin,
|
|
5
|
-
PluginContext,
|
|
6
|
-
PluginCategory,
|
|
7
|
-
PluginManifest,
|
|
8
|
-
PluginHealthCheck,
|
|
9
|
-
JsonSchema,
|
|
10
|
-
PluginSettings,
|
|
11
|
-
ScreenshotOptions,
|
|
12
|
-
ScreenshotResult,
|
|
13
|
-
ContentExtractionOptions,
|
|
14
|
-
ContentExtractionResult,
|
|
15
|
-
ConnectionValidationResult
|
|
16
|
-
} from '@ever-works/plugin';
|
|
17
|
-
|
|
18
|
-
import { ScrapflyClient, ScrapeConfig } from 'scrapfly-sdk';
|
|
19
|
-
|
|
20
|
-
// Security (SSRF): shared lexical guard rejecting non-HTTP(S) schemes and
|
|
21
|
-
// literal private/loopback/link-local/cloud-metadata IPs. Imported directly
|
|
22
|
-
// from the helper subpath because the plugin barrel intentionally does not
|
|
23
|
-
// re-export it (it pulls in node:net / node:dns).
|
|
24
|
-
import { isSafeWebhookUrl } from '@ever-works/plugin/helpers/ssrf-guard';
|
|
25
|
-
|
|
26
|
-
const API_KEY_ERROR =
|
|
27
|
-
'Scrapfly API key not configured. Set it in plugin settings or via PLUGIN_SCRAPFLY_API_KEY environment variable.';
|
|
28
|
-
|
|
29
|
-
export class ScrapflyPlugin implements IPlugin, IScreenshotPlugin, IContentExtractorPlugin {
|
|
30
|
-
readonly id = 'scrapfly';
|
|
31
|
-
readonly name = 'Scrapfly';
|
|
32
|
-
readonly version = '1.0.0';
|
|
33
|
-
readonly category: PluginCategory = 'content-extractor';
|
|
34
|
-
readonly capabilities: readonly string[] = ['screenshot', 'content-extractor'];
|
|
35
|
-
readonly providerName = 'Scrapfly';
|
|
36
|
-
|
|
37
|
-
readonly settingsSchema: JsonSchema = {
|
|
38
|
-
type: 'object',
|
|
39
|
-
properties: {
|
|
40
|
-
apiKey: {
|
|
41
|
-
type: 'string',
|
|
42
|
-
title: 'API Key',
|
|
43
|
-
description: 'Your Scrapfly API key. Get one at https://scrapfly.io',
|
|
44
|
-
'x-secret': true,
|
|
45
|
-
'x-envVar': 'PLUGIN_SCRAPFLY_API_KEY',
|
|
46
|
-
'x-scope': 'user'
|
|
47
|
-
}
|
|
48
|
-
},
|
|
49
|
-
required: ['apiKey']
|
|
50
|
-
};
|
|
51
|
-
|
|
52
|
-
readonly configurationMode: 'admin-only' | 'user-required' | 'hybrid' = 'hybrid';
|
|
53
|
-
|
|
54
|
-
private context?: PluginContext;
|
|
55
|
-
|
|
56
|
-
async capture(options: ScreenshotOptions): Promise<ScreenshotResult> {
|
|
57
|
-
// Security (SSRF): `options.url` is attacker-controllable (work source
|
|
58
|
-
// URLs, LLM-generated item URLs) and is forwarded to the Scrapfly
|
|
59
|
-
// backend to render. `canExtract()` validates the scheme but is part of
|
|
60
|
-
// the content-extractor interface and is never invoked on this path, so
|
|
61
|
-
// guard inline here. Block non-HTTP(S) schemes (e.g. gopher://, file://)
|
|
62
|
-
// and literal private/loopback/link-local/cloud-metadata targets (e.g.
|
|
63
|
-
// http://169.254.169.254/...) before building the ScrapeConfig.
|
|
64
|
-
// Legitimate https item URLs are unaffected.
|
|
65
|
-
if (!isSafeWebhookUrl(options.url)) {
|
|
66
|
-
return {
|
|
67
|
-
success: false,
|
|
68
|
-
error: `URL host is not safe to capture (SSRF guard blocked: ${options.url})`
|
|
69
|
-
};
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
const apiKey = this.getApiKey(options.settings);
|
|
73
|
-
|
|
74
|
-
try {
|
|
75
|
-
const client = new ScrapflyClient({ key: apiKey });
|
|
76
|
-
|
|
77
|
-
const width = options.viewportWidth ?? 1280;
|
|
78
|
-
const height = options.viewportHeight ?? 800;
|
|
79
|
-
|
|
80
|
-
const config = new ScrapeConfig({
|
|
81
|
-
url: options.url,
|
|
82
|
-
render_js: true,
|
|
83
|
-
rendering_wait: options.delay ? options.delay : undefined,
|
|
84
|
-
wait_for_selector: options.waitForSelector || undefined,
|
|
85
|
-
screenshots: { main: 'fullpage' },
|
|
86
|
-
country: 'us'
|
|
87
|
-
});
|
|
88
|
-
|
|
89
|
-
const response = await client.scrape(config);
|
|
90
|
-
const screenshotData = response.result.screenshots;
|
|
91
|
-
|
|
92
|
-
if (screenshotData?.main) {
|
|
93
|
-
const screenshotUrl = screenshotData.main.url;
|
|
94
|
-
const fileSize = screenshotData.main.size || undefined;
|
|
95
|
-
|
|
96
|
-
return {
|
|
97
|
-
success: true,
|
|
98
|
-
imageUrl: screenshotUrl,
|
|
99
|
-
width,
|
|
100
|
-
height,
|
|
101
|
-
fileSize
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
return {
|
|
106
|
-
success: false,
|
|
107
|
-
error: 'No screenshot data returned from Scrapfly'
|
|
108
|
-
};
|
|
109
|
-
} catch (error) {
|
|
110
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
111
|
-
this.context?.logger.error(`Scrapfly screenshot failed: ${errorMessage}`);
|
|
112
|
-
|
|
113
|
-
return {
|
|
114
|
-
success: false,
|
|
115
|
-
error: errorMessage
|
|
116
|
-
};
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
async getScreenshotUrl(options: ScreenshotOptions): Promise<string | null> {
|
|
121
|
-
const result = await this.capture(options);
|
|
122
|
-
return result.imageUrl || null;
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
async isAvailable(): Promise<boolean> {
|
|
126
|
-
if (!this.context) return false;
|
|
127
|
-
const settings = await this.context.getSettings();
|
|
128
|
-
return Boolean(settings?.apiKey);
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
async validateConnection(settings: Record<string, unknown>): Promise<ConnectionValidationResult> {
|
|
132
|
-
const apiKey = settings.apiKey as string | undefined;
|
|
133
|
-
if (!apiKey) {
|
|
134
|
-
return { success: false, message: 'Scrapfly API key is not configured.' };
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
try {
|
|
138
|
-
const response = await fetch(`https://api.scrapfly.io/account?key=${apiKey}`);
|
|
139
|
-
|
|
140
|
-
if (!response.ok) {
|
|
141
|
-
return {
|
|
142
|
-
success: false,
|
|
143
|
-
message: `Scrapfly connection failed (${response.status}): ${response.statusText}`
|
|
144
|
-
};
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
return { success: true, message: 'Scrapfly connection verified.' };
|
|
148
|
-
} catch (error) {
|
|
149
|
-
return {
|
|
150
|
-
success: false,
|
|
151
|
-
message: `Scrapfly connection failed: ${error instanceof Error ? error.message : String(error)}`
|
|
152
|
-
};
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
getMaxDimensions(): { width: number; height: number } {
|
|
157
|
-
return { width: 3840, height: 2160 };
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
async extract(options: ContentExtractionOptions): Promise<ContentExtractionResult> {
|
|
161
|
-
const startTime = Date.now();
|
|
162
|
-
|
|
163
|
-
// Security (SSRF): `extract()` relies entirely on the caller invoking
|
|
164
|
-
// `canExtract()` first, which cannot be guaranteed. `options.url` is
|
|
165
|
-
// attacker-controllable (every item's source_url, including URLs the
|
|
166
|
-
// community-PR LLM picks) and is forwarded to Scrapfly to fetch. Refuse
|
|
167
|
-
// non-HTTP(S) schemes and literal private/loopback/link-local/
|
|
168
|
-
// cloud-metadata targets before issuing the scrape. Mirrors
|
|
169
|
-
// local-content-extractor / pdf-extractor. Legitimate https URLs pass.
|
|
170
|
-
if (!isSafeWebhookUrl(options.url)) {
|
|
171
|
-
return {
|
|
172
|
-
success: false,
|
|
173
|
-
url: options.url,
|
|
174
|
-
error: `URL host is not safe to fetch (SSRF guard blocked: ${options.url})`,
|
|
175
|
-
duration: Date.now() - startTime
|
|
176
|
-
};
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
const apiKey = this.getApiKey(options.settings);
|
|
180
|
-
|
|
181
|
-
try {
|
|
182
|
-
const client = new ScrapflyClient({ key: apiKey });
|
|
183
|
-
|
|
184
|
-
const config = new ScrapeConfig({
|
|
185
|
-
url: options.url,
|
|
186
|
-
render_js: options.waitForJs !== false,
|
|
187
|
-
asp: true,
|
|
188
|
-
format: 'markdown',
|
|
189
|
-
country: 'us'
|
|
190
|
-
});
|
|
191
|
-
|
|
192
|
-
const response = await client.scrape(config);
|
|
193
|
-
const content = response.result.content || '';
|
|
194
|
-
|
|
195
|
-
if (!content) {
|
|
196
|
-
return {
|
|
197
|
-
success: false,
|
|
198
|
-
url: options.url,
|
|
199
|
-
error: 'No content returned from Scrapfly',
|
|
200
|
-
duration: Date.now() - startTime
|
|
201
|
-
};
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
const wordCount = content.split(/\s+/).filter((w: string) => w.length > 0).length;
|
|
205
|
-
|
|
206
|
-
return {
|
|
207
|
-
success: true,
|
|
208
|
-
url: options.url,
|
|
209
|
-
content,
|
|
210
|
-
markdown: content,
|
|
211
|
-
duration: Date.now() - startTime,
|
|
212
|
-
wordCount,
|
|
213
|
-
readingTime: Math.ceil(wordCount / 200)
|
|
214
|
-
};
|
|
215
|
-
} catch (error) {
|
|
216
|
-
return {
|
|
217
|
-
success: false,
|
|
218
|
-
url: options.url,
|
|
219
|
-
error: error instanceof Error ? error.message : String(error),
|
|
220
|
-
duration: Date.now() - startTime
|
|
221
|
-
};
|
|
222
|
-
}
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
async extractBatch(
|
|
226
|
-
urls: readonly string[],
|
|
227
|
-
options?: Partial<ContentExtractionOptions>
|
|
228
|
-
): Promise<readonly ContentExtractionResult[]> {
|
|
229
|
-
const batchSize = 5;
|
|
230
|
-
const results: ContentExtractionResult[] = [];
|
|
231
|
-
|
|
232
|
-
for (let i = 0; i < urls.length; i += batchSize) {
|
|
233
|
-
const batch = urls.slice(i, i + batchSize);
|
|
234
|
-
const batchResults = await Promise.all(batch.map((url) => this.extract({ url, ...options })));
|
|
235
|
-
results.push(...batchResults);
|
|
236
|
-
|
|
237
|
-
if (i + batchSize < urls.length) {
|
|
238
|
-
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
return results;
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
async canExtract(url: string): Promise<boolean> {
|
|
246
|
-
try {
|
|
247
|
-
const parsed = new URL(url);
|
|
248
|
-
return parsed.protocol === 'http:' || parsed.protocol === 'https:';
|
|
249
|
-
} catch {
|
|
250
|
-
return false;
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
private getApiKey(settings?: PluginSettings): string {
|
|
255
|
-
const apiKey = settings?.apiKey as string;
|
|
256
|
-
if (!apiKey) {
|
|
257
|
-
throw new Error(API_KEY_ERROR);
|
|
258
|
-
}
|
|
259
|
-
return apiKey;
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
async onLoad(context: PluginContext): Promise<void> {
|
|
263
|
-
this.context = context;
|
|
264
|
-
context.logger.log('Scrapfly Plugin loaded');
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
async onUnload(): Promise<void> {
|
|
268
|
-
this.context = undefined;
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
async healthCheck(): Promise<PluginHealthCheck> {
|
|
272
|
-
return {
|
|
273
|
-
status: 'healthy',
|
|
274
|
-
message: 'Scrapfly plugin is ready (API key required for operations)',
|
|
275
|
-
checkedAt: Date.now()
|
|
276
|
-
};
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
getManifest(): PluginManifest {
|
|
280
|
-
return {
|
|
281
|
-
id: this.id,
|
|
282
|
-
name: this.name,
|
|
283
|
-
version: this.version,
|
|
284
|
-
description: 'Screenshot capture and content extraction using the Scrapfly API',
|
|
285
|
-
category: this.category,
|
|
286
|
-
capabilities: [...this.capabilities],
|
|
287
|
-
author: { name: 'Ever Works Team' },
|
|
288
|
-
license: 'AGPL-3.0',
|
|
289
|
-
builtIn: true,
|
|
290
|
-
systemPlugin: false,
|
|
291
|
-
autoEnable: false,
|
|
292
|
-
homepage: 'https://scrapfly.io',
|
|
293
|
-
icon: {
|
|
294
|
-
type: 'url',
|
|
295
|
-
value: 'https://cdn.scrapfly.io/0.1.156/www/public/favicon.ico?version=0.1.156'
|
|
296
|
-
},
|
|
297
|
-
readme: [
|
|
298
|
-
'## What does Scrapfly do?',
|
|
299
|
-
'',
|
|
300
|
-
'Scrapfly is a web scraping and screenshot API that handles JavaScript rendering, anti-bot bypass, and proxy rotation. It can capture screenshots of any web page and extract content from even heavily protected sites.',
|
|
301
|
-
'',
|
|
302
|
-
'## Why use it?',
|
|
303
|
-
'',
|
|
304
|
-
'- **Anti-bot bypass** — handles CAPTCHAs, JavaScript challenges, and bot detection',
|
|
305
|
-
'- **Screenshot capture** — full-page screenshots with JavaScript rendering',
|
|
306
|
-
'- **Content extraction** — pulls raw HTML from any page, including SPAs',
|
|
307
|
-
'- **Global proxy network** — access region-locked content from any country',
|
|
308
|
-
'',
|
|
309
|
-
'## How it works in Ever Works',
|
|
310
|
-
'',
|
|
311
|
-
'Scrapfly serves dual purposes during work generation: capturing screenshots for item preview images and extracting content from web pages. Its anti-bot capabilities make it effective for scraping sites that block standard HTTP requests.',
|
|
312
|
-
'',
|
|
313
|
-
'## Getting started',
|
|
314
|
-
'',
|
|
315
|
-
'1. Sign up at [scrapfly.io](https://scrapfly.io)',
|
|
316
|
-
'2. Copy your API key from the dashboard',
|
|
317
|
-
'3. Enter the key in the **API Key** field below',
|
|
318
|
-
'4. Enable this plugin for screenshot capture and/or content extraction'
|
|
319
|
-
].join('\n')
|
|
320
|
-
};
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
export default ScrapflyPlugin;
|
package/tsconfig.json
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"compilerOptions": {
|
|
3
|
-
"target": "ES2022",
|
|
4
|
-
"types": ["node"],
|
|
5
|
-
"module": "NodeNext",
|
|
6
|
-
"moduleResolution": "NodeNext",
|
|
7
|
-
"declaration": true,
|
|
8
|
-
"declarationMap": true,
|
|
9
|
-
"sourceMap": true,
|
|
10
|
-
"outDir": "./dist",
|
|
11
|
-
"rootDir": "./src",
|
|
12
|
-
"strict": true,
|
|
13
|
-
"esModuleInterop": true,
|
|
14
|
-
"skipLibCheck": true,
|
|
15
|
-
"forceConsistentCasingInFileNames": true,
|
|
16
|
-
"resolveJsonModule": true,
|
|
17
|
-
"isolatedModules": true,
|
|
18
|
-
"noEmit": true
|
|
19
|
-
},
|
|
20
|
-
"include": ["src/**/*"],
|
|
21
|
-
"exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts"]
|
|
22
|
-
}
|
package/tsup.config.ts
DELETED