@ever-works/scrapfly-plugin 1.0.0

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/README.md ADDED
@@ -0,0 +1,73 @@
1
+ # @ever-works/scrapfly-plugin
2
+
3
+ Scrapfly Plugin - Screenshot capture and content extraction using Scrapfly API
4
+
5
+ ## Plugin metadata
6
+
7
+ | Field | Value |
8
+ | ------------ | --------------------------------- |
9
+ | ID | `scrapfly` |
10
+ | Category | `content-extractor` |
11
+ | Capabilities | `screenshot`, `content-extractor` |
12
+ | Author | Ever Works Team |
13
+ | License | AGPL-3.0 |
14
+ | Built-in | yes |
15
+ | Auto-enable | no |
16
+
17
+ ## What does Scrapfly do?
18
+
19
+ 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.
20
+
21
+ ## Why use it?
22
+
23
+ - **Anti-bot bypass** — handles CAPTCHAs, JavaScript challenges, and bot detection
24
+ - **Screenshot capture** — full-page screenshots with JavaScript rendering
25
+ - **Content extraction** — pulls raw HTML from any page, including SPAs
26
+ - **Global proxy network** — access region-locked content from any country
27
+
28
+ ## How it works in Ever Works
29
+
30
+ 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.
31
+
32
+ ## Getting started
33
+
34
+ 1. Sign up at [scrapfly.io](https://scrapfly.io)
35
+ 2. Copy your API key from the dashboard
36
+ 3. Enter the key in the **API Key** field below
37
+ 4. Enable this plugin for screenshot capture and/or content extraction
38
+
39
+ ## Settings
40
+
41
+ - **API Key** (`apiKey`) — required, secret, user-scoped. Get one at [scrapfly.io](https://scrapfly.io). Backed by env var `PLUGIN_SCRAPFLY_API_KEY`.
42
+
43
+ This plugin uses a `hybrid` configuration mode, so the API key can be supplied at the admin level, the user level, or via the environment variable.
44
+
45
+ ## Troubleshooting
46
+
47
+ | Symptom | Likely cause | Fix |
48
+ | ---------------------------------------------- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
49
+ | `401` / `403` from the extractor | API key / token missing or revoked | Re-enter the credential from the Scrapfly dashboard, or set `PLUGIN_SCRAPFLY_API_KEY` in the host environment for default fallback |
50
+ | `Failed to extract content` for a specific URL | Page requires authentication, JavaScript rendering, or a custom client (Notion, PDF, login wall) | Verify the URL is publicly reachable; if it requires JavaScript/auth, switch to a more capable extractor (`scrapfly` / `notion-extractor` / `pdf-extractor`) for that URL |
51
+ | Plugin not used during extraction | Another content-extractor plugin is set as the default | In **Settings → Plugins**, set `scrapfly` as the default for `content-extractor`, or disable competing plugins |
52
+ | `healthCheck` reports unhealthy | Credential invalid OR Scrapfly endpoint unreachable from the host | Verify the credential with a manual call to the upstream API and confirm outbound HTTPS is allowed by the firewall |
53
+
54
+ ## Local development
55
+
56
+ This plugin ships built-in with the Ever Works platform. To work on it locally from the monorepo root:
57
+
58
+ ```bash
59
+ pnpm install
60
+ pnpm --filter @ever-works/scrapfly-plugin build
61
+ pnpm --filter @ever-works/scrapfly-plugin test
62
+ ```
63
+
64
+ ## Documentation
65
+
66
+ - [Ever Works documentation](https://docs.ever.works)
67
+ - [Ever Works repository](https://github.com/ever-works/ever-works)
68
+ - [Plugin system](../../plugin/README.md)
69
+ - [Scrapfly homepage](https://scrapfly.io)
70
+
71
+ ## License
72
+
73
+ AGPL-3.0
package/package.json ADDED
@@ -0,0 +1,78 @@
1
+ {
2
+ "name": "@ever-works/scrapfly-plugin",
3
+ "version": "1.0.0",
4
+ "description": "Scrapfly Plugin - Screenshot capture and content extraction using Scrapfly API",
5
+ "author": {
6
+ "name": "Ever Co. LTD",
7
+ "email": "ever@ever.co",
8
+ "url": "https://ever.co"
9
+ },
10
+ "license": "AGPL-3.0",
11
+ "private": false,
12
+ "type": "module",
13
+ "main": "./dist/index.cjs",
14
+ "module": "./dist/index.js",
15
+ "types": "./dist/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js",
20
+ "require": "./dist/index.cjs"
21
+ }
22
+ },
23
+ "dependencies": {
24
+ "scrapfly-sdk": "^0.7.3"
25
+ },
26
+ "peerDependencies": {
27
+ "@ever-works/plugin": "1.1.0"
28
+ },
29
+ "devDependencies": {
30
+ "@types/node": "^22.0.0",
31
+ "tsup": "^8.4.0",
32
+ "typescript": "^5.7.3",
33
+ "vitest": "^4.1.0",
34
+ "@ever-works/plugin": "1.1.0"
35
+ },
36
+ "everworks": {
37
+ "plugin": {
38
+ "id": "scrapfly",
39
+ "name": "Scrapfly",
40
+ "version": "1.0.0",
41
+ "category": "content-extractor",
42
+ "capabilities": [
43
+ "screenshot",
44
+ "content-extractor"
45
+ ],
46
+ "description": "Screenshot capture and content extraction using the Scrapfly API. Supports JavaScript rendering, anti-bot bypass, and multiple output formats.",
47
+ "author": {
48
+ "name": "Ever Works Team"
49
+ },
50
+ "license": "AGPL-3.0",
51
+ "autoEnable": false,
52
+ "systemPlugin": false,
53
+ "builtIn": true,
54
+ "envVars": [
55
+ {
56
+ "name": "PLUGIN_SCRAPFLY_API_KEY",
57
+ "required": false,
58
+ "secret": true,
59
+ "description": "Scrapfly API key (optional - can be set via admin/user settings)"
60
+ }
61
+ ],
62
+ "distribution": "registry"
63
+ }
64
+ },
65
+ "publishConfig": {
66
+ "access": "restricted",
67
+ "registry": "https://registry.npmjs.org"
68
+ },
69
+ "scripts": {
70
+ "build": "tsc --noEmit && tsup",
71
+ "dev": "tsup --watch",
72
+ "type-check": "tsc --noEmit",
73
+ "clean": "rm -rf dist",
74
+ "test": "vitest run --passWithNoTests",
75
+ "test:watch": "vitest",
76
+ "test:coverage": "vitest run --coverage"
77
+ }
78
+ }
@@ -0,0 +1,288 @@
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 ADDED
@@ -0,0 +1,2 @@
1
+ export { ScrapflyPlugin } from './scrapfly.plugin.js';
2
+ export { ScrapflyPlugin as default } from './scrapfly.plugin.js';