scrapfly-sdk 0.11.1 → 0.12.1
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 +72 -5
- package/esm/browserconfig.d.ts +57 -9
- package/esm/browserconfig.d.ts.map +1 -1
- package/esm/browserconfig.js +63 -5
- package/esm/browserdownloads.d.ts +70 -0
- package/esm/browserdownloads.d.ts.map +1 -0
- package/esm/browserdownloads.js +215 -0
- package/esm/client.d.ts +224 -8
- package/esm/client.d.ts.map +1 -1
- package/esm/client.js +646 -62
- package/esm/crawl.d.ts +83 -1
- package/esm/crawl.d.ts.map +1 -1
- package/esm/crawl.js +73 -0
- package/esm/crawlerconfig.d.ts +54 -3
- package/esm/crawlerconfig.d.ts.map +1 -1
- package/esm/crawlerconfig.js +96 -2
- package/esm/crawlerresult.d.ts +374 -2
- package/esm/crawlerresult.d.ts.map +1 -1
- package/esm/crawlerresult.js +367 -1
- package/esm/errors.d.ts +12 -0
- package/esm/errors.d.ts.map +1 -1
- package/esm/errors.js +11 -0
- package/esm/main.d.ts +12 -7
- package/esm/main.d.ts.map +1 -1
- package/esm/main.js +10 -5
- package/esm/monitoringconfig.d.ts +2 -2
- package/esm/result.d.ts +11 -1
- package/esm/result.d.ts.map +1 -1
- package/esm/result.js +14 -5
- package/esm/scrapeconfig.d.ts +65 -1
- package/esm/scrapeconfig.d.ts.map +1 -1
- package/esm/scrapeconfig.js +88 -4
- package/esm/screenshotconfig.d.ts +9 -1
- package/esm/screenshotconfig.d.ts.map +1 -1
- package/esm/screenshotconfig.js +12 -1
- package/esm/types.d.ts +128 -0
- package/esm/types.d.ts.map +1 -1
- package/esm/types.js +22 -1
- package/esm/utils.d.ts.map +1 -1
- package/esm/utils.js +16 -2
- package/esm/webhookserver.d.ts +33 -15
- package/esm/webhookserver.d.ts.map +1 -1
- package/esm/webhookserver.js +197 -38
- package/package.json +1 -1
- package/script/browserconfig.d.ts +57 -9
- package/script/browserconfig.d.ts.map +1 -1
- package/script/browserconfig.js +63 -5
- package/script/browserdownloads.d.ts +70 -0
- package/script/browserdownloads.d.ts.map +1 -0
- package/script/browserdownloads.js +221 -0
- package/script/client.d.ts +224 -8
- package/script/client.d.ts.map +1 -1
- package/script/client.js +645 -61
- package/script/crawl.d.ts +83 -1
- package/script/crawl.d.ts.map +1 -1
- package/script/crawl.js +73 -0
- package/script/crawlerconfig.d.ts +54 -3
- package/script/crawlerconfig.d.ts.map +1 -1
- package/script/crawlerconfig.js +97 -3
- package/script/crawlerresult.d.ts +374 -2
- package/script/crawlerresult.d.ts.map +1 -1
- package/script/crawlerresult.js +374 -2
- package/script/errors.d.ts +12 -0
- package/script/errors.d.ts.map +1 -1
- package/script/errors.js +12 -1
- package/script/main.d.ts +12 -7
- package/script/main.d.ts.map +1 -1
- package/script/main.js +20 -4
- package/script/monitoringconfig.d.ts +2 -2
- package/script/result.d.ts +11 -1
- package/script/result.d.ts.map +1 -1
- package/script/result.js +14 -5
- package/script/scrapeconfig.d.ts +65 -1
- package/script/scrapeconfig.d.ts.map +1 -1
- package/script/scrapeconfig.js +88 -4
- package/script/screenshotconfig.d.ts +9 -1
- package/script/screenshotconfig.d.ts.map +1 -1
- package/script/screenshotconfig.js +12 -1
- package/script/types.d.ts +128 -0
- package/script/types.d.ts.map +1 -1
- package/script/types.js +23 -0
- package/script/utils.d.ts.map +1 -1
- package/script/utils.js +16 -2
- package/script/webhookserver.d.ts +33 -15
- package/script/webhookserver.d.ts.map +1 -1
- package/script/webhookserver.js +197 -38
- package/src/browserconfig.ts +74 -8
- package/src/browserdownloads.ts +266 -0
- package/src/client.ts +796 -65
- package/src/crawl.ts +106 -0
- package/src/crawlerconfig.ts +128 -5
- package/src/crawlerresult.ts +607 -3
- package/src/errors.ts +12 -0
- package/src/main.ts +55 -5
- package/src/monitoringconfig.ts +2 -2
- package/src/result.ts +17 -5
- package/src/scrapeconfig.ts +92 -3
- package/src/screenshotconfig.ts +14 -1
- package/src/types.ts +159 -1
- package/src/utils.ts +16 -2
- package/src/webhookserver.ts +235 -39
package/esm/client.js
CHANGED
|
@@ -5,9 +5,21 @@ import * as errors from './errors.js';
|
|
|
5
5
|
import { BrowserConfig } from './browserconfig.js';
|
|
6
6
|
import { ExtractionResult, ScrapeResult, ScreenshotResult } from './result.js';
|
|
7
7
|
import { log } from './logger.js';
|
|
8
|
-
import {
|
|
8
|
+
import { REFRESH_MAX_INTERVAL, REFRESH_MIN_INTERVAL } from './crawlerconfig.js';
|
|
9
|
+
import { CrawlerArtifact, CrawlerContents, CrawlerSearchResponse, CrawlerStatus, CrawlerUrls, parseCrawlerPromptStream, parseCrawlerRefreshState, } from './crawlerresult.js';
|
|
9
10
|
import { formatMonitoringDate, } from './monitoringconfig.js';
|
|
10
11
|
import { ScheduleAPIError, } from './schedule.js';
|
|
12
|
+
/** ERR::<RESOURCE>::* → error-class taxonomy. */
|
|
13
|
+
const RESOURCE_TO_ERROR = {
|
|
14
|
+
SCRAPE: errors.ScrapflyScrapeError,
|
|
15
|
+
WEBHOOK: errors.ScrapflyWebhookError,
|
|
16
|
+
PROXY: errors.ScrapflyProxyError,
|
|
17
|
+
SCHEDULE: errors.ScrapflyScheduleError,
|
|
18
|
+
ASP: errors.ScrapflyAspError,
|
|
19
|
+
SESSION: errors.ScrapflySessionError,
|
|
20
|
+
THROTTLE: errors.ScrapflyThrottleError,
|
|
21
|
+
CRAWLER: errors.ScrapflyCrawlerError,
|
|
22
|
+
};
|
|
11
23
|
/**
|
|
12
24
|
* Main entry point for the Scrapfly SDK.
|
|
13
25
|
*
|
|
@@ -122,21 +134,9 @@ export class ScrapflyClient {
|
|
|
122
134
|
case 429:
|
|
123
135
|
return new errors.TooManyRequests(message, args);
|
|
124
136
|
}
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
case 'WEBHOOK':
|
|
129
|
-
return new errors.ScrapflyWebhookError(message, args);
|
|
130
|
-
case 'PROXY':
|
|
131
|
-
return new errors.ScrapflyProxyError(message, args);
|
|
132
|
-
case 'SCHEDULE':
|
|
133
|
-
return new errors.ScrapflyScheduleError(message, args);
|
|
134
|
-
case 'ASP':
|
|
135
|
-
return new errors.ScrapflyAspError(message, args);
|
|
136
|
-
case 'SESSION':
|
|
137
|
-
return new errors.ScrapflySessionError(message, args);
|
|
138
|
-
case 'CRAWLER':
|
|
139
|
-
return new errors.ScrapflyCrawlerError(message, args);
|
|
137
|
+
const ResourceError = args.resource ? RESOURCE_TO_ERROR[args.resource] : undefined;
|
|
138
|
+
if (ResourceError) {
|
|
139
|
+
return new ResourceError(message, args);
|
|
140
140
|
}
|
|
141
141
|
if (args.resource) {
|
|
142
142
|
return new errors.ApiHttpClientError(message, args);
|
|
@@ -151,25 +151,48 @@ export class ScrapflyClient {
|
|
|
151
151
|
return new errors.UpstreamHttpServerError(message, args);
|
|
152
152
|
}
|
|
153
153
|
}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
case 'WEBHOOK':
|
|
158
|
-
return new errors.ScrapflyWebhookError(message, args);
|
|
159
|
-
case 'PROXY':
|
|
160
|
-
return new errors.ScrapflyProxyError(message, args);
|
|
161
|
-
case 'SCHEDULE':
|
|
162
|
-
return new errors.ScrapflyScheduleError(message, args);
|
|
163
|
-
case 'ASP':
|
|
164
|
-
return new errors.ScrapflyAspError(message, args);
|
|
165
|
-
case 'SESSION':
|
|
166
|
-
return new errors.ScrapflySessionError(message, args);
|
|
167
|
-
case 'CRAWLER':
|
|
168
|
-
return new errors.ScrapflyCrawlerError(message, args);
|
|
154
|
+
const ResourceError = args.resource ? RESOURCE_TO_ERROR[args.resource] : undefined;
|
|
155
|
+
if (ResourceError) {
|
|
156
|
+
return new ResourceError(message, args);
|
|
169
157
|
}
|
|
170
158
|
}
|
|
171
159
|
return new errors.ScrapflyError(message, args);
|
|
172
160
|
}
|
|
161
|
+
/** Build the typed per-part error for an API-generated batch error body. */
|
|
162
|
+
batchApiErrorPartToError(parsed, partHeaders) {
|
|
163
|
+
const code = typeof parsed.code === 'string' ? parsed.code : '';
|
|
164
|
+
const message = String(parsed.message ?? parsed.reason ?? 'API error');
|
|
165
|
+
const httpStatusCode = typeof parsed.http_code === 'number'
|
|
166
|
+
? parsed.http_code
|
|
167
|
+
: parseInt(partHeaders['x-scrapfly-scrape-status'] ?? '500', 10) || 500;
|
|
168
|
+
const isRetryable = parsed.retryable === true;
|
|
169
|
+
let documentationUrl;
|
|
170
|
+
if (parsed.links && typeof parsed.links === 'object' && !Array.isArray(parsed.links)) {
|
|
171
|
+
const values = Object.values(parsed.links);
|
|
172
|
+
if (values.length)
|
|
173
|
+
documentationUrl = values[0];
|
|
174
|
+
}
|
|
175
|
+
const args = {
|
|
176
|
+
code,
|
|
177
|
+
http_status_code: httpStatusCode,
|
|
178
|
+
is_retryable: isRetryable,
|
|
179
|
+
resource: code ? code.split('::')[1] : null,
|
|
180
|
+
documentation_url: documentationUrl,
|
|
181
|
+
};
|
|
182
|
+
const ResourceError = args.resource ? RESOURCE_TO_ERROR[args.resource] : undefined;
|
|
183
|
+
if (ResourceError) {
|
|
184
|
+
return new ResourceError(message, args);
|
|
185
|
+
}
|
|
186
|
+
switch (httpStatusCode) {
|
|
187
|
+
case 401:
|
|
188
|
+
return new errors.BadApiKeyError(message, args);
|
|
189
|
+
case 429:
|
|
190
|
+
return new errors.TooManyRequests(message, args);
|
|
191
|
+
}
|
|
192
|
+
return httpStatusCode >= 500
|
|
193
|
+
? new errors.ApiHttpServerError(message, args)
|
|
194
|
+
: new errors.ApiHttpClientError(message, args);
|
|
195
|
+
}
|
|
173
196
|
/**
|
|
174
197
|
* Handle clob and blob large objects
|
|
175
198
|
*/
|
|
@@ -177,8 +200,7 @@ export class ScrapflyClient {
|
|
|
177
200
|
let response;
|
|
178
201
|
try {
|
|
179
202
|
const url = new URL(result.content);
|
|
180
|
-
|
|
181
|
-
url.search = new URLSearchParams(params).toString();
|
|
203
|
+
url.searchParams.set('key', this.key);
|
|
182
204
|
response = await this.fetch({
|
|
183
205
|
url: url.toString(),
|
|
184
206
|
method: 'GET',
|
|
@@ -193,6 +215,20 @@ export class ScrapflyClient {
|
|
|
193
215
|
log.error('error', e);
|
|
194
216
|
throw e;
|
|
195
217
|
}
|
|
218
|
+
if (!response.ok) {
|
|
219
|
+
const body = await response.text();
|
|
220
|
+
let parsed = null;
|
|
221
|
+
try {
|
|
222
|
+
parsed = JSON.parse(body);
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
// Not an API error: a proxy's page, say.
|
|
226
|
+
}
|
|
227
|
+
const envelope = parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
|
|
228
|
+
? parsed
|
|
229
|
+
: { message: body.slice(0, 500) || response.statusText };
|
|
230
|
+
throw this.batchApiErrorPartToError(envelope, { 'x-scrapfly-scrape-status': String(response.status) });
|
|
231
|
+
}
|
|
196
232
|
let content;
|
|
197
233
|
if (format === 'clob') {
|
|
198
234
|
content = await response.text();
|
|
@@ -211,7 +247,8 @@ export class ScrapflyClient {
|
|
|
211
247
|
handleResponse(response, result) {
|
|
212
248
|
// success
|
|
213
249
|
log.debug('scrape log url: ', result.result.log_url);
|
|
214
|
-
|
|
250
|
+
// QUEUED: a scrape with a webhook, delivered to it later.
|
|
251
|
+
if (result.result.status === 'QUEUED' || (result.result.status === 'DONE' && result.result.success === true)) {
|
|
215
252
|
return result;
|
|
216
253
|
}
|
|
217
254
|
// something went wrong
|
|
@@ -631,6 +668,12 @@ export class ScrapflyClient {
|
|
|
631
668
|
// Drop `key` (batch key is in the URL).
|
|
632
669
|
const params = cfg.toApiParams({ key: this.key });
|
|
633
670
|
delete params.key;
|
|
671
|
+
// What a single scrape sends as the request itself: the API reads
|
|
672
|
+
// both keys of a batch entry and runs a GET without them.
|
|
673
|
+
params.method = cfg.method;
|
|
674
|
+
if (cfg.body !== undefined) {
|
|
675
|
+
params.body = cfg.body;
|
|
676
|
+
}
|
|
634
677
|
bodyConfigs.push(params);
|
|
635
678
|
}
|
|
636
679
|
const url = new URL(this.HOST + '/scrape/batch');
|
|
@@ -690,12 +733,26 @@ export class ScrapflyClient {
|
|
|
690
733
|
];
|
|
691
734
|
continue;
|
|
692
735
|
}
|
|
736
|
+
// API-generated error parts carry status >= 400 and an error body
|
|
737
|
+
// instead of the scrape envelope — surface them as typed errors.
|
|
738
|
+
const partStatus = parseInt(part.headers['x-scrapfly-scrape-status'] ?? '0', 10) || 0;
|
|
739
|
+
if (partStatus >= 400 &&
|
|
740
|
+
parsed &&
|
|
741
|
+
typeof parsed === 'object' &&
|
|
742
|
+
!Array.isArray(parsed) &&
|
|
743
|
+
!('result' in parsed) &&
|
|
744
|
+
!('config' in parsed)) {
|
|
745
|
+
yield [correlationId, this.batchApiErrorPartToError(parsed, part.headers)];
|
|
746
|
+
continue;
|
|
747
|
+
}
|
|
693
748
|
try {
|
|
749
|
+
// A config with a webhook is answered by its enqueue ack, the scrape's answer under `result`.
|
|
750
|
+
const envelope = parsed.enqueued === true && parsed.result ? parsed.result : parsed;
|
|
694
751
|
const result = new ScrapeResult({
|
|
695
|
-
config:
|
|
696
|
-
context:
|
|
697
|
-
result:
|
|
698
|
-
uuid:
|
|
752
|
+
config: envelope.config,
|
|
753
|
+
context: envelope.context,
|
|
754
|
+
result: envelope.result,
|
|
755
|
+
uuid: envelope.uuid,
|
|
699
756
|
});
|
|
700
757
|
yield [correlationId, result];
|
|
701
758
|
}
|
|
@@ -713,7 +770,7 @@ export class ScrapflyClient {
|
|
|
713
770
|
* Save screenshot response to a file
|
|
714
771
|
*/
|
|
715
772
|
async saveScreenshot(result, name, savePath) {
|
|
716
|
-
if (!result.image) {
|
|
773
|
+
if (!result.image || result.image.byteLength === 0) {
|
|
717
774
|
throw new Error('Screenshot binary does not exist');
|
|
718
775
|
}
|
|
719
776
|
const extension_name = result.metadata.extension_name;
|
|
@@ -733,23 +790,39 @@ export class ScrapflyClient {
|
|
|
733
790
|
* Turn scrapfly screenshot API response to ScreenshotResult or raise one of ScrapflyError
|
|
734
791
|
*/
|
|
735
792
|
async handleScreenshotResponse(response) {
|
|
736
|
-
// A
|
|
737
|
-
//
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
793
|
+
// A JSON answer is never an image: an error, or the 201 of a screenshot with a webhook.
|
|
794
|
+
// A Response body can only be consumed once, so it is read as text and parsed from that.
|
|
795
|
+
const isJson = (response.headers.get('content-type') ?? '').startsWith('application/json');
|
|
796
|
+
if (isJson || response.status === 201) {
|
|
797
|
+
const text = await response.text();
|
|
798
|
+
let jsonData = null;
|
|
799
|
+
try {
|
|
800
|
+
const parsed = JSON.parse(text);
|
|
801
|
+
if (parsed !== null && typeof parsed === 'object') {
|
|
802
|
+
jsonData = parsed;
|
|
803
|
+
}
|
|
745
804
|
}
|
|
746
|
-
|
|
747
|
-
|
|
805
|
+
catch {
|
|
806
|
+
jsonData = null;
|
|
807
|
+
}
|
|
808
|
+
const message = jsonData ? JSON.stringify(jsonData) : text || `API returned status ${response.status}`;
|
|
809
|
+
if (response.status == 401 || jsonData?.http_code == 401) {
|
|
810
|
+
throw new errors.BadApiKeyError(message);
|
|
811
|
+
}
|
|
812
|
+
if (jsonData) {
|
|
813
|
+
if ('error_id' in jsonData) {
|
|
814
|
+
throw new errors.ScreenshotApiError(JSON.stringify(jsonData));
|
|
815
|
+
}
|
|
816
|
+
// 201: a screenshot with a webhook, delivered to it later.
|
|
817
|
+
const job = jsonData.job_uuid;
|
|
818
|
+
if (response.status === 201 && jsonData.webhook_enqueued === true && typeof job === 'string' && job !== '') {
|
|
819
|
+
return new ScreenshotResult(response, new ArrayBuffer(0), job);
|
|
820
|
+
}
|
|
748
821
|
}
|
|
822
|
+
throw new errors.ScreenshotApiError(message);
|
|
749
823
|
}
|
|
750
824
|
if (!response.ok) {
|
|
751
|
-
|
|
752
|
-
throw new errors.ScreenshotApiError(typeof body === 'string' ? body : JSON.stringify(body));
|
|
825
|
+
throw new errors.ScreenshotApiError((await response.text()) || `API returned status ${response.status}`);
|
|
753
826
|
}
|
|
754
827
|
const data = await response.arrayBuffer();
|
|
755
828
|
const result = new ScreenshotResult(response, data);
|
|
@@ -851,7 +924,8 @@ export class ScrapflyClient {
|
|
|
851
924
|
throwCrawlerError(response, data) {
|
|
852
925
|
const httpCode = data.http_code ?? response.status;
|
|
853
926
|
const code = (data.code ?? '');
|
|
854
|
-
|
|
927
|
+
// The engine relays its own failures as `{error, code}`.
|
|
928
|
+
const message = data.message ?? (typeof data.error === 'string' ? data.error : JSON.stringify(data));
|
|
855
929
|
if (httpCode === 401) {
|
|
856
930
|
throw new errors.BadApiKeyError(message, { http_status_code: httpCode, code, api_response: data });
|
|
857
931
|
}
|
|
@@ -890,7 +964,7 @@ export class ScrapflyClient {
|
|
|
890
964
|
if (urlList !== undefined) {
|
|
891
965
|
// Strip url_list from the JSON config — the URLs go through the
|
|
892
966
|
// 'urls' multipart part instead, which the API gateway streams
|
|
893
|
-
// straight through to the
|
|
967
|
+
// straight through to the scraping backend.
|
|
894
968
|
delete params.url_list;
|
|
895
969
|
const form = new FormData();
|
|
896
970
|
const configBlob = new Blob([JSON.stringify(params)], { type: 'application/json' });
|
|
@@ -1257,6 +1331,319 @@ export class ScrapflyClient {
|
|
|
1257
1331
|
}
|
|
1258
1332
|
return response.ok;
|
|
1259
1333
|
}
|
|
1334
|
+
/**
|
|
1335
|
+
* Run one refresh of an existing crawl immediately, without waiting for the
|
|
1336
|
+
* next scheduled period.
|
|
1337
|
+
*
|
|
1338
|
+
* `POST /crawl/{uuid}/refresh` re-scrapes the crawl's own URLs in place:
|
|
1339
|
+
* same `crawler_uuid`, same artifacts, same search index. Only pages whose
|
|
1340
|
+
* content actually changed are re-indexed and pages that disappeared are
|
|
1341
|
+
* dropped, so everything already pointing at this crawl keeps working.
|
|
1342
|
+
*
|
|
1343
|
+
* A refresh bills the pages it re-scrapes, exactly like the original crawl.
|
|
1344
|
+
* What unchanged pages save is the embedding and the index write.
|
|
1345
|
+
*
|
|
1346
|
+
* The call returns as soon as the run is accepted; poll `crawlStatus` or
|
|
1347
|
+
* `crawlRefreshHistory` for the outcome. Do not retry it blindly: a retry
|
|
1348
|
+
* starts a second re-scrape of the whole site.
|
|
1349
|
+
*/
|
|
1350
|
+
async crawlRefreshNow(uuid) {
|
|
1351
|
+
if (!uuid) {
|
|
1352
|
+
throw new errors.ScrapflyCrawlerError('uuid must be a non-empty string');
|
|
1353
|
+
}
|
|
1354
|
+
let response;
|
|
1355
|
+
try {
|
|
1356
|
+
const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/refresh`);
|
|
1357
|
+
url.search = new URLSearchParams({ key: this.key }).toString();
|
|
1358
|
+
// One attempt: the server may have accepted the billable refresh even
|
|
1359
|
+
// when its response is lost or replaced by a gateway error.
|
|
1360
|
+
response = await this.fetch({
|
|
1361
|
+
url: url.toString(),
|
|
1362
|
+
method: 'POST',
|
|
1363
|
+
headers: {
|
|
1364
|
+
'user-agent': this.ua,
|
|
1365
|
+
'accept-encoding': 'gzip, deflate, br',
|
|
1366
|
+
accept: 'application/json',
|
|
1367
|
+
},
|
|
1368
|
+
}, 1);
|
|
1369
|
+
}
|
|
1370
|
+
catch (e) {
|
|
1371
|
+
log.error('error', e);
|
|
1372
|
+
throw e;
|
|
1373
|
+
}
|
|
1374
|
+
const data = (await response.json());
|
|
1375
|
+
if ('error_id' in data || data.http_code !== undefined) {
|
|
1376
|
+
this.throwCrawlerError(response, data);
|
|
1377
|
+
}
|
|
1378
|
+
return parseCrawlerRefreshState(data);
|
|
1379
|
+
}
|
|
1380
|
+
/**
|
|
1381
|
+
* Change the refresh schedule of an existing crawl.
|
|
1382
|
+
*
|
|
1383
|
+
* `PATCH /crawl/{uuid}/refresh` — only the fields passed are changed, so
|
|
1384
|
+
* turning a crawl off keeps its interval for when it is turned back on.
|
|
1385
|
+
*
|
|
1386
|
+
* Turning refresh on for a crawl started without it is allowed: the crawl
|
|
1387
|
+
* already holds the URL index a refresh walks.
|
|
1388
|
+
*/
|
|
1389
|
+
async crawlRefreshSettings(uuid, settings) {
|
|
1390
|
+
if (!uuid) {
|
|
1391
|
+
throw new errors.ScrapflyCrawlerError('uuid must be a non-empty string');
|
|
1392
|
+
}
|
|
1393
|
+
if (settings?.enabled === undefined && settings?.interval_seconds === undefined) {
|
|
1394
|
+
throw new errors.ScrapflyCrawlerError('pass at least one of enabled, interval_seconds');
|
|
1395
|
+
}
|
|
1396
|
+
if (settings.interval_seconds !== undefined &&
|
|
1397
|
+
(settings.interval_seconds < REFRESH_MIN_INTERVAL || settings.interval_seconds > REFRESH_MAX_INTERVAL)) {
|
|
1398
|
+
throw new errors.ScrapflyCrawlerError(`interval_seconds must be between ${REFRESH_MIN_INTERVAL} and ${REFRESH_MAX_INTERVAL} seconds`);
|
|
1399
|
+
}
|
|
1400
|
+
// Wire keys are the ones POST /crawl already takes, so a crawl body and a
|
|
1401
|
+
// later PATCH name the same things. The enabled/interval_seconds spelling
|
|
1402
|
+
// belongs to the state block this call answers with, not to its request;
|
|
1403
|
+
// the API decodes the body with unknown fields rejected.
|
|
1404
|
+
const payload = {};
|
|
1405
|
+
if (settings.enabled !== undefined)
|
|
1406
|
+
payload.refresh = settings.enabled;
|
|
1407
|
+
if (settings.interval_seconds !== undefined)
|
|
1408
|
+
payload.refresh_interval = settings.interval_seconds;
|
|
1409
|
+
let response;
|
|
1410
|
+
try {
|
|
1411
|
+
const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/refresh`);
|
|
1412
|
+
url.search = new URLSearchParams({ key: this.key }).toString();
|
|
1413
|
+
response = await this.fetch({
|
|
1414
|
+
url: url.toString(),
|
|
1415
|
+
method: 'PATCH',
|
|
1416
|
+
headers: {
|
|
1417
|
+
'user-agent': this.ua,
|
|
1418
|
+
'content-type': 'application/json',
|
|
1419
|
+
'accept-encoding': 'gzip, deflate, br',
|
|
1420
|
+
accept: 'application/json',
|
|
1421
|
+
},
|
|
1422
|
+
body: JSON.stringify(payload),
|
|
1423
|
+
});
|
|
1424
|
+
}
|
|
1425
|
+
catch (e) {
|
|
1426
|
+
log.error('error', e);
|
|
1427
|
+
throw e;
|
|
1428
|
+
}
|
|
1429
|
+
const data = (await response.json());
|
|
1430
|
+
if ('error_id' in data || data.http_code !== undefined) {
|
|
1431
|
+
this.throwCrawlerError(response, data);
|
|
1432
|
+
}
|
|
1433
|
+
return parseCrawlerRefreshState(data);
|
|
1434
|
+
}
|
|
1435
|
+
/**
|
|
1436
|
+
* Read a crawl's refresh timeline, newest last.
|
|
1437
|
+
*
|
|
1438
|
+
* `GET /crawl/{uuid}/refresh/history` — the server keeps the 50 most recent
|
|
1439
|
+
* runs; older rows are trimmed rather than paged, because the timeline
|
|
1440
|
+
* exists to show recent activity.
|
|
1441
|
+
*/
|
|
1442
|
+
async crawlRefreshHistory(uuid, opts) {
|
|
1443
|
+
if (!uuid) {
|
|
1444
|
+
throw new errors.ScrapflyCrawlerError('uuid must be a non-empty string');
|
|
1445
|
+
}
|
|
1446
|
+
let response;
|
|
1447
|
+
try {
|
|
1448
|
+
const url = new URL(`${this.HOST}/crawl/${encodeURIComponent(uuid)}/refresh/history`);
|
|
1449
|
+
const params = { key: this.key };
|
|
1450
|
+
if (opts?.limit !== undefined)
|
|
1451
|
+
params.limit = String(opts.limit);
|
|
1452
|
+
url.search = new URLSearchParams(params).toString();
|
|
1453
|
+
response = await this.fetch({
|
|
1454
|
+
url: url.toString(),
|
|
1455
|
+
method: 'GET',
|
|
1456
|
+
headers: {
|
|
1457
|
+
'user-agent': this.ua,
|
|
1458
|
+
'accept-encoding': 'gzip, deflate, br',
|
|
1459
|
+
accept: 'application/json',
|
|
1460
|
+
},
|
|
1461
|
+
});
|
|
1462
|
+
}
|
|
1463
|
+
catch (e) {
|
|
1464
|
+
log.error('error', e);
|
|
1465
|
+
throw e;
|
|
1466
|
+
}
|
|
1467
|
+
const data = (await response.json());
|
|
1468
|
+
if ('error_id' in data || data.http_code !== undefined) {
|
|
1469
|
+
this.throwCrawlerError(response, data);
|
|
1470
|
+
}
|
|
1471
|
+
return parseCrawlerRefreshState(data).history ?? [];
|
|
1472
|
+
}
|
|
1473
|
+
/**
|
|
1474
|
+
* Search across the search indexes of one or more crawls.
|
|
1475
|
+
*
|
|
1476
|
+
* `POST /crawl/search`: the collection endpoint is the real API and
|
|
1477
|
+
* {@link crawl.Crawl.search} is sugar over a one-element list so the two
|
|
1478
|
+
* cannot drift.
|
|
1479
|
+
*
|
|
1480
|
+
* Only crawls started with `search: true` whose index reached `READY` or
|
|
1481
|
+
* `PARTIAL` contribute. The rest come back in `skipped` with a reason and
|
|
1482
|
+
* never fail the call, so inspect `skipped` before concluding a crawl had
|
|
1483
|
+
* no match.
|
|
1484
|
+
*/
|
|
1485
|
+
async crawlSearch(crawlIds, query, opts) {
|
|
1486
|
+
if (!Array.isArray(crawlIds) || crawlIds.length === 0) {
|
|
1487
|
+
throw new errors.ScrapflyCrawlerError('crawl_ids must contain at least one crawler UUID');
|
|
1488
|
+
}
|
|
1489
|
+
if (!query) {
|
|
1490
|
+
throw new errors.ScrapflyCrawlerError('query must be a non-empty string');
|
|
1491
|
+
}
|
|
1492
|
+
const payload = { query, crawl_ids: crawlIds };
|
|
1493
|
+
if (opts?.limit !== undefined)
|
|
1494
|
+
payload.limit = opts.limit;
|
|
1495
|
+
if (opts?.mode !== undefined)
|
|
1496
|
+
payload.mode = opts.mode;
|
|
1497
|
+
if (opts?.filters !== undefined)
|
|
1498
|
+
payload.filters = opts.filters;
|
|
1499
|
+
if (opts?.cursor !== undefined)
|
|
1500
|
+
payload.cursor = opts.cursor;
|
|
1501
|
+
let response;
|
|
1502
|
+
try {
|
|
1503
|
+
const url = new URL(`${this.HOST}/crawl/search`);
|
|
1504
|
+
url.search = new URLSearchParams({ key: this.key }).toString();
|
|
1505
|
+
response = await this.fetch({
|
|
1506
|
+
url: url.toString(),
|
|
1507
|
+
method: 'POST',
|
|
1508
|
+
headers: {
|
|
1509
|
+
'user-agent': this.ua,
|
|
1510
|
+
'content-type': 'application/json',
|
|
1511
|
+
'accept-encoding': 'gzip, deflate, br',
|
|
1512
|
+
accept: 'application/json',
|
|
1513
|
+
},
|
|
1514
|
+
body: JSON.stringify(payload),
|
|
1515
|
+
});
|
|
1516
|
+
}
|
|
1517
|
+
catch (e) {
|
|
1518
|
+
log.error('error', e);
|
|
1519
|
+
throw e;
|
|
1520
|
+
}
|
|
1521
|
+
const data = (await response.json());
|
|
1522
|
+
if ('error_id' in data || data.http_code !== undefined) {
|
|
1523
|
+
this.throwCrawlerError(response, data);
|
|
1524
|
+
}
|
|
1525
|
+
return new CrawlerSearchResponse(data);
|
|
1526
|
+
}
|
|
1527
|
+
/**
|
|
1528
|
+
* Ask a question answered from the content of one or more crawls, streaming
|
|
1529
|
+
* the answer as it is generated.
|
|
1530
|
+
*
|
|
1531
|
+
* `POST /crawl/prompt`: the collection endpoint is the real API and
|
|
1532
|
+
* {@link crawl.Crawl.prompt} is sugar over a one-element list.
|
|
1533
|
+
*
|
|
1534
|
+
* Yields `source` frames, then `token` frames, then one `done`. An
|
|
1535
|
+
* `event: error` frame is thrown as `ScrapflyCrawlerError` rather than
|
|
1536
|
+
* yielded, and can arrive after tokens were already yielded because
|
|
1537
|
+
* generation fails mid-stream.
|
|
1538
|
+
*
|
|
1539
|
+
* Consume with `for await`; abandoning the iterator early cancels the body.
|
|
1540
|
+
*
|
|
1541
|
+
* Do not consume this with `EventSource`: it reconnects on close and would
|
|
1542
|
+
* silently re-run the whole fan-out and generation.
|
|
1543
|
+
*/
|
|
1544
|
+
async *crawlPrompt(crawlIds, prompt, opts) {
|
|
1545
|
+
if (!Array.isArray(crawlIds) || crawlIds.length === 0) {
|
|
1546
|
+
throw new errors.ScrapflyCrawlerError('crawl_ids must contain at least one crawler UUID');
|
|
1547
|
+
}
|
|
1548
|
+
if (!prompt) {
|
|
1549
|
+
throw new errors.ScrapflyCrawlerError('prompt must be a non-empty string');
|
|
1550
|
+
}
|
|
1551
|
+
const generation = { stream: true };
|
|
1552
|
+
if (opts?.model !== undefined)
|
|
1553
|
+
generation.model = opts.model;
|
|
1554
|
+
const payload = { prompt, crawl_ids: crawlIds, generation };
|
|
1555
|
+
if (opts?.search !== undefined)
|
|
1556
|
+
payload.search = opts.search;
|
|
1557
|
+
const url = new URL(`${this.HOST}/crawl/prompt`);
|
|
1558
|
+
url.search = new URLSearchParams({ key: this.key }).toString();
|
|
1559
|
+
// One attempt only: the request runs a fan-out and a generation, both
|
|
1560
|
+
// billable, so a retry doubles the bill.
|
|
1561
|
+
const response = await this.fetch({
|
|
1562
|
+
url: url.toString(),
|
|
1563
|
+
method: 'POST',
|
|
1564
|
+
headers: {
|
|
1565
|
+
'user-agent': this.ua,
|
|
1566
|
+
'content-type': 'application/json',
|
|
1567
|
+
accept: 'text/event-stream',
|
|
1568
|
+
},
|
|
1569
|
+
body: JSON.stringify(payload),
|
|
1570
|
+
}, 1);
|
|
1571
|
+
if (!response.ok) {
|
|
1572
|
+
const data = (await response.json().catch(() => ({})));
|
|
1573
|
+
this.throwCrawlerError(response, data);
|
|
1574
|
+
}
|
|
1575
|
+
if (response.body === null) {
|
|
1576
|
+
throw new errors.ScrapflyCrawlerError('prompt response carried no body');
|
|
1577
|
+
}
|
|
1578
|
+
yield* parseCrawlerPromptStream(response.body);
|
|
1579
|
+
}
|
|
1580
|
+
/**
|
|
1581
|
+
* Ask a question answered from the content of one or more crawls, and get
|
|
1582
|
+
* the whole answer in one object once generation completes.
|
|
1583
|
+
*
|
|
1584
|
+
* `POST /crawl/prompt` with `generation.stream: false`: the same facts as
|
|
1585
|
+
* the frames of {@link crawlPrompt}. {@link crawl.Crawl.promptAnswer} is
|
|
1586
|
+
* sugar over a one-element list.
|
|
1587
|
+
*/
|
|
1588
|
+
async crawlPromptAnswer(crawlIds, prompt, opts) {
|
|
1589
|
+
if (!Array.isArray(crawlIds) || crawlIds.length === 0) {
|
|
1590
|
+
throw new errors.ScrapflyCrawlerError('crawl_ids must contain at least one crawler UUID');
|
|
1591
|
+
}
|
|
1592
|
+
if (!prompt) {
|
|
1593
|
+
throw new errors.ScrapflyCrawlerError('prompt must be a non-empty string');
|
|
1594
|
+
}
|
|
1595
|
+
const generation = { stream: false };
|
|
1596
|
+
if (opts?.model !== undefined)
|
|
1597
|
+
generation.model = opts.model;
|
|
1598
|
+
const payload = { prompt, crawl_ids: crawlIds, generation };
|
|
1599
|
+
if (opts?.search !== undefined)
|
|
1600
|
+
payload.search = opts.search;
|
|
1601
|
+
return (await this.postCrawlerJson('/crawl/prompt', payload));
|
|
1602
|
+
}
|
|
1603
|
+
/**
|
|
1604
|
+
* Extract a structured object from the content of one or more crawls.
|
|
1605
|
+
*
|
|
1606
|
+
* `POST /crawl/extract` retrieves like {@link crawlPromptAnswer} and answers
|
|
1607
|
+
* with `data` shaped by `schema`, a JSON Schema handed to the model as its
|
|
1608
|
+
* response schema. There is no streaming variant. {@link crawl.Crawl.extract}
|
|
1609
|
+
* is sugar over a one-element list.
|
|
1610
|
+
*/
|
|
1611
|
+
async crawlExtract(crawlIds, prompt, schema, opts) {
|
|
1612
|
+
if (!Array.isArray(crawlIds) || crawlIds.length === 0) {
|
|
1613
|
+
throw new errors.ScrapflyCrawlerError('crawl_ids must contain at least one crawler UUID');
|
|
1614
|
+
}
|
|
1615
|
+
if (!prompt) {
|
|
1616
|
+
throw new errors.ScrapflyCrawlerError('prompt must be a non-empty string');
|
|
1617
|
+
}
|
|
1618
|
+
if (typeof schema !== 'object' || schema === null || Array.isArray(schema) || Object.keys(schema).length === 0) {
|
|
1619
|
+
throw new errors.ScrapflyCrawlerError('schema must be a non-empty JSON Schema object');
|
|
1620
|
+
}
|
|
1621
|
+
const payload = { prompt, crawl_ids: crawlIds, schema };
|
|
1622
|
+
if (opts?.search !== undefined)
|
|
1623
|
+
payload.search = opts.search;
|
|
1624
|
+
return (await this.postCrawlerJson('/crawl/extract', payload));
|
|
1625
|
+
}
|
|
1626
|
+
/** POST a JSON body to a crawler endpoint that generates, once, and return its JSON answer. */
|
|
1627
|
+
async postCrawlerJson(path, payload) {
|
|
1628
|
+
const url = new URL(`${this.HOST}${path}`);
|
|
1629
|
+
url.search = new URLSearchParams({ key: this.key }).toString();
|
|
1630
|
+
// One attempt only: a retry re-runs the fan-out and the generation.
|
|
1631
|
+
const response = await this.fetch({
|
|
1632
|
+
url: url.toString(),
|
|
1633
|
+
method: 'POST',
|
|
1634
|
+
headers: {
|
|
1635
|
+
'user-agent': this.ua,
|
|
1636
|
+
'content-type': 'application/json',
|
|
1637
|
+
accept: 'application/json',
|
|
1638
|
+
},
|
|
1639
|
+
body: JSON.stringify(payload),
|
|
1640
|
+
}, 1);
|
|
1641
|
+
if (!response.ok) {
|
|
1642
|
+
const data = (await response.json().catch(() => ({})));
|
|
1643
|
+
this.throwCrawlerError(response, data);
|
|
1644
|
+
}
|
|
1645
|
+
return (await response.json());
|
|
1646
|
+
}
|
|
1260
1647
|
// --- Cloud Browser ---
|
|
1261
1648
|
/**
|
|
1262
1649
|
* Get the WebSocket URL for a Cloud Browser session.
|
|
@@ -1271,18 +1658,29 @@ export class ScrapflyClient {
|
|
|
1271
1658
|
}
|
|
1272
1659
|
/**
|
|
1273
1660
|
* Return the deterministic project salt for this client's api_key. Matches
|
|
1274
|
-
* the `X-Browser-Project-Salt` response header returned on
|
|
1275
|
-
* Cloud Browser
|
|
1661
|
+
* the `X-Browser-Project-Salt` response header returned on VNC-enabled
|
|
1662
|
+
* Cloud Browser upgrades, where the salt is also the VNC password prefix.
|
|
1276
1663
|
*/
|
|
1277
1664
|
async cloudBrowserProjectSalt() {
|
|
1278
1665
|
return BrowserConfig.projectSalt(this.key);
|
|
1279
1666
|
}
|
|
1667
|
+
/**
|
|
1668
|
+
* Return the password a native VNC client must type to attach to a session
|
|
1669
|
+
* created with `config`: `<projectSalt>-<vnc_password>`.
|
|
1670
|
+
*
|
|
1671
|
+
* Copy this value into your VNC client when connecting to the TCP endpoint
|
|
1672
|
+
* (port 5901). The WebSocket endpoint `/run/<run_id>/vnc` takes the raw
|
|
1673
|
+
* `vnc_password` instead.
|
|
1674
|
+
*/
|
|
1675
|
+
async cloudBrowserVncPassword(config) {
|
|
1676
|
+
return config.vncClientPassword(this.key);
|
|
1677
|
+
}
|
|
1280
1678
|
/**
|
|
1281
1679
|
* Call the Cloud Browser Unblock API.
|
|
1282
1680
|
*
|
|
1283
1681
|
* Unblock always uses a residential proxy (no proxy pool selection) and
|
|
1284
1682
|
* always performs a GET — the endpoint's purpose is to harvest cookies /
|
|
1285
|
-
* clearance tokens via an
|
|
1683
|
+
* clearance tokens via an Unblocker navigation, not to proxy arbitrary
|
|
1286
1684
|
* HTTP requests.
|
|
1287
1685
|
*/
|
|
1288
1686
|
async cloudBrowserUnblock(options) {
|
|
@@ -1435,12 +1833,12 @@ export class ScrapflyClient {
|
|
|
1435
1833
|
return await response.json();
|
|
1436
1834
|
}
|
|
1437
1835
|
// ----- Cloud Browser Credential Vault -------------------------------------
|
|
1438
|
-
// Server contract documented
|
|
1836
|
+
// Server contract documented in the Vault API reference.
|
|
1439
1837
|
//
|
|
1440
1838
|
// SECURITY: the vault key is the customer-held secret that decrypts every
|
|
1441
1839
|
// item in the vault. The server emits it ONCE on POST /vault and POST
|
|
1442
1840
|
// /vault/{id}/rotate; never log it, never include it in error messages,
|
|
1443
|
-
// never put it in a breadcrumb
|
|
1841
|
+
// never put it in a breadcrumb, and never echo it back to a caller.
|
|
1444
1842
|
/**
|
|
1445
1843
|
* Create a new Cloud Browser Credential Vault. The response contains a
|
|
1446
1844
|
* one-time `key` that the caller MUST save locally — the server cannot
|
|
@@ -1679,6 +2077,183 @@ export class ScrapflyClient {
|
|
|
1679
2077
|
message: typeof body.message === 'string' ? body.message : '',
|
|
1680
2078
|
};
|
|
1681
2079
|
}
|
|
2080
|
+
// ----- Vault ↔ linked secret manager (1Password) ---------------------------
|
|
2081
|
+
// A linked vault mirrors an upstream secret manager instead of holding
|
|
2082
|
+
// operator-entered items. The provider's service-account token is sealed
|
|
2083
|
+
// under the vault key like any other secret, so every endpoint that carries
|
|
2084
|
+
// a token also carries X-Vault-Key: the server verifies the key BEFORE
|
|
2085
|
+
// sealing, because a well-formed wrong key would link the vault and leave a
|
|
2086
|
+
// token every later sync fails to open.
|
|
2087
|
+
/**
|
|
2088
|
+
* Link a vault to a secret manager. The token is sealed under `vaultKey`, so
|
|
2089
|
+
* the key is mandatory here. The vault must not already be linked and must
|
|
2090
|
+
* hold no rows owned by a previous service (the server answers 409).
|
|
2091
|
+
*/
|
|
2092
|
+
async cloudBrowserVaultServiceLink(vaultId, vaultKey, link) {
|
|
2093
|
+
if (!link.token) {
|
|
2094
|
+
throw new Error('cloudBrowserVaultServiceLink: token is required when linking a service');
|
|
2095
|
+
}
|
|
2096
|
+
// Same rule as the server's linked_service_data validation; caught here so a
|
|
2097
|
+
// malformed link does not cost a round trip.
|
|
2098
|
+
if (!link.linked_service_data?.vault_id && !link.linked_service_data?.vault_name) {
|
|
2099
|
+
throw new Error('cloudBrowserVaultServiceLink: linked_service_data requires vault_id or vault_name');
|
|
2100
|
+
}
|
|
2101
|
+
const url = new URL(this.cloudBrowserApiHost + '/vault/' + encodeURIComponent(vaultId) + '/service');
|
|
2102
|
+
url.searchParams.set('key', this.key);
|
|
2103
|
+
const response = await this.fetch({
|
|
2104
|
+
url: url.toString(),
|
|
2105
|
+
method: 'POST',
|
|
2106
|
+
headers: {
|
|
2107
|
+
'content-type': 'application/json',
|
|
2108
|
+
'user-agent': this.ua,
|
|
2109
|
+
'X-Vault-Key': vaultKey,
|
|
2110
|
+
},
|
|
2111
|
+
body: JSON.stringify({
|
|
2112
|
+
linked_service: link.linked_service,
|
|
2113
|
+
token: link.token,
|
|
2114
|
+
linked_service_data: link.linked_service_data,
|
|
2115
|
+
}),
|
|
2116
|
+
});
|
|
2117
|
+
if (!response.ok) {
|
|
2118
|
+
throw new Error(`Vault service link failed: ${response.status} ${await response.text()}`);
|
|
2119
|
+
}
|
|
2120
|
+
return await response.json();
|
|
2121
|
+
}
|
|
2122
|
+
/**
|
|
2123
|
+
* Update a link: edit the non-secret selection rules, rotate the token, or
|
|
2124
|
+
* both. `vaultKey` is required only when `token` is supplied, mirroring
|
|
2125
|
+
* `cloudBrowserVaultItemUpdate`; a config-only edit needs no key.
|
|
2126
|
+
*
|
|
2127
|
+
* A token rotation also clears the server's one-hour auth back-off, so a link
|
|
2128
|
+
* broken by a dead token syncs again on the next round.
|
|
2129
|
+
*/
|
|
2130
|
+
async cloudBrowserVaultServiceUpdate(vaultId, opts) {
|
|
2131
|
+
if (opts.token !== undefined && opts.token !== '' && (opts.vaultKey === undefined || opts.vaultKey === '')) {
|
|
2132
|
+
throw new Error('cloudBrowserVaultServiceUpdate: vaultKey is required when rotating the service token');
|
|
2133
|
+
}
|
|
2134
|
+
const url = new URL(this.cloudBrowserApiHost + '/vault/' + encodeURIComponent(vaultId) + '/service');
|
|
2135
|
+
url.searchParams.set('key', this.key);
|
|
2136
|
+
const body = {};
|
|
2137
|
+
if (opts.token !== undefined)
|
|
2138
|
+
body.token = opts.token;
|
|
2139
|
+
if (opts.linked_service_data !== undefined)
|
|
2140
|
+
body.linked_service_data = opts.linked_service_data;
|
|
2141
|
+
const headers = {
|
|
2142
|
+
'content-type': 'application/json',
|
|
2143
|
+
'user-agent': this.ua,
|
|
2144
|
+
};
|
|
2145
|
+
if (opts.vaultKey !== undefined && opts.vaultKey !== '') {
|
|
2146
|
+
headers['X-Vault-Key'] = opts.vaultKey;
|
|
2147
|
+
}
|
|
2148
|
+
const response = await this.fetch({
|
|
2149
|
+
url: url.toString(),
|
|
2150
|
+
method: 'PATCH',
|
|
2151
|
+
headers,
|
|
2152
|
+
body: JSON.stringify(body),
|
|
2153
|
+
});
|
|
2154
|
+
if (!response.ok) {
|
|
2155
|
+
throw new Error(`Vault service update failed: ${response.status} ${await response.text()}`);
|
|
2156
|
+
}
|
|
2157
|
+
return await response.json();
|
|
2158
|
+
}
|
|
2159
|
+
/**
|
|
2160
|
+
* Unlink the provider. `keepItems` governs only the mirrored rows — kept as
|
|
2161
|
+
* plain manual items, or deleted — while the sealed token is removed either
|
|
2162
|
+
* way, so no vault key is needed.
|
|
2163
|
+
*
|
|
2164
|
+
* Dropping the rows is irreversible, so the default is to keep them and the
|
|
2165
|
+
* flag always goes on the wire explicitly rather than relying on a default at
|
|
2166
|
+
* either end.
|
|
2167
|
+
*/
|
|
2168
|
+
async cloudBrowserVaultServiceUnlink(vaultId, opts = {}) {
|
|
2169
|
+
const url = new URL(this.cloudBrowserApiHost + '/vault/' + encodeURIComponent(vaultId) + '/service');
|
|
2170
|
+
url.searchParams.set('key', this.key);
|
|
2171
|
+
url.searchParams.set('keep_items', (opts.keepItems ?? true) ? 'true' : 'false');
|
|
2172
|
+
const response = await this.fetch({
|
|
2173
|
+
url: url.toString(),
|
|
2174
|
+
method: 'DELETE',
|
|
2175
|
+
headers: { 'user-agent': this.ua },
|
|
2176
|
+
});
|
|
2177
|
+
if (!response.ok) {
|
|
2178
|
+
throw new Error(`Vault service unlink failed: ${response.status} ${await response.text()}`);
|
|
2179
|
+
}
|
|
2180
|
+
const body = await response.json();
|
|
2181
|
+
return {
|
|
2182
|
+
success: body.success !== undefined ? Boolean(body.success) : true,
|
|
2183
|
+
message: typeof body.message === 'string' ? body.message : '',
|
|
2184
|
+
};
|
|
2185
|
+
}
|
|
2186
|
+
/**
|
|
2187
|
+
* Force a reconcile against the provider now, bypassing the sync TTL and the
|
|
2188
|
+
* back-off a failed round leaves behind. Requires the vault key: the server
|
|
2189
|
+
* opens the sealed token with it and re-seals every mirrored row.
|
|
2190
|
+
*
|
|
2191
|
+
* The server budget is 25s; the SDK pins no per-call timeout, so the runtime's
|
|
2192
|
+
* own fetch default applies.
|
|
2193
|
+
*/
|
|
2194
|
+
async cloudBrowserVaultServiceSync(vaultId, vaultKey) {
|
|
2195
|
+
const url = new URL(this.cloudBrowserApiHost + '/vault/' + encodeURIComponent(vaultId) + '/service/sync');
|
|
2196
|
+
url.searchParams.set('key', this.key);
|
|
2197
|
+
const response = await this.fetch({
|
|
2198
|
+
url: url.toString(),
|
|
2199
|
+
method: 'POST',
|
|
2200
|
+
headers: {
|
|
2201
|
+
'user-agent': this.ua,
|
|
2202
|
+
'X-Vault-Key': vaultKey,
|
|
2203
|
+
},
|
|
2204
|
+
});
|
|
2205
|
+
if (!response.ok) {
|
|
2206
|
+
throw new Error(`Vault service sync failed: ${response.status} ${await response.text()}`);
|
|
2207
|
+
}
|
|
2208
|
+
return await response.json();
|
|
2209
|
+
}
|
|
2210
|
+
/**
|
|
2211
|
+
* Probe the provider: proves a token is live and lists the upstream vaults it
|
|
2212
|
+
* can read. Writes nothing, so it never moves the vault's sync state.
|
|
2213
|
+
*
|
|
2214
|
+
* With no `token` the sealed token of an existing link is probed (the vault
|
|
2215
|
+
* key opens it). Passing an unsaved `token` instead enumerates the upstream
|
|
2216
|
+
* vaults BEFORE a link exists, which is how a caller picks `vault_id`.
|
|
2217
|
+
*
|
|
2218
|
+
* `linkedService` stays optional and undefaulted here: this is the one endpoint
|
|
2219
|
+
* whose empty discriminator the server itself resolves to 1Password, and a
|
|
2220
|
+
* client-side default would send a field the bodyless stored-token path must
|
|
2221
|
+
* not carry.
|
|
2222
|
+
*
|
|
2223
|
+
* The server budget is 10s; the SDK pins no per-call timeout, so the runtime's
|
|
2224
|
+
* own fetch default applies.
|
|
2225
|
+
*/
|
|
2226
|
+
async cloudBrowserVaultServiceTest(vaultId, vaultKey, opts = {}) {
|
|
2227
|
+
const url = new URL(this.cloudBrowserApiHost + '/vault/' + encodeURIComponent(vaultId) + '/service/test');
|
|
2228
|
+
url.searchParams.set('key', this.key);
|
|
2229
|
+
const headers = {
|
|
2230
|
+
'user-agent': this.ua,
|
|
2231
|
+
'X-Vault-Key': vaultKey,
|
|
2232
|
+
};
|
|
2233
|
+
// A bodyless request is what selects the stored-token path server-side, so
|
|
2234
|
+
// send a body only when the caller supplied something to probe with.
|
|
2235
|
+
let body;
|
|
2236
|
+
if (opts.token !== undefined || opts.linkedService !== undefined) {
|
|
2237
|
+
const payload = {};
|
|
2238
|
+
if (opts.linkedService !== undefined)
|
|
2239
|
+
payload.linked_service = opts.linkedService;
|
|
2240
|
+
if (opts.token !== undefined)
|
|
2241
|
+
payload.token = opts.token;
|
|
2242
|
+
body = JSON.stringify(payload);
|
|
2243
|
+
headers['content-type'] = 'application/json';
|
|
2244
|
+
}
|
|
2245
|
+
const response = await this.fetch({
|
|
2246
|
+
url: url.toString(),
|
|
2247
|
+
method: 'POST',
|
|
2248
|
+
headers,
|
|
2249
|
+
body,
|
|
2250
|
+
});
|
|
2251
|
+
if (!response.ok) {
|
|
2252
|
+
throw new Error(`Vault service test failed: ${response.status} ${await response.text()}`);
|
|
2253
|
+
}
|
|
2254
|
+
const json = await response.json();
|
|
2255
|
+
return { ...json, vaults_visible: json.vaults_visible ?? [] };
|
|
2256
|
+
}
|
|
1682
2257
|
/**
|
|
1683
2258
|
* Download a debug session recording video.
|
|
1684
2259
|
* Returns the video as an ArrayBuffer (stream from server).
|
|
@@ -1759,7 +2334,12 @@ export class ScrapflyClient {
|
|
|
1759
2334
|
// pause/resume/execute methods work regardless of kind.
|
|
1760
2335
|
// -------------------------------------------------------------------------
|
|
1761
2336
|
/** Create a Web Scraping API schedule. `scrape_config` is the same shape
|
|
1762
|
-
* accepted by `/scrape` (e.g. `{ url, render_js, asp, ... }`).
|
|
2337
|
+
* accepted by `/scrape` (e.g. `{ url, render_js, asp, ... }`). This dict is
|
|
2338
|
+
* forwarded to the API verbatim, so its keys are wire keys, not the SDK
|
|
2339
|
+
* option names. The anti-bot bypass may be spelled either way here: the API
|
|
2340
|
+
* folds `unblocker` into `asp` on the STORED config, with the same precedence
|
|
2341
|
+
* the SDK uses (a supplied `asp` wins; `unblocker` is read only when `asp` is
|
|
2342
|
+
* absent, `null` or `""`), so both names reach the replayed scrape. */
|
|
1763
2343
|
async createScrapeSchedule(scrapeConfig, request) {
|
|
1764
2344
|
return await this.scheduleRequest('POST', '/scrape/schedules', undefined, this.buildCreateBody('scrape_config', scrapeConfig, request));
|
|
1765
2345
|
}
|
|
@@ -1767,7 +2347,11 @@ export class ScrapflyClient {
|
|
|
1767
2347
|
async createScreenshotSchedule(screenshotConfig, request) {
|
|
1768
2348
|
return await this.scheduleRequest('POST', '/screenshot/schedules', undefined, this.buildCreateBody('screenshot_config', screenshotConfig, request));
|
|
1769
2349
|
}
|
|
1770
|
-
/** Create a Crawler API schedule.
|
|
2350
|
+
/** Create a Crawler API schedule. `crawler_config` is forwarded verbatim and
|
|
2351
|
+
* its keys are wire keys, not the SDK option names. As with
|
|
2352
|
+
* `createScrapeSchedule`, the anti-bot bypass may be spelled `asp` or
|
|
2353
|
+
* `unblocker`: the API folds the alias into `asp` on the stored config before
|
|
2354
|
+
* it is ever replayed. */
|
|
1771
2355
|
async createCrawlerSchedule(crawlerConfig, request) {
|
|
1772
2356
|
return await this.scheduleRequest('POST', '/crawl/schedules', undefined, this.buildCreateBody('crawler_config', crawlerConfig, request));
|
|
1773
2357
|
}
|
|
@@ -1775,7 +2359,7 @@ export class ScrapflyClient {
|
|
|
1775
2359
|
async getSchedule(id) {
|
|
1776
2360
|
return await this.scheduleRequest('GET', `/schedules/${encodeURIComponent(id)}`);
|
|
1777
2361
|
}
|
|
1778
|
-
/** List
|
|
2362
|
+
/** List the schedules of the API key's project and environment, optionally filtered by kind/status. */
|
|
1779
2363
|
async listSchedules(opts) {
|
|
1780
2364
|
return await this.scheduleRequest('GET', '/schedules', opts);
|
|
1781
2365
|
}
|