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B,CAAE,MACA,OAAO,EAAS,UAClB,CACF,GAEI,cAAgB,UAClB,IACE,aAAa,EAAS,UAAS,GAAS,EAAM,YAChD,CAAE,MAAO,GACP,OAAO,EAAS,UAClB","file":"/npm/prerendererest@1.0.2/index.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/prerendererest@1.0.2/index.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","#!/usr/bin/env node\n\nconst puppeteer = require(\"puppeteer\");\nconst express = require(\"express\");\nconst serveStatic = require(\"serve-static\");\nconst fallback = require(\"express-history-api-fallback\");\nconst path = require(\"path\");\nconst nativeFs = require(\"fs\");\nconst mkdirp = require(\"mkdirp\");\nconst minify = require(\"html-minifier\").minify;\n\n// Main flow:\n// run() → startServer() → crawl() → fetchPage() → save HTML files\n\n// Usage:\n// node react_snap_replacement.js --include \"/index.html,/about.html\" --source \"./build\" --headless\n\nconst defaultOptions = {\n\n  port: 45678,\n  crawl: true,\n  source: \"./docs\",\n  destination: \"./docs\",\n  include: [\"/index.html\"],\n  userAgent: \"Prerendererest\",\n  headless: false,\n  puppeteerArgs: [\"--no-sandbox\", \"--disable-setuid-sandbox\"],\n  puppeteer: { cache: false },\n  minifyHtml: {\n    collapseWhitespace: true,\n    removeComments: true\n  },\n  viewport: { width: 480, height: 850 },\n  skipThirdPartyRequests: false,\n  concurrency: 1,\n  inlineCss: false,\n  removeStyleTags: false,\n  preloadImages: false,\n  asyncScriptTags: false,\n  removeScriptTags: false,\n  skipExistingCheck: false,\n};\n\nconst defaults = userOptions => {\n  const options = { ...defaultOptions, ...userOptions };\n  options.destination = options.destination || options.source;\n  if (!options.include.length) throw new Error(\"Include option should be non-empty\");\n  return options;\n};\n\nconst crawl = async (opt) => {\n  const {\n    options,\n    basePath,\n    beforeFetch,\n    afterFetch,\n    onEnd,\n    publicPath,\n    sourceDir\n  } = opt;\n  let streamClosed = false;\n  const errorReport = {\n    pageErrors: [],\n    consoleErrors: [],\n    httpErrors: [],\n    fetchErrors: []\n  };\n\n  // exit process\n  const onSigint = () => {\n    console.log(\"\\nGracefully shutting down...\");\n    process.exit(1);\n  };\n  process.on(\"SIGINT\", onSigint);\n \n  // Exit on unhandled promise rejections\n  process.on(\"unhandledRejection\", error => {\n    console.log(\"🔥  UnhandledPromiseRejectionWarning\", error);\n    errorReport.pageErrors.push({ route: 'global', error: error.message });\n  });\n\n  const queue = [];\n  let enqued = 0;\n  let processed = 0;\n  const uniqueUrls = new Set();\n  const sourcemapStore = {};\n\n  // Add a URL to the queue if it's not already there and it's not a third-party URL\n  const addToQueue = newUrl => {\n    if(!newUrl) return;\n    if(newUrl.includes('mailto:')) return;\n    if(newUrl.includes('javascript:')) return;\n    const { hostname, search, hash } = new URL(newUrl);\n    newUrl = newUrl.replace(`${search || \"\"}${hash || \"\"}`, \"\");\n    if (hostname === \"localhost\" && !uniqueUrls.has(newUrl) && !streamClosed) {\n      uniqueUrls.add(newUrl);\n      enqued++;\n      queue.push(newUrl);\n      if (enqued == 2 && options.crawl) {\n        addToQueue(`${basePath}${publicPath}404.html`);\n      }\n    }\n  };\n\n  const browser = await puppeteer.launch({\n    headless: options.headless,\n    args: options.puppeteerArgs,\n    executablePath: options.puppeteerExecutablePath,\n    ignoreHTTPSErrors: options.puppeteerIgnoreHTTPSErrors,\n    handleSIGINT: false\n  });\n\n  // \n  const fetchPage = async pageUrl => {\n    const route = pageUrl.replace(basePath, \"\");\n  \n    let skipExistingFile = false;\n    const routePath = route.replace(/\\//g, path.sep);\n    const { ext } = path.parse(routePath);\n\n    if (ext !== \".html\" && ext !== \"\") {\n      const filePath = path.join(sourceDir, routePath);\n      console.log(`🕸 Inspecting File ${filePath}`);\n      skipExistingFile = nativeFs.existsSync(filePath);\n    }\n    else{ \n    }\n  \n    // Crawl the page if it's not already crawled and it's not a third-party URL\n    if (!skipExistingFile) {\n        console.log(`🕸 Pulling file ${route}`);\n      try {\n        const page = await browser.newPage();\n        const client = await page.target().createCDPSession();\n        await client.send('ServiceWorker.disable');\n        await page.setCacheEnabled(options.puppeteer.cache);\n        if (options.viewport) await page.setViewport(options.viewport);\n        if (options.skipThirdPartyRequests) await skipThirdPartyRequests({ page, options, basePath });\n        enableLogging({ page, options, route, onError: (error) => { \n          errorReport.pageErrors.push({ route, error }); \n        }, sourcemapStore, errorReport });\n        if (beforeFetch) await beforeFetch({ page, route });\n        await page.setUserAgent(options.userAgent);\n        const tracker = createTracker(page);\n        try {\n          await page.goto(pageUrl, { waitUntil: \"networkidle2\" });\n        } catch (e) {\n          e.message = tracker.augmentTimeoutError(e.message);\n          throw e;\n        } finally {\n          tracker.dispose();\n        }\n        if (options.waitFor) await page.waitFor(options.waitFor);\n        if (options.crawl) {\n          console.log(`🕸 Crawling Rendered Page: ${route}`);\n          const links = await getLinks({ page }); \n          links.forEach(addToQueue);\n        }\n        if (afterFetch) await afterFetch({ page, route, browser, addToQueue });\n        await page.close();\n        console.log(`✅  crawled ${processed + 1} out of ${enqued} (${route})`);\n      } catch (e) {\n        console.log(`🔥  error at ${route}`, e);\n        errorReport.fetchErrors.push({ route, error: e.message });\n      }\n    } \n    else{\n        console.log(`DID NOT CRAWL ${route}`);\n      }\n    processed++;\n    if (enqued === processed) {\n      streamClosed = true;\n    }\n    return pageUrl;\n  };\n\n  if (options.include) {\n    options.include.map(x => addToQueue(`${basePath}${x}`));\n  }\n\n  while (queue.length > 0) {\n    await Promise.all(\n      queue.splice(0, options.concurrency).map(fetchPage)\n    );\n  }\n\n  await browser.close();\n  \n  // Print error report\n  console.log('\\n📊 CRAWLING COMPLETE - ERROR REPORT:');\n  console.log('=====================================');\n  \n  const totalErrors = errorReport.pageErrors.length + errorReport.consoleErrors.length + \n                     errorReport.httpErrors.length + errorReport.fetchErrors.length;\n  \n  if (totalErrors === 0) {\n    console.log('✅ No errors detected during crawling!');\n  } else {\n    console.log(`❌ Total errors found: ${totalErrors}\\n`);\n    \n    if (errorReport.fetchErrors.length > 0) {\n      console.log(`🔥 Fetch Errors (${errorReport.fetchErrors.length}):`);\n      errorReport.fetchErrors.forEach(({ route, error }) => {\n        console.log(`  - ${route}: ${error}`);\n      });\n      console.log('');\n    }\n    \n    if (errorReport.pageErrors.length > 0) {\n      console.log(`🔥 Page Errors (${errorReport.pageErrors.length}):`);\n      errorReport.pageErrors.forEach(({ route, error }) => {\n        console.log(`  - ${route}: ${error}`);\n      });\n      console.log('');\n    }\n    \n    if (errorReport.consoleErrors.length > 0) {\n      console.log(`🔥 Console Errors (${errorReport.consoleErrors.length}):`);\n      errorReport.consoleErrors.forEach(({ route, error }) => {\n        console.log(`  - ${route}: ${error}`);\n      });\n      console.log('');\n    }\n    \n    if (errorReport.httpErrors.length > 0) {\n      console.log(`⚠️  HTTP Errors (${errorReport.httpErrors.length}):`);\n      errorReport.httpErrors.forEach(({ route, error }) => {\n        console.log(`  - ${route}: ${error}`);\n      });\n      console.log('');\n    }\n  }\n  \n  onEnd && onEnd();\n};\n\nconst run = async (userOptions, { fs } = { fs: nativeFs }) => {\n  const options = defaults(userOptions);\n  const sourceDir = path.normalize(`${process.cwd()}/${options.source}`);\n  const destinationDir = path.normalize(`${process.cwd()}/${options.destination}`);\n\n  const startServer = options => {\n    const app = express()\n      .use(options.publicPath || '/', serveStatic(sourceDir))\n      .use(fallback(\"200.html\", { root: sourceDir }));\n    const server = require(\"http\").createServer(app);\n    server.listen(options.port);\n    return server;\n  };\n\n  if (!options.skipExistingCheck && fs.existsSync(path.join(sourceDir, \"200.html\"))) {\n    throw new Error(\"Cannot run prerendererest - this will break the build\");\n  }\n\n  fs.createReadStream(path.join(sourceDir, \"index.html\")).pipe(fs.createWriteStream(path.join(sourceDir, \"200.html\")));\n  if (destinationDir !== sourceDir) {\n    mkdirp.sync(destinationDir);\n    fs.createReadStream(path.join(sourceDir, \"index.html\")).pipe(fs.createWriteStream(path.join(destinationDir, \"200.html\")));\n  }\n\n  const server = startServer(options);\n  const basePath = `http://localhost:${options.port}`;\n\n  await crawl({\n    options,\n    basePath,\n    publicPath: options.publicPath || '/',\n    sourceDir,\n    beforeFetch: async ({ page }) => {\n      if (options.skipThirdPartyRequests) {\n        await page.setRequestInterception(true);\n        page.on('request', request => {\n          if (request.url().startsWith(basePath)) {\n            request.continue();\n          } else {\n            request.abort();\n          }\n        });\n      }\n    },\n    afterFetch: async ({ page, route }) => {\n      const content = await page.content();\n      const minifiedContent = minify(content, options.minifyHtml);\n      const routePath = route.replace(options.publicPath || '/', \"\");\n      const filePath = path.join(destinationDir, routePath);\n \n      // Create directories if they do not exist\n      if (!fs.existsSync(path.dirname(filePath))) {\n          fs.mkdirSync(path.dirname(filePath), { recursive: true });\n      }\n      fs.writeFileSync(filePath, minifiedContent);\n    },\n    onEnd: () => {\n      server.close();\n    },\n  });\n};\n\nif (require.main === module) {\n  const args = process.argv.slice(2);\n  const userOptions = {};\n  \n  // Show help if requested\n  if (args.includes('--help') || args.includes('-h')) {\n    console.log(`\nUsage: prerendererest [options]\n\nOptions:\n  --source <path>              Source directory (default: ./docs)\n  --destination <path>         Destination directory (default: same as source)\n  --include <pages>            Comma-separated list of pages to include (default: /index.html)\n  --headless                   Run browser in headless mode\n  --crawl                      Enable automatic crawling (default: true)\n  --no-crawl                   Disable automatic crawling\n  --port <number>              Port for local server (default: 45678)\n  --concurrency <number>       Number of concurrent processes (default: 1)\n  --userAgent <string>         Custom user agent (default: Prerendererest)\n  --viewport <json>            Viewport size as JSON object (default: {\"width\":480,\"height\":850})\n  --skipThirdPartyRequests     Block external requests during rendering\n  --skipExistingCheck          Skip the 200.html existence check\n  --minifyHtml <json>          HTML minification options as JSON\n  --removeScriptTags           Remove script tags from HTML\n  --removeStyleTags            Remove style tags from HTML\n  --asyncScriptTags            Add async attribute to script tags\n  --inlineCss                  Inline CSS styles\n  --preloadImages              Add preload hints for images\n  --puppeteerArgs <args>       Comma-separated Puppeteer arguments\n  -h, --help                   Show this help message\n\nExamples:\n  prerendererest --source ./build --headless\n  prerendererest --include \"/index.html,/about.html\" --source ./build --headless\n  prerendererest --source ./build --destination ./dist --crawl --concurrency 4\n`);\n    process.exit(0);\n  }\n  \n  for (let i = 0; i < args.length; i++) {\n    if (args[i] === '--include' && args[i + 1]) {\n      userOptions.include = args[i + 1].split(',');\n      i++;\n    } else if (args[i] === '--source' && args[i + 1]) {\n      userOptions.source = args[i + 1];\n      i++;\n    } else if (args[i] === '--destination' && args[i + 1]) {\n      userOptions.destination = args[i + 1];\n      i++;\n    } else if (args[i] === '--headless') {\n      userOptions.headless = true;\n    } else if (args[i] === '--port' && args[i + 1]) {\n      userOptions.port = parseInt(args[i + 1], 10);\n      i++;\n    } else if (args[i] === '--crawl') {\n      userOptions.crawl = true;\n    } else if (args[i] === '--no-crawl') {\n      userOptions.crawl = false;\n    } else if (args[i] === '--userAgent' && args[i + 1]) {\n      userOptions.userAgent = args[i + 1];\n      i++;\n    } else if (args[i] === '--puppeteerArgs' && args[i + 1]) {\n      userOptions.puppeteerArgs = args[i + 1].split(',');\n      i++;\n    } else if (args[i] === '--puppeteer.cache' && args[i + 1]) {\n      userOptions.puppeteer = userOptions.puppeteer || {};\n      userOptions.puppeteer.cache = args[i + 1] === 'true';\n      i++;\n    } else if (args[i] === '--minifyHtml' && args[i + 1]) {\n      try {\n        userOptions.minifyHtml = JSON.parse(args[i + 1]);\n      } catch {\n        // ignore parse error\n      }\n      i++;\n    } else if (args[i] === '--viewport' && args[i + 1]) {\n      try {\n        userOptions.viewport = JSON.parse(args[i + 1]);\n      } catch {\n        // ignore parse error\n      }\n      i++;\n    } else if (args[i] === '--skipThirdPartyRequests') {\n      userOptions.skipThirdPartyRequests = true;\n    } else if (args[i] === '--concurrency' && args[i + 1]) {\n      userOptions.concurrency = parseInt(args[i + 1], 10);\n      i++;\n    } else if (args[i] === '--inlineCss') {\n      userOptions.inlineCss = true;\n    } else if (args[i] === '--removeStyleTags') {\n      userOptions.removeStyleTags = true;\n    } else if (args[i] === '--preloadImages') {\n      userOptions.preloadImages = true;\n    } else if (args[i] === '--asyncScriptTags') {\n      userOptions.asyncScriptTags = true;\n    } else if (args[i] === '--removeScriptTags') {\n      userOptions.removeScriptTags = true;\n    } else if (args[i] === '--skipExistingCheck') {\n      userOptions.skipExistingCheck = true;\n    }\n  }\n  \n  run(userOptions).catch(e => {\n    console.error(e);\n    process.exit(1);\n  });\n}\n\nexports.run = run;\nexports.defaultOptions = defaultOptions;\n\n// Helper functions for crawling\nconst skipThirdPartyRequests = async opt => {\n  const { page, options, basePath } = opt;\n  if (!options.skipThirdPartyRequests) return;\n  await page.setRequestInterception(true);\n  page.on(\"request\", request => {\n    if (request.url().startsWith(basePath)) {\n      request.continue();\n    } else {\n      request.abort();\n    }\n  });\n};\n\nconst enableLogging = opt => {\n  const { page, options, route, onError, sourcemapStore, errorReport } = opt;\n  page.on(\"console\", msg => {\n    const text = msg.text();\n    if (text === \"JSHandle@object\") {\n      Promise.all(msg.args().map(objectToJson)).then(args =>\n        console.log(`💬  console.log at ${route}:`, ...args)\n      );\n    } else if (text === \"JSHandle@error\") {\n      Promise.all(msg.args().map(errorToString)).then(args => {\n        console.log(`💬  console.log at ${route}:`, ...args);\n        errorReport.consoleErrors.push({ route, error: args.join(' ') });\n      });\n    } else {\n      console.log(`️️️💬  console.log at ${route}:`, text);\n    }\n  });\n  page.on(\"error\", msg => {\n    console.log(`🔥  error at ${route}:`, msg);\n    errorReport.pageErrors.push({ route, error: msg.message });\n    onError && onError(msg.message);\n  });\n  page.on(\"pageerror\", e => {\n    if (options.sourceMaps) {\n      mapStackTrace(e.stack || e.message, {\n        isChromeOrEdge: true,\n        store: sourcemapStore || {}\n      })\n        .then(result => {\n          const stackRows = result.split(\"\\n\");\n          const puppeteerLine =\n            stackRows.findIndex(x => x.includes(\"puppeteer\")) ||\n            stackRows.length - 1;\n\n          const errorMsg = `${(e.stack || e.message).split(\"\\n\")[0] + \"\\n\"}${stackRows.slice(0, puppeteerLine).join(\"\\n\")}`;\n          console.log(`🔥  pageerror at ${route}: ${errorMsg}`);\n          errorReport.pageErrors.push({ route, error: errorMsg });\n        })\n        .catch(e2 => {\n          console.log(`🔥  pageerror at ${route}:`, e);\n          console.log(`️️️⚠️  warning at ${route} (error in source maps):`, e2.message);\n          errorReport.pageErrors.push({ route, error: e.message });\n        });\n    } else {\n      console.log(`🔥  pageerror at ${route}:`, e);\n      errorReport.pageErrors.push({ route, error: e.message });\n    }\n    onError && onError(e.message);\n  });\n  page.on(\"response\", response => {\n    if (response.status() >= 400) {\n      let responseRoute = \"\";\n      try {\n        responseRoute = response._request\n          .headers()\n          .referer.replace(`http://localhost:${options.port}`, \"\");\n      } catch (e) {}\n      const errorMsg = `got ${response.status()} HTTP code for ${response.url()}`;\n      console.log(`️️️⚠️  warning at ${responseRoute}: ${errorMsg}`);\n      errorReport.httpErrors.push({ route: responseRoute, error: errorMsg });\n    }\n  });\n};\n\nconst getLinks = async opt => {\n  const { page } = opt;\n  const anchors = await page.evaluate(() =>\n    Array.from(document.querySelectorAll(\"a\")).map(anchor => {\n      if (anchor.href.baseVal) {\n        const a = document.createElement(\"a\");\n        a.href = anchor.href.baseVal;\n        return a.href;\n      }\n      return anchor.href;\n    })\n  );\n\n  const iframes = await page.evaluate(() =>\n    Array.from(document.querySelectorAll(\"iframe\")).map(iframe => iframe.src)\n  );\n  return anchors.concat(iframes);\n};\n\n\nconst createTracker = (page) => {\n  let requestCount = 0;\n  let successCount = 0;\n  let failureCount = 0;\n  const pendingRequests = new Set();\n\n  const updateStatus = (request) => {\n    if (request._failureText) { failureCount += 1; } \n    else { successCount += 1; }\n    pendingRequests.delete(request);\n  };\n\n  const onRequest = (request) => {\n    requestCount += 1;\n    pendingRequests.add(request);\n  };\n\n  const onRequestFinished = (request) => updateStatus(request);\n  const onRequestFailed = (request) => updateStatus(request);\n\n  page.on('request', onRequest);\n  page.on('requestfinished', onRequestFinished);\n  page.on('requestfailed', onRequestFailed);\n\n  const dispose = () => {\n    page.off('request', onRequest);\n    page.off('requestfinished', onRequestFinished);\n    page.off('requestfailed', onRequestFailed);\n  };\n\n  const augmentTimeoutError = (error) => {\n    return `${error.message}\\nPending requests: ${pendingRequests.size}\\nSuccess requests: ${successCount}\\nFailure requests: ${failureCount}\\nRequest count: ${requestCount}`;\n  };\n\n  return {\n    dispose,\n    augmentTimeoutError,\n  };\n};\n\nconst objectToJson = async jsHandle => {\n  try {\n    return await jsHandle.jsonValue();\n  } catch (e) {\n    // If jsonValue fails, try to get a string representation\n    try {\n      return await jsHandle.evaluate(obj => {\n        if (obj === null) return 'null';\n        if (obj === undefined) return 'undefined';\n        if (typeof obj === 'function') return obj.toString();\n        if (typeof obj === 'object') {\n          try {\n            return JSON.stringify(obj, null, 2);\n          } catch {\n            return Object.prototype.toString.call(obj);\n          }\n        }\n        return String(obj);\n      });\n    } catch {\n      return jsHandle.toString();\n    }\n  }\n};\nconst errorToString = async jsHandle => {\n    try {\n      return await jsHandle.evaluate(error => error.toString());\n    } catch (e) {\n      return jsHandle.toString();\n    }\n  };\n"]}