@taodigital/crawler 0.0.0-stage → 1.2.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 (494) hide show
  1. package/Dockerfile +82 -0
  2. package/README.md +10 -2
  3. package/dist/accessibility-auditor.d.ts +29 -0
  4. package/dist/accessibility-auditor.js +57 -0
  5. package/dist/accessibility-auditor.js.map +7 -0
  6. package/dist/accessibility-tree-crawler.d.ts +44 -0
  7. package/dist/accessibility-tree-crawler.js +156 -0
  8. package/dist/accessibility-tree-crawler.js.map +7 -0
  9. package/dist/advanced-ui-probes.d.ts +47 -0
  10. package/dist/advanced-ui-probes.js +310 -0
  11. package/dist/advanced-ui-probes.js.map +7 -0
  12. package/dist/ai-login.d.ts +32 -0
  13. package/dist/ai-login.js +250 -0
  14. package/dist/ai-login.js.map +7 -0
  15. package/dist/auth-token-rotator.d.ts +47 -0
  16. package/dist/auth-token-rotator.js +58 -0
  17. package/dist/auth-token-rotator.js.map +7 -0
  18. package/dist/auth.d.ts +20 -0
  19. package/dist/auth.js +348 -0
  20. package/dist/auth.js.map +7 -0
  21. package/dist/browser-extension.d.ts +37 -0
  22. package/dist/browser-extension.js +113 -0
  23. package/dist/browser-extension.js.map +7 -0
  24. package/dist/captcha-solver.d.ts +16 -0
  25. package/dist/captcha-solver.js +105 -0
  26. package/dist/captcha-solver.js.map +7 -0
  27. package/dist/color-contrast.d.ts +30 -0
  28. package/dist/color-contrast.js +78 -0
  29. package/dist/color-contrast.js.map +7 -0
  30. package/dist/content-chunker.d.ts +18 -0
  31. package/dist/content-chunker.js +152 -0
  32. package/dist/content-chunker.js.map +7 -0
  33. package/dist/content-dedup.d.ts +23 -0
  34. package/dist/content-dedup.js +60 -0
  35. package/dist/content-dedup.js.map +7 -0
  36. package/dist/cookie-consent.d.ts +25 -0
  37. package/dist/cookie-consent.js +78 -0
  38. package/dist/cookie-consent.js.map +7 -0
  39. package/dist/cookie-jar.d.ts +20 -0
  40. package/dist/cookie-jar.js +61 -0
  41. package/dist/cookie-jar.js.map +7 -0
  42. package/dist/crawl-session-manager.d.ts +44 -0
  43. package/dist/crawl-session-manager.js +145 -0
  44. package/dist/crawl-session-manager.js.map +7 -0
  45. package/dist/crawler.d.ts +233 -0
  46. package/dist/crawler.js +6239 -0
  47. package/dist/crawler.js.map +7 -0
  48. package/dist/crud-interaction.d.ts +31 -0
  49. package/dist/crud-interaction.js +264 -0
  50. package/dist/crud-interaction.js.map +7 -0
  51. package/dist/custom-js-injector.d.ts +42 -0
  52. package/dist/custom-js-injector.js +50 -0
  53. package/dist/custom-js-injector.js.map +7 -0
  54. package/dist/dark-mode-capture.d.ts +23 -0
  55. package/dist/dark-mode-capture.js +75 -0
  56. package/dist/dark-mode-capture.js.map +7 -0
  57. package/dist/dead-link-detector.d.ts +37 -0
  58. package/dist/dead-link-detector.js +50 -0
  59. package/dist/dead-link-detector.js.map +7 -0
  60. package/dist/dropdown-enumerator.d.ts +20 -0
  61. package/dist/dropdown-enumerator.js +230 -0
  62. package/dist/dropdown-enumerator.js.map +7 -0
  63. package/dist/element-hash.d.ts +9 -0
  64. package/dist/element-hash.js +9 -0
  65. package/dist/element-hash.js.map +7 -0
  66. package/dist/email-otp.d.ts +42 -0
  67. package/dist/email-otp.js +177 -0
  68. package/dist/email-otp.js.map +7 -0
  69. package/dist/engine-router.d.ts +47 -0
  70. package/dist/engine-router.js +94 -0
  71. package/dist/engine-router.js.map +7 -0
  72. package/dist/export/bulk-export.d.ts +26 -0
  73. package/dist/export/bulk-export.js +76 -0
  74. package/dist/export/bulk-export.js.map +7 -0
  75. package/dist/export/vector-export.d.ts +76 -0
  76. package/dist/export/vector-export.js +85 -0
  77. package/dist/export/vector-export.js.map +7 -0
  78. package/dist/extractors/advanced.d.ts +64 -0
  79. package/dist/extractors/advanced.js +265 -0
  80. package/dist/extractors/advanced.js.map +7 -0
  81. package/dist/extractors/artifact-envelope.d.ts +63 -0
  82. package/dist/extractors/artifact-envelope.js +63 -0
  83. package/dist/extractors/artifact-envelope.js.map +7 -0
  84. package/dist/extractors/branding-extractor.d.ts +46 -0
  85. package/dist/extractors/branding-extractor.js +104 -0
  86. package/dist/extractors/branding-extractor.js.map +7 -0
  87. package/dist/extractors/summary-extractor.d.ts +10 -0
  88. package/dist/extractors/summary-extractor.js +36 -0
  89. package/dist/extractors/summary-extractor.js.map +7 -0
  90. package/dist/failure-analysis-agent.d.ts +16 -0
  91. package/dist/failure-analysis-agent.js +42 -0
  92. package/dist/failure-analysis-agent.js.map +7 -0
  93. package/dist/feature-flag-detector.d.ts +30 -0
  94. package/dist/feature-flag-detector.js +55 -0
  95. package/dist/feature-flag-detector.js.map +7 -0
  96. package/dist/filter-pagination-crawler.d.ts +52 -0
  97. package/dist/filter-pagination-crawler.js +299 -0
  98. package/dist/filter-pagination-crawler.js.map +7 -0
  99. package/dist/form-detector.d.ts +34 -0
  100. package/dist/form-detector.js +58 -0
  101. package/dist/form-detector.js.map +7 -0
  102. package/dist/frontier.d.ts +40 -0
  103. package/dist/frontier.js +103 -0
  104. package/dist/frontier.js.map +7 -0
  105. package/dist/gap-pass.d.ts +36 -0
  106. package/dist/gap-pass.js +115 -0
  107. package/dist/gap-pass.js.map +7 -0
  108. package/dist/graphql-detector.d.ts +39 -0
  109. package/dist/graphql-detector.js +86 -0
  110. package/dist/graphql-detector.js.map +7 -0
  111. package/dist/http-engine.d.ts +80 -0
  112. package/dist/http-engine.js +318 -0
  113. package/dist/http-engine.js.map +7 -0
  114. package/dist/incremental-diff.d.ts +116 -0
  115. package/dist/incremental-diff.js +137 -0
  116. package/dist/incremental-diff.js.map +7 -0
  117. package/dist/index.d.ts +52 -0
  118. package/dist/index.js +83 -0
  119. package/dist/index.js.map +7 -0
  120. package/dist/input-fuzzer.d.ts +30 -0
  121. package/dist/input-fuzzer.js +105 -0
  122. package/dist/input-fuzzer.js.map +7 -0
  123. package/dist/interactive-probe.d.ts +144 -0
  124. package/dist/interactive-probe.js +865 -0
  125. package/dist/interactive-probe.js.map +7 -0
  126. package/dist/job-queue.d.ts +297 -0
  127. package/dist/job-queue.js +3812 -0
  128. package/dist/job-queue.js.map +7 -0
  129. package/dist/js-coverage.d.ts +29 -0
  130. package/dist/js-coverage.js +56 -0
  131. package/dist/js-coverage.js.map +7 -0
  132. package/dist/js-router-detector.d.ts +17 -0
  133. package/dist/js-router-detector.js +90 -0
  134. package/dist/js-router-detector.js.map +7 -0
  135. package/dist/language-detector.d.ts +22 -0
  136. package/dist/language-detector.js +57 -0
  137. package/dist/language-detector.js.map +7 -0
  138. package/dist/link-classifier.d.ts +23 -0
  139. package/dist/link-classifier.js +40 -0
  140. package/dist/link-classifier.js.map +7 -0
  141. package/dist/live-view.d.ts +36 -0
  142. package/dist/live-view.js +105 -0
  143. package/dist/live-view.js.map +7 -0
  144. package/dist/locator-extractor.d.ts +46 -0
  145. package/dist/locator-extractor.js +220 -0
  146. package/dist/locator-extractor.js.map +7 -0
  147. package/dist/logger.d.ts +2 -0
  148. package/dist/logger.js +10 -0
  149. package/dist/logger.js.map +7 -0
  150. package/dist/markdown-extract.d.ts +8 -0
  151. package/dist/markdown-extract.js +54 -0
  152. package/dist/markdown-extract.js.map +7 -0
  153. package/dist/multi-context-handler.d.ts +55 -0
  154. package/dist/multi-context-handler.js +182 -0
  155. package/dist/multi-context-handler.js.map +7 -0
  156. package/dist/native-crawler.d.ts +69 -0
  157. package/dist/native-crawler.js +839 -0
  158. package/dist/native-crawler.js.map +7 -0
  159. package/dist/nested-window-crawler.d.ts +41 -0
  160. package/dist/nested-window-crawler.js +172 -0
  161. package/dist/nested-window-crawler.js.map +7 -0
  162. package/dist/network-action-correlator.d.ts +47 -0
  163. package/dist/network-action-correlator.js +209 -0
  164. package/dist/network-action-correlator.js.map +7 -0
  165. package/dist/network-observer.d.ts +49 -0
  166. package/dist/network-observer.js +149 -0
  167. package/dist/network-observer.js.map +7 -0
  168. package/dist/network-throttle.d.ts +25 -0
  169. package/dist/network-throttle.js +34 -0
  170. package/dist/network-throttle.js.map +7 -0
  171. package/dist/openapi-generator.d.ts +49 -0
  172. package/dist/openapi-generator.js +89 -0
  173. package/dist/openapi-generator.js.map +7 -0
  174. package/dist/pdf-extractor.d.ts +28 -0
  175. package/dist/pdf-extractor.js +81 -0
  176. package/dist/pdf-extractor.js.map +7 -0
  177. package/dist/performance-metrics-collector.d.ts +50 -0
  178. package/dist/performance-metrics-collector.js +155 -0
  179. package/dist/performance-metrics-collector.js.map +7 -0
  180. package/dist/performance-metrics.d.ts +52 -0
  181. package/dist/performance-metrics.js +83 -0
  182. package/dist/performance-metrics.js.map +7 -0
  183. package/dist/phash.d.ts +50 -0
  184. package/dist/phash.js +136 -0
  185. package/dist/phash.js.map +7 -0
  186. package/dist/pii-scrubber.d.ts +21 -0
  187. package/dist/pii-scrubber.js +75 -0
  188. package/dist/pii-scrubber.js.map +7 -0
  189. package/dist/playwright-recorder.d.ts +39 -0
  190. package/dist/playwright-recorder.js +123 -0
  191. package/dist/playwright-recorder.js.map +7 -0
  192. package/dist/policies/crawl-safety.d.ts +9 -0
  193. package/dist/policies/crawl-safety.js +41 -0
  194. package/dist/policies/crawl-safety.js.map +7 -0
  195. package/dist/profiles/domain-profile.d.ts +19 -0
  196. package/dist/profiles/domain-profile.js +160 -0
  197. package/dist/profiles/domain-profile.js.map +7 -0
  198. package/dist/proxy.d.ts +50 -0
  199. package/dist/proxy.js +165 -0
  200. package/dist/proxy.js.map +7 -0
  201. package/dist/rate-limiter.d.ts +31 -0
  202. package/dist/rate-limiter.js +64 -0
  203. package/dist/rate-limiter.js.map +7 -0
  204. package/dist/redirect-tracker.d.ts +37 -0
  205. package/dist/redirect-tracker.js +65 -0
  206. package/dist/redirect-tracker.js.map +7 -0
  207. package/dist/redis-frontier.d.ts +48 -0
  208. package/dist/redis-frontier.js +126 -0
  209. package/dist/redis-frontier.js.map +7 -0
  210. package/dist/redis-queue.d.ts +48 -0
  211. package/dist/redis-queue.js +165 -0
  212. package/dist/redis-queue.js.map +7 -0
  213. package/dist/response-cache.d.ts +38 -0
  214. package/dist/response-cache.js +140 -0
  215. package/dist/response-cache.js.map +7 -0
  216. package/dist/responsive-detector.d.ts +29 -0
  217. package/dist/responsive-detector.js +46 -0
  218. package/dist/responsive-detector.js.map +7 -0
  219. package/dist/retry-policy.d.ts +20 -0
  220. package/dist/retry-policy.js +54 -0
  221. package/dist/retry-policy.js.map +7 -0
  222. package/dist/robots-txt.d.ts +9 -0
  223. package/dist/robots-txt.js +77 -0
  224. package/dist/robots-txt.js.map +7 -0
  225. package/dist/screen-reader.d.ts +15 -0
  226. package/dist/screen-reader.js +48 -0
  227. package/dist/screen-reader.js.map +7 -0
  228. package/dist/screenshot-masker.d.ts +28 -0
  229. package/dist/screenshot-masker.js +62 -0
  230. package/dist/screenshot-masker.js.map +7 -0
  231. package/dist/seo-checker.d.ts +33 -0
  232. package/dist/seo-checker.js +91 -0
  233. package/dist/seo-checker.js.map +7 -0
  234. package/dist/service-worker-interceptor.d.ts +36 -0
  235. package/dist/service-worker-interceptor.js +136 -0
  236. package/dist/service-worker-interceptor.js.map +7 -0
  237. package/dist/session-capture.d.ts +39 -0
  238. package/dist/session-capture.js +274 -0
  239. package/dist/session-capture.js.map +7 -0
  240. package/dist/session-export.d.ts +49 -0
  241. package/dist/session-export.js +117 -0
  242. package/dist/session-export.js.map +7 -0
  243. package/dist/shadow-dom-crawler.d.ts +35 -0
  244. package/dist/shadow-dom-crawler.js +132 -0
  245. package/dist/shadow-dom-crawler.js.map +7 -0
  246. package/dist/sitemap-writer.d.ts +21 -0
  247. package/dist/sitemap-writer.js +47 -0
  248. package/dist/sitemap-writer.js.map +7 -0
  249. package/dist/sitemap.d.ts +51 -0
  250. package/dist/sitemap.js +160 -0
  251. package/dist/sitemap.js.map +7 -0
  252. package/dist/skyvern.d.ts +56 -0
  253. package/dist/skyvern.js +129 -0
  254. package/dist/skyvern.js.map +7 -0
  255. package/dist/sqs-queue.d.ts +13 -0
  256. package/dist/sqs-queue.js +115 -0
  257. package/dist/sqs-queue.js.map +7 -0
  258. package/dist/sso-token.d.ts +29 -0
  259. package/dist/sso-token.js +76 -0
  260. package/dist/sso-token.js.map +7 -0
  261. package/dist/state-graph.d.ts +59 -0
  262. package/dist/state-graph.js +193 -0
  263. package/dist/state-graph.js.map +7 -0
  264. package/dist/stealth/human-behavior.d.ts +20 -0
  265. package/dist/stealth/human-behavior.js +202 -0
  266. package/dist/stealth/human-behavior.js.map +7 -0
  267. package/dist/telemetry.d.ts +34 -0
  268. package/dist/telemetry.js +77 -0
  269. package/dist/telemetry.js.map +7 -0
  270. package/dist/test-executor.d.ts +81 -0
  271. package/dist/test-executor.js +443 -0
  272. package/dist/test-executor.js.map +7 -0
  273. package/dist/tls-fingerprint.d.ts +50 -0
  274. package/dist/tls-fingerprint.js +81 -0
  275. package/dist/tls-fingerprint.js.map +7 -0
  276. package/dist/url-pattern-completer.d.ts +28 -0
  277. package/dist/url-pattern-completer.js +122 -0
  278. package/dist/url-pattern-completer.js.map +7 -0
  279. package/dist/visual-diff-verdict.d.ts +40 -0
  280. package/dist/visual-diff-verdict.js +27 -0
  281. package/dist/visual-diff-verdict.js.map +7 -0
  282. package/dist/webhook-notifier.d.ts +30 -0
  283. package/dist/webhook-notifier.js +76 -0
  284. package/dist/webhook-notifier.js.map +7 -0
  285. package/dist/websocket-detector.d.ts +24 -0
  286. package/dist/websocket-detector.js +60 -0
  287. package/dist/websocket-detector.js.map +7 -0
  288. package/dist/worker.d.ts +1 -0
  289. package/dist/worker.js +33 -0
  290. package/dist/worker.js.map +7 -0
  291. package/package.json +49 -4
  292. package/src/accessibility-auditor.ts +102 -0
  293. package/src/accessibility-tree-crawler.ts +246 -0
  294. package/src/advanced-ui-probes.ts +470 -0
  295. package/src/ai-login.ts +298 -0
  296. package/src/auth-token-rotator.ts +89 -0
  297. package/src/auth.ts +418 -0
  298. package/src/browser-extension.ts +186 -0
  299. package/src/captcha-solver.ts +143 -0
  300. package/src/color-contrast.ts +116 -0
  301. package/src/content-chunker.ts +170 -0
  302. package/src/content-dedup.ts +99 -0
  303. package/src/cookie-consent.ts +106 -0
  304. package/src/cookie-jar.ts +91 -0
  305. package/src/crawl-session-manager.ts +231 -0
  306. package/src/crawler.ts +7123 -0
  307. package/src/crawler.ts.rej +12 -0
  308. package/src/crud-interaction.ts +386 -0
  309. package/src/custom-js-injector.ts +93 -0
  310. package/src/dark-mode-capture.ts +110 -0
  311. package/src/dead-link-detector.ts +76 -0
  312. package/src/dropdown-enumerator.ts +312 -0
  313. package/src/element-hash.ts +16 -0
  314. package/src/email-otp.ts +252 -0
  315. package/src/engine-router.ts +141 -0
  316. package/src/export/bulk-export.ts +85 -0
  317. package/src/export/vector-export.ts +160 -0
  318. package/src/extractors/advanced.ts +309 -0
  319. package/src/extractors/artifact-envelope.ts +111 -0
  320. package/src/extractors/branding-extractor.ts +159 -0
  321. package/src/extractors/summary-extractor.ts +49 -0
  322. package/src/failure-analysis-agent.ts +51 -0
  323. package/src/feature-flag-detector.ts +97 -0
  324. package/src/filter-pagination-crawler.ts +500 -0
  325. package/src/form-detector.ts +103 -0
  326. package/src/frontier.test.ts +64 -0
  327. package/src/frontier.ts +144 -0
  328. package/src/gap-pass.ts +165 -0
  329. package/src/graphql-detector.ts +129 -0
  330. package/src/http-engine.ts +453 -0
  331. package/src/incremental-diff.ts +259 -0
  332. package/src/index.ts +52 -0
  333. package/src/input-fuzzer.ts +129 -0
  334. package/src/interactive-probe.ts +1136 -0
  335. package/src/job-queue.test.ts +187 -0
  336. package/src/job-queue.ts +4504 -0
  337. package/src/js-coverage.ts +87 -0
  338. package/src/js-router-detector.ts +112 -0
  339. package/src/language-detector.ts +82 -0
  340. package/src/link-classifier.ts +65 -0
  341. package/src/live-view.ts +146 -0
  342. package/src/locator-extractor.ts +309 -0
  343. package/src/logger.ts +9 -0
  344. package/src/markdown-extract.test.ts +73 -0
  345. package/src/markdown-extract.ts +76 -0
  346. package/src/multi-context-handler.ts +296 -0
  347. package/src/native-crawler.ts +1108 -0
  348. package/src/nested-window-crawler.ts +310 -0
  349. package/src/network-action-correlator.ts +320 -0
  350. package/src/network-observer.ts +204 -0
  351. package/src/network-throttle.ts +69 -0
  352. package/src/openapi-generator.ts +135 -0
  353. package/src/pdf-extractor.ts +123 -0
  354. package/src/performance-metrics-collector.ts +243 -0
  355. package/src/performance-metrics.ts +134 -0
  356. package/src/phash.ts +184 -0
  357. package/src/pii-scrubber.ts +99 -0
  358. package/src/playwright-recorder.ts +170 -0
  359. package/src/policies/crawl-safety.ts +52 -0
  360. package/src/profiles/domain-profile.ts +190 -0
  361. package/src/proxy.ts +238 -0
  362. package/src/rate-limiter.ts +87 -0
  363. package/src/redirect-tracker.ts +97 -0
  364. package/src/redis-frontier.ts +143 -0
  365. package/src/redis-queue.ts +208 -0
  366. package/src/response-cache.ts +150 -0
  367. package/src/responsive-detector.ts +92 -0
  368. package/src/retry-policy.ts +87 -0
  369. package/src/robots-txt.ts +96 -0
  370. package/src/screen-reader.ts +98 -0
  371. package/src/screenshot-masker.ts +98 -0
  372. package/src/seo-checker.ts +134 -0
  373. package/src/service-worker-interceptor.ts +185 -0
  374. package/src/session-capture.ts +335 -0
  375. package/src/session-export.test.ts +75 -0
  376. package/src/session-export.ts +172 -0
  377. package/src/shadow-dom-crawler.ts +198 -0
  378. package/src/sitemap-writer.ts +65 -0
  379. package/src/sitemap.test.ts +127 -0
  380. package/src/sitemap.ts +233 -0
  381. package/src/skyvern.ts +199 -0
  382. package/src/sqs-queue.ts +129 -0
  383. package/src/sso-token.ts +120 -0
  384. package/src/state-graph.ts +280 -0
  385. package/src/stealth/human-behavior.ts +227 -0
  386. package/src/telemetry.ts +122 -0
  387. package/src/test-executor.test.ts +72 -0
  388. package/src/test-executor.ts +578 -0
  389. package/src/tls-fingerprint.ts +111 -0
  390. package/src/url-pattern-completer.ts +161 -0
  391. package/src/vendor.d.ts +20 -0
  392. package/src/visual-diff-verdict.test.ts +80 -0
  393. package/src/visual-diff-verdict.ts +59 -0
  394. package/src/webhook-notifier.ts +109 -0
  395. package/src/websocket-detector.ts +83 -0
  396. package/src/worker.ts +50 -0
  397. package/tsconfig.json +13 -0
  398. package/types/accessibility-auditor.d.ts +29 -0
  399. package/types/accessibility-tree-crawler.d.ts +44 -0
  400. package/types/advanced-ui-probes.d.ts +47 -0
  401. package/types/ai-login.d.ts +32 -0
  402. package/types/auth-token-rotator.d.ts +47 -0
  403. package/types/auth.d.ts +20 -0
  404. package/types/browser-extension.d.ts +37 -0
  405. package/types/bull-worker.d.ts +6 -0
  406. package/types/captcha-solver.d.ts +16 -0
  407. package/types/color-contrast.d.ts +30 -0
  408. package/types/content-chunker.d.ts +18 -0
  409. package/types/content-dedup.d.ts +23 -0
  410. package/types/cookie-consent.d.ts +25 -0
  411. package/types/cookie-jar.d.ts +20 -0
  412. package/types/crawl-session-manager.d.ts +44 -0
  413. package/types/crawler.d.ts +233 -0
  414. package/types/crud-interaction.d.ts +31 -0
  415. package/types/custom-js-injector.d.ts +42 -0
  416. package/types/dark-mode-capture.d.ts +23 -0
  417. package/types/dead-link-detector.d.ts +37 -0
  418. package/types/dropdown-enumerator.d.ts +20 -0
  419. package/types/element-hash.d.ts +9 -0
  420. package/types/email-otp.d.ts +42 -0
  421. package/types/engine-router.d.ts +47 -0
  422. package/types/export/bulk-export.d.ts +26 -0
  423. package/types/export/vector-export.d.ts +76 -0
  424. package/types/extractors/advanced.d.ts +64 -0
  425. package/types/extractors/artifact-envelope.d.ts +63 -0
  426. package/types/extractors/branding-extractor.d.ts +46 -0
  427. package/types/extractors/summary-extractor.d.ts +10 -0
  428. package/types/failure-analysis-agent.d.ts +16 -0
  429. package/types/feature-flag-detector.d.ts +30 -0
  430. package/types/filter-pagination-crawler.d.ts +52 -0
  431. package/types/form-detector.d.ts +34 -0
  432. package/types/frontier.d.ts +40 -0
  433. package/types/gap-pass.d.ts +36 -0
  434. package/types/graphql-detector.d.ts +39 -0
  435. package/types/http-engine.d.ts +80 -0
  436. package/types/incremental-diff.d.ts +116 -0
  437. package/types/index.d.ts +52 -0
  438. package/types/input-fuzzer.d.ts +30 -0
  439. package/types/interactive-probe.d.ts +144 -0
  440. package/types/job-queue.d.ts +308 -0
  441. package/types/js-coverage.d.ts +29 -0
  442. package/types/js-router-detector.d.ts +17 -0
  443. package/types/language-detector.d.ts +22 -0
  444. package/types/link-classifier.d.ts +23 -0
  445. package/types/live-view.d.ts +36 -0
  446. package/types/locator-extractor.d.ts +46 -0
  447. package/types/logger.d.ts +2 -0
  448. package/types/markdown-extract.d.ts +8 -0
  449. package/types/multi-context-handler.d.ts +55 -0
  450. package/types/native-crawler.d.ts +69 -0
  451. package/types/nested-window-crawler.d.ts +41 -0
  452. package/types/network-action-correlator.d.ts +47 -0
  453. package/types/network-observer.d.ts +49 -0
  454. package/types/network-throttle.d.ts +25 -0
  455. package/types/openapi-generator.d.ts +49 -0
  456. package/types/pdf-extractor.d.ts +28 -0
  457. package/types/performance-metrics-collector.d.ts +50 -0
  458. package/types/performance-metrics.d.ts +52 -0
  459. package/types/phash.d.ts +50 -0
  460. package/types/pii-scrubber.d.ts +21 -0
  461. package/types/playwright-recorder.d.ts +39 -0
  462. package/types/policies/crawl-safety.d.ts +9 -0
  463. package/types/profiles/domain-profile.d.ts +19 -0
  464. package/types/proxy.d.ts +50 -0
  465. package/types/rate-limiter.d.ts +31 -0
  466. package/types/redirect-tracker.d.ts +37 -0
  467. package/types/redis-frontier.d.ts +48 -0
  468. package/types/redis-queue.d.ts +48 -0
  469. package/types/response-cache.d.ts +38 -0
  470. package/types/responsive-detector.d.ts +29 -0
  471. package/types/retry-policy.d.ts +20 -0
  472. package/types/robots-txt.d.ts +9 -0
  473. package/types/screen-reader.d.ts +15 -0
  474. package/types/screenshot-masker.d.ts +28 -0
  475. package/types/seo-checker.d.ts +33 -0
  476. package/types/service-worker-interceptor.d.ts +36 -0
  477. package/types/session-capture.d.ts +39 -0
  478. package/types/session-export.d.ts +49 -0
  479. package/types/shadow-dom-crawler.d.ts +35 -0
  480. package/types/sitemap-writer.d.ts +21 -0
  481. package/types/sitemap.d.ts +51 -0
  482. package/types/skyvern.d.ts +56 -0
  483. package/types/sqs-queue.d.ts +13 -0
  484. package/types/sso-token.d.ts +29 -0
  485. package/types/state-graph.d.ts +59 -0
  486. package/types/stealth/human-behavior.d.ts +20 -0
  487. package/types/telemetry.d.ts +34 -0
  488. package/types/test-executor.d.ts +84 -0
  489. package/types/tls-fingerprint.d.ts +50 -0
  490. package/types/url-pattern-completer.d.ts +28 -0
  491. package/types/visual-diff-verdict.d.ts +40 -0
  492. package/types/webhook-notifier.d.ts +30 -0
  493. package/types/websocket-detector.d.ts +24 -0
  494. package/types/worker.d.ts +1 -0
package/src/sitemap.ts ADDED
@@ -0,0 +1,233 @@
1
+ /**
2
+ * Sitemap.xml discovery — seeds the crawl queue from a project's sitemap
3
+ * instead of (or alongside) plain link-following, matching crawl4AI's
4
+ * sitemap-seeding capability. Best-effort throughout: most sites don't have
5
+ * a sitemap, or it 404s, or it's malformed — none of that should ever fail
6
+ * a crawl, it just means sitemap seeding contributes nothing this run.
7
+ */
8
+ import { XMLParser } from 'fast-xml-parser';
9
+ import { ProxyAgent } from 'undici';
10
+ import { assertCrawlUrlSafe } from '@taodigital/core/dist/ssrf-guard.js';
11
+ import { logger } from './logger.js';
12
+
13
+ const FETCH_TIMEOUT_MS = 10_000;
14
+ const MAX_SITEMAP_INDEX_DEPTH = 3; // sitemap index -> sub-sitemaps -> (no deeper nesting expected)
15
+ const MAX_SUB_SITEMAPS = 50; // bound fan-out from a single sitemap index
16
+
17
+ async function getSitemapMaxUrls(): Promise<number> {
18
+ const { getSystemConfig } = await import('@taodigital/core');
19
+ const cfg = await getSystemConfig('crawl_tuning');
20
+ return parseInt(String(cfg?.sitemapMaxUrls ?? '5000'), 10);
21
+ }
22
+
23
+ function toArray<T>(x: T | T[] | undefined | null): T[] {
24
+ if (x == null) return [];
25
+ return Array.isArray(x) ? x : [x];
26
+ }
27
+
28
+ /** Registrable-host key: lowercased hostname with a leading `www.` stripped. */
29
+ function hostKey(hostname: string): string {
30
+ return hostname.replace(/^www\./i, '').toLowerCase();
31
+ }
32
+
33
+ /**
34
+ * Same-site check that tolerates www/non-www and http/https differences — a sitemap on
35
+ * `vercel.com` is valid for a project pointed at `www.vercel.com` (and vice versa).
36
+ */
37
+ export function sameSite(candidateUrl: string, siteOrigin: string): boolean {
38
+ try {
39
+ const originHost = /^https?:\/\//i.test(siteOrigin) ? new URL(siteOrigin).hostname : siteOrigin;
40
+ return hostKey(new URL(candidateUrl).hostname) === hostKey(originHost);
41
+ } catch {
42
+ return false;
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Pulls page URLs and sub-sitemap URLs out of an already-XML-parsed sitemap
48
+ * document (either a <urlset> or a <sitemapindex>), filtered to same-origin
49
+ * and deduped. Pure function — no I/O — for direct unit testing without a
50
+ * real HTTP fetch.
51
+ */
52
+ export function extractUrlsFromParsedSitemap(parsed: any, origin: string, maxUrls = 5000): { pageUrls: string[]; subSitemapUrls: string[] } {
53
+ const rawPageUrls: string[] = [];
54
+ let subSitemapUrls: string[] = [];
55
+
56
+ if (parsed?.sitemapindex) {
57
+ subSitemapUrls = toArray(parsed.sitemapindex.sitemap)
58
+ .map((s: any) => s?.loc)
59
+ .filter((loc: any): loc is string => typeof loc === 'string')
60
+ .slice(0, MAX_SUB_SITEMAPS);
61
+ }
62
+
63
+ if (parsed?.urlset) {
64
+ rawPageUrls.push(
65
+ ...toArray(parsed.urlset.url)
66
+ .map((u: any) => u?.loc)
67
+ .filter((loc: any): loc is string => typeof loc === 'string'),
68
+ );
69
+ }
70
+
71
+ // Same-site only (www/protocol-tolerant) — a sitemap listing external URLs shouldn't seed this project's queue.
72
+ const sameOrigin = rawPageUrls.filter((u) => sameSite(u, origin));
73
+
74
+ return { pageUrls: [...new Set(sameOrigin)].slice(0, maxUrls), subSitemapUrls };
75
+ }
76
+
77
+ async function fetchAndParseXml(url: string, dispatcher?: any): Promise<any | null> {
78
+ // Same SSRF posture as the crawl itself (assertCrawlUrlSafe, not the
79
+ // stricter webhook-oriented assertResolvesToPublicAddress) — a sitemap
80
+ // living on a tenant's internal/VPN-only staging server is a legitimate
81
+ // crawl target, not an attack; only loopback/cloud-metadata are blocked.
82
+ try {
83
+ assertCrawlUrlSafe(url);
84
+ } catch {
85
+ return null;
86
+ }
87
+ try {
88
+ // Redirects followed normally here (unlike the webhook-dispatch.ts
89
+ // 'manual' pattern) — an http→https or bare→www redirect on the
90
+ // sitemap is completely ordinary, and Playwright's actual page
91
+ // navigation later in the crawl already follows redirects to whatever
92
+ // this same site sends it to; a sitemap fetch isn't a more sensitive
93
+ // operation than that.
94
+ const res = await fetch(url, {
95
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
96
+ headers: { 'User-Agent': 'ZeTa-AI-Crawler/1.0 (+sitemap-discovery)' },
97
+ ...(dispatcher ? { dispatcher } : {}),
98
+ });
99
+ if (!res.ok) return null;
100
+ const text = await res.text();
101
+ return new XMLParser().parse(text);
102
+ } catch {
103
+ return null;
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Fetches and parses a sitemap (or sitemap index, recursed up to a small
109
+ * depth) into a flat, deduped list of same-origin URLs.
110
+ */
111
+ export async function fetchSitemapUrls(sitemapUrl: string, origin: string, depth = 0, dispatcher?: any, maxUrls?: number): Promise<string[]> {
112
+ if (depth > MAX_SITEMAP_INDEX_DEPTH) return [];
113
+ if (maxUrls === undefined) maxUrls = await getSitemapMaxUrls();
114
+ const parsed = await fetchAndParseXml(sitemapUrl, dispatcher);
115
+ if (!parsed) return [];
116
+
117
+ const { pageUrls, subSitemapUrls } = extractUrlsFromParsedSitemap(parsed, origin, maxUrls);
118
+ const collected = [...pageUrls];
119
+
120
+ if (subSitemapUrls.length > 0 && collected.length < maxUrls) {
121
+ const subResults = await Promise.all(
122
+ subSitemapUrls.slice(0, 10).map(subUrl => fetchSitemapUrls(subUrl, origin, depth + 1, dispatcher, maxUrls))
123
+ );
124
+ for (const sub of subResults) collected.push(...sub);
125
+ }
126
+
127
+ return [...new Set(collected)].slice(0, maxUrls);
128
+ }
129
+
130
+ /**
131
+ * Discovers a project's sitemap (default `${origin}/sitemap.xml`, or an
132
+ * explicit override) and returns the URLs it lists. Never throws.
133
+ */
134
+ export async function discoverSitemapUrls(appUrl: string, sitemapUrl?: string): Promise<string[]> {
135
+ let origin: string;
136
+ try {
137
+ origin = new URL(appUrl).origin;
138
+ } catch {
139
+ return [];
140
+ }
141
+ const target = sitemapUrl || `${origin}/sitemap.xml`;
142
+ try {
143
+ return await fetchSitemapUrls(target, origin);
144
+ } catch (err) {
145
+ logger.warn({ err: String(err), target }, '[sitemap] discovery failed, continuing without it');
146
+ return [];
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Build an undici ProxyAgent from a proxy URL. Parses credentials manually because
152
+ * DataImpulse-style usernames contain commas (country codes) that break new URL().
153
+ * Returns undefined for no/auto proxy — the caller then fetches directly.
154
+ */
155
+ export function buildProxyDispatcher(proxyUrl?: string): ProxyAgent | undefined {
156
+ if (!proxyUrl || proxyUrl === 'auto') return undefined;
157
+ try {
158
+ const m = proxyUrl.match(/^(https?):\/\/(?:([^:@]*)(?::([^@]*))?@)?(.+)$/);
159
+ if (!m) return new ProxyAgent(proxyUrl);
160
+ const [, scheme, user, pass, hostPort] = m;
161
+ const uri = `${scheme}://${hostPort}`;
162
+ if (user) {
163
+ const token = 'Basic ' + Buffer.from(`${decodeURIComponent(user)}:${decodeURIComponent(pass ?? '')}`).toString('base64');
164
+ return new ProxyAgent({ uri, token });
165
+ }
166
+ return new ProxyAgent({ uri });
167
+ } catch {
168
+ return undefined;
169
+ }
170
+ }
171
+
172
+ /** Extract same-origin `Sitemap:` directives from a robots.txt body. */
173
+ export function parseRobotsSitemaps(robotsTxt: string, origin: string): string[] {
174
+ const out: string[] = [];
175
+ for (const line of robotsTxt.split(/\r?\n/)) {
176
+ const m = line.match(/^\s*sitemap:\s*(\S+)/i);
177
+ if (m && sameSite(m[1], origin)) out.push(m[1]);
178
+ }
179
+ return [...new Set(out)];
180
+ }
181
+
182
+ export interface UrlCandidate {
183
+ url: string;
184
+ source: 'sitemap' | 'robots' | 'link';
185
+ }
186
+
187
+ /**
188
+ * Pre-crawl URL discovery for the review-before-crawl flow: reads robots.txt Sitemap
189
+ * directives and sitemap.xml (recursed, same-origin), proxy-aware. Returns a deduped
190
+ * candidate list the user can review and seed before launching the Playwright crawl.
191
+ * Never throws — bot-protected sites (Akamai/Cloudflare) simply yield an empty list.
192
+ */
193
+ export async function discoverProjectUrls(
194
+ appUrl: string,
195
+ opts?: { sitemapUrl?: string; proxyUrl?: string },
196
+ ): Promise<{ candidates: UrlCandidate[]; sitemapFound: boolean }> {
197
+ let origin: string;
198
+ try { origin = new URL(appUrl).origin; } catch { return { candidates: [], sitemapFound: false }; }
199
+
200
+ const dispatcher = buildProxyDispatcher(opts?.proxyUrl);
201
+ const maxUrls = await getSitemapMaxUrls();
202
+
203
+ // 1. robots.txt → declared sitemaps
204
+ let robotsSitemaps: string[] = [];
205
+ try {
206
+ assertCrawlUrlSafe(`${origin}/robots.txt`);
207
+ const res = await fetch(`${origin}/robots.txt`, {
208
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
209
+ headers: { 'User-Agent': 'ZeTa-AI-Crawler/1.0 (+url-discovery)' },
210
+ ...(dispatcher ? { dispatcher } : {}),
211
+ });
212
+ if (res.ok) robotsSitemaps = parseRobotsSitemaps(await res.text(), origin);
213
+ } catch { /* best-effort */ }
214
+
215
+ // 2. sitemap targets: explicit override + robots-declared + conventional default
216
+ const robotsSet = new Set(robotsSitemaps);
217
+ const sitemapTargets = [...new Set([
218
+ ...(opts?.sitemapUrl ? [opts.sitemapUrl] : []),
219
+ ...robotsSitemaps,
220
+ `${origin}/sitemap.xml`,
221
+ ])];
222
+
223
+ const seen = new Map<string, UrlCandidate>();
224
+ let sitemapFound = false;
225
+ for (const sm of sitemapTargets) {
226
+ const urls = await fetchSitemapUrls(sm, origin, 0, dispatcher, maxUrls);
227
+ if (urls.length) sitemapFound = true;
228
+ const source: UrlCandidate['source'] = robotsSet.has(sm) ? 'robots' : 'sitemap';
229
+ for (const u of urls) if (!seen.has(u)) seen.set(u, { url: u, source });
230
+ }
231
+
232
+ return { candidates: [...seen.values()].slice(0, maxUrls), sitemapFound };
233
+ }
package/src/skyvern.ts ADDED
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Skyvern Vision Fallback
3
+ *
4
+ * Skyvern combines computer vision + LLM reasoning to navigate sites that
5
+ * defeat DOM-based approaches: CAPTCHAs, legacy apps, visual-only login flows,
6
+ * government portals. It's the "break glass" option when Stagehand fails.
7
+ *
8
+ * Production setup (Phase 4+):
9
+ * 1. Self-host: https://github.com/Skyvern-AI/skyvern
10
+ * 2. Or use cloud: https://app.skyvern.com
11
+ * 3. Set SKYVERN_API_URL + SKYVERN_API_KEY in .env
12
+ *
13
+ * Pricing note: vision tasks cost more per step than DOM-based Stagehand.
14
+ * Use only when the fast path fails.
15
+ */
16
+
17
+ export interface SkyvernTask {
18
+ taskDescription: string;
19
+ url: string;
20
+ credentials?: { username: string; password: string; oneTimeCode?: string };
21
+ }
22
+
23
+ export interface SkyvernConfig {
24
+ apiUrl: string;
25
+ apiKey: string;
26
+ llmKey?: string;
27
+ llmApiKey?: string;
28
+ }
29
+
30
+ export interface SkyvernStep {
31
+ order: number;
32
+ action_type: string;
33
+ element_description?: string;
34
+ reasoning?: string;
35
+ success: boolean;
36
+ screenshot_url?: string;
37
+ duration_ms?: number;
38
+ error?: string;
39
+ }
40
+
41
+ export interface SkyvernNavigateResult {
42
+ screenshotUrls: string[];
43
+ visitedUrls: string[];
44
+ status: 'success' | 'failed' | 'partial';
45
+ steps?: SkyvernStep[];
46
+ taskId?: string;
47
+ durationMs?: number;
48
+ triggerReason?: string;
49
+ }
50
+
51
+ /**
52
+ * Gap 5: Post-login navigation via Skyvern vision for apps where DOM analysis
53
+ * cannot discover screens (canvas, WebGL, legacy Flash-replacement stacks).
54
+ * Skyvern drives the browser via screenshot + LLM, returning visited page list.
55
+ */
56
+ export async function skyvernNavigate(
57
+ startUrl: string,
58
+ navigationGoals: string[],
59
+ tenantConfig?: SkyvernConfig,
60
+ triggerReason?: string,
61
+ ): Promise<SkyvernNavigateResult> {
62
+ const apiUrl = tenantConfig?.apiUrl || process.env.SKYVERN_API_URL;
63
+ const apiKey = tenantConfig?.apiKey || process.env.SKYVERN_API_KEY;
64
+
65
+ if (!apiUrl || !apiKey) {
66
+ console.warn('[skyvern] skyvernNavigate: no API config — skipping post-login vision navigation');
67
+ return { screenshotUrls: [], visitedUrls: [], status: 'failed' };
68
+ }
69
+
70
+ const visitedUrls: string[] = [];
71
+ const screenshotUrls: string[] = [];
72
+ const skyvernSteps: SkyvernStep[] = [];
73
+ let lastTaskId: string | undefined;
74
+ let totalDurationMs = 0;
75
+
76
+ for (const goal of navigationGoals) {
77
+ try {
78
+ const taskStart = Date.now();
79
+ const res = await fetch(`${apiUrl}/api/v1/tasks`, {
80
+ method: 'POST',
81
+ headers: { 'Content-Type': 'application/json', 'x-api-key': apiKey },
82
+ body: JSON.stringify({
83
+ url: startUrl,
84
+ navigation_goal: goal,
85
+ ...(tenantConfig?.llmKey ? { llm_key: tenantConfig.llmKey } : process.env.SKYVERN_LLM_KEY ? { llm_key: process.env.SKYVERN_LLM_KEY } : {}),
86
+ ...(tenantConfig?.llmApiKey ? { llm_api_key: tenantConfig.llmApiKey } : process.env.OPENAI_API_KEY ? { llm_api_key: process.env.OPENAI_API_KEY } : {}),
87
+ }),
88
+ });
89
+ if (!res.ok) continue;
90
+ const data: any = await res.json();
91
+ const taskId: string = data.task_id;
92
+ if (!taskId) continue;
93
+ lastTaskId = taskId;
94
+
95
+ // Poll for task completion (max 60s per goal)
96
+ let done = false;
97
+ for (let p = 0; p < 12 && !done; p++) {
98
+ await new Promise((r) => setTimeout(r, 5000));
99
+ const poll = await fetch(`${apiUrl}/api/v1/tasks/${taskId}`, {
100
+ headers: { 'x-api-key': apiKey },
101
+ }).catch(() => null);
102
+ if (!poll?.ok) continue;
103
+ const pollData: any = await poll.json();
104
+ if (pollData.status === 'completed' || pollData.status === 'failed') {
105
+ done = true;
106
+ totalDurationMs += Date.now() - taskStart;
107
+ if (pollData.status === 'completed') {
108
+ if (pollData.output?.url) visitedUrls.push(pollData.output.url);
109
+ if (pollData.output?.screenshot_url) screenshotUrls.push(pollData.output.screenshot_url);
110
+ }
111
+
112
+ // Fetch step-level detail from Skyvern
113
+ try {
114
+ const stepsRes = await fetch(`${apiUrl}/api/v1/tasks/${taskId}/steps`, {
115
+ headers: { 'x-api-key': apiKey },
116
+ }).catch(() => null);
117
+ if (stepsRes?.ok) {
118
+ const stepsData: any = await stepsRes.json();
119
+ const stepsList = Array.isArray(stepsData) ? stepsData : (stepsData?.steps ?? []);
120
+ for (const s of stepsList) {
121
+ if (s.output?.screenshot_url) screenshotUrls.push(s.output.screenshot_url);
122
+ skyvernSteps.push({
123
+ order: s.step_order ?? s.order ?? 0,
124
+ action_type: s.action_type ?? s.action ?? 'unknown',
125
+ element_description: s.output?.element_description,
126
+ reasoning: s.output?.llm_response?.action_description ?? s.output?.reasoning,
127
+ success: s.status === 'completed',
128
+ screenshot_url: s.output?.screenshot_url,
129
+ error: s.status === 'failed' ? (s.output?.errors?.[0] ?? 'Step failed') : undefined,
130
+ });
131
+ }
132
+ }
133
+ } catch { /* non-fatal */ }
134
+ }
135
+ }
136
+ } catch (err) {
137
+ console.warn(`[skyvern] Navigation goal failed: ${goal}`, err);
138
+ }
139
+ }
140
+
141
+ return {
142
+ screenshotUrls,
143
+ visitedUrls,
144
+ status: visitedUrls.length > 0 ? 'success' : screenshotUrls.length > 0 ? 'partial' : 'failed',
145
+ steps: skyvernSteps,
146
+ taskId: lastTaskId,
147
+ durationMs: totalDurationMs || undefined,
148
+ triggerReason,
149
+ };
150
+ }
151
+
152
+ export async function skyvernFallback(task: SkyvernTask, tenantConfig?: SkyvernConfig): Promise<'success' | 'failed'> {
153
+ const apiUrl = tenantConfig?.apiUrl || process.env.SKYVERN_API_URL;
154
+ const apiKey = tenantConfig?.apiKey || process.env.SKYVERN_API_KEY;
155
+
156
+ if (!apiUrl || !apiKey) {
157
+ console.warn(
158
+ '[skyvern] Vision fallback disabled — set SKYVERN_API_URL + SKYVERN_API_KEY in .env to enable.',
159
+ '\n[skyvern] Self-host: https://github.com/Skyvern-AI/skyvern'
160
+ );
161
+ return 'failed';
162
+ }
163
+
164
+ try {
165
+ const res = await fetch(`${apiUrl}/api/v1/tasks`, {
166
+ method: 'POST',
167
+ headers: { 'Content-Type': 'application/json', 'x-api-key': apiKey },
168
+ body: JSON.stringify({
169
+ url: task.url,
170
+ navigation_goal: task.taskDescription,
171
+ ...(task.credentials && {
172
+ navigation_payload: {
173
+ username: task.credentials.username,
174
+ password: task.credentials.password,
175
+ ...(task.credentials.oneTimeCode && { otp: task.credentials.oneTimeCode }),
176
+ },
177
+ }),
178
+ ...(tenantConfig?.llmKey ? { llm_key: tenantConfig.llmKey } : process.env.SKYVERN_LLM_KEY ? { llm_key: process.env.SKYVERN_LLM_KEY } : {}),
179
+ ...(tenantConfig?.llmApiKey ? { llm_api_key: tenantConfig.llmApiKey } : process.env.OPENAI_API_KEY ? { llm_api_key: process.env.OPENAI_API_KEY } : {}),
180
+ }),
181
+ });
182
+
183
+ if (!res.ok) {
184
+ const body = await res.text().catch(() => '');
185
+ console.error(`[skyvern] Task creation failed: ${res.status}`, body);
186
+ return 'failed';
187
+ }
188
+
189
+ const data: any = await res.json();
190
+ console.log(`[skyvern] Task queued: ${data.task_id}. Poll GET /api/v1/tasks/${data.task_id} for completion.`);
191
+ // Full implementation: poll until status === "completed" | "failed".
192
+ // For Phase 1 the login already happened in the browser context Skyvern manages,
193
+ // so returning 'success' here means we can proceed in that browser session.
194
+ return 'success';
195
+ } catch (err) {
196
+ console.error('[skyvern] Error:', err);
197
+ return 'failed';
198
+ }
199
+ }
@@ -0,0 +1,129 @@
1
+ import {
2
+ SQSClient,
3
+ SendMessageCommand,
4
+ ReceiveMessageCommand,
5
+ DeleteMessageCommand,
6
+ GetQueueAttributesCommand,
7
+ } from '@aws-sdk/client-sqs';
8
+
9
+ const sqs = new SQSClient({ region: process.env.AWS_REGION ?? 'us-east-1' });
10
+
11
+ function getQueueUrl(): string {
12
+ const url = process.env.SQS_QUEUE_URL ?? process.env.SQS_CRAWL_QUEUE_URL;
13
+ if (!url) throw new Error('SQS_QUEUE_URL not configured');
14
+ return url;
15
+ }
16
+
17
+ function getDlqUrl(): string | null {
18
+ return process.env.SQS_DLQ_URL ?? null;
19
+ }
20
+
21
+ export async function sendJobToSqs(jobId: string): Promise<void> {
22
+ await sqs.send(new SendMessageCommand({
23
+ QueueUrl: getQueueUrl(),
24
+ MessageBody: JSON.stringify({ jobId }),
25
+ }));
26
+ }
27
+
28
+ /** Returns the approximate number of messages in the SQS DLQ. */
29
+ export async function getDlqStats(): Promise<{ approximateMessageCount: number; dlqUrl: string | null }> {
30
+ const dlqUrl = getDlqUrl();
31
+ if (!dlqUrl) return { approximateMessageCount: 0, dlqUrl: null };
32
+ try {
33
+ const { Attributes = {} } = await sqs.send(new GetQueueAttributesCommand({
34
+ QueueUrl: dlqUrl,
35
+ AttributeNames: ['ApproximateNumberOfMessages'],
36
+ }));
37
+ return {
38
+ approximateMessageCount: parseInt(Attributes.ApproximateNumberOfMessages ?? '0', 10),
39
+ dlqUrl,
40
+ };
41
+ } catch (err: any) {
42
+ console.error('[sqs-dlq] getDlqStats error:', err.message);
43
+ return { approximateMessageCount: 0, dlqUrl };
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Redrive up to `maxMessages` messages from the SQS DLQ back to the main queue.
49
+ * Each message is received from the DLQ, re-sent to the main queue, then deleted
50
+ * from the DLQ. Returns the number of messages successfully redriven.
51
+ */
52
+ export async function redriveFromDlq(maxMessages = 10): Promise<number> {
53
+ const dlqUrl = getDlqUrl();
54
+ if (!dlqUrl) {
55
+ console.warn('[sqs-dlq] SQS_DLQ_URL not configured — cannot redrive');
56
+ return 0;
57
+ }
58
+ const mainUrl = getQueueUrl();
59
+ let totalRedriven = 0;
60
+
61
+ while (totalRedriven < maxMessages) {
62
+ const batch = Math.min(10, maxMessages - totalRedriven);
63
+ const { Messages = [] } = await sqs.send(new ReceiveMessageCommand({
64
+ QueueUrl: dlqUrl,
65
+ MaxNumberOfMessages: batch,
66
+ WaitTimeSeconds: 1,
67
+ }));
68
+ if (Messages.length === 0) break;
69
+
70
+ for (const msg of Messages) {
71
+ try {
72
+ await sqs.send(new SendMessageCommand({
73
+ QueueUrl: mainUrl,
74
+ MessageBody: msg.Body!,
75
+ }));
76
+ await sqs.send(new DeleteMessageCommand({
77
+ QueueUrl: dlqUrl,
78
+ ReceiptHandle: msg.ReceiptHandle!,
79
+ }));
80
+ totalRedriven++;
81
+ console.log('[sqs-dlq] redriven message:', msg.MessageId);
82
+ } catch (err: any) {
83
+ console.error('[sqs-dlq] redrive error for message', msg.MessageId, ':', err.message);
84
+ }
85
+ }
86
+ }
87
+
88
+ return totalRedriven;
89
+ }
90
+
91
+ export async function startSqsWorker(): Promise<void> {
92
+ const queueUrl = getQueueUrl();
93
+ const { claimSpecificJob, dispatchClaimedJob } = await import('./job-queue.js');
94
+ console.log('[sqs-worker] starting, queue:', queueUrl);
95
+
96
+ while (true) {
97
+ try {
98
+ const { Messages = [] } = await sqs.send(new ReceiveMessageCommand({
99
+ QueueUrl: queueUrl,
100
+ WaitTimeSeconds: 20,
101
+ MaxNumberOfMessages: 2,
102
+ }));
103
+
104
+ await Promise.all(Messages.map(async (msg) => {
105
+ let jobId = '?';
106
+ try {
107
+ const data = JSON.parse(msg.Body!);
108
+ jobId = data.jobId;
109
+ // Atomically move QUEUED → RUNNING; returns null if another worker beat us.
110
+ const claimed = await claimSpecificJob(jobId);
111
+ if (claimed) {
112
+ await dispatchClaimedJob(claimed);
113
+ }
114
+ // Delete whether we ran it or another worker did — message is handled either way.
115
+ await sqs.send(new DeleteMessageCommand({
116
+ QueueUrl: queueUrl,
117
+ ReceiptHandle: msg.ReceiptHandle!,
118
+ }));
119
+ } catch (err: any) {
120
+ console.error(`[sqs-worker] job ${jobId} failed — leaving for SQS redrive:`, err.message);
121
+ // Do NOT delete — SQS visibility timeout expires and DLQ handles retry.
122
+ }
123
+ }));
124
+ } catch (err: any) {
125
+ console.error('[sqs-worker] receive error:', err.message);
126
+ await new Promise((r) => setTimeout(r, 2000));
127
+ }
128
+ }
129
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * SSO token retrieval for Okta and Azure AD.
3
+ * Uses OAuth2 ROPC (Resource Owner Password Credentials) flow to get access tokens
4
+ * without browser-based login.
5
+ *
6
+ * Note: ROPC is deprecated in OAuth 2.1 but still supported by Okta and Azure AD
7
+ * for service accounts and automated testing scenarios.
8
+ */
9
+
10
+ export type SsoProvider = 'okta' | 'azure_ad' | 'generic_oidc';
11
+
12
+ export interface SsoConfig {
13
+ provider: SsoProvider;
14
+ /** Okta domain (e.g. 'mycompany.okta.com') or Azure tenant ID */
15
+ domain: string;
16
+ /** OAuth2 client ID */
17
+ clientId: string;
18
+ /** OAuth2 client secret (for client_credentials or confidential ROPC) */
19
+ clientSecret?: string;
20
+ /** Scopes to request (space-separated). Default: 'openid profile' */
21
+ scope?: string;
22
+ }
23
+
24
+ /**
25
+ * Get an access token using ROPC flow (username + password → token).
26
+ * Returns the access token string.
27
+ */
28
+ export async function getSsoToken(
29
+ config: SsoConfig,
30
+ username: string,
31
+ password: string
32
+ ): Promise<string> {
33
+ let tokenUrl: string;
34
+ const params: Record<string, string> = {
35
+ grant_type: 'password',
36
+ username,
37
+ password,
38
+ scope: config.scope ?? 'openid profile',
39
+ client_id: config.clientId,
40
+ };
41
+
42
+ if (config.clientSecret) {
43
+ params.client_secret = config.clientSecret;
44
+ }
45
+
46
+ switch (config.provider) {
47
+ case 'okta':
48
+ tokenUrl = `https://${config.domain}/oauth2/v1/token`;
49
+ break;
50
+ case 'azure_ad':
51
+ // domain here is the tenant ID (e.g. XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX or 'mycompany.onmicrosoft.com')
52
+ tokenUrl = `https://login.microsoftonline.com/${config.domain}/oauth2/v2.0/token`;
53
+ break;
54
+ case 'generic_oidc':
55
+ tokenUrl = config.domain.startsWith('http') ? config.domain : `https://${config.domain}/oauth2/token`;
56
+ break;
57
+ default:
58
+ throw new Error(`Unknown SSO provider: ${config.provider}`);
59
+ }
60
+
61
+ const res = await fetch(tokenUrl, {
62
+ method: 'POST',
63
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
64
+ body: new URLSearchParams(params).toString(),
65
+ });
66
+
67
+ if (!res.ok) {
68
+ const body = await res.text().catch(() => res.statusText);
69
+ throw new Error(`SSO token request failed (${res.status}): ${body}`);
70
+ }
71
+
72
+ const data = await res.json() as { access_token?: string; error?: string; error_description?: string };
73
+ if (data.error) throw new Error(`SSO error: ${data.error} — ${data.error_description}`);
74
+ if (!data.access_token) throw new Error('SSO response missing access_token');
75
+
76
+ return data.access_token;
77
+ }
78
+
79
+ /**
80
+ * Get a client credentials token (no user — for service accounts).
81
+ */
82
+ export async function getSsoClientCredentialsToken(
83
+ config: SsoConfig
84
+ ): Promise<string> {
85
+ if (!config.clientSecret) throw new Error('clientSecret required for client credentials flow');
86
+
87
+ let tokenUrl: string;
88
+ switch (config.provider) {
89
+ case 'okta':
90
+ tokenUrl = `https://${config.domain}/oauth2/v1/token`;
91
+ break;
92
+ case 'azure_ad':
93
+ tokenUrl = `https://login.microsoftonline.com/${config.domain}/oauth2/v2.0/token`;
94
+ break;
95
+ default:
96
+ tokenUrl = `https://${config.domain}/oauth2/token`;
97
+ }
98
+
99
+ const res = await fetch(tokenUrl, {
100
+ method: 'POST',
101
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
102
+ body: new URLSearchParams({
103
+ grant_type: 'client_credentials',
104
+ client_id: config.clientId,
105
+ client_secret: config.clientSecret,
106
+ scope: config.scope ?? 'openid profile',
107
+ }).toString(),
108
+ });
109
+
110
+ if (!res.ok) {
111
+ const body = await res.text().catch(() => res.statusText);
112
+ throw new Error(`SSO client credentials failed (${res.status}): ${body}`);
113
+ }
114
+
115
+ const data = await res.json() as { access_token?: string; error?: string; error_description?: string };
116
+ if (data.error) throw new Error(`SSO error: ${data.error} — ${data.error_description}`);
117
+ if (!data.access_token) throw new Error('SSO response missing access_token');
118
+
119
+ return data.access_token;
120
+ }