scrapfly-sdk 0.10.3 → 0.10.5

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 (166) hide show
  1. package/esm/browserconfig.d.ts +70 -1
  2. package/esm/browserconfig.d.ts.map +1 -1
  3. package/esm/browserconfig.js +44 -1
  4. package/esm/client.d.ts +33 -0
  5. package/esm/client.d.ts.map +1 -1
  6. package/esm/client.js +33 -5
  7. package/esm/crawl.d.ts +4 -0
  8. package/esm/crawl.d.ts.map +1 -1
  9. package/esm/crawl.js +4 -0
  10. package/esm/crawlerresult.d.ts +7 -0
  11. package/esm/crawlerresult.d.ts.map +1 -1
  12. package/esm/errors.d.ts +43 -0
  13. package/esm/errors.d.ts.map +1 -1
  14. package/esm/errors.js +43 -16
  15. package/esm/extractionconfig.d.ts +54 -9
  16. package/esm/extractionconfig.d.ts.map +1 -1
  17. package/esm/extractionconfig.js +37 -13
  18. package/esm/logger.d.ts +1 -0
  19. package/esm/logger.d.ts.map +1 -1
  20. package/esm/logger.js +1 -0
  21. package/esm/main.d.ts +27 -0
  22. package/esm/main.d.ts.map +1 -1
  23. package/esm/main.js +27 -0
  24. package/esm/monitoringconfig.d.ts +48 -11
  25. package/esm/monitoringconfig.d.ts.map +1 -1
  26. package/esm/monitoringconfig.js +14 -0
  27. package/esm/result.d.ts +2 -0
  28. package/esm/result.d.ts.map +1 -1
  29. package/esm/scrapeconfig.d.ts +10 -8
  30. package/esm/scrapeconfig.d.ts.map +1 -1
  31. package/esm/scrapeconfig.js +10 -8
  32. package/esm/screenshotconfig.d.ts +59 -26
  33. package/esm/screenshotconfig.d.ts.map +1 -1
  34. package/esm/screenshotconfig.js +38 -26
  35. package/esm/webhookserver.d.ts +24 -0
  36. package/esm/webhookserver.d.ts.map +1 -1
  37. package/esm/webhookserver.js +24 -0
  38. package/package.json +1 -1
  39. package/script/browserconfig.d.ts +70 -1
  40. package/script/browserconfig.d.ts.map +1 -1
  41. package/script/browserconfig.js +44 -1
  42. package/script/client.d.ts +33 -0
  43. package/script/client.d.ts.map +1 -1
  44. package/script/client.js +33 -5
  45. package/script/crawl.d.ts +4 -0
  46. package/script/crawl.d.ts.map +1 -1
  47. package/script/crawl.js +4 -0
  48. package/script/crawlerresult.d.ts +7 -0
  49. package/script/crawlerresult.d.ts.map +1 -1
  50. package/script/errors.d.ts +43 -0
  51. package/script/errors.d.ts.map +1 -1
  52. package/script/errors.js +43 -16
  53. package/script/extractionconfig.d.ts +54 -9
  54. package/script/extractionconfig.d.ts.map +1 -1
  55. package/script/extractionconfig.js +37 -13
  56. package/script/logger.d.ts +1 -0
  57. package/script/logger.d.ts.map +1 -1
  58. package/script/logger.js +1 -0
  59. package/script/main.d.ts +27 -0
  60. package/script/main.d.ts.map +1 -1
  61. package/script/main.js +27 -0
  62. package/script/monitoringconfig.d.ts +48 -11
  63. package/script/monitoringconfig.d.ts.map +1 -1
  64. package/script/monitoringconfig.js +14 -0
  65. package/script/result.d.ts +2 -0
  66. package/script/result.d.ts.map +1 -1
  67. package/script/scrapeconfig.d.ts +10 -8
  68. package/script/scrapeconfig.d.ts.map +1 -1
  69. package/script/scrapeconfig.js +10 -8
  70. package/script/screenshotconfig.d.ts +59 -26
  71. package/script/screenshotconfig.d.ts.map +1 -1
  72. package/script/screenshotconfig.js +38 -26
  73. package/script/webhookserver.d.ts +24 -0
  74. package/script/webhookserver.d.ts.map +1 -1
  75. package/script/webhookserver.js +24 -0
  76. package/src/_dnt.shims.ts +64 -0
  77. package/src/batch.ts +272 -0
  78. package/src/browserconfig.ts +187 -0
  79. package/src/client.ts +1637 -0
  80. package/src/crawl.ts +255 -0
  81. package/src/crawlerconfig.ts +363 -0
  82. package/src/crawlerresult.ts +478 -0
  83. package/src/deps/jsr.io/@std/path/1.0.1/_common/assert_path.ts +10 -0
  84. package/src/deps/jsr.io/@std/path/1.0.1/_common/basename.ts +53 -0
  85. package/src/deps/jsr.io/@std/path/1.0.1/_common/common.ts +26 -0
  86. package/src/deps/jsr.io/@std/path/1.0.1/_common/constants.ts +49 -0
  87. package/src/deps/jsr.io/@std/path/1.0.1/_common/dirname.ts +9 -0
  88. package/src/deps/jsr.io/@std/path/1.0.1/_common/format.ts +25 -0
  89. package/src/deps/jsr.io/@std/path/1.0.1/_common/from_file_url.ts +10 -0
  90. package/src/deps/jsr.io/@std/path/1.0.1/_common/glob_to_reg_exp.ts +290 -0
  91. package/src/deps/jsr.io/@std/path/1.0.1/_common/normalize.ts +9 -0
  92. package/src/deps/jsr.io/@std/path/1.0.1/_common/normalize_string.ts +74 -0
  93. package/src/deps/jsr.io/@std/path/1.0.1/_common/relative.ts +10 -0
  94. package/src/deps/jsr.io/@std/path/1.0.1/_common/strip_trailing_separators.ts +25 -0
  95. package/src/deps/jsr.io/@std/path/1.0.1/_common/to_file_url.ts +17 -0
  96. package/src/deps/jsr.io/@std/path/1.0.1/_os.ts +31 -0
  97. package/src/deps/jsr.io/@std/path/1.0.1/basename.ts +35 -0
  98. package/src/deps/jsr.io/@std/path/1.0.1/common.ts +35 -0
  99. package/src/deps/jsr.io/@std/path/1.0.1/constants.ts +18 -0
  100. package/src/deps/jsr.io/@std/path/1.0.1/dirname.ts +28 -0
  101. package/src/deps/jsr.io/@std/path/1.0.1/extname.ts +27 -0
  102. package/src/deps/jsr.io/@std/path/1.0.1/format.ts +30 -0
  103. package/src/deps/jsr.io/@std/path/1.0.1/from_file_url.ts +30 -0
  104. package/src/deps/jsr.io/@std/path/1.0.1/glob_to_regexp.ts +94 -0
  105. package/src/deps/jsr.io/@std/path/1.0.1/is_absolute.ts +30 -0
  106. package/src/deps/jsr.io/@std/path/1.0.1/is_glob.ts +49 -0
  107. package/src/deps/jsr.io/@std/path/1.0.1/join.ts +28 -0
  108. package/src/deps/jsr.io/@std/path/1.0.1/join_globs.ts +42 -0
  109. package/src/deps/jsr.io/@std/path/1.0.1/mod.ts +55 -0
  110. package/src/deps/jsr.io/@std/path/1.0.1/normalize.ts +31 -0
  111. package/src/deps/jsr.io/@std/path/1.0.1/normalize_glob.ts +45 -0
  112. package/src/deps/jsr.io/@std/path/1.0.1/parse.ts +44 -0
  113. package/src/deps/jsr.io/@std/path/1.0.1/posix/_util.ts +10 -0
  114. package/src/deps/jsr.io/@std/path/1.0.1/posix/basename.ts +39 -0
  115. package/src/deps/jsr.io/@std/path/1.0.1/posix/constants.ts +15 -0
  116. package/src/deps/jsr.io/@std/path/1.0.1/posix/dirname.ts +55 -0
  117. package/src/deps/jsr.io/@std/path/1.0.1/posix/extname.ts +73 -0
  118. package/src/deps/jsr.io/@std/path/1.0.1/posix/format.ts +31 -0
  119. package/src/deps/jsr.io/@std/path/1.0.1/posix/from_file_url.ts +25 -0
  120. package/src/deps/jsr.io/@std/path/1.0.1/posix/glob_to_regexp.ts +94 -0
  121. package/src/deps/jsr.io/@std/path/1.0.1/posix/is_absolute.ts +25 -0
  122. package/src/deps/jsr.io/@std/path/1.0.1/posix/join.ts +27 -0
  123. package/src/deps/jsr.io/@std/path/1.0.1/posix/join_globs.ts +44 -0
  124. package/src/deps/jsr.io/@std/path/1.0.1/posix/normalize.ts +41 -0
  125. package/src/deps/jsr.io/@std/path/1.0.1/posix/normalize_glob.ts +42 -0
  126. package/src/deps/jsr.io/@std/path/1.0.1/posix/parse.ts +121 -0
  127. package/src/deps/jsr.io/@std/path/1.0.1/posix/relative.ts +103 -0
  128. package/src/deps/jsr.io/@std/path/1.0.1/posix/resolve.ts +69 -0
  129. package/src/deps/jsr.io/@std/path/1.0.1/posix/to_file_url.ts +32 -0
  130. package/src/deps/jsr.io/@std/path/1.0.1/posix/to_namespaced_path.ts +21 -0
  131. package/src/deps/jsr.io/@std/path/1.0.1/relative.ts +32 -0
  132. package/src/deps/jsr.io/@std/path/1.0.1/resolve.ts +32 -0
  133. package/src/deps/jsr.io/@std/path/1.0.1/to_file_url.ts +30 -0
  134. package/src/deps/jsr.io/@std/path/1.0.1/to_namespaced_path.ts +31 -0
  135. package/src/deps/jsr.io/@std/path/1.0.1/types.ts +40 -0
  136. package/src/deps/jsr.io/@std/path/1.0.1/windows/_util.ts +28 -0
  137. package/src/deps/jsr.io/@std/path/1.0.1/windows/basename.ts +48 -0
  138. package/src/deps/jsr.io/@std/path/1.0.1/windows/constants.ts +15 -0
  139. package/src/deps/jsr.io/@std/path/1.0.1/windows/dirname.ts +114 -0
  140. package/src/deps/jsr.io/@std/path/1.0.1/windows/extname.ts +86 -0
  141. package/src/deps/jsr.io/@std/path/1.0.1/windows/format.ts +31 -0
  142. package/src/deps/jsr.io/@std/path/1.0.1/windows/from_file_url.ts +34 -0
  143. package/src/deps/jsr.io/@std/path/1.0.1/windows/glob_to_regexp.ts +92 -0
  144. package/src/deps/jsr.io/@std/path/1.0.1/windows/is_absolute.ts +40 -0
  145. package/src/deps/jsr.io/@std/path/1.0.1/windows/join.ts +72 -0
  146. package/src/deps/jsr.io/@std/path/1.0.1/windows/join_globs.ts +45 -0
  147. package/src/deps/jsr.io/@std/path/1.0.1/windows/normalize.ts +132 -0
  148. package/src/deps/jsr.io/@std/path/1.0.1/windows/normalize_glob.ts +42 -0
  149. package/src/deps/jsr.io/@std/path/1.0.1/windows/parse.ts +184 -0
  150. package/src/deps/jsr.io/@std/path/1.0.1/windows/relative.ts +128 -0
  151. package/src/deps/jsr.io/@std/path/1.0.1/windows/resolve.ts +174 -0
  152. package/src/deps/jsr.io/@std/path/1.0.1/windows/to_file_url.ts +38 -0
  153. package/src/deps/jsr.io/@std/path/1.0.1/windows/to_namespaced_path.ts +60 -0
  154. package/src/deps.ts +4 -0
  155. package/src/errors.ts +82 -0
  156. package/src/extractionconfig.ts +217 -0
  157. package/src/logger.ts +53 -0
  158. package/src/main.ts +88 -0
  159. package/src/monitoringconfig.ts +88 -0
  160. package/src/polyfill.ts +37 -0
  161. package/src/result.ts +340 -0
  162. package/src/scrapeconfig.ts +450 -0
  163. package/src/screenshotconfig.ts +237 -0
  164. package/src/types.ts +2 -0
  165. package/src/utils.ts +86 -0
  166. package/src/webhookserver.ts +90 -0
@@ -0,0 +1,174 @@
1
+ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
2
+ // This module is browser compatible.
3
+ import * as dntShim from "../../../../../../_dnt.shims.js";
4
+
5
+
6
+ import { CHAR_COLON } from "../_common/constants.js";
7
+ import { normalizeString } from "../_common/normalize_string.js";
8
+ import { assertPath } from "../_common/assert_path.js";
9
+ import { isPathSeparator, isWindowsDeviceRoot } from "./_util.js";
10
+
11
+ /**
12
+ * Resolves path segments into a `path`.
13
+ *
14
+ * @example Usage
15
+ * ```ts
16
+ * import { resolve } from "@std/path/windows/resolve";
17
+ * import { assertEquals } from "@std/assert";
18
+ *
19
+ * const resolved = resolve("C:\\foo\\bar", "..\\baz");
20
+ * assertEquals(resolved, "C:\\foo\\baz");
21
+ * ```
22
+ *
23
+ * @param pathSegments The path segments to process to path
24
+ * @returns The resolved path
25
+ */
26
+ export function resolve(...pathSegments: string[]): string {
27
+ let resolvedDevice = "";
28
+ let resolvedTail = "";
29
+ let resolvedAbsolute = false;
30
+
31
+ for (let i = pathSegments.length - 1; i >= -1; i--) {
32
+ let path: string;
33
+ // deno-lint-ignore no-explicit-any
34
+ const { Deno } = dntShim.dntGlobalThis as any;
35
+ if (i >= 0) {
36
+ path = pathSegments[i]!;
37
+ } else if (!resolvedDevice) {
38
+ if (typeof Deno?.cwd !== "function") {
39
+ throw new TypeError("Resolved a drive-letter-less path without a CWD.");
40
+ }
41
+ path = Deno.cwd();
42
+ } else {
43
+ if (
44
+ typeof Deno?.env?.get !== "function" || typeof Deno?.cwd !== "function"
45
+ ) {
46
+ throw new TypeError("Resolved a relative path without a CWD.");
47
+ }
48
+ path = Deno.cwd();
49
+
50
+ // Verify that a cwd was found and that it actually points
51
+ // to our drive. If not, default to the drive's root.
52
+ if (
53
+ path === undefined ||
54
+ path.slice(0, 3).toLowerCase() !== `${resolvedDevice.toLowerCase()}\\`
55
+ ) {
56
+ path = `${resolvedDevice}\\`;
57
+ }
58
+ }
59
+
60
+ assertPath(path);
61
+
62
+ const len = path.length;
63
+
64
+ // Skip empty entries
65
+ if (len === 0) continue;
66
+
67
+ let rootEnd = 0;
68
+ let device = "";
69
+ let isAbsolute = false;
70
+ const code = path.charCodeAt(0);
71
+
72
+ // Try to match a root
73
+ if (len > 1) {
74
+ if (isPathSeparator(code)) {
75
+ // Possible UNC root
76
+
77
+ // If we started with a separator, we know we at least have an
78
+ // absolute path of some kind (UNC or otherwise)
79
+ isAbsolute = true;
80
+
81
+ if (isPathSeparator(path.charCodeAt(1))) {
82
+ // Matched double path separator at beginning
83
+ let j = 2;
84
+ let last = j;
85
+ // Match 1 or more non-path separators
86
+ for (; j < len; ++j) {
87
+ if (isPathSeparator(path.charCodeAt(j))) break;
88
+ }
89
+ if (j < len && j !== last) {
90
+ const firstPart = path.slice(last, j);
91
+ // Matched!
92
+ last = j;
93
+ // Match 1 or more path separators
94
+ for (; j < len; ++j) {
95
+ if (!isPathSeparator(path.charCodeAt(j))) break;
96
+ }
97
+ if (j < len && j !== last) {
98
+ // Matched!
99
+ last = j;
100
+ // Match 1 or more non-path separators
101
+ for (; j < len; ++j) {
102
+ if (isPathSeparator(path.charCodeAt(j))) break;
103
+ }
104
+ if (j === len) {
105
+ // We matched a UNC root only
106
+ device = `\\\\${firstPart}\\${path.slice(last)}`;
107
+ rootEnd = j;
108
+ } else if (j !== last) {
109
+ // We matched a UNC root with leftovers
110
+
111
+ device = `\\\\${firstPart}\\${path.slice(last, j)}`;
112
+ rootEnd = j;
113
+ }
114
+ }
115
+ }
116
+ } else {
117
+ rootEnd = 1;
118
+ }
119
+ } else if (isWindowsDeviceRoot(code)) {
120
+ // Possible device root
121
+
122
+ if (path.charCodeAt(1) === CHAR_COLON) {
123
+ device = path.slice(0, 2);
124
+ rootEnd = 2;
125
+ if (len > 2) {
126
+ if (isPathSeparator(path.charCodeAt(2))) {
127
+ // Treat separator following drive name as an absolute path
128
+ // indicator
129
+ isAbsolute = true;
130
+ rootEnd = 3;
131
+ }
132
+ }
133
+ }
134
+ }
135
+ } else if (isPathSeparator(code)) {
136
+ // `path` contains just a path separator
137
+ rootEnd = 1;
138
+ isAbsolute = true;
139
+ }
140
+
141
+ if (
142
+ device.length > 0 &&
143
+ resolvedDevice.length > 0 &&
144
+ device.toLowerCase() !== resolvedDevice.toLowerCase()
145
+ ) {
146
+ // This path points to another device so it is not applicable
147
+ continue;
148
+ }
149
+
150
+ if (resolvedDevice.length === 0 && device.length > 0) {
151
+ resolvedDevice = device;
152
+ }
153
+ if (!resolvedAbsolute) {
154
+ resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`;
155
+ resolvedAbsolute = isAbsolute;
156
+ }
157
+
158
+ if (resolvedAbsolute && resolvedDevice.length > 0) break;
159
+ }
160
+
161
+ // At this point the path should be resolved to a full absolute path,
162
+ // but handle relative paths to be safe (might happen when Deno.cwd()
163
+ // fails)
164
+
165
+ // Normalize the tail path
166
+ resolvedTail = normalizeString(
167
+ resolvedTail,
168
+ !resolvedAbsolute,
169
+ "\\",
170
+ isPathSeparator,
171
+ );
172
+
173
+ return resolvedDevice + (resolvedAbsolute ? "\\" : "") + resolvedTail || ".";
174
+ }
@@ -0,0 +1,38 @@
1
+ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
2
+ // This module is browser compatible.
3
+
4
+ import { encodeWhitespace } from "../_common/to_file_url.js";
5
+ import { isAbsolute } from "./is_absolute.js";
6
+
7
+ /**
8
+ * Converts a path string to a file URL.
9
+ *
10
+ * @example Usage
11
+ * ```ts
12
+ * import { toFileUrl } from "@std/path/windows/to-file-url";
13
+ * import { assertEquals } from "@std/assert";
14
+ *
15
+ * assertEquals(toFileUrl("\\home\\foo"), new URL("file:///home/foo"));
16
+ * assertEquals(toFileUrl("C:\\Users\\foo"), new URL("file:///C:/Users/foo"));
17
+ * assertEquals(toFileUrl("\\\\127.0.0.1\\home\\foo"), new URL("file://127.0.0.1/home/foo"));
18
+ * ```
19
+ * @param path The path to convert.
20
+ * @returns The file URL.
21
+ */
22
+ export function toFileUrl(path: string): URL {
23
+ if (!isAbsolute(path)) {
24
+ throw new TypeError("Must be an absolute path.");
25
+ }
26
+ const [, hostname, pathname] = path.match(
27
+ /^(?:[/\\]{2}([^/\\]+)(?=[/\\](?:[^/\\]|$)))?(.*)/,
28
+ )!;
29
+ const url = new URL("file:///");
30
+ url.pathname = encodeWhitespace(pathname!.replace(/%/g, "%25"));
31
+ if (hostname !== undefined && hostname !== "localhost") {
32
+ url.hostname = hostname;
33
+ if (!url.hostname) {
34
+ throw new TypeError("Invalid hostname.");
35
+ }
36
+ }
37
+ return url;
38
+ }
@@ -0,0 +1,60 @@
1
+ // Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
2
+ // This module is browser compatible.
3
+
4
+ import {
5
+ CHAR_BACKWARD_SLASH,
6
+ CHAR_COLON,
7
+ CHAR_DOT,
8
+ CHAR_QUESTION_MARK,
9
+ } from "../_common/constants.js";
10
+ import { isWindowsDeviceRoot } from "./_util.js";
11
+ import { resolve } from "./resolve.js";
12
+
13
+ /**
14
+ * Resolves path to a namespace path
15
+ *
16
+ * @example Usage
17
+ * ```ts
18
+ * import { toNamespacedPath } from "@std/path/windows/to-namespaced-path";
19
+ * import { assertEquals } from "@std/assert";
20
+ *
21
+ * const namespaced = toNamespacedPath("C:\\foo\\bar");
22
+ * assertEquals(namespaced, "\\\\?\\C:\\foo\\bar");
23
+ * ```
24
+ *
25
+ * @param path The path to resolve to namespaced path
26
+ * @returns The resolved namespaced path
27
+ */
28
+ export function toNamespacedPath(path: string): string {
29
+ // Note: this will *probably* throw somewhere.
30
+ if (typeof path !== "string") return path;
31
+ if (path.length === 0) return "";
32
+
33
+ const resolvedPath = resolve(path);
34
+
35
+ if (resolvedPath.length >= 3) {
36
+ if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
37
+ // Possible UNC root
38
+
39
+ if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
40
+ const code = resolvedPath.charCodeAt(2);
41
+ if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
42
+ // Matched non-long UNC root, convert the path to a long UNC path
43
+ return `\\\\?\\UNC\\${resolvedPath.slice(2)}`;
44
+ }
45
+ }
46
+ } else if (isWindowsDeviceRoot(resolvedPath.charCodeAt(0))) {
47
+ // Possible device root
48
+
49
+ if (
50
+ resolvedPath.charCodeAt(1) === CHAR_COLON &&
51
+ resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
52
+ ) {
53
+ // Matched device root, convert the path to a long UNC path
54
+ return `\\\\?\\${resolvedPath}`;
55
+ }
56
+ }
57
+ }
58
+
59
+ return path;
60
+ }
package/src/deps.ts ADDED
@@ -0,0 +1,4 @@
1
+ import * as cheerio from 'cheerio';
2
+ import * as path from './deps/jsr.io/@std/path/1.0.1/mod.js';
3
+
4
+ export { cheerio, path };
package/src/errors.ts ADDED
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Base class for every error thrown by the Scrapfly SDK.
3
+ *
4
+ * Concrete subclasses distinguish config-level, HTTP-level, and
5
+ * API-specific failures so callers can catch the exact category they
6
+ * care about without string-matching on error messages.
7
+ */
8
+ export class ScrapflyError extends Error {
9
+ /** Extra context carried alongside the error message (response body, request params, etc.). */
10
+ args: Record<string, any>;
11
+
12
+ /**
13
+ * @param message Human-readable description of the failure.
14
+ * @param args Optional structured context to attach to the error.
15
+ */
16
+ constructor(message: string, args: Record<string, any> = {}) {
17
+ super(message);
18
+ this.args = args;
19
+ }
20
+ }
21
+
22
+ /** Raised when a ScrapeConfig is constructed with invalid parameters. */
23
+ export class ScrapeConfigError extends ScrapflyError {}
24
+ /** Raised when a ScreenshotConfig is constructed with invalid parameters. */
25
+ export class ScreenshotConfigError extends ScrapflyError {}
26
+ /** Raised when an ExtractionConfig is constructed with invalid parameters. */
27
+ export class ExtractionConfigError extends ScrapflyError {}
28
+ /** Raised when a CrawlerConfig is constructed with invalid parameters. */
29
+ export class CrawlerConfigError extends ScrapflyError {}
30
+
31
+ /** Raised when scrape parameters cannot be encoded into a request. */
32
+ export class EncodeError extends ScrapflyError {}
33
+ /** Raised when a response carries an unexpected or unsupported Content-Type. */
34
+ export class ContentTypeError extends ScrapflyError {}
35
+
36
+ /** Base error for every HTTP-level failure surfaced by the SDK. */
37
+ export class HttpError extends ScrapflyError {}
38
+ /** Raised when the upstream target returned an error to Scrapfly. */
39
+ export class UpstreamHttpError extends HttpError {}
40
+ /** Raised when the upstream target returned a 4xx client error. */
41
+ export class UpstreamHttpClientError extends UpstreamHttpError {}
42
+ /** Raised when the upstream target returned a 5xx server error. */
43
+ export class UpstreamHttpServerError extends UpstreamHttpClientError {}
44
+
45
+ /** Raised when the Scrapfly API itself returned a 4xx client error. */
46
+ export class ApiHttpClientError extends HttpError {}
47
+ /** Raised when the API key provided to the client is missing, invalid, or revoked. */
48
+ export class BadApiKeyError extends ApiHttpClientError {}
49
+
50
+ /** Raised when the request is rate-limited (HTTP 429). */
51
+ export class TooManyRequests extends HttpError {}
52
+ /** Raised when the Scrapfly API returned a 5xx server error. */
53
+ export class ApiHttpServerError extends HttpError {}
54
+ /** Raised when a scrape call fails for a reason not captured by a more specific subclass. */
55
+ export class ScrapflyScrapeError extends HttpError {}
56
+ /** Raised when proxy settings do not match an available proxy (invalid pool, unsupported country, ...). */
57
+ export class ScrapflyProxyError extends HttpError {}
58
+ /** Raised when the request is throttled by Scrapfly (e.g. burst limits). */
59
+ export class ScrapflyThrottleError extends HttpError {}
60
+ /** Raised when Scrapfly failed to bypass anti-scraping protection on the target. */
61
+ export class ScrapflyAspError extends HttpError {}
62
+ /** Raised when a scheduled scrape cannot be created or fulfilled. */
63
+ export class ScrapflyScheduleError extends HttpError {}
64
+ /** Raised when a webhook is invalid or cannot be delivered (e.g. full queue). */
65
+ export class ScrapflyWebhookError extends HttpError {}
66
+ /** Raised when a session is accessed concurrently in a way that violates session semantics. */
67
+ export class ScrapflySessionError extends HttpError {}
68
+ /** Raised when concurrent requests exceed the account's concurrency limit. */
69
+ export class TooManyConcurrentRequests extends HttpError {}
70
+ /** Raised when the account is out of scrape credits. */
71
+ export class QuotaLimitReached extends HttpError {}
72
+ /** Raised for screenshot-API-specific failures. */
73
+ export class ScreenshotApiError extends ApiHttpClientError {}
74
+ /** Raised for extraction-API-specific failures. */
75
+ export class ExtractionApiError extends ApiHttpClientError {}
76
+ /**
77
+ * Raised for crawler-API-specific failures.
78
+ *
79
+ * Covers crawler job lifecycle errors such as ALREADY_STARTED,
80
+ * NOT_STARTED, FAILED, CANCELLED, TIMEOUT, etc.
81
+ */
82
+ export class ScrapflyCrawlerError extends HttpError {}
@@ -0,0 +1,217 @@
1
+ import * as errors from './errors.js';
2
+ import { urlsafe_b64encode } from './utils.js';
3
+ import { ExtractionConfigError } from './errors.js';
4
+
5
+ /** Compression format declared for documents submitted to the Extraction API. */
6
+ export enum CompressionFormat {
7
+ /** gzip compression. */
8
+ GZIP = 'gzip',
9
+ /** zstd compression. */
10
+ ZSTD = 'zstd',
11
+ /** DEFLATE compression. */
12
+ DEFLATE = 'deflate',
13
+ }
14
+
15
+ /**
16
+ * User-facing options accepted by {@link ExtractionConfig}. See the
17
+ * [Extraction API reference](https://scrapfly.io/docs/extraction-api)
18
+ * for the authoritative list of valid values.
19
+ */
20
+ type ExtractionConfigOptions = {
21
+ /** Document body to extract from. */
22
+ body: string;
23
+ /** Content-Type of the body (e.g. "text/html"). */
24
+ content_type: string;
25
+ /** URL associated with the document (used for link resolution). */
26
+ url?: string;
27
+ /** Character set of the document. */
28
+ charset?: string;
29
+ /** Name of a saved extraction template. */
30
+ extraction_template?: string;
31
+ /** Inline extraction template, used instead of a saved one. */
32
+ extraction_ephemeral_template?: object;
33
+ /** Natural-language prompt for LLM-based extraction. */
34
+ extraction_prompt?: string;
35
+ /** Override the LLM model used for prompt-based extraction. */
36
+ extraction_model?: string;
37
+ /** Whether the provided body is already compressed. */
38
+ is_document_compressed?: boolean;
39
+ /** Compression format of the body. See {@link CompressionFormat}. */
40
+ document_compression_format?: 'gzip' | 'zstd' | 'deflate' | CompressionFormat;
41
+ /** Webhook name to notify when extraction completes. */
42
+ webhook?: string;
43
+ /** Request timeout in milliseconds. */
44
+ timeout?: number;
45
+
46
+ /** @deprecated Use {@link extraction_template} instead. */
47
+ template?: string;
48
+ /** @deprecated Use {@link extraction_ephemeral_template} instead. */
49
+ ephemeral_template?: object;
50
+ };
51
+
52
+ /**
53
+ * Configuration for an Extraction API call. Holds the document to
54
+ * extract from and the template/prompt/model that should drive the
55
+ * extraction.
56
+ */
57
+ export class ExtractionConfig {
58
+ /** Document body. */
59
+ body: string | Uint8Array;
60
+ /** Content-Type of the body. */
61
+ content_type: string;
62
+ /** URL associated with the document. */
63
+ url?: string;
64
+ /** Character set of the document. */
65
+ charset?: string;
66
+ /** Saved extraction template name. */
67
+ extraction_template?: string;
68
+ /** Inline extraction template. */
69
+ extraction_ephemeral_template?: object;
70
+ /** Natural-language extraction prompt. */
71
+ extraction_prompt?: string;
72
+ /** LLM model override for prompt-based extraction. */
73
+ extraction_model?: string;
74
+ /** Whether the body is pre-compressed. */
75
+ is_document_compressed?: boolean;
76
+ /** Compression format of the body. */
77
+ document_compression_format?: 'gzip' | 'zstd' | 'deflate' | CompressionFormat;
78
+ /** Webhook name to notify on completion. */
79
+ webhook?: string;
80
+ /** Request timeout in milliseconds. */
81
+ timeout?: number;
82
+
83
+ /** @deprecated Use {@link extraction_template} instead. */
84
+ template?: string;
85
+ /** @deprecated Use {@link extraction_ephemeral_template} instead. */
86
+ ephemeral_template?: object;
87
+
88
+ /**
89
+ * @param options See {@link ExtractionConfigOptions}.
90
+ * @throws {@link errors.ExtractionConfigError} if an unknown option is supplied.
91
+ */
92
+ constructor(options: ExtractionConfigOptions) {
93
+ this.validateOptions(options);
94
+ if (options.template) {
95
+ console.warn(
96
+ `Deprecation warning: 'template' is deprecated. Use 'extraction_template' instead.`
97
+ );
98
+ this.extraction_template = options.template;
99
+ } else {
100
+ this.extraction_template = options.extraction_template;
101
+ }
102
+ if (options.ephemeral_template) {
103
+ console.warn(
104
+ `Deprecation warning: 'ephemeral_template' is deprecated. Use 'extraction_ephemeral_template' instead.`
105
+ );
106
+ this.extraction_ephemeral_template = options.ephemeral_template;
107
+ } else {
108
+ this.extraction_ephemeral_template = options.extraction_ephemeral_template;
109
+ }
110
+
111
+ if (
112
+ options.document_compression_format &&
113
+ !Object.values(CompressionFormat).includes(options.document_compression_format as CompressionFormat)
114
+ ) {
115
+ throw new errors.ExtractionConfigError(
116
+ `Invalid CompressionFormat param value: ${options.document_compression_format}`,
117
+ );
118
+ }
119
+ this.body = options.body;
120
+ this.content_type = options.content_type;
121
+ this.url = options.url ?? this.url;
122
+ this.charset = options.charset ?? this.charset;
123
+ this.extraction_template = options.extraction_template ?? this.extraction_template;
124
+ this.extraction_ephemeral_template = options.extraction_ephemeral_template ?? this.extraction_ephemeral_template;
125
+ this.extraction_prompt = options.extraction_prompt ?? this.extraction_prompt;
126
+ this.extraction_model = options.extraction_model ?? this.extraction_model;
127
+ this.is_document_compressed = options.is_document_compressed ?? this.is_document_compressed;
128
+ this.document_compression_format = options.document_compression_format ?? this.document_compression_format;
129
+ this.webhook = options.webhook ?? this.webhook;
130
+ this.timeout = options.timeout ?? this.timeout;
131
+ }
132
+
133
+ private validateOptions(options: Partial<ExtractionConfigOptions>) {
134
+ const validKeys = new Set(Object.keys(this) as Array<keyof ExtractionConfig>);
135
+ for (const key in options) {
136
+ if (!validKeys.has(key as keyof ExtractionConfig)) {
137
+ throw new errors.ExtractionConfigError(`Invalid option provided: ${key}`);
138
+ }
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Encode this config as the query-string parameters sent to the
144
+ * Extraction API.
145
+ *
146
+ * @param options.key Scrapfly API key.
147
+ * @returns A record suitable for `URLSearchParams` construction.
148
+ * @throws {@link ExtractionConfigError} on conflicting or incompatible options.
149
+ */
150
+ toApiParams(options: { key: string }): Record<string, any> {
151
+ const params: Record<string, any> = {
152
+ key: options.key,
153
+ };
154
+ params.content_type = this.content_type;
155
+
156
+ if (this.url) {
157
+ params.url = encodeURI(this.url);
158
+ }
159
+
160
+ if (this.charset) {
161
+ params.charset = this.charset;
162
+ }
163
+
164
+ if (this.extraction_template && this.extraction_ephemeral_template) {
165
+ throw new ExtractionConfigError(
166
+ 'You cannot pass both parameters extraction_template and extraction_ephemeral_template. You must choose',
167
+ );
168
+ }
169
+
170
+ if (this.extraction_template) {
171
+ params.extraction_template = this.extraction_template;
172
+ }
173
+
174
+ if (this.extraction_ephemeral_template) {
175
+ params.extraction_template = 'ephemeral:' + urlsafe_b64encode(JSON.stringify(this.extraction_ephemeral_template));
176
+ }
177
+
178
+ if (this.extraction_prompt) {
179
+ params.extraction_prompt = this.extraction_prompt;
180
+ }
181
+
182
+ if (this.extraction_model) {
183
+ params.extraction_model = this.extraction_model;
184
+ }
185
+
186
+ if (this.document_compression_format) {
187
+ if (this.is_document_compressed === undefined) {
188
+ throw new errors.ExtractionConfigError(
189
+ `When declaring compression format, your must declare the ` +
190
+ `is_document_compressed parameter to compress the document or skip it.`,
191
+ );
192
+ }
193
+ if (this.is_document_compressed === false) {
194
+ // if (this.document_compression_format === CompressionFormat.GZIP) {
195
+ // XXX: This breaks cloudflare workers for some reason
196
+ // const compressed = gzip(new TextEncoder().encode(this.body as string));
197
+ // this.body = new Uint8Array(compressed);
198
+ // throw new Error("automatic gzip is not supported yet, pass gzipped ");
199
+ // } else {
200
+ throw new errors.ExtractionConfigError(
201
+ `Auto compression for ${this.document_compression_format} format isn't available. ` +
202
+ `You can manually compress to ${this.document_compression_format}.`,
203
+ );
204
+ // }
205
+ }
206
+ }
207
+
208
+ if (this.webhook) {
209
+ params.webhook_name = this.webhook;
210
+ }
211
+ if (this.timeout) {
212
+ params.timeout = this.timeout;
213
+ }
214
+
215
+ return params;
216
+ }
217
+ }
package/src/logger.ts ADDED
@@ -0,0 +1,53 @@
1
+ enum LogLevel {
2
+ DEBUG = 'DEBUG',
3
+ INFO = 'INFO',
4
+ WARN = 'WARN',
5
+ ERROR = 'ERROR',
6
+ }
7
+
8
+ class Logger {
9
+ private level: LogLevel;
10
+ public name: string;
11
+
12
+ constructor(name: string, level: LogLevel = LogLevel.INFO) {
13
+ this.name = name;
14
+ this.level = level;
15
+ }
16
+
17
+ debug(...args: any[]): void {
18
+ if (this.level <= LogLevel.DEBUG) {
19
+ console.log(...args);
20
+ }
21
+ }
22
+
23
+ info(...args: any[]): void {
24
+ if (this.level <= LogLevel.INFO) {
25
+ console.info(...args);
26
+ }
27
+ }
28
+
29
+ warn(...args: any[]): void {
30
+ if (this.level <= LogLevel.WARN) {
31
+ console.warn(...args);
32
+ }
33
+ }
34
+
35
+ error(...args: any[]): void {
36
+ if (this.level <= LogLevel.ERROR) {
37
+ console.error(...args);
38
+ }
39
+ }
40
+
41
+ setLevel(level: string): void {
42
+ if (Object.values(LogLevel).includes(level as LogLevel)) {
43
+ this.level = level as LogLevel;
44
+ } else {
45
+ console.error(`Invalid log level: ${level}`);
46
+ }
47
+ }
48
+ }
49
+
50
+ export default Logger;
51
+
52
+ /** Shared logger instance used by the SDK. Callers can set its log level to silence or unmute output. */
53
+ export const log: Logger = new Logger('scrapfly');