@detiq/crawler 0.1.3

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 (412) hide show
  1. package/Dockerfile +49 -0
  2. package/README.md +11 -0
  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/ai-login.d.ts +32 -0
  7. package/dist/ai-login.js +177 -0
  8. package/dist/ai-login.js.map +7 -0
  9. package/dist/auth-token-rotator.d.ts +47 -0
  10. package/dist/auth-token-rotator.js +58 -0
  11. package/dist/auth-token-rotator.js.map +7 -0
  12. package/dist/auth.d.ts +20 -0
  13. package/dist/auth.js +329 -0
  14. package/dist/auth.js.map +7 -0
  15. package/dist/browser-extension.d.ts +37 -0
  16. package/dist/browser-extension.js +113 -0
  17. package/dist/browser-extension.js.map +7 -0
  18. package/dist/captcha-solver.d.ts +16 -0
  19. package/dist/captcha-solver.js +105 -0
  20. package/dist/captcha-solver.js.map +7 -0
  21. package/dist/color-contrast.d.ts +30 -0
  22. package/dist/color-contrast.js +78 -0
  23. package/dist/color-contrast.js.map +7 -0
  24. package/dist/content-chunker.d.ts +18 -0
  25. package/dist/content-chunker.js +152 -0
  26. package/dist/content-chunker.js.map +7 -0
  27. package/dist/content-dedup.d.ts +23 -0
  28. package/dist/content-dedup.js +60 -0
  29. package/dist/content-dedup.js.map +7 -0
  30. package/dist/cookie-consent.d.ts +25 -0
  31. package/dist/cookie-consent.js +78 -0
  32. package/dist/cookie-consent.js.map +7 -0
  33. package/dist/cookie-jar.d.ts +20 -0
  34. package/dist/cookie-jar.js +61 -0
  35. package/dist/cookie-jar.js.map +7 -0
  36. package/dist/crawler.d.ts +179 -0
  37. package/dist/crawler.js +3672 -0
  38. package/dist/crawler.js.map +7 -0
  39. package/dist/custom-js-injector.d.ts +42 -0
  40. package/dist/custom-js-injector.js +50 -0
  41. package/dist/custom-js-injector.js.map +7 -0
  42. package/dist/dark-mode-capture.d.ts +23 -0
  43. package/dist/dark-mode-capture.js +75 -0
  44. package/dist/dark-mode-capture.js.map +7 -0
  45. package/dist/dead-link-detector.d.ts +37 -0
  46. package/dist/dead-link-detector.js +50 -0
  47. package/dist/dead-link-detector.js.map +7 -0
  48. package/dist/element-hash.d.ts +9 -0
  49. package/dist/element-hash.js +9 -0
  50. package/dist/element-hash.js.map +7 -0
  51. package/dist/email-otp.d.ts +42 -0
  52. package/dist/email-otp.js +177 -0
  53. package/dist/email-otp.js.map +7 -0
  54. package/dist/engine-router.d.ts +47 -0
  55. package/dist/engine-router.js +94 -0
  56. package/dist/engine-router.js.map +7 -0
  57. package/dist/export/bulk-export.d.ts +26 -0
  58. package/dist/export/bulk-export.js +76 -0
  59. package/dist/export/bulk-export.js.map +7 -0
  60. package/dist/export/vector-export.d.ts +76 -0
  61. package/dist/export/vector-export.js +85 -0
  62. package/dist/export/vector-export.js.map +7 -0
  63. package/dist/extractors/advanced.d.ts +54 -0
  64. package/dist/extractors/advanced.js +245 -0
  65. package/dist/extractors/advanced.js.map +7 -0
  66. package/dist/extractors/artifact-envelope.d.ts +63 -0
  67. package/dist/extractors/artifact-envelope.js +63 -0
  68. package/dist/extractors/artifact-envelope.js.map +7 -0
  69. package/dist/failure-analysis-agent.d.ts +16 -0
  70. package/dist/failure-analysis-agent.js +40 -0
  71. package/dist/failure-analysis-agent.js.map +7 -0
  72. package/dist/feature-flag-detector.d.ts +30 -0
  73. package/dist/feature-flag-detector.js +55 -0
  74. package/dist/feature-flag-detector.js.map +7 -0
  75. package/dist/form-detector.d.ts +34 -0
  76. package/dist/form-detector.js +58 -0
  77. package/dist/form-detector.js.map +7 -0
  78. package/dist/frontier.d.ts +32 -0
  79. package/dist/frontier.js +83 -0
  80. package/dist/frontier.js.map +7 -0
  81. package/dist/gap-pass.d.ts +35 -0
  82. package/dist/gap-pass.js +81 -0
  83. package/dist/gap-pass.js.map +7 -0
  84. package/dist/graphql-detector.d.ts +39 -0
  85. package/dist/graphql-detector.js +86 -0
  86. package/dist/graphql-detector.js.map +7 -0
  87. package/dist/http-engine.d.ts +80 -0
  88. package/dist/http-engine.js +304 -0
  89. package/dist/http-engine.js.map +7 -0
  90. package/dist/incremental-diff.d.ts +59 -0
  91. package/dist/incremental-diff.js +61 -0
  92. package/dist/incremental-diff.js.map +7 -0
  93. package/dist/index.d.ts +35 -0
  94. package/dist/index.js +61 -0
  95. package/dist/index.js.map +7 -0
  96. package/dist/input-fuzzer.d.ts +30 -0
  97. package/dist/input-fuzzer.js +105 -0
  98. package/dist/input-fuzzer.js.map +7 -0
  99. package/dist/interactive-probe.d.ts +104 -0
  100. package/dist/interactive-probe.js +442 -0
  101. package/dist/interactive-probe.js.map +7 -0
  102. package/dist/job-queue.d.ts +171 -0
  103. package/dist/job-queue.js +2256 -0
  104. package/dist/job-queue.js.map +7 -0
  105. package/dist/js-coverage.d.ts +29 -0
  106. package/dist/js-coverage.js +56 -0
  107. package/dist/js-coverage.js.map +7 -0
  108. package/dist/js-router-detector.d.ts +17 -0
  109. package/dist/js-router-detector.js +90 -0
  110. package/dist/js-router-detector.js.map +7 -0
  111. package/dist/language-detector.d.ts +22 -0
  112. package/dist/language-detector.js +57 -0
  113. package/dist/language-detector.js.map +7 -0
  114. package/dist/link-classifier.d.ts +23 -0
  115. package/dist/link-classifier.js +40 -0
  116. package/dist/link-classifier.js.map +7 -0
  117. package/dist/live-view.d.ts +36 -0
  118. package/dist/live-view.js +100 -0
  119. package/dist/live-view.js.map +7 -0
  120. package/dist/logger.d.ts +2 -0
  121. package/dist/logger.js +10 -0
  122. package/dist/logger.js.map +7 -0
  123. package/dist/markdown-extract.d.ts +8 -0
  124. package/dist/markdown-extract.js +54 -0
  125. package/dist/markdown-extract.js.map +7 -0
  126. package/dist/native-crawler.d.ts +69 -0
  127. package/dist/native-crawler.js +839 -0
  128. package/dist/native-crawler.js.map +7 -0
  129. package/dist/network-observer.d.ts +49 -0
  130. package/dist/network-observer.js +149 -0
  131. package/dist/network-observer.js.map +7 -0
  132. package/dist/network-throttle.d.ts +25 -0
  133. package/dist/network-throttle.js +34 -0
  134. package/dist/network-throttle.js.map +7 -0
  135. package/dist/openapi-generator.d.ts +49 -0
  136. package/dist/openapi-generator.js +89 -0
  137. package/dist/openapi-generator.js.map +7 -0
  138. package/dist/pdf-extractor.d.ts +28 -0
  139. package/dist/pdf-extractor.js +81 -0
  140. package/dist/pdf-extractor.js.map +7 -0
  141. package/dist/performance-metrics.d.ts +53 -0
  142. package/dist/performance-metrics.js +83 -0
  143. package/dist/performance-metrics.js.map +7 -0
  144. package/dist/phash.d.ts +38 -0
  145. package/dist/phash.js +115 -0
  146. package/dist/phash.js.map +7 -0
  147. package/dist/pii-scrubber.d.ts +21 -0
  148. package/dist/pii-scrubber.js +75 -0
  149. package/dist/pii-scrubber.js.map +7 -0
  150. package/dist/playwright-recorder.d.ts +39 -0
  151. package/dist/playwright-recorder.js +123 -0
  152. package/dist/playwright-recorder.js.map +7 -0
  153. package/dist/policies/crawl-safety.d.ts +9 -0
  154. package/dist/policies/crawl-safety.js +37 -0
  155. package/dist/policies/crawl-safety.js.map +7 -0
  156. package/dist/profiles/domain-profile.d.ts +19 -0
  157. package/dist/profiles/domain-profile.js +140 -0
  158. package/dist/profiles/domain-profile.js.map +7 -0
  159. package/dist/proxy.d.ts +50 -0
  160. package/dist/proxy.js +165 -0
  161. package/dist/proxy.js.map +7 -0
  162. package/dist/rate-limiter.d.ts +31 -0
  163. package/dist/rate-limiter.js +64 -0
  164. package/dist/rate-limiter.js.map +7 -0
  165. package/dist/redirect-tracker.d.ts +37 -0
  166. package/dist/redirect-tracker.js +65 -0
  167. package/dist/redirect-tracker.js.map +7 -0
  168. package/dist/redis-frontier.d.ts +48 -0
  169. package/dist/redis-frontier.js +126 -0
  170. package/dist/redis-frontier.js.map +7 -0
  171. package/dist/redis-queue.d.ts +48 -0
  172. package/dist/redis-queue.js +165 -0
  173. package/dist/redis-queue.js.map +7 -0
  174. package/dist/response-cache.d.ts +38 -0
  175. package/dist/response-cache.js +140 -0
  176. package/dist/response-cache.js.map +7 -0
  177. package/dist/responsive-detector.d.ts +29 -0
  178. package/dist/responsive-detector.js +46 -0
  179. package/dist/responsive-detector.js.map +7 -0
  180. package/dist/retry-policy.d.ts +20 -0
  181. package/dist/retry-policy.js +54 -0
  182. package/dist/retry-policy.js.map +7 -0
  183. package/dist/robots-txt.d.ts +9 -0
  184. package/dist/robots-txt.js +77 -0
  185. package/dist/robots-txt.js.map +7 -0
  186. package/dist/screen-reader.d.ts +16 -0
  187. package/dist/screen-reader.js +46 -0
  188. package/dist/screen-reader.js.map +7 -0
  189. package/dist/screenshot-masker.d.ts +28 -0
  190. package/dist/screenshot-masker.js +62 -0
  191. package/dist/screenshot-masker.js.map +7 -0
  192. package/dist/seo-checker.d.ts +33 -0
  193. package/dist/seo-checker.js +91 -0
  194. package/dist/seo-checker.js.map +7 -0
  195. package/dist/session-capture.d.ts +35 -0
  196. package/dist/session-capture.js +267 -0
  197. package/dist/session-capture.js.map +7 -0
  198. package/dist/session-export.d.ts +49 -0
  199. package/dist/session-export.js +117 -0
  200. package/dist/session-export.js.map +7 -0
  201. package/dist/sitemap-writer.d.ts +21 -0
  202. package/dist/sitemap-writer.js +47 -0
  203. package/dist/sitemap-writer.js.map +7 -0
  204. package/dist/sitemap.d.ts +51 -0
  205. package/dist/sitemap.js +152 -0
  206. package/dist/sitemap.js.map +7 -0
  207. package/dist/skyvern.d.ts +56 -0
  208. package/dist/skyvern.js +129 -0
  209. package/dist/skyvern.js.map +7 -0
  210. package/dist/sqs-queue.d.ts +2 -0
  211. package/dist/sqs-queue.js +47 -0
  212. package/dist/sqs-queue.js.map +7 -0
  213. package/dist/sso-token.d.ts +29 -0
  214. package/dist/sso-token.js +76 -0
  215. package/dist/sso-token.js.map +7 -0
  216. package/dist/stealth/human-behavior.d.ts +20 -0
  217. package/dist/stealth/human-behavior.js +168 -0
  218. package/dist/stealth/human-behavior.js.map +7 -0
  219. package/dist/telemetry.d.ts +34 -0
  220. package/dist/telemetry.js +77 -0
  221. package/dist/telemetry.js.map +7 -0
  222. package/dist/test-executor.d.ts +67 -0
  223. package/dist/test-executor.js +311 -0
  224. package/dist/test-executor.js.map +7 -0
  225. package/dist/tls-fingerprint.d.ts +50 -0
  226. package/dist/tls-fingerprint.js +81 -0
  227. package/dist/tls-fingerprint.js.map +7 -0
  228. package/dist/url-pattern-completer.d.ts +28 -0
  229. package/dist/url-pattern-completer.js +87 -0
  230. package/dist/url-pattern-completer.js.map +7 -0
  231. package/dist/visual-diff-verdict.d.ts +40 -0
  232. package/dist/visual-diff-verdict.js +25 -0
  233. package/dist/visual-diff-verdict.js.map +7 -0
  234. package/dist/webhook-notifier.d.ts +30 -0
  235. package/dist/webhook-notifier.js +76 -0
  236. package/dist/webhook-notifier.js.map +7 -0
  237. package/dist/websocket-detector.d.ts +24 -0
  238. package/dist/websocket-detector.js +60 -0
  239. package/dist/websocket-detector.js.map +7 -0
  240. package/dist/worker.d.ts +1 -0
  241. package/dist/worker.js +33 -0
  242. package/dist/worker.js.map +7 -0
  243. package/package.json +45 -0
  244. package/src/accessibility-auditor.ts +102 -0
  245. package/src/ai-login.ts +218 -0
  246. package/src/auth-token-rotator.ts +89 -0
  247. package/src/auth.ts +396 -0
  248. package/src/browser-extension.ts +186 -0
  249. package/src/captcha-solver.ts +143 -0
  250. package/src/color-contrast.ts +116 -0
  251. package/src/content-chunker.ts +170 -0
  252. package/src/content-dedup.ts +99 -0
  253. package/src/cookie-consent.ts +106 -0
  254. package/src/cookie-jar.ts +91 -0
  255. package/src/crawler.ts +4305 -0
  256. package/src/custom-js-injector.ts +93 -0
  257. package/src/dark-mode-capture.ts +110 -0
  258. package/src/dead-link-detector.ts +76 -0
  259. package/src/element-hash.ts +16 -0
  260. package/src/email-otp.ts +252 -0
  261. package/src/engine-router.ts +141 -0
  262. package/src/export/bulk-export.ts +85 -0
  263. package/src/export/vector-export.ts +160 -0
  264. package/src/extractors/advanced.ts +283 -0
  265. package/src/extractors/artifact-envelope.ts +111 -0
  266. package/src/failure-analysis-agent.ts +49 -0
  267. package/src/feature-flag-detector.ts +97 -0
  268. package/src/form-detector.ts +103 -0
  269. package/src/frontier.test.ts +64 -0
  270. package/src/frontier.ts +112 -0
  271. package/src/gap-pass.ts +122 -0
  272. package/src/graphql-detector.ts +129 -0
  273. package/src/http-engine.ts +433 -0
  274. package/src/incremental-diff.ts +121 -0
  275. package/src/index.ts +35 -0
  276. package/src/input-fuzzer.ts +129 -0
  277. package/src/interactive-probe.ts +623 -0
  278. package/src/job-queue.test.ts +120 -0
  279. package/src/job-queue.ts +2701 -0
  280. package/src/js-coverage.ts +87 -0
  281. package/src/js-router-detector.ts +112 -0
  282. package/src/language-detector.ts +82 -0
  283. package/src/link-classifier.ts +65 -0
  284. package/src/live-view.ts +141 -0
  285. package/src/logger.ts +9 -0
  286. package/src/markdown-extract.test.ts +73 -0
  287. package/src/markdown-extract.ts +76 -0
  288. package/src/native-crawler.ts +1106 -0
  289. package/src/network-observer.ts +204 -0
  290. package/src/network-throttle.ts +69 -0
  291. package/src/openapi-generator.ts +135 -0
  292. package/src/pdf-extractor.ts +123 -0
  293. package/src/performance-metrics.ts +134 -0
  294. package/src/phash.ts +151 -0
  295. package/src/pii-scrubber.ts +99 -0
  296. package/src/playwright-recorder.ts +170 -0
  297. package/src/policies/crawl-safety.ts +46 -0
  298. package/src/profiles/domain-profile.ts +167 -0
  299. package/src/proxy.ts +238 -0
  300. package/src/rate-limiter.ts +87 -0
  301. package/src/redirect-tracker.ts +97 -0
  302. package/src/redis-frontier.ts +143 -0
  303. package/src/redis-queue.ts +208 -0
  304. package/src/response-cache.ts +150 -0
  305. package/src/responsive-detector.ts +92 -0
  306. package/src/retry-policy.ts +87 -0
  307. package/src/robots-txt.ts +96 -0
  308. package/src/screen-reader.ts +89 -0
  309. package/src/screenshot-masker.ts +98 -0
  310. package/src/seo-checker.ts +134 -0
  311. package/src/session-capture.ts +325 -0
  312. package/src/session-export.test.ts +75 -0
  313. package/src/session-export.ts +172 -0
  314. package/src/sitemap-writer.ts +65 -0
  315. package/src/sitemap.test.ts +131 -0
  316. package/src/sitemap.ts +224 -0
  317. package/src/skyvern.ts +199 -0
  318. package/src/sqs-queue.ts +49 -0
  319. package/src/sso-token.ts +120 -0
  320. package/src/stealth/human-behavior.ts +191 -0
  321. package/src/telemetry.ts +122 -0
  322. package/src/test-executor.test.ts +72 -0
  323. package/src/test-executor.ts +424 -0
  324. package/src/tls-fingerprint.ts +111 -0
  325. package/src/url-pattern-completer.ts +114 -0
  326. package/src/visual-diff-verdict.test.ts +80 -0
  327. package/src/visual-diff-verdict.ts +57 -0
  328. package/src/webhook-notifier.ts +109 -0
  329. package/src/websocket-detector.ts +83 -0
  330. package/src/worker.ts +48 -0
  331. package/tsconfig.json +13 -0
  332. package/types/accessibility-auditor.d.ts +29 -0
  333. package/types/ai-login.d.ts +32 -0
  334. package/types/auth-token-rotator.d.ts +47 -0
  335. package/types/auth.d.ts +20 -0
  336. package/types/browser-extension.d.ts +37 -0
  337. package/types/bull-worker.d.ts +6 -0
  338. package/types/captcha-solver.d.ts +16 -0
  339. package/types/color-contrast.d.ts +30 -0
  340. package/types/content-chunker.d.ts +18 -0
  341. package/types/content-dedup.d.ts +23 -0
  342. package/types/cookie-consent.d.ts +25 -0
  343. package/types/cookie-jar.d.ts +20 -0
  344. package/types/crawler.d.ts +179 -0
  345. package/types/custom-js-injector.d.ts +42 -0
  346. package/types/dark-mode-capture.d.ts +23 -0
  347. package/types/dead-link-detector.d.ts +37 -0
  348. package/types/element-hash.d.ts +9 -0
  349. package/types/email-otp.d.ts +42 -0
  350. package/types/engine-router.d.ts +47 -0
  351. package/types/export/bulk-export.d.ts +26 -0
  352. package/types/export/vector-export.d.ts +76 -0
  353. package/types/extractors/advanced.d.ts +54 -0
  354. package/types/extractors/artifact-envelope.d.ts +63 -0
  355. package/types/failure-analysis-agent.d.ts +16 -0
  356. package/types/feature-flag-detector.d.ts +30 -0
  357. package/types/form-detector.d.ts +34 -0
  358. package/types/frontier.d.ts +32 -0
  359. package/types/gap-pass.d.ts +35 -0
  360. package/types/graphql-detector.d.ts +39 -0
  361. package/types/http-engine.d.ts +80 -0
  362. package/types/incremental-diff.d.ts +59 -0
  363. package/types/index.d.ts +35 -0
  364. package/types/input-fuzzer.d.ts +30 -0
  365. package/types/interactive-probe.d.ts +104 -0
  366. package/types/job-queue.d.ts +171 -0
  367. package/types/js-coverage.d.ts +29 -0
  368. package/types/js-router-detector.d.ts +17 -0
  369. package/types/language-detector.d.ts +22 -0
  370. package/types/link-classifier.d.ts +23 -0
  371. package/types/live-view.d.ts +36 -0
  372. package/types/logger.d.ts +2 -0
  373. package/types/markdown-extract.d.ts +8 -0
  374. package/types/native-crawler.d.ts +69 -0
  375. package/types/network-observer.d.ts +49 -0
  376. package/types/network-throttle.d.ts +25 -0
  377. package/types/openapi-generator.d.ts +49 -0
  378. package/types/pdf-extractor.d.ts +28 -0
  379. package/types/performance-metrics.d.ts +53 -0
  380. package/types/phash.d.ts +38 -0
  381. package/types/pii-scrubber.d.ts +21 -0
  382. package/types/playwright-recorder.d.ts +39 -0
  383. package/types/policies/crawl-safety.d.ts +9 -0
  384. package/types/profiles/domain-profile.d.ts +19 -0
  385. package/types/proxy.d.ts +50 -0
  386. package/types/rate-limiter.d.ts +31 -0
  387. package/types/redirect-tracker.d.ts +37 -0
  388. package/types/redis-frontier.d.ts +48 -0
  389. package/types/redis-queue.d.ts +48 -0
  390. package/types/response-cache.d.ts +38 -0
  391. package/types/responsive-detector.d.ts +29 -0
  392. package/types/retry-policy.d.ts +20 -0
  393. package/types/robots-txt.d.ts +9 -0
  394. package/types/screen-reader.d.ts +16 -0
  395. package/types/screenshot-masker.d.ts +28 -0
  396. package/types/seo-checker.d.ts +33 -0
  397. package/types/session-capture.d.ts +38 -0
  398. package/types/session-export.d.ts +49 -0
  399. package/types/sitemap-writer.d.ts +21 -0
  400. package/types/sitemap.d.ts +51 -0
  401. package/types/skyvern.d.ts +56 -0
  402. package/types/sqs-queue.d.ts +2 -0
  403. package/types/sso-token.d.ts +29 -0
  404. package/types/stealth/human-behavior.d.ts +20 -0
  405. package/types/telemetry.d.ts +34 -0
  406. package/types/test-executor.d.ts +67 -0
  407. package/types/tls-fingerprint.d.ts +50 -0
  408. package/types/url-pattern-completer.d.ts +28 -0
  409. package/types/visual-diff-verdict.d.ts +40 -0
  410. package/types/webhook-notifier.d.ts +30 -0
  411. package/types/websocket-detector.d.ts +24 -0
  412. package/types/worker.d.ts +1 -0
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Custom JS injector — run user-provided JavaScript in the context of each crawled page.
3
+ *
4
+ * Use cases:
5
+ * - Extract custom data points not captured by standard extractors
6
+ * - Set localStorage/sessionStorage values before crawl
7
+ * - Override fetch() to intercept API calls
8
+ * - Simulate user events (keydown, focus, etc.)
9
+ * - Bypass specific anti-bot checks
10
+ *
11
+ * Security: scripts run in the page context (sandboxed by Chromium's renderer).
12
+ * They cannot access the Node.js process or file system.
13
+ * ZeTa validates scripts are strings before injection.
14
+ */
15
+
16
+ import type { Page } from 'playwright';
17
+
18
+ export interface JsInjectionOpts {
19
+ /** Script to run on every page BEFORE navigation (via page.addInitScript) */
20
+ initScript?: string;
21
+ /** Script to run on every page AFTER navigation completes (via page.evaluate) */
22
+ postLoadScript?: string;
23
+ /** Key-value pairs to set in localStorage before page load */
24
+ localStorage?: Record<string, string>;
25
+ /** Key-value pairs to set in sessionStorage before page load */
26
+ sessionStorage?: Record<string, string>;
27
+ /** Cookie key-value pairs to add before page load */
28
+ cookies?: Array<{ name: string; value: string; domain?: string; path?: string }>;
29
+ }
30
+
31
+ export interface JsInjectionResult {
32
+ initScriptApplied: boolean;
33
+ postLoadResult: unknown;
34
+ storageSet: boolean;
35
+ cookiesSet: number;
36
+ error?: string;
37
+ }
38
+
39
+ export async function injectCustomJs(page: Page, opts: JsInjectionOpts): Promise<JsInjectionResult> {
40
+ const result: JsInjectionResult = {
41
+ initScriptApplied: false,
42
+ postLoadResult: null,
43
+ storageSet: false,
44
+ cookiesSet: 0,
45
+ };
46
+
47
+ // Set cookies via Playwright context
48
+ if (opts.cookies?.length) {
49
+ try {
50
+ await page.context().addCookies(
51
+ opts.cookies.map(c => ({ name: c.name, value: c.value, domain: c.domain ?? '', path: c.path ?? '/', url: page.url() || undefined }))
52
+ );
53
+ result.cookiesSet = opts.cookies.length;
54
+ } catch (e: any) {
55
+ result.error = `Cookie injection failed: ${e.message}`;
56
+ }
57
+ }
58
+
59
+ // Init script (runs before page load on every navigation)
60
+ if (opts.initScript || opts.localStorage || opts.sessionStorage) {
61
+ const storageSetup = [
62
+ opts.localStorage ? `Object.entries(${JSON.stringify(opts.localStorage)}).forEach(([k,v])=>localStorage.setItem(k,v));` : '',
63
+ opts.sessionStorage ? `Object.entries(${JSON.stringify(opts.sessionStorage)}).forEach(([k,v])=>sessionStorage.setItem(k,v));` : '',
64
+ ].filter(Boolean).join('\n');
65
+
66
+ const combinedInit = [storageSetup, opts.initScript ?? ''].filter(Boolean).join('\n');
67
+ try {
68
+ await page.addInitScript(combinedInit);
69
+ result.initScriptApplied = true;
70
+ result.storageSet = !!(opts.localStorage || opts.sessionStorage);
71
+ } catch (e: any) {
72
+ result.error = `Init script failed: ${e.message}`;
73
+ }
74
+ }
75
+
76
+ // Post-load script (runs after navigation)
77
+ if (opts.postLoadScript) {
78
+ try {
79
+ result.postLoadResult = await page.evaluate(opts.postLoadScript);
80
+ } catch (e: any) {
81
+ result.error = `Post-load script failed: ${e.message}`;
82
+ }
83
+ }
84
+
85
+ return result;
86
+ }
87
+
88
+ /** Safe string validator — ensures script is a string, not an object/function reference */
89
+ export function validateScript(script: unknown): string {
90
+ if (typeof script !== 'string') throw new Error('Script must be a string');
91
+ if (script.length > 50_000) throw new Error('Script too large (>50KB)');
92
+ return script;
93
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Dark mode capture — screenshot pages in both light and dark color schemes.
3
+ *
4
+ * Uses Playwright's page.emulateMedia({ colorScheme: 'dark' }) to force dark mode,
5
+ * then captures a screenshot. Compares with light mode to determine if dark mode
6
+ * is supported (significant visual difference).
7
+ *
8
+ * Also detects prefers-color-scheme media query support in CSS.
9
+ */
10
+
11
+ import type { Page } from 'playwright';
12
+
13
+ export interface DarkModeCapture {
14
+ url: string;
15
+ lightScreenshot?: Buffer;
16
+ darkScreenshot?: Buffer;
17
+ hasDarkMode: boolean;
18
+ hasCssDarkMode: boolean; // @media (prefers-color-scheme: dark) detected in stylesheets
19
+ backgroundColorLight?: string;
20
+ backgroundColorDark?: string;
21
+ capturedAt: string;
22
+ }
23
+
24
+ async function getBackgroundColor(page: Page): Promise<string> {
25
+ try {
26
+ return await page.evaluate(() => {
27
+ const body = document.body;
28
+ return window.getComputedStyle(body).backgroundColor;
29
+ });
30
+ } catch {
31
+ return 'unknown';
32
+ }
33
+ }
34
+
35
+ function colorsAreDifferent(a: string, b: string): boolean {
36
+ if (a === b) return false;
37
+ if (a === 'unknown' || b === 'unknown') return false;
38
+ // Parse rgb(r, g, b) and compare luminance
39
+ const parse = (c: string) => {
40
+ const m = c.match(/\d+/g);
41
+ return m ? m.map(Number) : [0, 0, 0];
42
+ };
43
+ const [ar, ag, ab] = parse(a);
44
+ const [br, bg, bb] = parse(b);
45
+ const lumA = 0.299 * ar + 0.587 * ag + 0.114 * ab;
46
+ const lumB = 0.299 * br + 0.587 * bg + 0.114 * bb;
47
+ return Math.abs(lumA - lumB) > 30; // significant luminance difference
48
+ }
49
+
50
+ async function hasCssDarkModeSupport(page: Page): Promise<boolean> {
51
+ try {
52
+ return await page.evaluate(() => {
53
+ const sheets = Array.from(document.styleSheets);
54
+ for (const sheet of sheets) {
55
+ try {
56
+ const rules = Array.from(sheet.cssRules ?? []);
57
+ for (const rule of rules) {
58
+ if (rule instanceof CSSMediaRule && rule.conditionText?.includes('prefers-color-scheme')) {
59
+ return true;
60
+ }
61
+ }
62
+ } catch { /* cross-origin stylesheet — skip */ }
63
+ }
64
+ return false;
65
+ });
66
+ } catch {
67
+ return false;
68
+ }
69
+ }
70
+
71
+ export async function captureDarkMode(
72
+ page: Page,
73
+ url: string,
74
+ opts: { takeScreenshots?: boolean } = {},
75
+ ): Promise<DarkModeCapture> {
76
+ const capturedAt = new Date().toISOString();
77
+ const { takeScreenshots = false } = opts;
78
+
79
+ // Light mode
80
+ await page.emulateMedia({ colorScheme: 'light' }).catch(() => {});
81
+ const backgroundColorLight = await getBackgroundColor(page);
82
+ const hasCssDark = await hasCssDarkModeSupport(page);
83
+ const lightScreenshot = takeScreenshots
84
+ ? await page.screenshot({ type: 'jpeg', quality: 60 }).catch(() => undefined)
85
+ : undefined;
86
+
87
+ // Dark mode
88
+ await page.emulateMedia({ colorScheme: 'dark' }).catch(() => {});
89
+ await page.waitForTimeout(300); // allow CSS transitions
90
+ const backgroundColorDark = await getBackgroundColor(page);
91
+ const darkScreenshot = takeScreenshots
92
+ ? await page.screenshot({ type: 'jpeg', quality: 60 }).catch(() => undefined)
93
+ : undefined;
94
+
95
+ // Restore light mode
96
+ await page.emulateMedia({ colorScheme: 'light' }).catch(() => {});
97
+
98
+ const hasDarkMode = colorsAreDifferent(backgroundColorLight, backgroundColorDark) || hasCssDark;
99
+
100
+ return {
101
+ url,
102
+ lightScreenshot,
103
+ darkScreenshot,
104
+ hasDarkMode,
105
+ hasCssDarkMode: hasCssDark,
106
+ backgroundColorLight,
107
+ backgroundColorDark,
108
+ capturedAt,
109
+ };
110
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Dead link detector — tracks broken links discovered during crawl.
3
+ *
4
+ * A "dead link" is a URL that:
5
+ * - Returns 404, 410, or other 4xx/5xx responses
6
+ * - Times out after maxRetries
7
+ * - Redirects to an error page (detected by title heuristic)
8
+ *
9
+ * Results: list of broken links with source page, status code, and anchor text.
10
+ * Used for: SEO audit export, test report enrichment.
11
+ */
12
+
13
+ export interface DeadLink {
14
+ url: string;
15
+ statusCode: number;
16
+ sourceUrl?: string;
17
+ anchorText?: string;
18
+ checkedAt: string;
19
+ reason: 'http-error' | 'timeout' | 'dns-error';
20
+ }
21
+
22
+ export class DeadLinkTracker {
23
+ private deadLinks: DeadLink[] = [];
24
+ private checked = new Map<string, number>(); // url → statusCode
25
+
26
+ record(
27
+ url: string,
28
+ statusCode: number,
29
+ source?: { sourceUrl?: string; anchorText?: string },
30
+ ): void {
31
+ if (this.checked.has(url)) return;
32
+ this.checked.set(url, statusCode);
33
+ if (statusCode >= 400) {
34
+ this.deadLinks.push({
35
+ url,
36
+ statusCode,
37
+ sourceUrl: source?.sourceUrl,
38
+ anchorText: source?.anchorText,
39
+ checkedAt: new Date().toISOString(),
40
+ reason: statusCode === 0 ? 'timeout' : 'http-error',
41
+ });
42
+ }
43
+ }
44
+
45
+ recordTimeout(url: string, sourceUrl?: string): void {
46
+ if (this.checked.has(url)) return;
47
+ this.checked.set(url, 0);
48
+ this.deadLinks.push({ url, statusCode: 0, sourceUrl, checkedAt: new Date().toISOString(), reason: 'timeout' });
49
+ }
50
+
51
+ getDeadLinks(): DeadLink[] {
52
+ return [...this.deadLinks];
53
+ }
54
+
55
+ isKnownBroken(url: string): boolean {
56
+ const code = this.checked.get(url);
57
+ return code !== undefined && code >= 400;
58
+ }
59
+
60
+ stats(): { total: number; by404: number; by5xx: number; byTimeout: number } {
61
+ return {
62
+ total: this.deadLinks.length,
63
+ by404: this.deadLinks.filter(l => l.statusCode === 404).length,
64
+ by5xx: this.deadLinks.filter(l => l.statusCode >= 500).length,
65
+ byTimeout: this.deadLinks.filter(l => l.reason === 'timeout').length,
66
+ };
67
+ }
68
+
69
+ toCsv(): string {
70
+ const rows = [['URL', 'Status', 'Source URL', 'Anchor Text', 'Checked At']];
71
+ for (const l of this.deadLinks) {
72
+ rows.push([l.url, String(l.statusCode), l.sourceUrl ?? '', l.anchorText ?? '', l.checkedAt]);
73
+ }
74
+ return rows.map(r => r.map(c => `"${c.replace(/"/g, '""')}"`).join(',')).join('\n');
75
+ }
76
+ }
@@ -0,0 +1,16 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ /**
4
+ * Compute a stable fingerprint of a screen's element set.
5
+ * Sorted so insertion-order changes (React re-renders) don't produce false positives.
6
+ * Returns first 16 hex chars of SHA-256.
7
+ */
8
+ export function computeElementHash(
9
+ elements: Array<{ role: string; meaning: string }>,
10
+ ): string {
11
+ const pairs = elements
12
+ .map((e) => `${e.role.toLowerCase()}:${e.meaning.toLowerCase().trim()}`)
13
+ .sort()
14
+ .join('|');
15
+ return createHash('sha256').update(pairs).digest('hex').slice(0, 16);
16
+ }
@@ -0,0 +1,252 @@
1
+ /**
2
+ * Email OTP retrieval — supports 3 providers:
3
+ * mailslurp — managed SaaS (existing, no self-hosting)
4
+ * imap — any real IMAP mailbox (Gmail, Outlook, custom domain catch-all)
5
+ * mailpit — self-hosted SMTP trap (dev/staging only)
6
+ *
7
+ * Use mailslurp or imap for production apps.
8
+ * Use mailpit only when you can point the app's SMTP at the trap server.
9
+ */
10
+
11
+ export type EmailOTPProvider = 'mailslurp' | 'imap' | 'mailpit';
12
+
13
+ export interface EmailContent {
14
+ /** 4-8 digit OTP code, if found. */
15
+ otp?: string;
16
+ /** Magic link URL to navigate to, if found. */
17
+ magicLink?: string;
18
+ }
19
+
20
+ export interface EmailOTPConfig {
21
+ provider: EmailOTPProvider;
22
+ // MailSlurp
23
+ apiKey?: string;
24
+ inboxId?: string;
25
+ // IMAP (Gmail app-password, Outlook, custom IMAP)
26
+ imapHost?: string;
27
+ imapPort?: number;
28
+ imapUser?: string;
29
+ imapPass?: string;
30
+ imapTls?: boolean;
31
+ // Mailpit (REST API at baseUrl)
32
+ mailpitBaseUrl?: string;
33
+ }
34
+
35
+ const POLL_INTERVAL_MS = 2_000;
36
+ const MAX_WAIT_MS = 60_000;
37
+
38
+ /** Extract OTP code from email body text. Prefers 6-digit, falls back to 4-8 digit. */
39
+ function extractOTP(text: string): string | null {
40
+ const m6 = text.match(/\b(\d{6})\b/);
41
+ if (m6) return m6[1];
42
+ const m48 = text.match(/\b(\d{4,8})\b/);
43
+ if (m48) return m48[1];
44
+ const magic = text.match(/\b([A-Z0-9]{6,10})\b/);
45
+ if (magic) return magic[1];
46
+ return null;
47
+ }
48
+
49
+ /** Extract a magic-link URL from email body text. Matches /verify, /magic, /auth/callback, ?token= etc. */
50
+ function extractMagicLink(text: string): string | null {
51
+ const magicPath = /\/(verify|magic|login|auth|confirm|sign-in)[/?#]/i;
52
+ const magicQuery = /[?&](token|magic_token|login_token|auth_token|key)=/i;
53
+ const urlMatches = text.match(/https:\/\/[^\s<>"')\]]+/g);
54
+ if (!urlMatches) return null;
55
+ for (const raw of urlMatches) {
56
+ try {
57
+ const u = new URL(raw.replace(/[>'")\].,]+$/, ''));
58
+ if (magicPath.test(u.pathname) || magicQuery.test(u.search)) return u.toString();
59
+ } catch { /* skip malformed URLs */ }
60
+ }
61
+ return null;
62
+ }
63
+
64
+ function parseEmailContent(text: string): EmailContent {
65
+ const magicLink = extractMagicLink(text);
66
+ if (magicLink) return { magicLink };
67
+ const otp = extractOTP(text);
68
+ if (otp) return { otp };
69
+ return {};
70
+ }
71
+
72
+ // ── MailSlurp ────────────────────────────────────────────────────────────────
73
+
74
+ const MAILSLURP_BASE = 'https://api.mailslurp.com';
75
+
76
+ async function waitForContentMailSlurp(apiKey: string, inboxId: string, since: string): Promise<EmailContent | null> {
77
+ const deadline = Date.now() + MAX_WAIT_MS;
78
+ while (Date.now() < deadline) {
79
+ await new Promise(r => setTimeout(r, POLL_INTERVAL_MS));
80
+ try {
81
+ const listRes = await fetch(
82
+ `${MAILSLURP_BASE}/inboxes/${inboxId}/emails?sort=DESC&limit=5&since=${encodeURIComponent(since)}`,
83
+ { headers: { 'x-api-key': apiKey } }
84
+ );
85
+ if (!listRes.ok) continue;
86
+ const emails = await listRes.json() as Array<{ id: string }>;
87
+ if (!emails.length) continue;
88
+ const bodyRes = await fetch(`${MAILSLURP_BASE}/emails/${emails[0].id}`, { headers: { 'x-api-key': apiKey } });
89
+ if (!bodyRes.ok) continue;
90
+ const email = await bodyRes.json() as { body?: string; subject?: string };
91
+ const content = parseEmailContent((email.body ?? '') + ' ' + (email.subject ?? ''));
92
+ if (content.otp || content.magicLink) return content;
93
+ } catch { /* retry */ }
94
+ }
95
+ return null;
96
+ }
97
+
98
+ async function getInboxEmailMailSlurp(apiKey: string, inboxId: string): Promise<string | null> {
99
+ try {
100
+ const res = await fetch(`${MAILSLURP_BASE}/inboxes/${inboxId}`, { headers: { 'x-api-key': apiKey } });
101
+ if (!res.ok) return null;
102
+ const data = await res.json() as { emailAddress?: string };
103
+ return data.emailAddress ?? null;
104
+ } catch { return null; }
105
+ }
106
+
107
+ // ── Mailpit (SMTP trap REST API) ──────────────────────────────────────────────
108
+
109
+ async function waitForContentMailpit(baseUrl: string, since: Date): Promise<EmailContent | null> {
110
+ const deadline = Date.now() + MAX_WAIT_MS;
111
+ const sinceMs = since.getTime();
112
+ while (Date.now() < deadline) {
113
+ await new Promise(r => setTimeout(r, POLL_INTERVAL_MS));
114
+ try {
115
+ const res = await fetch(`${baseUrl}/api/v1/messages?limit=10`);
116
+ if (!res.ok) continue;
117
+ const data = await res.json() as { messages?: Array<{ ID: string; Created: string; Snippet: string; Subject: string }> };
118
+ const recent = (data.messages ?? []).filter(m => new Date(m.Created).getTime() > sinceMs);
119
+ for (const msg of recent) {
120
+ const snippet = parseEmailContent(msg.Snippet + ' ' + msg.Subject);
121
+ if (snippet.otp || snippet.magicLink) return snippet;
122
+ // Fetch full body — snippet may truncate the magic link
123
+ const bodyRes = await fetch(`${baseUrl}/api/v1/message/${msg.ID}`);
124
+ if (!bodyRes.ok) continue;
125
+ const body = await bodyRes.json() as { Text?: { Body?: string }; Subject?: string };
126
+ const full = parseEmailContent((body.Text?.Body ?? '') + ' ' + (body.Subject ?? ''));
127
+ if (full.otp || full.magicLink) return full;
128
+ }
129
+ } catch { /* retry */ }
130
+ }
131
+ return null;
132
+ }
133
+
134
+ // ── IMAP (any mailbox) ────────────────────────────────────────────────────────
135
+
136
+ async function waitForContentImap(
137
+ cfg: { host: string; port: number; user: string; pass: string; tls: boolean },
138
+ since: Date
139
+ ): Promise<EmailContent | null> {
140
+ let ImapFlow: any;
141
+ try {
142
+ const mod = await import('imapflow');
143
+ ImapFlow = mod.ImapFlow;
144
+ } catch {
145
+ throw new Error('IMAP provider requires imapflow package. Add it to dependencies.');
146
+ }
147
+
148
+ const client = new ImapFlow({
149
+ host: cfg.host,
150
+ port: cfg.port,
151
+ secure: cfg.tls,
152
+ auth: { user: cfg.user, pass: cfg.pass },
153
+ logger: false,
154
+ });
155
+
156
+ try {
157
+ await client.connect();
158
+ const lock = await client.getMailboxLock('INBOX');
159
+ try {
160
+ const deadline = Date.now() + MAX_WAIT_MS;
161
+ while (Date.now() < deadline) {
162
+ const uids = await client.search({ seen: false, since });
163
+ if (uids.length) {
164
+ for await (const msg of client.fetch(uids.slice(-5), { source: true })) {
165
+ const { simpleParser } = await import('mailparser');
166
+ const parsed = await simpleParser(msg.source);
167
+ const text = (parsed.text ?? '') + ' ' + (parsed.subject ?? '');
168
+ const content = parseEmailContent(text);
169
+ if (content.otp || content.magicLink) return content;
170
+ }
171
+ }
172
+ await new Promise(r => setTimeout(r, POLL_INTERVAL_MS));
173
+ }
174
+ return null;
175
+ } finally {
176
+ lock.release();
177
+ }
178
+ } finally {
179
+ await client.logout().catch(() => {});
180
+ }
181
+ }
182
+
183
+ // ── Public API ────────────────────────────────────────────────────────────────
184
+
185
+ /**
186
+ * Wait for an email and return its OTP code or magic link URL.
187
+ * Prefer this over waitForEmailOTP when the app may send passwordless magic links.
188
+ */
189
+ export async function waitForEmailContent(
190
+ config: EmailOTPConfig,
191
+ since: string | Date
192
+ ): Promise<EmailContent | null> {
193
+ const sinceStr = typeof since === 'string' ? since : since.toISOString();
194
+ const sinceDate = typeof since === 'string' ? new Date(since) : since;
195
+
196
+ switch (config.provider) {
197
+ case 'mailslurp':
198
+ if (!config.apiKey || !config.inboxId) throw new Error('mailslurp requires apiKey + inboxId');
199
+ return waitForContentMailSlurp(config.apiKey, config.inboxId, sinceStr);
200
+
201
+ case 'mailpit':
202
+ return waitForContentMailpit(config.mailpitBaseUrl ?? 'http://mailpit:8025', sinceDate);
203
+
204
+ case 'imap':
205
+ if (!config.imapHost || !config.imapUser || !config.imapPass) {
206
+ throw new Error('imap requires imapHost, imapUser, imapPass');
207
+ }
208
+ return waitForContentImap({
209
+ host: config.imapHost,
210
+ port: config.imapPort ?? 993,
211
+ user: config.imapUser,
212
+ pass: config.imapPass,
213
+ tls: config.imapTls !== false,
214
+ }, sinceDate);
215
+
216
+ default:
217
+ return null;
218
+ }
219
+ }
220
+
221
+ /**
222
+ * Wait for an OTP email and extract the code.
223
+ * @deprecated Use waitForEmailContent which also handles magic links.
224
+ */
225
+ export async function waitForEmailOTP(
226
+ config: EmailOTPConfig,
227
+ since: string | Date
228
+ ): Promise<string | null> {
229
+ const content = await waitForEmailContent(config, since);
230
+ return content?.otp ?? null;
231
+ }
232
+
233
+ /**
234
+ * Get the email address for a MailSlurp inbox (used to display in UI).
235
+ * Returns null for IMAP/Mailpit providers — use imapUser directly.
236
+ */
237
+ export async function getInboxEmail(
238
+ configOrApiKey: EmailOTPConfig | string,
239
+ inboxId?: string
240
+ ): Promise<string | null> {
241
+ // Legacy call: getInboxEmail(apiKey, inboxId)
242
+ if (typeof configOrApiKey === 'string') {
243
+ return getInboxEmailMailSlurp(configOrApiKey, inboxId ?? '');
244
+ }
245
+ if (configOrApiKey.provider === 'mailslurp' && configOrApiKey.apiKey && configOrApiKey.inboxId) {
246
+ return getInboxEmailMailSlurp(configOrApiKey.apiKey, configOrApiKey.inboxId);
247
+ }
248
+ if (configOrApiKey.provider === 'imap') {
249
+ return configOrApiKey.imapUser ?? null;
250
+ }
251
+ return null;
252
+ }
@@ -0,0 +1,141 @@
1
+ import type { DomainProfile } from './profiles/domain-profile.js';
2
+
3
+ export type CrawlEngineName =
4
+ | 'http'
5
+ | 'browser'
6
+ | 'browser-stealth'
7
+ | 'stagehand'
8
+ | 'vision'
9
+ | 'recorded-session'
10
+ | 'native';
11
+
12
+ export interface CrawlRouteDecisionInput {
13
+ appUrl: string;
14
+ appType?: string | null;
15
+ hasCredentials: boolean;
16
+ hasStorageState: boolean;
17
+ hasAuthToken: boolean;
18
+ hasSkyvern: boolean;
19
+ hasProxy: boolean;
20
+ profile: DomainProfile;
21
+ previousFailureReason?: string;
22
+ }
23
+
24
+ export interface CrawlRouteDecision {
25
+ engines: CrawlEngineName[];
26
+ reasons: string[];
27
+ confidence: number;
28
+ }
29
+
30
+ /**
31
+ * Per-domain rendering predictor — learns whether a domain requires a full browser
32
+ * or can be served by the fast HTTP engine. Implements adaptive crawlee-python pattern.
33
+ *
34
+ * Strategy:
35
+ * 1. On first encounter of a domain, classify the HTTP response body.
36
+ * 2. Store the decision in memory (Map). All future URLs on same domain skip re-testing.
37
+ * 3. "Requires browser" signals: React/Vue/Angular root with no content, tiny body (<500 chars meaningful text).
38
+ */
39
+ export class RenderingTypePredictor {
40
+ private cache = new Map<string, 'http' | 'browser'>();
41
+
42
+ /** Return cached decision if available, undefined if unknown. */
43
+ getCached(url: string): 'http' | 'browser' | undefined {
44
+ try {
45
+ return this.cache.get(new URL(url).hostname);
46
+ } catch {
47
+ return undefined;
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Analyze an HTTP response body to predict if JS rendering is required.
53
+ * Returns 'browser' if JS-heavy signals detected, 'http' otherwise.
54
+ */
55
+ predict(url: string, htmlBody: string, statusCode: number): 'http' | 'browser' {
56
+ let decision: 'http' | 'browser' = 'http';
57
+ try {
58
+ if (statusCode >= 400) {
59
+ decision = 'browser'; // let browser handle error pages
60
+ } else {
61
+ const bodyLen = htmlBody.length;
62
+ // Strip tags to get raw text
63
+ const textOnly = htmlBody.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
64
+ const wordCount = textOnly.split(/\s+/).filter(w => w.length > 2).length;
65
+
66
+ // SPA signals: very short text, presence of React/Vue/Angular root markers
67
+ const hasSpaRoot = /<div[^>]*\s+id=["'](?:root|app|__nuxt|__next|app-root)["'][^>]*>\s*<\/div>/i.test(htmlBody)
68
+ || /<app-root[^>]*>\s*<\/app-root>/i.test(htmlBody);
69
+ const hasNoscriptFallback = /<noscript[^>]*>[\s\S]{100,}/i.test(htmlBody);
70
+ const tinyBody = bodyLen < 3000 && wordCount < 50;
71
+
72
+ if ((hasSpaRoot && wordCount < 100) || (tinyBody && !hasNoscriptFallback)) {
73
+ decision = 'browser';
74
+ }
75
+ }
76
+ } catch { /* default http */ }
77
+
78
+ try {
79
+ this.cache.set(new URL(url).hostname, decision);
80
+ } catch { /* ignore */ }
81
+ return decision;
82
+ }
83
+
84
+ /** Force a domain to use a specific engine (e.g. after observing crawl errors). */
85
+ set(url: string, engine: 'http' | 'browser'): void {
86
+ try { this.cache.set(new URL(url).hostname, engine); } catch { /* ignore */ }
87
+ }
88
+
89
+ stats(): { cached: number; browserDomains: string[]; httpDomains: string[] } {
90
+ const browserDomains: string[] = [];
91
+ const httpDomains: string[] = [];
92
+ for (const [domain, engine] of this.cache) {
93
+ if (engine === 'browser') browserDomains.push(domain);
94
+ else httpDomains.push(domain);
95
+ }
96
+ return { cached: this.cache.size, browserDomains, httpDomains };
97
+ }
98
+ }
99
+
100
+ /** Singleton predictor — shared across crawl jobs in the same process. */
101
+ export const renderingPredictor = new RenderingTypePredictor();
102
+
103
+ export function chooseCrawlEngines(input: CrawlRouteDecisionInput): CrawlRouteDecision {
104
+ const engines: CrawlEngineName[] = [];
105
+ const reasons: string[] = [];
106
+
107
+ const appType = input.appType?.toLowerCase();
108
+ if (appType === 'android' || appType === 'ios' || appType === 'windows' || appType === 'macos') {
109
+ return { engines: ['native'], reasons: [`appType=${input.appType}`], confidence: 0.95 };
110
+ }
111
+
112
+ if (input.hasStorageState || input.hasAuthToken) {
113
+ engines.push('recorded-session');
114
+ reasons.push('session/token auth available');
115
+ }
116
+
117
+ engines.push(input.hasProxy ? 'browser-stealth' : 'browser');
118
+ reasons.push(input.hasProxy ? 'proxy configured; prefer stealth browser path' : 'default browser path');
119
+
120
+ if (input.hasCredentials || input.profile.industry !== 'unknown') {
121
+ engines.push('stagehand');
122
+ reasons.push(input.hasCredentials ? 'credentials available for AI login/navigation' : `domain profile=${input.profile.industry}`);
123
+ }
124
+
125
+ const hardUi = input.profile.industry === 'legacy-enterprise' || /captcha|blocked|canvas|iframe|bot/i.test(input.previousFailureReason ?? '');
126
+ if (input.hasSkyvern && hardUi) {
127
+ engines.push('vision');
128
+ reasons.push('hard UI or previous block detected; vision fallback enabled');
129
+ }
130
+
131
+ if (engines.length === 1) {
132
+ engines.unshift('http');
133
+ reasons.push('HTTP/static extraction can be attempted before browser escalation');
134
+ }
135
+
136
+ return {
137
+ engines: Array.from(new Set(engines)),
138
+ reasons,
139
+ confidence: input.profile.confidence,
140
+ };
141
+ }