on_Snapshot__11_chrome_wait.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/env node
  2. /**
  3. * Wait for Chrome session files to exist (cdp_url.txt + target_id.txt).
  4. *
  5. * This is a foreground hook that blocks until the Chrome tab is ready,
  6. * so downstream hooks can safely connect to CDP.
  7. *
  8. * Usage: on_Snapshot__11_chrome_wait.js --url=<url> --snapshot-id=<uuid>
  9. */
  10. const fs = require('fs');
  11. const path = require('path');
  12. // Add NODE_MODULES_DIR to module resolution paths if set
  13. if (process.env.NODE_MODULES_DIR) module.paths.unshift(process.env.NODE_MODULES_DIR);
  14. const {
  15. getEnvInt,
  16. waitForChromeSession,
  17. readCdpUrl,
  18. readTargetId,
  19. } = require('./chrome_utils.js');
  20. const CHROME_SESSION_DIR = '.';
  21. const CHROME_SESSION_REQUIRED_ERROR = 'No Chrome session found (chrome plugin must run first)';
  22. function parseArgs() {
  23. const args = {};
  24. process.argv.slice(2).forEach(arg => {
  25. if (arg.startsWith('--')) {
  26. const [key, ...valueParts] = arg.slice(2).split('=');
  27. args[key.replace(/-/g, '_')] = valueParts.join('=') || true;
  28. }
  29. });
  30. return args;
  31. }
  32. async function main() {
  33. const args = parseArgs();
  34. const url = args.url;
  35. const snapshotId = args.snapshot_id;
  36. if (!url || !snapshotId) {
  37. console.error('Usage: on_Snapshot__11_chrome_wait.js --url=<url> --snapshot-id=<uuid>');
  38. process.exit(1);
  39. }
  40. const timeoutSeconds = getEnvInt('CHROME_TAB_TIMEOUT', getEnvInt('CHROME_TIMEOUT', getEnvInt('TIMEOUT', 60)));
  41. const timeoutMs = timeoutSeconds * 1000;
  42. console.error(`[chrome_wait] Waiting for Chrome session (timeout=${timeoutSeconds}s)...`);
  43. const ready = await waitForChromeSession(CHROME_SESSION_DIR, timeoutMs);
  44. if (!ready) {
  45. const error = CHROME_SESSION_REQUIRED_ERROR;
  46. console.error(`[chrome_wait] ERROR: ${error}`);
  47. console.log(JSON.stringify({ type: 'ArchiveResult', status: 'failed', output_str: error }));
  48. process.exit(1);
  49. }
  50. const cdpUrl = readCdpUrl(CHROME_SESSION_DIR);
  51. const targetId = readTargetId(CHROME_SESSION_DIR);
  52. if (!cdpUrl || !targetId) {
  53. const error = CHROME_SESSION_REQUIRED_ERROR;
  54. console.error(`[chrome_wait] ERROR: ${error}`);
  55. console.log(JSON.stringify({ type: 'ArchiveResult', status: 'failed', output_str: error }));
  56. process.exit(1);
  57. }
  58. console.error(`[chrome_wait] Chrome session ready (cdp_url=${cdpUrl.slice(0, 32)}..., target_id=${targetId}).`);
  59. console.log(JSON.stringify({ type: 'ArchiveResult', status: 'succeeded', output_str: 'chrome session ready' }));
  60. process.exit(0);
  61. }
  62. main().catch(e => {
  63. console.error(`Fatal error: ${e.message}`);
  64. process.exit(1);
  65. });