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.
Files changed (101) hide show
  1. package/README.md +72 -5
  2. package/esm/browserconfig.d.ts +57 -9
  3. package/esm/browserconfig.d.ts.map +1 -1
  4. package/esm/browserconfig.js +63 -5
  5. package/esm/browserdownloads.d.ts +70 -0
  6. package/esm/browserdownloads.d.ts.map +1 -0
  7. package/esm/browserdownloads.js +215 -0
  8. package/esm/client.d.ts +224 -8
  9. package/esm/client.d.ts.map +1 -1
  10. package/esm/client.js +646 -62
  11. package/esm/crawl.d.ts +83 -1
  12. package/esm/crawl.d.ts.map +1 -1
  13. package/esm/crawl.js +73 -0
  14. package/esm/crawlerconfig.d.ts +54 -3
  15. package/esm/crawlerconfig.d.ts.map +1 -1
  16. package/esm/crawlerconfig.js +96 -2
  17. package/esm/crawlerresult.d.ts +374 -2
  18. package/esm/crawlerresult.d.ts.map +1 -1
  19. package/esm/crawlerresult.js +367 -1
  20. package/esm/errors.d.ts +12 -0
  21. package/esm/errors.d.ts.map +1 -1
  22. package/esm/errors.js +11 -0
  23. package/esm/main.d.ts +12 -7
  24. package/esm/main.d.ts.map +1 -1
  25. package/esm/main.js +10 -5
  26. package/esm/monitoringconfig.d.ts +2 -2
  27. package/esm/result.d.ts +11 -1
  28. package/esm/result.d.ts.map +1 -1
  29. package/esm/result.js +14 -5
  30. package/esm/scrapeconfig.d.ts +65 -1
  31. package/esm/scrapeconfig.d.ts.map +1 -1
  32. package/esm/scrapeconfig.js +88 -4
  33. package/esm/screenshotconfig.d.ts +9 -1
  34. package/esm/screenshotconfig.d.ts.map +1 -1
  35. package/esm/screenshotconfig.js +12 -1
  36. package/esm/types.d.ts +128 -0
  37. package/esm/types.d.ts.map +1 -1
  38. package/esm/types.js +22 -1
  39. package/esm/utils.d.ts.map +1 -1
  40. package/esm/utils.js +16 -2
  41. package/esm/webhookserver.d.ts +33 -15
  42. package/esm/webhookserver.d.ts.map +1 -1
  43. package/esm/webhookserver.js +197 -38
  44. package/package.json +1 -1
  45. package/script/browserconfig.d.ts +57 -9
  46. package/script/browserconfig.d.ts.map +1 -1
  47. package/script/browserconfig.js +63 -5
  48. package/script/browserdownloads.d.ts +70 -0
  49. package/script/browserdownloads.d.ts.map +1 -0
  50. package/script/browserdownloads.js +221 -0
  51. package/script/client.d.ts +224 -8
  52. package/script/client.d.ts.map +1 -1
  53. package/script/client.js +645 -61
  54. package/script/crawl.d.ts +83 -1
  55. package/script/crawl.d.ts.map +1 -1
  56. package/script/crawl.js +73 -0
  57. package/script/crawlerconfig.d.ts +54 -3
  58. package/script/crawlerconfig.d.ts.map +1 -1
  59. package/script/crawlerconfig.js +97 -3
  60. package/script/crawlerresult.d.ts +374 -2
  61. package/script/crawlerresult.d.ts.map +1 -1
  62. package/script/crawlerresult.js +374 -2
  63. package/script/errors.d.ts +12 -0
  64. package/script/errors.d.ts.map +1 -1
  65. package/script/errors.js +12 -1
  66. package/script/main.d.ts +12 -7
  67. package/script/main.d.ts.map +1 -1
  68. package/script/main.js +20 -4
  69. package/script/monitoringconfig.d.ts +2 -2
  70. package/script/result.d.ts +11 -1
  71. package/script/result.d.ts.map +1 -1
  72. package/script/result.js +14 -5
  73. package/script/scrapeconfig.d.ts +65 -1
  74. package/script/scrapeconfig.d.ts.map +1 -1
  75. package/script/scrapeconfig.js +88 -4
  76. package/script/screenshotconfig.d.ts +9 -1
  77. package/script/screenshotconfig.d.ts.map +1 -1
  78. package/script/screenshotconfig.js +12 -1
  79. package/script/types.d.ts +128 -0
  80. package/script/types.d.ts.map +1 -1
  81. package/script/types.js +23 -0
  82. package/script/utils.d.ts.map +1 -1
  83. package/script/utils.js +16 -2
  84. package/script/webhookserver.d.ts +33 -15
  85. package/script/webhookserver.d.ts.map +1 -1
  86. package/script/webhookserver.js +197 -38
  87. package/src/browserconfig.ts +74 -8
  88. package/src/browserdownloads.ts +266 -0
  89. package/src/client.ts +796 -65
  90. package/src/crawl.ts +106 -0
  91. package/src/crawlerconfig.ts +128 -5
  92. package/src/crawlerresult.ts +607 -3
  93. package/src/errors.ts +12 -0
  94. package/src/main.ts +55 -5
  95. package/src/monitoringconfig.ts +2 -2
  96. package/src/result.ts +17 -5
  97. package/src/scrapeconfig.ts +92 -3
  98. package/src/screenshotconfig.ts +14 -1
  99. package/src/types.ts +159 -1
  100. package/src/utils.ts +16 -2
  101. package/src/webhookserver.ts +235 -39
package/src/main.ts CHANGED
@@ -13,8 +13,7 @@
13
13
  * const client = new ScrapflyClient({ key: 'your-api-key' });
14
14
  * const result = await client.scrape(new ScrapeConfig({
15
15
  * url: 'https://web-scraping.dev/products',
16
- * render_js: true,
17
- * asp: true,
16
+ * proxy_pool: ScrapeConfig.UNBLOCKER,
18
17
  * }));
19
18
  * console.log(result.content);
20
19
  * ```
@@ -40,8 +39,33 @@ export {
40
39
  export { ExtractionConfig } from './extractionconfig.js';
41
40
  export { BrowserConfig, ProxyPool, OperatingSystem } from './browserconfig.js';
42
41
  export type { BrowserConfigOptions } from './browserconfig.js';
43
- export type { Vault, VaultItem, VaultItemCreate, VaultItemType, VaultSecret } from './types.js';
44
- /** Namespace of every error class the SDK can throw. See {@link ScrapflyError}. */
42
+ export { BrowserDownloadError, CloudBrowserDownloads, parseDownloads } from './browserdownloads.js';
43
+ export type { BrowserDownload, CdpSend, CdpSession, CloudBrowserDownloadsOptions, WaitForOptions } from './browserdownloads.js';
44
+ // Enum, hence a value export: callers name VaultLinkedService.ONE_PASSWORD.
45
+ export { VaultLinkedService } from './types.js';
46
+ export type {
47
+ Vault,
48
+ VaultItem,
49
+ VaultItemCreate,
50
+ VaultLinkedServiceValue,
51
+ VaultItemSource,
52
+ VaultItemType,
53
+ VaultOnePasswordData,
54
+ VaultProbeResult,
55
+ VaultProbeVault,
56
+ VaultSecret,
57
+ VaultServiceLink,
58
+ VaultServiceUpdate,
59
+ VaultSyncCounts,
60
+ VaultSyncMode,
61
+ VaultSyncReport,
62
+ VaultSyncStatus,
63
+ VaultType,
64
+ } from './types.js';
65
+ /**
66
+ * Namespace of the API error classes, {@link ScrapflyError} and its subclasses: `errors.ScrapflyAspError`.
67
+ * `BrowserDownloadError` and `ScheduleAPIError` are exported at the root.
68
+ */
45
69
  export * as errors from './errors.js';
46
70
 
47
71
  export { ExtractionResult, ScrapeResult, ScreenshotResult } from './result.js';
@@ -55,16 +79,42 @@ export { Crawl } from './crawl.js';
55
79
  export {
56
80
  CrawlerArtifact,
57
81
  CrawlerContents,
82
+ CrawlerSearchResponse,
58
83
  CrawlerStatus,
59
84
  CrawlerUrls,
85
+ isSearchable,
86
+ parseCrawlerPromptStream,
87
+ parseCrawlerRefreshState,
88
+ parseCrawlerSearchState,
60
89
  parseCrawlerWebhook,
90
+ refreshChanged,
61
91
  } from './crawlerresult.js';
62
92
  export type {
63
93
  CrawlerArtifactType,
94
+ CrawlerExtractResponse,
64
95
  CrawlerLifecycleWebhook,
96
+ CrawlerPromptAnswer,
97
+ CrawlerPromptDone,
98
+ CrawlerPromptEvent,
99
+ CrawlerPromptSearch,
100
+ CrawlerPromptSource,
101
+ CrawlerRefreshEntry,
102
+ CrawlerRefreshState,
103
+ CrawlerRefreshStatus,
104
+ CrawlerSearchCrawl,
105
+ CrawlerSearchMode,
106
+ CrawlerSearchResult,
107
+ CrawlerSearchScores,
108
+ CrawlerSearchSkipped,
109
+ CrawlerSearchState,
110
+ CrawlerSearchStats,
111
+ CrawlerSearchStatus,
112
+ CrawlerSearchWebhook,
113
+ CrawlerSkipReason,
65
114
  CrawlerState,
66
115
  CrawlerStatusValue,
67
116
  CrawlerStopReason,
117
+ CrawlerUpdatedWebhook,
68
118
  CrawlerUrlDiscoveredWebhook,
69
119
  CrawlerUrlEntry,
70
120
  CrawlerUrlFailedWebhook,
@@ -96,4 +146,4 @@ export type {
96
146
 
97
147
  export { log } from './logger.js';
98
148
 
99
- export { createServer, verifySignature } from './webhookserver.js';
149
+ export { createServer, ResourceType, verifySignature } from './webhookserver.js';
@@ -59,8 +59,8 @@ export interface CloudBrowserMonitoringOptions {
59
59
  /** Time window to aggregate over. */
60
60
  period?: MonitoringPeriod;
61
61
  /**
62
- * Optional filter to a single proxy pool
63
- * (e.g. `public_datacenter_pool`, `public_residential_pool`, `byop`).
62
+ * Optional filter to a single proxy pool, as the runs record it:
63
+ * `datacenter`, `residential`, `tor` or `byop`.
64
64
  */
65
65
  proxyPool?: string;
66
66
  /** Window start. */
package/src/result.ts CHANGED
@@ -17,6 +17,13 @@ export type ConfigData = {
17
17
  debug: boolean;
18
18
  raise_on_upstream_error: boolean;
19
19
  cache_ttl: number;
20
+ /**
21
+ * The pool the request asked for, the way the account reads it: Tor reads `public_tor_pool` and one of the
22
+ * account's own pools its name. Otherwise, when the Unblocker ran (asked, or forced by a target that requires
23
+ * it), `basic` and `unblocker` read `unblocker` and any other pool `unblocker_ultra`. Without the Unblocker a
24
+ * Scrapfly pool reads by its network (`basic`, `unblocker`, `mobile`, `isp`) and any other name as sent.
25
+ * `context.proxy.pool` reads the same.
26
+ */
20
27
  proxy_pool: string;
21
28
  session?: string;
22
29
  tags: Set<string>;
@@ -74,6 +81,7 @@ export type ContextData = {
74
81
  country: string;
75
82
  identity: string;
76
83
  network: string;
84
+ /** The same name as {@link ConfigData.proxy_pool}. */
77
85
  pool: string;
78
86
  };
79
87
  redirects: Array<string>;
@@ -211,10 +219,10 @@ export class ScrapeResult {
211
219
 
212
220
  get selector(): cheerio.CheerioAPI {
213
221
  if (!this._selector) {
214
- const headers = normalizeHeaders(this.result.response_headers);
215
- if (!headers['content-type'].includes('text/html')) {
222
+ const contentType = normalizeHeaders(this.result.response_headers)['content-type'] ?? '';
223
+ if (!contentType.includes('text/html')) {
216
224
  throw new errors.ContentTypeError(
217
- `Cannot use selector on non-html content-type, received: ${this.result.response_headers['content-type']}`,
225
+ `Cannot use selector on non-html content-type, received: ${contentType}`,
218
226
  );
219
227
  }
220
228
  this._selector = cheerio.load(this.result.content);
@@ -297,11 +305,15 @@ export class ScreenshotResult {
297
305
  image: ArrayBuffer;
298
306
  metadata: ScreenshotMetadata;
299
307
  result: object | null;
308
+ /** The job of a screenshot with a webhook: the image is delivered to the webhook, `image` and `metadata` are empty. */
309
+ job_uuid: string | null;
300
310
 
301
- constructor(response: Response, data: ArrayBuffer) {
311
+ constructor(response: Response, data: ArrayBuffer, job_uuid: string | null = null) {
302
312
  this.image = data;
303
- this.metadata = this.defineMetadata(response);
313
+ this.metadata =
314
+ job_uuid === null ? this.defineMetadata(response) : { extension_name: '', upstream_status_code: 0, upstream_url: '' };
304
315
  this.result = this.decodeResponse(response, data); // raw result
316
+ this.job_uuid = job_uuid;
305
317
  }
306
318
 
307
319
  private defineMetadata(response: Response): ScreenshotMetadata {
@@ -54,10 +54,35 @@ type ScrapeConfigOptions = {
54
54
  cost_budget?: number;
55
55
  ssl?: boolean;
56
56
  dns?: boolean;
57
+ /**
58
+ * The Unblocker (anti-bot bypass), the current name for what used to be
59
+ * called `asp`. Sent to the API as the `asp` query parameter; only the
60
+ * SDK-facing name changed.
61
+ *
62
+ * @deprecated Use `proxy_pool` (`ScrapeConfig.UNBLOCKER_ULTRA` for the
63
+ * Unblocker). The migration guide covers requests written before the proxy
64
+ * pools: https://scrapfly.io/new-pricing#legacy-spellings
65
+ */
66
+ unblocker?: boolean;
67
+ /**
68
+ * @deprecated Alias of {@link unblocker}: use `proxy_pool`
69
+ * (`ScrapeConfig.UNBLOCKER_ULTRA` for the Unblocker). When both are supplied
70
+ * `asp` wins, so existing code cannot have its meaning changed by a later
71
+ * `unblocker`.
72
+ */
57
73
  asp?: boolean;
58
74
  debug?: boolean;
59
75
  raise_on_upstream_error?: boolean;
60
76
  cache_ttl?: number;
77
+ /**
78
+ * Proxy pool: `basic` (datacenter proxies, Unblocker off), `unblocker`
79
+ * (residential proxies and the Unblocker), `unblocker_ultra` (residential
80
+ * proxies and the Unblocker, the only pool accepted by the targets and
81
+ * anti-bot protections that have a price of their own: they refuse `basic`
82
+ * and `unblocker` with `ERR::PROXY::UNBLOCKER_ULTRA_REQUIRED`) or `auto`
83
+ * (the API picks the pool from the target's profile), see
84
+ * {@link ScrapeConfig.BASIC}. Each sets the Unblocker itself.
85
+ */
61
86
  proxy_pool?: string;
62
87
  session?: string;
63
88
  tags?: string[];
@@ -111,9 +136,22 @@ type ScrapeConfigOptions = {
111
136
  };
112
137
 
113
138
  export class ScrapeConfig {
139
+ // Proxy pools, sent as `proxy_pool`. Each sets both the proxies and the
140
+ // Unblocker. AUTO lets the API pick the pool before the request, from the
141
+ // target's profile: the Unblocker on datacenter proxies, or the pool the
142
+ // target needs, priced as the pool it runs on.
143
+ static BASIC = 'basic';
144
+ static UNBLOCKER = 'unblocker';
145
+ static UNBLOCKER_ULTRA = 'unblocker_ultra';
146
+ static AUTO = 'auto';
147
+
148
+ // The Tor network, the only pool that reaches .onion hidden services.
149
+ static PUBLIC_TOR_POOL = 'public_tor_pool';
150
+
151
+ // Pool names written before the proxy pools, still accepted. The migration
152
+ // guide covers them: https://scrapfly.io/new-pricing#legacy-spellings
114
153
  static PUBLIC_DATACENTER_POOL = 'public_datacenter_pool';
115
154
  static PUBLIC_RESIDENTIAL_POOL = 'public_residential_pool';
116
- static PUBLIC_TOR_POOL = 'public_tor_pool';
117
155
 
118
156
  url: string;
119
157
  retry = true;
@@ -125,10 +163,24 @@ export class ScrapeConfig {
125
163
  cost_budget?: number;
126
164
  ssl = false;
127
165
  dns = false;
166
+ /**
167
+ * Storage for the anti-bot bypass toggle, under its deprecated name.
168
+ * `unblocker` is an accessor over this same field — see below.
169
+ *
170
+ * @deprecated Use `proxy_pool` (`ScrapeConfig.UNBLOCKER_ULTRA` for the Unblocker).
171
+ */
128
172
  asp = false;
129
173
  debug = false;
130
174
  raise_on_upstream_error = true;
131
175
  cache_ttl?: number;
176
+ /**
177
+ * Proxy pool: `basic` (datacenter proxies, Unblocker off), `unblocker`
178
+ * (residential proxies and the Unblocker), `unblocker_ultra` (residential
179
+ * proxies and the Unblocker, the only pool accepted by the targets and
180
+ * anti-bot protections that have a price of their own) or `auto` (the API
181
+ * picks the pool from the target's profile), see {@link ScrapeConfig.BASIC}.
182
+ * Each sets the Unblocker itself.
183
+ */
132
184
  proxy_pool?: string;
133
185
  session?: string;
134
186
  tags: Set<string> = new Set<string>();
@@ -190,7 +242,11 @@ export class ScrapeConfig {
190
242
  this.cache = options.cache ?? this.cache;
191
243
  this.cache_clear = options.cache_clear ?? this.cache_clear;
192
244
  this.cost_budget = options.cost_budget ?? this.cost_budget;
193
- this.asp = options.asp ?? this.asp;
245
+ // `asp` is the deprecated alias of `unblocker` and an explicitly supplied
246
+ // `asp` always wins; `unblocker` applies only when `asp` was not supplied.
247
+ // `??` and not `||`, so an explicit `false` on either name turns the
248
+ // feature off instead of falling through to the other name.
249
+ this.asp = options.asp ?? options.unblocker ?? this.asp;
194
250
  this.headers = options.headers
195
251
  ? Object.fromEntries(Object.entries(options.headers).map(([k, v]) => [k.toLowerCase(), v]))
196
252
  : {};
@@ -256,10 +312,38 @@ export class ScrapeConfig {
256
312
  }
257
313
  }
258
314
 
315
+ /**
316
+ * The Unblocker toggle, the current name for what used to be `asp`.
317
+ * Deprecated: use `proxy_pool` (`ScrapeConfig.UNBLOCKER_ULTRA` for the
318
+ * Unblocker). The migration guide covers requests written before the proxy
319
+ * pools: https://scrapfly.io/new-pricing#legacy-spellings
320
+ *
321
+ * An accessor over the single `asp` field rather than a second stored
322
+ * property: one storage slot means the two names can never disagree, so
323
+ * `config.unblocker = true` after construction is exactly `config.asp = true`
324
+ * and `toApiParams` has one value to read. It also keeps `unblocker` out of
325
+ * the instance's own keys, so serializers that iterate them do not sprout a
326
+ * duplicate of `asp`.
327
+ */
328
+ get unblocker(): boolean {
329
+ return this.asp;
330
+ }
331
+
332
+ set unblocker(value: boolean) {
333
+ this.asp = value;
334
+ }
335
+
336
+ /**
337
+ * Option names the constructor accepts that are not own properties of the
338
+ * instance. `unblocker` is an accessor, so it lives on the prototype and the
339
+ * `Object.keys(this)` allow-list below never sees it.
340
+ */
341
+ private static readonly ALIAS_OPTION_KEYS: ReadonlySet<string> = new Set(['unblocker']);
342
+
259
343
  private validateOptions(options: Partial<ScrapeConfigOptions>) {
260
344
  const validKeys = new Set(Object.keys(this) as Array<keyof ScrapeConfig>);
261
345
  for (const key in options) {
262
- if (!validKeys.has(key as keyof ScrapeConfig)) {
346
+ if (!validKeys.has(key as keyof ScrapeConfig) && !ScrapeConfig.ALIAS_OPTION_KEYS.has(key)) {
263
347
  throw new ScrapeConfigError(`Invalid option provided: ${key}`);
264
348
  }
265
349
  }
@@ -359,6 +443,11 @@ export class ScrapeConfig {
359
443
  }
360
444
  }
361
445
 
446
+ // The wire key stays `asp` for both names. A published package version is
447
+ // immutable and upgraded per installation, so emitting `unblocker` against
448
+ // an API deployment that has not learned that name yet would silently drop
449
+ // a paid feature: the scrape succeeds, is billed, and returns a blocked
450
+ // page. Renaming the emitted key is a separate, later release.
362
451
  if (this.asp === true) {
363
452
  params.asp = true;
364
453
  }
@@ -22,7 +22,7 @@ export enum Format {
22
22
  PNG = 'png',
23
23
  /** WebP encoding. */
24
24
  WEBP = 'webp',
25
- /** Animated GIF encoding. */
25
+ /** GIF encoding, single frame. */
26
26
  GIF = 'gif',
27
27
  }
28
28
 
@@ -83,6 +83,12 @@ type ScreenshotConfigOptions = {
83
83
  vision_deficiency?: 'deuteranopia' | 'protanopia' | 'tritanopia' | 'achromatopsia' | 'blurredVision' | 'reducedContrast' | VisionDeficiency;
84
84
  /** Webhook name to notify when the screenshot completes. */
85
85
  webhook?: string;
86
+ /**
87
+ * Proxy pool: `basic`, `unblocker`, `unblocker_ultra` or `auto` (see
88
+ * `ScrapeConfig.BASIC`); any other value is ignored here. Unset, the API's
89
+ * screenshot defaults apply. The screenshot price is the same on every pool.
90
+ */
91
+ proxy_pool?: string;
86
92
  };
87
93
 
88
94
  /**
@@ -113,6 +119,8 @@ export class ScreenshotConfig {
113
119
  cache_clear?: boolean;
114
120
  vision_deficiency?: 'deuteranopia' | 'protanopia' | 'tritanopia' | 'achromatopsia' | 'blurredVision' | 'reducedContrast' | VisionDeficiency;
115
121
  webhook?: string;
122
+ /** Proxy pool: `basic`, `unblocker`, `unblocker_ultra` or `auto`; any other value is ignored here. */
123
+ proxy_pool?: string;
116
124
 
117
125
  constructor(options: ScreenshotConfigOptions) {
118
126
  this.validateOptions(options);
@@ -143,6 +151,7 @@ export class ScreenshotConfig {
143
151
  this.cache_clear = options.cache_clear ?? this.cache_clear;
144
152
  this.vision_deficiency = options.vision_deficiency ?? this.vision_deficiency;
145
153
  this.webhook = options.webhook;
154
+ this.proxy_pool = options.proxy_pool;
146
155
  }
147
156
 
148
157
  private validateOptions(options: Partial<ScreenshotConfigOptions>) {
@@ -232,6 +241,10 @@ export class ScreenshotConfig {
232
241
  params.webhook_name = this.webhook;
233
242
  }
234
243
 
244
+ if (this.proxy_pool) {
245
+ params.proxy_pool = this.proxy_pool;
246
+ }
247
+
235
248
  return params;
236
249
  }
237
250
  }
package/src/types.ts CHANGED
@@ -8,7 +8,6 @@ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'HEAD';
8
8
  // encrypted server-side under a customer-held vault key. The server emits the
9
9
  // raw vault key exactly once on POST /vault and POST /vault/{id}/rotate; the
10
10
  // SDK MUST never log, print, or include it in error messages.
11
- // See compliance memory at agent_secret_tokenization_boundary.md.
12
11
  // ---------------------------------------------------------------------------
13
12
 
14
13
  /** Vault metadata returned by the server (no secret material). */
@@ -20,12 +19,28 @@ export type Vault = {
20
19
  name: string;
21
20
  description?: string;
22
21
  item_count?: number;
22
+ /** Number of mirrored rows. Populated by `cloudBrowserVaultGet` only. */
23
+ linked_item_count?: number;
24
+ // Link metadata. Non-secret by construction: the provider service-account
25
+ // token is a sealed item, never one of these fields.
26
+ vault_type?: VaultType;
27
+ linked_service?: VaultLinkedService;
28
+ /** Stored `linked_service_data`, which carries the server-owned `token_item_id`. */
29
+ linked_service_data?: VaultOnePasswordData & { token_item_id?: string };
30
+ linked_sync_at?: string;
31
+ linked_sync_started_at?: string;
32
+ linked_sync_status?: VaultSyncStatus;
33
+ linked_sync_error?: string;
34
+ linked_sync_counts?: VaultSyncCounts;
23
35
  created_at?: string;
24
36
  updated_at?: string;
25
37
  // Allow forward-compat fields the server may add.
26
38
  [k: string]: unknown;
27
39
  };
28
40
 
41
+ /** Whether a vault's items are operator-entered or mirrored from a provider. */
42
+ export type VaultType = 'manual' | 'linked_service';
43
+
29
44
  /** Discriminator for the secret payload of a {@link VaultItem}. */
30
45
  export type VaultItemType = 'password' | 'passkey' | 'cookie' | 'totp';
31
46
 
@@ -101,11 +116,32 @@ export type VaultItem = {
101
116
  secret_blob?: string;
102
117
  master_key_version?: number;
103
118
  metadata?: Record<string, unknown>;
119
+ /**
120
+ * Provenance. Anything other than `manual` is owned by the linked-service
121
+ * syncer: the item endpoints refuse to mutate such a row, and the next sync
122
+ * overwrites or deletes it.
123
+ */
124
+ source?: VaultItemSource;
125
+ /** Upstream diff key; set on mirrored rows only. */
126
+ source_ref?: string;
127
+ /** Opaque upstream revision the sync diff compares without decrypting. */
128
+ source_version?: string;
129
+ source_synced_at?: string;
104
130
  created_at?: string;
105
131
  updated_at?: string;
106
132
  [k: string]: unknown;
107
133
  };
108
134
 
135
+ /**
136
+ * `source` of a {@link VaultItem}. The sealed provider token is never listed.
137
+ *
138
+ * Server-written. The server's own domain is wider, reserving `service_token`,
139
+ * but that row is never returned to a caller so it is not listed here. Kept as
140
+ * literals so a mirrored row reads as plain data; comparing it against
141
+ * `VaultLinkedService.ONE_PASSWORD` still type-checks.
142
+ */
143
+ export type VaultItemSource = 'manual' | `${VaultLinkedService}`;
144
+
109
145
  /** Payload accepted by `cloudBrowserVaultItemCreate`. */
110
146
  export type VaultItemCreate = {
111
147
  type: VaultItemType;
@@ -115,3 +151,125 @@ export type VaultItemCreate = {
115
151
  secret: VaultSecret;
116
152
  metadata?: Record<string, unknown>;
117
153
  };
154
+
155
+ // ---------------------------------------------------------------------------
156
+ // Linked secret managers (1Password).
157
+ //
158
+ // A linked vault mirrors an upstream secret manager: the provider's
159
+ // service-account token is sealed under the vault key as a reserved item, and
160
+ // the syncer owns every row it imports. The token travels in the request body
161
+ // of link / update / test and is NEVER stored by the caller, logged, or echoed
162
+ // back by the server.
163
+ // ---------------------------------------------------------------------------
164
+
165
+ /**
166
+ * Linked-service discriminator, and the only closed value set a caller has to
167
+ * name when linking. 1Password is the sole entry in the server's linked-service
168
+ * registry; anything else is a 400, not a typed provider error.
169
+ */
170
+ export enum VaultLinkedService {
171
+ /**
172
+ * 1Password service account. Also the `source` written on every row its
173
+ * syncer mirrors.
174
+ */
175
+ ONE_PASSWORD = '1password',
176
+ }
177
+
178
+ /**
179
+ * Accepted on the wire: the enum member or its own string value. Derived from
180
+ * {@link VaultLinkedService} so the literal is declared once; the server
181
+ * registry, not this type, is the authority on what links.
182
+ */
183
+ export type VaultLinkedServiceValue = `${VaultLinkedService}`;
184
+
185
+ /**
186
+ * When the mirror is refreshed. `on_session` refreshes at most once per
187
+ * `sync_ttl_s` when a Cloud Browser session opens the vault; `manual` only
188
+ * syncs on `cloudBrowserVaultServiceSync`. (`live` is rejected by the server.)
189
+ */
190
+ export type VaultSyncMode = 'manual' | 'on_session';
191
+
192
+ /** Outcome of the last sync round, as stored on the vault row. */
193
+ export type VaultSyncStatus =
194
+ | 'running'
195
+ | 'ok'
196
+ | 'partial'
197
+ | 'auth_failed'
198
+ | 'rate_limited'
199
+ | 'scope_error'
200
+ | 'unavailable'
201
+ | 'error';
202
+
203
+ /**
204
+ * Non-secret selection rules of a 1Password link (`linked_service_data`).
205
+ *
206
+ * `vault_id` or `vault_name` is required — the server rejects a document with
207
+ * neither. `token_item_id` is deliberately absent: the server binds it when the
208
+ * token is sealed, and a PATCH body cannot redirect the token lookup because
209
+ * the stored id always wins.
210
+ */
211
+ export type VaultOnePasswordData = {
212
+ /** Upstream vault id. Survives an upstream rename, unlike `vault_name`. */
213
+ vault_id?: string;
214
+ vault_name?: string;
215
+ /** Glob over upstream item titles, 128 characters max. */
216
+ title_filter?: string;
217
+ /** At most 16 tags. */
218
+ tags?: string[];
219
+ sync_mode?: VaultSyncMode;
220
+ /** Refresh TTL in seconds, 60 .. 86400. Defaults to 900 server-side. */
221
+ sync_ttl_s?: number;
222
+ };
223
+
224
+ /** Payload accepted by `cloudBrowserVaultServiceLink`. */
225
+ export type VaultServiceLink = {
226
+ /**
227
+ * Required: `POST /vault/{id}/service` has no server-side default. The raw
228
+ * wire value stays assignable so untyped JavaScript callers keep working.
229
+ */
230
+ linked_service: VaultLinkedServiceValue;
231
+ /** Provider service-account token. Sealed under the vault key on arrival. */
232
+ token: string;
233
+ linked_service_data: VaultOnePasswordData;
234
+ };
235
+
236
+ /**
237
+ * Payload accepted by `cloudBrowserVaultServiceUpdate`. `linked_service` is not
238
+ * settable: the stored discriminator is what the server updates against.
239
+ */
240
+ export type VaultServiceUpdate = {
241
+ /** Rotates the sealed token. Requires the vault key; omit for a config-only edit. */
242
+ token?: string;
243
+ linked_service_data?: VaultOnePasswordData;
244
+ };
245
+
246
+ /** Per-round reconcile counts, also stored as `linked_sync_counts`. */
247
+ export type VaultSyncCounts = {
248
+ imported: number;
249
+ updated: number;
250
+ deleted: number;
251
+ /** Rows the reconcile refused, which is what makes a round `partial`. */
252
+ skipped: number;
253
+ /** Upstream items the provider could not map. Does not make a round partial. */
254
+ unmirrored: number;
255
+ };
256
+
257
+ /** Body of `cloudBrowserVaultServiceSync`. */
258
+ export type VaultSyncReport = VaultSyncCounts & {
259
+ status: VaultSyncStatus;
260
+ warnings?: string[];
261
+ };
262
+
263
+ /** One upstream vault the service account can read. */
264
+ export type VaultProbeVault = {
265
+ id: string;
266
+ title: string;
267
+ };
268
+
269
+ /** Body of `cloudBrowserVaultServiceTest`. Reads nothing and writes nothing. */
270
+ export type VaultProbeResult = {
271
+ vaults_visible: VaultProbeVault[];
272
+ /** Active items in the selected upstream vault; 0 when none is selected yet. */
273
+ item_count: number;
274
+ warnings?: string[];
275
+ };
package/src/utils.ts CHANGED
@@ -23,6 +23,18 @@ export type RequestOptions = {
23
23
  body?: string | Uint8Array | any;
24
24
  };
25
25
 
26
+ const KEY_IN_URL = /(?<=[?&]key=)[^&\s)'"]+/g;
27
+
28
+ /**
29
+ * Mask the API key in a fetch error, in place: Deno prints the request URL,
30
+ * query and key included, in the message and in the stack it captured.
31
+ */
32
+ function maskKey(error: unknown): void {
33
+ if (!(error instanceof Error)) return;
34
+ error.message = error.message.replace(KEY_IN_URL, 'REDACTED');
35
+ if (error.stack !== undefined) error.stack = error.stack.replace(KEY_IN_URL, 'REDACTED');
36
+ }
37
+
26
38
  export async function fetchRetry(
27
39
  config: RequestOptions,
28
40
  retries: number = 3,
@@ -46,8 +58,9 @@ export async function fetchRetry(
46
58
  body: reqInit.body as any,
47
59
  };
48
60
  const response = await fetch(new Request(url, init));
49
- // retry 5xx status codes
50
- if (response.status >= 500 && response.status < 600) {
61
+ // Retry 5xx status codes. A single-attempt caller reads the 5xx body
62
+ // itself: it carries the typed error.
63
+ if (response.status >= 500 && response.status < 600 && retries > 1) {
51
64
  const _text = await response.text(); // consume response to prevent leak
52
65
  lastError = new Error(`Fetch failed with status: ${response.status}`);
53
66
  if (attempt < retries) {
@@ -58,6 +71,7 @@ export async function fetchRetry(
58
71
  return response;
59
72
  }
60
73
  } catch (error) {
74
+ maskKey(error);
61
75
  lastError = error;
62
76
 
63
77
  // AbortError should never be retried: it means the caller explicitly