screenshotone-api-sdk 1.1.24 → 1.1.25

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 CHANGED
@@ -36,7 +36,7 @@ const url = client.generateTakeURL(options);
36
36
  console.log(url);
37
37
  // expected output: https://api.screenshotone.com/take?url=https%3A%2F%2Fexample.com&delay=3&block_ads=true&access_key=%3Caccess+key%3E&signature=7f3419ece2c53ed2c7923c7d5deef290d662c3643822bf69ec8259ce10b3ea61
38
38
 
39
- // download the screenshot and handle potential API errors
39
+ // download the screenshot and handle potential errors
40
40
  try {
41
41
  const imageBlob = await client.take(options);
42
42
 
@@ -49,6 +49,15 @@ try {
49
49
  // Error Code: error.errorCode
50
50
  // Error Message: error.errorMessage
51
51
  // Documentation URL: error.documentationUrl
52
+ } else if (error instanceof screenshotone.ConnectionError) {
53
+ // The connection to the API failed, for example with ECONNRESET.
54
+ // error.message explains what happened and what usually causes it.
55
+ // Code: error.code, for example "ECONNRESET"
56
+ // Phase: error.phase, "request" (before the API responded) or "response" (while downloading)
57
+ // Attempts: error.attempts
58
+ // Time from the last attempt's start to the failure: error.lastElapsedMs
59
+ // Time from the first attempt's start, retry waits included: error.totalElapsedMs
60
+ console.error(error.message);
52
61
  } else {
53
62
  // An unexpected error occurred
54
63
  console.error("An unexpected error occurred:", error.message);
@@ -56,6 +65,27 @@ try {
56
65
  }
57
66
  ```
58
67
 
68
+ ### Connection errors and retries
69
+
70
+ A request can fail on the network between your server and the API, for example with `ECONNRESET` when a proxy, NAT gateway or firewall closes the connection. The SDK then throws a `ConnectionError` that says:
71
+
72
+ - whether the connection broke before the API responded (`phase: "request"`) or while the result was downloading (`phase: "response"`, with `httpStatusCode`)
73
+ - how many attempts were made (`attempts`)
74
+ - how long after the last attempt started (`lastElapsedMs`), and how long after the first one started, waits between retries included (`totalElapsedMs`)
75
+ - what usually causes it
76
+
77
+ To retry connection resets automatically, set `maxRetries`. It's 0 by default, so the SDK doesn't retry unless you set it:
78
+
79
+ ```javascript
80
+ const client = new screenshotone.Client("<access key>", "<secret key>", {
81
+ maxRetries: 3,
82
+ });
83
+ ```
84
+
85
+ Retries apply only to `ECONNRESET` and wait with exponential backoff. A retry sends the request again. If the API had already finished the first one, the retry renders the screenshot again and counts toward your usage again, unless the result is served from the cache.
86
+
87
+ Many requests starting at once make connection resets more likely. If you take screenshots in large batches, limit how many requests run at the same time.
88
+
59
89
  ## Build and publish (a manual for SDK developers)
60
90
 
61
91
  To build and publish the SDK:
@@ -5,3 +5,40 @@ export default class APIError extends Error {
5
5
  readonly documentationUrl?: string;
6
6
  constructor(message: string, httpStatusCode?: number, errorCode?: string, errorMessage?: string, documentationUrl?: string);
7
7
  }
8
+ /**
9
+ * Where the connection failed: before the API responded ("request") or while
10
+ * the response was downloading ("response").
11
+ */
12
+ export declare type ConnectionErrorPhase = "request" | "response";
13
+ /**
14
+ * The connection to the API failed, for example with ECONNRESET. The message
15
+ * explains what happened and what usually causes it.
16
+ */
17
+ export declare class ConnectionError extends Error {
18
+ /** The system error code, for example "ECONNRESET". */
19
+ readonly code: string;
20
+ /** Whether the connection failed before the API responded or while the response was downloading. */
21
+ readonly phase: ConnectionErrorPhase;
22
+ /** Milliseconds from the start of the last attempt to the failure. */
23
+ readonly lastElapsedMs: number;
24
+ /**
25
+ * Milliseconds from the start of the first attempt to the failure, waits
26
+ * between retries included. Equals lastElapsedMs when there was one attempt.
27
+ */
28
+ readonly totalElapsedMs: number;
29
+ /** How many times the request was sent, retries included. */
30
+ readonly attempts: number;
31
+ /** The HTTP status of the response that was downloading, when the phase is "response". */
32
+ readonly httpStatusCode?: number;
33
+ /** The underlying error message. */
34
+ readonly reason?: string;
35
+ constructor(message: string, details: {
36
+ code: string;
37
+ phase: ConnectionErrorPhase;
38
+ lastElapsedMs: number;
39
+ totalElapsedMs: number;
40
+ attempts: number;
41
+ httpStatusCode?: number;
42
+ reason?: string;
43
+ });
44
+ }
@@ -1,5 +1,6 @@
1
- import APIError from "./errors";
2
- export { APIError };
1
+ import APIError, { ConnectionError, ConnectionErrorPhase } from "./errors";
2
+ export { APIError, ConnectionError };
3
+ export type { ConnectionErrorPhase };
3
4
  export interface ClientOptions {
4
5
  /** API base URL. Defaults to https://api.screenshotone.com. */
5
6
  apiBaseUrl?: string;
@@ -24,6 +25,9 @@ export declare class Client {
24
25
  */
25
26
  constructor(accessKey: string, secretKey: string, options?: ClientOptions | string);
26
27
  private withConnectionResetRetries;
28
+ private send;
29
+ private read;
30
+ private connectionError;
27
31
  /**
28
32
  * Generates an URL that can be used to send GET requests for taking screenshots.
29
33
  *
package/dist/errors.js CHANGED
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConnectionError = void 0;
3
4
  class APIError extends Error {
4
5
  constructor(message, httpStatusCode, errorCode, errorMessage, documentationUrl) {
5
6
  super(message);
@@ -10,3 +11,21 @@ class APIError extends Error {
10
11
  }
11
12
  }
12
13
  exports.default = APIError;
14
+ /**
15
+ * The connection to the API failed, for example with ECONNRESET. The message
16
+ * explains what happened and what usually causes it.
17
+ */
18
+ class ConnectionError extends Error {
19
+ constructor(message, details) {
20
+ super(message);
21
+ this.name = "ConnectionError";
22
+ this.code = details.code;
23
+ this.phase = details.phase;
24
+ this.lastElapsedMs = details.lastElapsedMs;
25
+ this.totalElapsedMs = details.totalElapsedMs;
26
+ this.attempts = details.attempts;
27
+ this.httpStatusCode = details.httpStatusCode;
28
+ this.reason = details.reason;
29
+ }
30
+ }
31
+ exports.ConnectionError = ConnectionError;
package/dist/main.js CHANGED
@@ -1,21 +1,109 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
2
25
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
27
  };
5
28
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.AnimateOptions = exports.TakeOptions = exports.Client = exports.APIError = void 0;
29
+ exports.AnimateOptions = exports.TakeOptions = exports.Client = exports.ConnectionError = exports.APIError = void 0;
7
30
  const big_js_1 = __importDefault(require("big.js"));
8
31
  const cross_fetch_1 = __importDefault(require("cross-fetch"));
9
32
  const signature_1 = require("./signature");
10
- const errors_1 = __importDefault(require("./errors"));
33
+ const errors_1 = __importStar(require("./errors"));
11
34
  exports.APIError = errors_1.default;
35
+ Object.defineProperty(exports, "ConnectionError", { enumerable: true, get: function () { return errors_1.ConnectionError; } });
12
36
  const API_BASE_URL = "https://api.screenshotone.com";
13
37
  const API_TAKE_PATH = "/take";
14
38
  const API_ANIMATE_PATH = "/animate";
39
+ // the only error code the client retries
40
+ const RETRYABLE_CODE = "ECONNRESET";
15
41
  function isConnectionReset(error) {
16
42
  return (typeof error === "object" &&
17
43
  error !== null &&
18
- error.code === "ECONNRESET");
44
+ error.code === RETRYABLE_CODE);
45
+ }
46
+ const CONNECTION_FAILURES = {
47
+ ECONNRESET: "the connection was reset",
48
+ EPIPE: "the connection was closed while the request was being sent",
49
+ ERR_STREAM_PREMATURE_CLOSE: "the connection closed before the whole response arrived",
50
+ ECONNREFUSED: "the connection was refused",
51
+ ETIMEDOUT: "the connection timed out",
52
+ EHOSTUNREACH: "the API host is unreachable",
53
+ ENETUNREACH: "the network is unreachable",
54
+ ENOTFOUND: "the API host name couldn't be resolved",
55
+ EAI_AGAIN: "the API host name couldn't be resolved",
56
+ };
57
+ // an open connection that broke, rather than one that couldn't be opened
58
+ const DROPPED_CONNECTION_CODES = [
59
+ "ECONNRESET",
60
+ "EPIPE",
61
+ "ERR_STREAM_PREMATURE_CLOSE",
62
+ ];
63
+ // The code of a network failure, or undefined for any other error. node-fetch,
64
+ // which cross-fetch uses in Node, rejects with a FetchError of type "system";
65
+ // fetch built on undici rejects with a TypeError caused by the system error.
66
+ function networkFailureCode(error) {
67
+ if (typeof error !== "object" || error === null) {
68
+ return undefined;
69
+ }
70
+ const { type, code, cause } = error;
71
+ if (type === "system" && typeof code === "string") {
72
+ return code;
73
+ }
74
+ if (error instanceof TypeError && typeof cause === "object" && cause) {
75
+ const causeCode = cause.code;
76
+ if (typeof causeCode === "string") {
77
+ return causeCode;
78
+ }
79
+ }
80
+ return undefined;
81
+ }
82
+ // the request URL without its query and fragment, which hold the access key
83
+ // and the signature, whatever the URL's form
84
+ function withoutQuery(url) {
85
+ return url.split(/[?#]/, 1)[0];
86
+ }
87
+ // The text without the request's query: exactly as sent, in any URL the text
88
+ // mentions (whatever its scheme spelling, or none), and any credential left.
89
+ function redact(text, url) {
90
+ const query = url.slice(withoutQuery(url).length);
91
+ return (query ? text.split(query).join("") : text)
92
+ .replace(/((?:[a-z][a-z0-9+.-]*:)?\/\/[^\s?#]+)[?#]\S*?(?=:?(?:\s|$))/gi, "$1")
93
+ .replace(/\b(access_key|signature)=[^&\s]+/gi, "$1=[redacted]");
94
+ }
95
+ function formatDuration(ms) {
96
+ return ms < 1000 ? `${ms} ms` : `${(ms / 1000).toFixed(1)} s`;
97
+ }
98
+ function reasonOf(error, url) {
99
+ if (!(error instanceof Error)) {
100
+ return undefined;
101
+ }
102
+ const cause = error.cause;
103
+ const message = error instanceof TypeError && cause instanceof Error
104
+ ? cause.message
105
+ : error.message;
106
+ return redact(message, url);
19
107
  }
20
108
  /**
21
109
  * Represents an API client for the ScreenshotOne.com API.
@@ -39,9 +127,11 @@ class Client {
39
127
  this.maxRetries = maxRetries;
40
128
  }
41
129
  async withConnectionResetRetries(operation) {
130
+ const attempts = { current: 0 };
42
131
  for (let retry = 0;; retry++) {
132
+ attempts.current = retry + 1;
43
133
  try {
44
- return await operation();
134
+ return await operation(attempts);
45
135
  }
46
136
  catch (error) {
47
137
  if (!isConnectionReset(error) || retry >= this.maxRetries) {
@@ -52,6 +142,85 @@ class Client {
52
142
  }
53
143
  }
54
144
  }
145
+ // Sends the request. A network failure becomes a ConnectionError.
146
+ async send(url, attempts) {
147
+ const startedAt = Date.now();
148
+ attempts.firstStartedAt ??= startedAt;
149
+ const request = {
150
+ url,
151
+ attempt: attempts.current,
152
+ startedAt,
153
+ firstStartedAt: attempts.firstStartedAt,
154
+ };
155
+ try {
156
+ return { ...request, response: await (0, cross_fetch_1.default)(url) };
157
+ }
158
+ catch (error) {
159
+ throw this.connectionError(error, request, "request") ?? error;
160
+ }
161
+ }
162
+ // Reads the response body. A network failure becomes a ConnectionError.
163
+ async read(request, body) {
164
+ try {
165
+ return await body(request.response);
166
+ }
167
+ catch (error) {
168
+ throw (this.connectionError(error, request, "response", request.response.status) ?? error);
169
+ }
170
+ }
171
+ // A ConnectionError that explains a network failure, or undefined for any
172
+ // other error
173
+ connectionError(error, request, phase, httpStatusCode) {
174
+ const code = networkFailureCode(error);
175
+ if (!code) {
176
+ return undefined;
177
+ }
178
+ const now = Date.now();
179
+ const lastElapsedMs = now - request.startedAt;
180
+ const totalElapsedMs = now - request.firstStartedAt;
181
+ const endpoint = withoutQuery(request.url);
182
+ const when = request.attempt > 1
183
+ ? `${formatDuration(lastElapsedMs)} after the last of ${request.attempt} attempts to ${endpoint} started, ${formatDuration(totalElapsedMs)} after the first`
184
+ : `${formatDuration(lastElapsedMs)} after the request to ${endpoint} started`;
185
+ const failure = `${CONNECTION_FAILURES[code] ?? "the connection failed"} (${code}) ${when}`;
186
+ const dropped = DROPPED_CONNECTION_CODES.includes(code);
187
+ const sentences = phase === "request"
188
+ ? [
189
+ `The connection to the ScreenshotOne API failed before a response arrived: ${failure}.`,
190
+ ]
191
+ : [
192
+ `The connection to the ScreenshotOne API failed while downloading the response (HTTP ${httpStatusCode}): ${failure}.`,
193
+ httpStatusCode !== undefined && httpStatusCode < 400
194
+ ? "The API had already finished the request. Unless the result came from the cache, it counts toward your usage."
195
+ : "The API had responded with an error, but its details couldn't be read.",
196
+ ];
197
+ if (dropped) {
198
+ if (phase === "request") {
199
+ sentences.push("The API might not have received the request, or the connection broke while the API was working on it.");
200
+ }
201
+ sentences.push("This usually happens on the network between your server and the API: a proxy, NAT gateway or firewall closed the connection, or an idle kept-alive connection was reused after the network had closed it. It's more likely when many requests start at once.");
202
+ sentences.push(request.attempt > 1
203
+ ? `It failed on all ${request.attempt} attempts. Limit how many requests run at once.`
204
+ : code === RETRYABLE_CODE && this.maxRetries === 0
205
+ ? "Limit how many requests run at once, or set the maxRetries client option to retry automatically."
206
+ : "Limit how many requests run at once.");
207
+ }
208
+ else if (code === "ENOTFOUND" || code === "EAI_AGAIN") {
209
+ sentences.push("Check your server's DNS settings.");
210
+ }
211
+ else {
212
+ sentences.push("Check that your server can reach the API, including firewall and proxy settings.");
213
+ }
214
+ return new errors_1.ConnectionError(sentences.join(" "), {
215
+ code,
216
+ phase,
217
+ lastElapsedMs,
218
+ totalElapsedMs,
219
+ attempts: request.attempt,
220
+ httpStatusCode,
221
+ reason: reasonOf(error, request.url),
222
+ });
223
+ }
55
224
  /**
56
225
  * Generates an URL that can be used to send GET requests for taking screenshots.
57
226
  *
@@ -104,17 +273,18 @@ class Client {
104
273
  */
105
274
  async take(options) {
106
275
  const url = await this.generateSignedTakeURL(options);
107
- return this.withConnectionResetRetries(async () => {
108
- const response = await (0, cross_fetch_1.default)(url);
276
+ return this.withConnectionResetRetries(async (attempts) => {
277
+ const request = await this.send(url, attempts);
278
+ const response = request.response;
109
279
  if (response.ok) {
110
- return await response.blob();
280
+ return await this.read(request, (r) => r.blob());
111
281
  }
112
282
  try {
113
- const data = await response.json();
283
+ const data = await this.read(request, (r) => r.json());
114
284
  throw new errors_1.default(`Failed to generate screenshot, response returned ${response.status} (${response.statusText}): ${data?.error_message}`, response.status, data?.error_code, data?.error_message, data?.documentation_url);
115
285
  }
116
286
  catch (e) {
117
- if (e instanceof errors_1.default || isConnectionReset(e)) {
287
+ if (e instanceof errors_1.default || e instanceof errors_1.ConnectionError) {
118
288
  throw e;
119
289
  }
120
290
  throw new Error(`failed to take screenshot, response returned ${response.status} ${response.statusText}`);
@@ -129,17 +299,18 @@ class Client {
129
299
  */
130
300
  async animate(options) {
131
301
  const url = await this.generateSignedAnimateURL(options);
132
- return this.withConnectionResetRetries(async () => {
133
- const response = await (0, cross_fetch_1.default)(url);
302
+ return this.withConnectionResetRetries(async (attempts) => {
303
+ const request = await this.send(url, attempts);
304
+ const response = request.response;
134
305
  if (response.ok) {
135
- return await response.blob();
306
+ return await this.read(request, (r) => r.blob());
136
307
  }
137
308
  try {
138
- const data = await response.json();
309
+ const data = await this.read(request, (r) => r.json());
139
310
  throw new errors_1.default(`Failed to generate animation, response returned ${response.status} (${response.statusText}): ${data?.error_message}`, response.status, data?.error_code, data?.error_message, data?.documentation_url);
140
311
  }
141
312
  catch (e) {
142
- if (e instanceof errors_1.default || isConnectionReset(e)) {
313
+ if (e instanceof errors_1.default || e instanceof errors_1.ConnectionError) {
143
314
  throw e;
144
315
  }
145
316
  throw new Error(`Failed to generate animation, response returned ${response.status} (${response.statusText})`);
@@ -172,15 +343,16 @@ class Client {
172
343
  const url = options instanceof TakeOptions
173
344
  ? await this.generateSignedTakeURL(options)
174
345
  : await this.generateSignedAnimateURL(options);
175
- return this.withConnectionResetRetries(async () => {
176
- const response = await (0, cross_fetch_1.default)(url);
346
+ return this.withConnectionResetRetries(async (attempts) => {
347
+ const request = await this.send(url, attempts);
348
+ const response = request.response;
177
349
  if (response.ok) {
178
350
  return {
179
351
  key: response.headers.get("X-ScreenshotOne-Store-Key"),
180
352
  bucket: response.headers.get("X-ScreenshotOne-Store-Bucket"),
181
353
  };
182
354
  }
183
- const data = await response.json();
355
+ const data = await this.read(request, (r) => r.json());
184
356
  throw new errors_1.default(`Failed to generate animation, response returned ${response.status} (${response.statusText}): ${data?.error_message}`, response.status, data?.error_code, data?.error_message, data?.documentation_url);
185
357
  });
186
358
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "screenshotone-api-sdk",
3
3
  "homepage": "https://screenshotone.com",
4
- "version": "1.1.24",
4
+ "version": "1.1.25",
5
5
  "description": "Use ScreenshotOne.com API to generate screenshots of any website.",
6
6
  "repository": {
7
7
  "type": "git",
package/src/errors.ts CHANGED
@@ -13,4 +13,58 @@ export default class APIError extends Error {
13
13
  this.errorMessage = errorMessage;
14
14
  this.documentationUrl = documentationUrl;
15
15
  }
16
+ }
17
+
18
+ /**
19
+ * Where the connection failed: before the API responded ("request") or while
20
+ * the response was downloading ("response").
21
+ */
22
+ export type ConnectionErrorPhase = "request" | "response";
23
+
24
+ /**
25
+ * The connection to the API failed, for example with ECONNRESET. The message
26
+ * explains what happened and what usually causes it.
27
+ */
28
+ export class ConnectionError extends Error {
29
+ /** The system error code, for example "ECONNRESET". */
30
+ public readonly code: string;
31
+ /** Whether the connection failed before the API responded or while the response was downloading. */
32
+ public readonly phase: ConnectionErrorPhase;
33
+ /** Milliseconds from the start of the last attempt to the failure. */
34
+ public readonly lastElapsedMs: number;
35
+ /**
36
+ * Milliseconds from the start of the first attempt to the failure, waits
37
+ * between retries included. Equals lastElapsedMs when there was one attempt.
38
+ */
39
+ public readonly totalElapsedMs: number;
40
+ /** How many times the request was sent, retries included. */
41
+ public readonly attempts: number;
42
+ /** The HTTP status of the response that was downloading, when the phase is "response". */
43
+ public readonly httpStatusCode?: number;
44
+ /** The underlying error message. */
45
+ public readonly reason?: string;
46
+
47
+ constructor(
48
+ message: string,
49
+ details: {
50
+ code: string;
51
+ phase: ConnectionErrorPhase;
52
+ lastElapsedMs: number;
53
+ totalElapsedMs: number;
54
+ attempts: number;
55
+ httpStatusCode?: number;
56
+ reason?: string;
57
+ }
58
+ ) {
59
+ super(message);
60
+
61
+ this.name = "ConnectionError";
62
+ this.code = details.code;
63
+ this.phase = details.phase;
64
+ this.lastElapsedMs = details.lastElapsedMs;
65
+ this.totalElapsedMs = details.totalElapsedMs;
66
+ this.attempts = details.attempts;
67
+ this.httpStatusCode = details.httpStatusCode;
68
+ this.reason = details.reason;
69
+ }
16
70
  }
package/src/main.ts CHANGED
@@ -1,13 +1,14 @@
1
1
  import Big from "big.js";
2
2
  import fetch from "cross-fetch";
3
3
  import { signQueryString } from "./signature";
4
- import APIError from "./errors";
4
+ import APIError, { ConnectionError, ConnectionErrorPhase } from "./errors";
5
5
 
6
6
  const API_BASE_URL = "https://api.screenshotone.com";
7
7
  const API_TAKE_PATH = "/take";
8
8
  const API_ANIMATE_PATH = "/animate";
9
9
 
10
- export { APIError };
10
+ export { APIError, ConnectionError };
11
+ export type { ConnectionErrorPhase };
11
12
 
12
13
  export interface ClientOptions {
13
14
  /** API base URL. Defaults to https://api.screenshotone.com. */
@@ -20,14 +21,117 @@ export interface ClientOptions {
20
21
  maxRetries?: number;
21
22
  }
22
23
 
24
+ // the only error code the client retries
25
+ const RETRYABLE_CODE = "ECONNRESET";
26
+
23
27
  function isConnectionReset(error: unknown): boolean {
24
28
  return (
25
29
  typeof error === "object" &&
26
30
  error !== null &&
27
- (error as { code?: unknown }).code === "ECONNRESET"
31
+ (error as { code?: unknown }).code === RETRYABLE_CODE
28
32
  );
29
33
  }
30
34
 
35
+ type FetchResponse = Awaited<ReturnType<typeof fetch>>;
36
+
37
+ // one call's attempts: the current one, and when the first one started
38
+ interface Attempts {
39
+ current: number;
40
+ firstStartedAt?: number;
41
+ }
42
+
43
+ // what a ConnectionError reports about the request that failed
44
+ interface SentRequest {
45
+ url: string;
46
+ attempt: number;
47
+ startedAt: number;
48
+ firstStartedAt: number;
49
+ }
50
+
51
+ const CONNECTION_FAILURES: Record<string, string> = {
52
+ ECONNRESET: "the connection was reset",
53
+ EPIPE: "the connection was closed while the request was being sent",
54
+ ERR_STREAM_PREMATURE_CLOSE:
55
+ "the connection closed before the whole response arrived",
56
+ ECONNREFUSED: "the connection was refused",
57
+ ETIMEDOUT: "the connection timed out",
58
+ EHOSTUNREACH: "the API host is unreachable",
59
+ ENETUNREACH: "the network is unreachable",
60
+ ENOTFOUND: "the API host name couldn't be resolved",
61
+ EAI_AGAIN: "the API host name couldn't be resolved",
62
+ };
63
+
64
+ // an open connection that broke, rather than one that couldn't be opened
65
+ const DROPPED_CONNECTION_CODES = [
66
+ "ECONNRESET",
67
+ "EPIPE",
68
+ "ERR_STREAM_PREMATURE_CLOSE",
69
+ ];
70
+
71
+ // The code of a network failure, or undefined for any other error. node-fetch,
72
+ // which cross-fetch uses in Node, rejects with a FetchError of type "system";
73
+ // fetch built on undici rejects with a TypeError caused by the system error.
74
+ function networkFailureCode(error: unknown): string | undefined {
75
+ if (typeof error !== "object" || error === null) {
76
+ return undefined;
77
+ }
78
+
79
+ const { type, code, cause } = error as {
80
+ type?: unknown;
81
+ code?: unknown;
82
+ cause?: unknown;
83
+ };
84
+ if (type === "system" && typeof code === "string") {
85
+ return code;
86
+ }
87
+
88
+ if (error instanceof TypeError && typeof cause === "object" && cause) {
89
+ const causeCode = (cause as { code?: unknown }).code;
90
+ if (typeof causeCode === "string") {
91
+ return causeCode;
92
+ }
93
+ }
94
+
95
+ return undefined;
96
+ }
97
+
98
+ // the request URL without its query and fragment, which hold the access key
99
+ // and the signature, whatever the URL's form
100
+ function withoutQuery(url: string): string {
101
+ return url.split(/[?#]/, 1)[0];
102
+ }
103
+
104
+ // The text without the request's query: exactly as sent, in any URL the text
105
+ // mentions (whatever its scheme spelling, or none), and any credential left.
106
+ function redact(text: string, url: string): string {
107
+ const query = url.slice(withoutQuery(url).length);
108
+
109
+ return (query ? text.split(query).join("") : text)
110
+ .replace(
111
+ /((?:[a-z][a-z0-9+.-]*:)?\/\/[^\s?#]+)[?#]\S*?(?=:?(?:\s|$))/gi,
112
+ "$1"
113
+ )
114
+ .replace(/\b(access_key|signature)=[^&\s]+/gi, "$1=[redacted]");
115
+ }
116
+
117
+ function formatDuration(ms: number): string {
118
+ return ms < 1000 ? `${ms} ms` : `${(ms / 1000).toFixed(1)} s`;
119
+ }
120
+
121
+ function reasonOf(error: unknown, url: string): string | undefined {
122
+ if (!(error instanceof Error)) {
123
+ return undefined;
124
+ }
125
+
126
+ const cause = (error as { cause?: unknown }).cause;
127
+ const message =
128
+ error instanceof TypeError && cause instanceof Error
129
+ ? cause.message
130
+ : error.message;
131
+
132
+ return redact(message, url);
133
+ }
134
+
31
135
  /**
32
136
  * Represents an API client for the ScreenshotOne.com API.
33
137
  */
@@ -66,11 +170,13 @@ export class Client {
66
170
  }
67
171
 
68
172
  private async withConnectionResetRetries<T>(
69
- operation: () => Promise<T>
173
+ operation: (attempts: Attempts) => Promise<T>
70
174
  ): Promise<T> {
175
+ const attempts: Attempts = { current: 0 };
71
176
  for (let retry = 0; ; retry++) {
177
+ attempts.current = retry + 1;
72
178
  try {
73
- return await operation();
179
+ return await operation(attempts);
74
180
  } catch (error) {
75
181
  if (!isConnectionReset(error) || retry >= this.maxRetries) {
76
182
  throw error;
@@ -83,6 +189,118 @@ export class Client {
83
189
  }
84
190
  }
85
191
 
192
+ // Sends the request. A network failure becomes a ConnectionError.
193
+ private async send(
194
+ url: string,
195
+ attempts: Attempts
196
+ ): Promise<SentRequest & { response: FetchResponse }> {
197
+ const startedAt = Date.now();
198
+ attempts.firstStartedAt ??= startedAt;
199
+ const request = {
200
+ url,
201
+ attempt: attempts.current,
202
+ startedAt,
203
+ firstStartedAt: attempts.firstStartedAt,
204
+ };
205
+ try {
206
+ return { ...request, response: await fetch(url) };
207
+ } catch (error) {
208
+ throw this.connectionError(error, request, "request") ?? error;
209
+ }
210
+ }
211
+
212
+ // Reads the response body. A network failure becomes a ConnectionError.
213
+ private async read<T>(
214
+ request: SentRequest & { response: FetchResponse },
215
+ body: (response: FetchResponse) => Promise<T>
216
+ ): Promise<T> {
217
+ try {
218
+ return await body(request.response);
219
+ } catch (error) {
220
+ throw (
221
+ this.connectionError(
222
+ error,
223
+ request,
224
+ "response",
225
+ request.response.status
226
+ ) ?? error
227
+ );
228
+ }
229
+ }
230
+
231
+ // A ConnectionError that explains a network failure, or undefined for any
232
+ // other error
233
+ private connectionError(
234
+ error: unknown,
235
+ request: SentRequest,
236
+ phase: ConnectionErrorPhase,
237
+ httpStatusCode?: number
238
+ ): ConnectionError | undefined {
239
+ const code = networkFailureCode(error);
240
+ if (!code) {
241
+ return undefined;
242
+ }
243
+
244
+ const now = Date.now();
245
+ const lastElapsedMs = now - request.startedAt;
246
+ const totalElapsedMs = now - request.firstStartedAt;
247
+ const endpoint = withoutQuery(request.url);
248
+ const when =
249
+ request.attempt > 1
250
+ ? `${formatDuration(lastElapsedMs)} after the last of ${request.attempt} attempts to ${endpoint} started, ${formatDuration(totalElapsedMs)} after the first`
251
+ : `${formatDuration(lastElapsedMs)} after the request to ${endpoint} started`;
252
+ const failure = `${
253
+ CONNECTION_FAILURES[code] ?? "the connection failed"
254
+ } (${code}) ${when}`;
255
+ const dropped = DROPPED_CONNECTION_CODES.includes(code);
256
+
257
+ const sentences =
258
+ phase === "request"
259
+ ? [
260
+ `The connection to the ScreenshotOne API failed before a response arrived: ${failure}.`,
261
+ ]
262
+ : [
263
+ `The connection to the ScreenshotOne API failed while downloading the response (HTTP ${httpStatusCode}): ${failure}.`,
264
+ httpStatusCode !== undefined && httpStatusCode < 400
265
+ ? "The API had already finished the request. Unless the result came from the cache, it counts toward your usage."
266
+ : "The API had responded with an error, but its details couldn't be read.",
267
+ ];
268
+
269
+ if (dropped) {
270
+ if (phase === "request") {
271
+ sentences.push(
272
+ "The API might not have received the request, or the connection broke while the API was working on it."
273
+ );
274
+ }
275
+ sentences.push(
276
+ "This usually happens on the network between your server and the API: a proxy, NAT gateway or firewall closed the connection, or an idle kept-alive connection was reused after the network had closed it. It's more likely when many requests start at once."
277
+ );
278
+ sentences.push(
279
+ request.attempt > 1
280
+ ? `It failed on all ${request.attempt} attempts. Limit how many requests run at once.`
281
+ : code === RETRYABLE_CODE && this.maxRetries === 0
282
+ ? "Limit how many requests run at once, or set the maxRetries client option to retry automatically."
283
+ : "Limit how many requests run at once."
284
+ );
285
+ } else if (code === "ENOTFOUND" || code === "EAI_AGAIN") {
286
+ sentences.push("Check your server's DNS settings.");
287
+ } else {
288
+ sentences.push(
289
+ "Check that your server can reach the API, including firewall and proxy settings."
290
+ );
291
+ }
292
+
293
+ return new ConnectionError(sentences.join(" "), {
294
+ code,
295
+ phase,
296
+ lastElapsedMs,
297
+ totalElapsedMs,
298
+ attempts: request.attempt,
299
+ httpStatusCode,
300
+ reason: reasonOf(error, request.url),
301
+ });
302
+ }
303
+
86
304
  /**
87
305
  * Generates an URL that can be used to send GET requests for taking screenshots.
88
306
  *
@@ -143,14 +361,15 @@ export class Client {
143
361
  */
144
362
  async take(options: TakeOptions): Promise<Blob> {
145
363
  const url = await this.generateSignedTakeURL(options);
146
- return this.withConnectionResetRetries(async () => {
147
- const response = await fetch(url);
364
+ return this.withConnectionResetRetries(async (attempts) => {
365
+ const request = await this.send(url, attempts);
366
+ const response = request.response;
148
367
  if (response.ok) {
149
- return await response.blob();
368
+ return await this.read(request, (r) => r.blob());
150
369
  }
151
370
 
152
371
  try {
153
- const data = await response.json();
372
+ const data = await this.read(request, (r) => r.json());
154
373
 
155
374
  throw new APIError(
156
375
  `Failed to generate screenshot, response returned ${response.status} (${response.statusText}): ${data?.error_message}`,
@@ -160,7 +379,7 @@ export class Client {
160
379
  data?.documentation_url
161
380
  );
162
381
  } catch (e) {
163
- if (e instanceof APIError || isConnectionReset(e)) {
382
+ if (e instanceof APIError || e instanceof ConnectionError) {
164
383
  throw e;
165
384
  }
166
385
 
@@ -179,14 +398,15 @@ export class Client {
179
398
  */
180
399
  async animate(options: AnimateOptions): Promise<Blob> {
181
400
  const url = await this.generateSignedAnimateURL(options);
182
- return this.withConnectionResetRetries(async () => {
183
- const response = await fetch(url);
401
+ return this.withConnectionResetRetries(async (attempts) => {
402
+ const request = await this.send(url, attempts);
403
+ const response = request.response;
184
404
  if (response.ok) {
185
- return await response.blob();
405
+ return await this.read(request, (r) => r.blob());
186
406
  }
187
407
 
188
408
  try {
189
- const data = await response.json();
409
+ const data = await this.read(request, (r) => r.json());
190
410
 
191
411
  throw new APIError(
192
412
  `Failed to generate animation, response returned ${response.status} (${response.statusText}): ${data?.error_message}`,
@@ -196,7 +416,7 @@ export class Client {
196
416
  data?.documentation_url
197
417
  );
198
418
  } catch (e) {
199
- if (e instanceof APIError || isConnectionReset(e)) {
419
+ if (e instanceof APIError || e instanceof ConnectionError) {
200
420
  throw e;
201
421
  }
202
422
 
@@ -245,8 +465,9 @@ export class Client {
245
465
  ? await this.generateSignedTakeURL(options)
246
466
  : await this.generateSignedAnimateURL(options);
247
467
 
248
- return this.withConnectionResetRetries(async () => {
249
- const response = await fetch(url);
468
+ return this.withConnectionResetRetries(async (attempts) => {
469
+ const request = await this.send(url, attempts);
470
+ const response = request.response;
250
471
  if (response.ok) {
251
472
  return {
252
473
  key: response.headers.get("X-ScreenshotOne-Store-Key"),
@@ -254,7 +475,7 @@ export class Client {
254
475
  };
255
476
  }
256
477
 
257
- const data = await response.json();
478
+ const data = await this.read(request, (r) => r.json());
258
479
 
259
480
  throw new APIError(
260
481
  `Failed to generate animation, response returned ${response.status} (${response.statusText}): ${data?.error_message}`,