mcp-scraper 0.92.1 → 0.93.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 (47) hide show
  1. package/CHANGELOG.md +45 -26
  2. package/README.md +4 -4
  3. package/THIRD_PARTY_NOTICES.html +203 -0
  4. package/dist/bin/api-server.js +1 -1
  5. package/dist/bin/mcp-scraper-cli.js +1 -1
  6. package/dist/bin/mcp-scraper-core.js +1 -1
  7. package/dist/bin/mcp-scraper-install.js +1 -1
  8. package/dist/bin/mcp-stdio-server.js +1 -1
  9. package/dist/bin/paa-harvest.js +1 -1
  10. package/dist/chunk-2SP57VCG.js +15 -15
  11. package/dist/{chunk-QHHOKLQY.js → chunk-5JKBFNYF.js} +1 -1
  12. package/dist/{chunk-ZJZMDWDI.js → chunk-5QYW4CSJ.js} +5 -5
  13. package/dist/{chunk-YXUPFECS.js → chunk-AFFMCO7R.js} +2 -2
  14. package/dist/chunk-AYQSKD7D.js +1 -0
  15. package/dist/chunk-DT2FYN6N.js +1 -0
  16. package/dist/{chunk-TCLSPE3P.js → chunk-IJF4VXJ7.js} +1 -1
  17. package/dist/chunk-KPQM4UDJ.js +6 -0
  18. package/dist/chunk-M5QHXNFZ.js +3 -3
  19. package/dist/{chunk-ZMNUI5LB.js → chunk-M5VZVMPC.js} +8 -8
  20. package/dist/{chunk-T2IJVEHG.js → chunk-NLKA6SHC.js} +1 -1
  21. package/dist/{chunk-QXAXPIHM.js → chunk-OD2WLHEN.js} +243 -240
  22. package/dist/chunk-ORB4RHCK.js +4 -4
  23. package/dist/chunk-SH5KB4P7.js +1 -0
  24. package/dist/chunk-UN6FVDJQ.js +1 -0
  25. package/dist/{chunk-JHMI6HEO.js → chunk-W2T4NTCE.js} +1 -1
  26. package/dist/chunk-WJ4XFLS4.js +15 -15
  27. package/dist/{chunk-GPZ7ITF6.js → chunk-X6RD3Y4W.js} +1 -1
  28. package/dist/chunk-Y6MKMSOC.js +1 -0
  29. package/dist/{extract-bundle-5QTPVIWO.js → extract-bundle-C3N6E6V7.js} +1 -1
  30. package/dist/{gmail-service-EOC7KJSK.js → gmail-service-6V5MFBYH.js} +1 -1
  31. package/dist/index.cjs +57 -57
  32. package/dist/index.d.cts +162 -121
  33. package/dist/index.d.ts +162 -121
  34. package/dist/index.js +6 -6
  35. package/dist/{server-NAQTBNPX.js → server-KWGXYWYO.js} +71 -71
  36. package/dist/{site-extract-repository-U4G25TR2.js → site-extract-repository-2LFDP6FZ.js} +1 -1
  37. package/dist/{stripe-event-worker-KW3DR6GB.js → stripe-event-worker-IJXA6T37.js} +1 -1
  38. package/dist/worker-ASXALAY7.js +1 -0
  39. package/package.json +17 -136
  40. package/dist/chunk-2BN2TB3U.js +0 -1
  41. package/dist/chunk-2TZBO52D.js +0 -1
  42. package/dist/chunk-4FROKQJN.js +0 -1
  43. package/dist/chunk-GCLSGYYE.js +0 -1
  44. package/dist/chunk-K6MN7UED.js +0 -2
  45. package/dist/chunk-RECKUOEF.js +0 -1
  46. package/dist/chunk-RSPA4IWH.js +0 -1
  47. package/dist/worker-MSLXSR4M.js +0 -1
@@ -43,13 +43,13 @@ import{t as s}from"./chunk-WJ4XFLS4.js";import{createHash as v,randomUUID as m}f
43
43
  SET provider_source_key = NULL, error_message = NULL, updated_at = datetime('now')
44
44
  WHERE finalized_at < datetime('now', ?)
45
45
  AND (provider_source_key IS NOT NULL OR error_message IS NOT NULL)`,args:[r]}),t.execute({sql:`UPDATE harvest_attempts
46
- SET provider_session_id = NULL, kernel_session_id = NULL, error = NULL,
47
- kernel_delete_error = NULL, browser_close_error = NULL,
46
+ SET provider_session_id = NULL, \u006b\u0065\u0072\u006e\u0065\u006c_session_id = NULL, error = NULL,
47
+ \u006b\u0065\u0072\u006e\u0065\u006c_delete_error = NULL, browser_close_error = NULL,
48
48
  provider_error_message = NULL, provider_detail_json = NULL,
49
49
  provider_disconnect_message = NULL, debug_json = NULL
50
50
  WHERE completed_at < datetime('now', ?)
51
- AND (provider_session_id IS NOT NULL OR kernel_session_id IS NOT NULL OR error IS NOT NULL
52
- OR kernel_delete_error IS NOT NULL OR browser_close_error IS NOT NULL
51
+ AND (provider_session_id IS NOT NULL OR \u006b\u0065\u0072\u006e\u0065\u006c_session_id IS NOT NULL OR error IS NOT NULL
52
+ OR \u006b\u0065\u0072\u006e\u0065\u006c_delete_error IS NOT NULL OR browser_close_error IS NOT NULL
53
53
  OR provider_error_message IS NOT NULL OR provider_detail_json IS NOT NULL
54
54
  OR provider_disconnect_message IS NOT NULL OR debug_json IS NOT NULL)`,args:[r]})]);return{operationAttempts:i.rowsAffected,providerReceipts:n.rowsAffected,legacyHarvestAttempts:o.rowsAffected}}async function D(e){let t={billing_authorizations:{column:"id"},billing_events:{column:"id"},billing_debits:{column:"idempotency_key"},billing_credits:{column:"idempotency_key"},ledger:{column:"id"}}[e.billingTable],i=a(e.billingKey,"billingKey"),n=await s().execute({sql:`SELECT b.user_id AS billing_user_id, r.user_id AS run_user_id
55
55
  FROM operation_runs r
@@ -0,0 +1 @@
1
+ function R(e,_=!1,n="light",r=1){let E=_&&n==="full"?r>=2?75e3:45e3:_?4e4:4e5,t=Math.min(E+5e3,795e3);return{serverMs:E,clientMs:t}}function s(){return(process.env.BROWSER_SERVICE_API_KEY??process.env.\u004b\u0045\u0052\u004e\u0045\u004c_API_KEY)?.trim()||void 0}function S(){return(process.env.BROWSER_AGENT_PROFILE_NAME??process.env.BROWSER_SERVICE_PROFILE_NAME??process.env.\u004b\u0045\u0052\u004e\u0045\u004c_BROWSER_PROFILE_NAME??process.env.\u004b\u0045\u0052\u004e\u0045\u004c_PROFILE_NAME)?.trim()||void 0}function u(){let e=(process.env.BROWSER_AGENT_PROFILE_SAVE_CHANGES??process.env.BROWSER_SERVICE_PROFILE_SAVE_CHANGES??process.env.\u004b\u0045\u0052\u004e\u0045\u004c_BROWSER_PROFILE_SAVE_CHANGES??process.env.\u004b\u0045\u0052\u004e\u0045\u004c_PROFILE_SAVE_CHANGES)?.trim().toLowerCase();if(e){if(["1","true","yes","on"].includes(e))return!0;if(["0","false","no","off"].includes(e))return!1}}export{R as a,s as b,S as c,u as d};
@@ -0,0 +1 @@
1
+ var m={schemaVersion:1,ratePolicy:{version:"serp-page-2026-09-24",effectiveDate:"2026-09-24T00:00:00.000Z"},costEvidence:{id:"serp-page-rate-basis-2026-09",status:"owner-approved"},operationCosts:{serp:{credits:20,unit:"per page (ordinary search)",label:"SERP search",notes:"search_serp light mode returns one page of organic positions, URLs, titles, and descriptions by default. Full mode returns available same-page SERP features. Either mode requests two pages only when pages:2 is explicit. Light searches cost 20 credits per delivered page, or 35 credits per delivered page if the backup supplies the result. One-page full searches cost 35 credits. Explicit two-page full searches return organic results only for 40 credits, with rich features marked unsupported. If only page 1 is delivered, the search is marked partial and billed for one delivered page. A temporary 35-credit-per-requested-page hold is settled to the delivered rate. Location, language, device, recency, and optional module fields do not change ordinary searches. Saved browser identity and capture_serp_snapshot searches retain their 60-credit base price; optional page snapshots add 1 credit per attempted URL."},paa:{credits:10,unit:"per question (+400 credit base)",label:"PAA harvest",notes:"Returns original-query PAA questions with answers and sources plus organic results and Google entity IDs. Optional same-page SERP modules are flag-controlled. Billed 400 credit base + 10 per question actually returned (unused estimate refunded)."},page_scrape:{credits:1,unit:"per page",label:"Page crawl / extract",notes:"Applies to both single-URL extraction and per-page site crawls."},listing_create:{credits:10,unit:"per new listing",label:"Directory or wiki listing creation",notes:"Fixed total price for a new Local Sourcebook directory listing or Transparent Commons wiki entity. Sourcebook acquisition is included."},listing_edit:{credits:2,unit:"per existing listing revision",label:"Directory or wiki listing edit",notes:"Fixed total price for refreshing an existing Local Sourcebook listing or revising an existing Transparent Commons entity."},url_map:{credits:5,unit:"per mapping operation",label:"Site URL mapping",notes:"Flat rate for the full /map-urls call regardless of URL count discovered."},yt_channel:{credits:2,unit:"per call",label:"YouTube search / channel harvest"},yt_transcription:{credits:200,unit:"base + 2/min of video",label:"YouTube transcription",notes:"Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},fb_ad:{credits:7,unit:"per call",label:"Facebook search / ad lookup"},maps_search:{credits:5,unit:"per search",label:"Maps business search",notes:"Returns up to 50 Google Maps business/profile candidates. Use maps_place_intel to hydrate selected businesses."},maps_place:{credits:60,unit:"per business",label:"Maps business lookup",notes:"Base lookup. Reviews billed separately per card at maps_review rate."},maps_review:{credits:1,unit:"per review card",label:"Maps review",notes:"Charged after extraction when includeReviews is true."},fb_search:{credits:8,unit:"per search",label:"Facebook ad library search",notes:"Browser automation to search Facebook Ads Library by keyword."},google_ads_search:{credits:6,unit:"per search",label:"Google Ads Transparency search",notes:"Browser automation to find advertisers in Google Ads Transparency Center by domain or name."},google_ads_intel:{credits:2,unit:"per call",label:"Google Ads Transparency advertiser intel",notes:"Lists and hydrates an advertiser's creatives with image URLs and video references."},google_ads_transcribe:{credits:200,unit:"base + 2/min of video",label:"Google ad video transcription",notes:"Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},fb_transcribe:{credits:200,unit:"base + 2/min of video",label:"Facebook video / ad transcription",notes:"Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},fb_reels_inventory:{credits:4,unit:"per profile scan",label:"Facebook Reel URL inventory",notes:"Collects canonical Reel URLs from a Facebook profile. Logged-out scans are capped at 60 URLs; saved browser profiles can request larger inventories."},tiktok_transcribe:{credits:200,unit:"base + 2/min of video",label:"TikTok video transcription",notes:"Transcribes a public TikTok video from its playback media. Flat 200-credit base plus 2 credits per minute, reconciled after transcription."},instagram_profile:{credits:4,unit:"per profile scan",label:"Instagram profile content discovery",notes:"Browser extraction of public Instagram profile grid links. Complete history may require a logged-in profile."},instagram_media:{credits:4,unit:"per post or reel",label:"Instagram media download",notes:"Extracts post text, image URLs, and reel audio/video tracks, with local downloads when the server can write files."},instagram_transcribe:{credits:200,unit:"base + 2/min of video",label:"Instagram media transcription",notes:"Whisper transcription of selected Instagram audio/video media. Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},browser_minute:{credits:120,unit:"per minute of use",label:"Interactive browser session",notes:"Metered per minute of use for the whole time the browser session is open. Close the session to stop the meter; abandoned sessions are auto-closed after a short idle window."},reddit_thread:{credits:30,unit:"per thread",label:"Reddit thread base lookup",notes:"Base lookup for the post itself. Comments billed separately per comment at reddit_comment rate. Refunded if the thread cannot be retrieved."},reddit_comment:{credits:2,unit:"per comment",label:"Reddit comment",notes:"Charged per comment actually extracted, billed down automatically if the balance runs out mid-thread."},video_analysis:{credits:6667,unit:"per 120 frames (max 480)",label:"Video breakdown (frame-by-frame + transcript)",notes:"Full multi-lens video breakdown: samples frames across a video (up to 30 minutes), analyzes each with vision AI, transcribes the audio, then produces summary, pacing/energy, words-per-minute, topic outline, key points, hook analysis, visual style, and a how-to-replicate recipe with a quality-control pass. $1 per 120 frames requested (max 480 = $4); billed down automatically if the video cannot use the requested frames, and refunded fully if the run fails."},trustpilot_reviews:{credits:5,unit:"per call",label:"Trustpilot review harvest",notes:"Base lookup. Reviews billed separately per card at trustpilot_review rate. Refunded if no reviews are found."},trustpilot_review:{credits:1,unit:"per review card",label:"Trustpilot review card",notes:"Charged per review actually extracted, billed down automatically if the balance runs out mid-page."},g2_reviews:{credits:5,unit:"per call",label:"G2 review harvest",notes:"Base lookup. Reviews billed separately per card at g2_review rate. Refunded if no reviews are found."},g2_review:{credits:2,unit:"per review card",label:"G2 review card",notes:"Charged per review actually extracted (each card carries up to 3 Q&A sections), billed down automatically if the balance runs out mid-page."},diff_page:{credits:1,unit:"per check",label:"Page change check",notes:"Same cost as a single page extract \u2014 one scrape is performed per check, then compared against your last stored snapshot for that URL."}},publicTiers:[{tier:"starter",label:"Starter",monthlyUsd:12,credits:8e4,concurrency:3},{tier:"growth",label:"Growth",monthlyUsd:40,credits:266667,concurrency:10},{tier:"scale",label:"Scale",monthlyUsd:100,credits:8e5,concurrency:20}],credits:{mcPerCredit:100,freeSignupCredits:0},inventory:{totalTools:362,scraperTools:236,memoryTools:126},concurrencyPack:{ratePolicyVersion:"2026-08-14.concurrency-pack-v1",monthlyUsd:5,currency:"usd",interval:"month",billingUnit:"pack",slotsPerPack:2},scaleCreditPack:{ratePolicyVersion:"2026-09-21.scale-credit-pack-v1",eligibleTier:"scale",incrementUsd:10,creditsPerIncrement:8e4,maxQuantity:100,currency:"usd",expiryMonths:3},addons:{memory:{monthlyUsd:19,quotaGb:5,freeQuotaGb:.01},scheduling:{billingMode:"credits",entitlement:"paid_plan_included",separateSubscriptionRequired:!1,chargeEvent:"started_occurrence",runBaseCredits:75,runBaseMc:7500,llmCostMultiplier:1.5,llmCostMultiplierBps:15e3,modes:{connection_sync:{runBaseCredits:75,modelCostBilling:"none",modelCostMultiplier:0},agent:{runBaseCredits:75,modelCostBilling:"actual_reported_cost",modelCostMultiplier:1.5,modelCostMultiplierBps:15e3}}},connectedAccounts:{schemaVersion:2,ratePolicyVersion:"2026-08-03.connected-usage-v3",effectiveAt:"2026-08-03T00:00:00.000Z",entitlement:"paid_plan_add_on",connection:{billingMode:"flat_recurring_credits",amountCredits:15e3,interval:"month",unit:"active_connection",proration:"none"},usage:{billingMode:"credits",settlementMode:"authoritative_receipt",rounding:"aggregate_then_ceil_to_mc",functionRun:{credits:2,mc:200,unit:"per_function_run"},proxyRequest:{credits:2,mc:200,unit:"per_proxy_request"},compute:{creditsPerSecond:5,mcPerSecond:500,sourceUnit:"millisecond",unit:"per_compute_second",formula:"ceil(computeMilliseconds * mcPerSecond / 1000)"}}}}};var t={serp:6e3,serp_headless:6e3,serp_headful:6e3,paa:1e3,paa_base:4e4,page_scrape:100,url_map:500,yt_channel:200,yt_transcription:200,fb_ad:700,maps_search:500,maps_place:6e3,maps_review:100,fb_search:800,fb_search_result:100,fb_page_intel:700,fb_page_intel_ad:50,fb_reels_inventory:400,fb_transcribe:33300,tiktok_transcribe:33300,google_ads_search:600,google_ads_intel:200,google_ads_transcribe:33300,instagram_profile:400,instagram_media:400,instagram_transcribe:33300,browser_minute:12e3,reddit_thread:3e3,reddit_comment:200,video_analysis:666700,trustpilot_reviews:500,trustpilot_review:100,g2_reviews:500,g2_review:200,diff_page:100,listing_create:1e3,listing_edit:200};function ce(e){return e===!0?t.serp_headless:t.serp_headful}var q=t.browser_minute/6e4;function le(e){return Math.round(e*q)}var _e=1e3,a=100,d=20,g=35;function de(e,r){return e*a*(r==="apify"?d:g)}var pe=d,V=t.serp_headful/a,ue=t.paa_base/a,me=t.paa/a,ge=t.page_scrape/a,H={billingMode:"credits",chargeEvent:"accepted_write",validationCredits:0,create:{credits:t.listing_create/a,mc:t.listing_create},edit:{credits:t.listing_edit/a,mc:t.listing_edit},surfaces:["local_sourcebook","transparent_commons"],sourcebookAcquisitionIncluded:!0},$=2e6,K=3,v=1e4,y=1e9,W=75,be=W*a,Q=15e3,fe=Q/v,Ee=5e3,Z="2026-08-03.connected-usage-v3",S=15e3,Re=S*a,A=2,N=2,I=5,w=A*a,k=N*a,O=I*a,he={schemaVersion:2,ratePolicyVersion:Z,effectiveAt:"2026-08-03T00:00:00.000Z",provider:"nango",entitlement:"paid_plan_add_on",connection:{billingMode:"flat_recurring_credits",amountCredits:S,interval:"month",unit:"active_connection",proration:"none"},usage:{billingMode:"credits",settlementMode:"authoritative_receipt",rounding:"aggregate_then_ceil_to_mc",functionRun:{credits:A,mc:w,unit:"per_function_run"},proxyRequest:{credits:N,mc:k,unit:"per_proxy_request"},compute:{creditsPerSecond:I,mcPerSecond:O,sourceUnit:"millisecond",unit:"per_compute_second",formula:"ceil(computeMilliseconds * mcPerSecond / 1000)"}}};function b(e,r){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${r} must be a non-negative safe integer`);return BigInt(e)}function _(e){if(e>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("connected usage charge exceeds the safe integer range");return Number(e)}function Ce(e){let r=b(e.functionRuns,"functionRuns"),o=b(e.proxyRequests,"proxyRequests"),n=b(e.computeMilliseconds,"computeMilliseconds"),s=r*BigInt(w),c=o*BigInt(k),l=n*BigInt(O),u=l===0n?0n:(l+999n)/1000n,C=s+c+u;return{functionRunMc:_(s),proxyRequestMc:_(c),computeMc:_(u),amountMc:_(C),credits:_(C)/a}}function ye(e,r){if(!Number.isFinite(e)||e<0)throw new Error("costUsd must be a finite non-negative number");if(!Number.isInteger(r)||r<0)throw new Error("markupBps must be a non-negative integer");let n=BigInt(Math.round(e*y))*BigInt(r)*BigInt($),s=BigInt(y)*BigInt(v)*BigInt(K),c=n===0n?0n:(n+s-1n)/s;if(c>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("calculated mc exceeds the safe integer range");return Number(c)}var X=[{key:"serp",label:"SERP search",aliases:["search_serp","serp","google search","organic results"],credits:d,unit:"per page (ordinary search)",notes:`search_serp light mode returns one page of organic positions, URLs, titles, and descriptions by default. Full mode returns available same-page SERP features. Either mode requests two pages only when pages:2 is explicit. Light searches cost ${d} credits per delivered page, or ${g} credits per delivered page if the backup supplies the result. One-page full searches cost ${g} credits. Explicit two-page full searches return organic results only for ${d*2} credits, with rich features marked unsupported. If only page 1 is delivered, the search is marked partial and billed for one delivered page. A temporary ${g}-credit-per-requested-page hold is settled to the delivered rate. Location, language, device, recency, and optional module fields do not change ordinary searches. Saved browser identity and capture_serp_snapshot searches retain their ${V}-credit base price; optional page snapshots add ${i(t.page_scrape)} credit per attempted URL.`},{key:"paa",label:"PAA harvest",aliases:["harvest_paa","paa","people also ask","questions"],credits:i(t.paa),unit:`per question (+${i(t.paa_base)} credit base)`,notes:`Returns original-query PAA questions with answers and sources plus organic results and Google entity IDs. Optional same-page SERP modules are flag-controlled. Billed ${i(t.paa_base)} credit base + ${i(t.paa)} per question actually returned (unused estimate refunded).`},{key:"page_scrape",label:"Page crawl / extract",aliases:["extract_url","extract_site","page scrape","url scrape","single page","site crawl"],credits:i(t.page_scrape),unit:"per page",notes:"Applies to both single-URL extraction and per-page site crawls."},{key:"listing_create",label:"Directory or wiki listing creation",aliases:["local-sourcebook-capture","commons_submit_entity","directory listing","wiki listing"],credits:i(t.listing_create),unit:"per new listing",notes:"Fixed total price for a new Local Sourcebook directory listing or Transparent Commons wiki entity. Sourcebook acquisition is included."},{key:"listing_edit",label:"Directory or wiki listing edit",aliases:["local_sourcebook_refresh","commons_submit_entity","listing refresh","wiki edit"],credits:i(t.listing_edit),unit:"per existing listing revision",notes:"Fixed total price for refreshing an existing Local Sourcebook listing or revising an existing Transparent Commons entity."},{key:"url_map",label:"Site URL mapping",aliases:["map_site_urls","url map","site map","crawl urls"],credits:i(t.url_map),unit:"per mapping operation",notes:"Flat rate for the full /map-urls call regardless of URL count discovered."},{key:"yt_channel",label:"YouTube search / channel harvest",aliases:["youtube_harvest","youtube search","youtube channel","yt_channel"],credits:i(t.yt_channel),unit:"per call"},{key:"yt_transcription",label:"YouTube transcription",aliases:["youtube_transcribe","youtube transcript","transcription","yt_transcription"],credits:i(2e4),unit:"base + 2/min of video",notes:"Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},{key:"fb_ad",label:"Facebook search / ad lookup",aliases:["facebook_page_intel","facebook_ad_search","facebook_ad","facebook ads","fb ads"],credits:i(t.fb_ad),unit:"per call"},{key:"maps_search",label:"Maps business search",aliases:["maps_search","google maps search","gmb search","gbp search","business profiles"],credits:i(t.maps_search),unit:"per search",notes:"Returns up to 50 Google Maps business/profile candidates. Use maps_place_intel to hydrate selected businesses."},{key:"maps_place",label:"Maps business lookup",aliases:["maps_place_intel","google maps","maps place","place intel"],credits:i(t.maps_place),unit:"per business",notes:"Base lookup. Reviews billed separately per card at maps_review rate."},{key:"maps_review",label:"Maps review",aliases:["maps_reviews","google reviews","review cards","reviews"],credits:i(t.maps_review),unit:"per review card",notes:"Charged after extraction when includeReviews is true."},{key:"fb_search",label:"Facebook ad library search",aliases:["facebook_search","fb_search","fb ad search"],credits:i(t.fb_search),unit:"per search",notes:"Browser automation to search Facebook Ads Library by keyword."},{key:"google_ads_search",label:"Google Ads Transparency search",aliases:["google_ads_search","google ads search","ads transparency search"],credits:i(t.google_ads_search),unit:"per search",notes:"Browser automation to find advertisers in Google Ads Transparency Center by domain or name."},{key:"google_ads_intel",label:"Google Ads Transparency advertiser intel",aliases:["google_ads_page_intel","google ads intel","ads transparency intel"],credits:i(t.google_ads_intel),unit:"per call",notes:"Lists and hydrates an advertiser's creatives with image URLs and video references."},{key:"google_ads_transcribe",label:"Google ad video transcription",aliases:["google_ads_transcribe","google ad transcript"],credits:i(2e4),unit:"base + 2/min of video",notes:"Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},{key:"fb_transcribe",label:"Facebook video / ad transcription",aliases:["facebook_transcribe","facebook_video_transcribe","fb_transcribe","fb ad transcript"],credits:i(2e4),unit:"base + 2/min of video",notes:"Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},{key:"fb_reels_inventory",label:"Facebook Reel URL inventory",aliases:["facebook_reels_inventory","facebook reels","facebook reel urls","facebook profile reels"],credits:i(t.fb_reels_inventory),unit:"per profile scan",notes:"Collects canonical Reel URLs from a Facebook profile. Logged-out scans are capped at 60 URLs; saved browser profiles can request larger inventories."},{key:"tiktok_transcribe",label:"TikTok video transcription",aliases:["tiktok_video_transcribe","tiktok transcript"],credits:i(2e4),unit:"base + 2/min of video",notes:"Transcribes a public TikTok video from its playback media. Flat 200-credit base plus 2 credits per minute, reconciled after transcription."},{key:"instagram_profile",label:"Instagram profile content discovery",aliases:["instagram_profile_content","instagram profile","instagram content list","ig profile"],credits:i(t.instagram_profile),unit:"per profile scan",notes:"Browser extraction of public Instagram profile grid links. Complete history may require a logged-in profile."},{key:"instagram_media",label:"Instagram media download",aliases:["instagram_media_download","instagram reel download","instagram post download","ig media"],credits:i(t.instagram_media),unit:"per post or reel",notes:"Extracts post text, image URLs, and reel audio/video tracks, with local downloads when the server can write files."},{key:"instagram_transcribe",label:"Instagram media transcription",aliases:["instagram transcript","instagram reel transcript","ig transcribe"],credits:i(2e4),unit:"base + 2/min of video",notes:"Whisper transcription of selected Instagram audio/video media. Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},{key:"browser_minute",label:"Interactive browser session",aliases:["browser_open","browser agent","browser_agent","live browser","browse","browser control","interactive browser"],credits:i(t.browser_minute),unit:"per minute of use",notes:"Metered per minute of use for the whole time the browser session is open. Close the session to stop the meter; abandoned sessions are auto-closed after a short idle window."},{key:"reddit_thread",label:"Reddit thread base lookup",aliases:["reddit","reddit_thread","reddit comments","subreddit","reddit post"],credits:i(t.reddit_thread),unit:"per thread",notes:"Base lookup for the post itself. Comments billed separately per comment at reddit_comment rate. Refunded if the thread cannot be retrieved."},{key:"reddit_comment",label:"Reddit comment",aliases:["reddit_comment","reddit comments"],credits:i(t.reddit_comment),unit:"per comment",notes:"Charged per comment actually extracted, billed down automatically if the balance runs out mid-thread."},{key:"video_analysis",label:"Video breakdown (frame-by-frame + transcript)",aliases:["video_frame_analysis","video breakdown","video analysis","analyze video"],credits:i(t.video_analysis),unit:"per 120 frames (max 480)",notes:"Full multi-lens video breakdown: samples frames across a video (up to 30 minutes), analyzes each with vision AI, transcribes the audio, then produces summary, pacing/energy, words-per-minute, topic outline, key points, hook analysis, visual style, and a how-to-replicate recipe with a quality-control pass. $1 per 120 frames requested (max 480 = $4); billed down automatically if the video cannot use the requested frames, and refunded fully if the run fails."},{key:"trustpilot_reviews",label:"Trustpilot review harvest",aliases:["trustpilot_reviews","trustpilot","trustpilot reviews"],credits:i(t.trustpilot_reviews),unit:"per call",notes:"Base lookup. Reviews billed separately per card at trustpilot_review rate. Refunded if no reviews are found."},{key:"trustpilot_review",label:"Trustpilot review card",aliases:["trustpilot_review","trustpilot card"],credits:i(t.trustpilot_review),unit:"per review card",notes:"Charged per review actually extracted, billed down automatically if the balance runs out mid-page."},{key:"g2_reviews",label:"G2 review harvest",aliases:["g2_reviews","g2","g2 reviews"],credits:i(t.g2_reviews),unit:"per call",notes:"Base lookup. Reviews billed separately per card at g2_review rate. Refunded if no reviews are found."},{key:"g2_review",label:"G2 review card",aliases:["g2_review","g2 card"],credits:i(t.g2_review),unit:"per review card",notes:"Charged per review actually extracted (each card carries up to 3 Q&A sections), billed down automatically if the balance runs out mid-page."},{key:"diff_page",label:"Page change check",aliases:["diff_page","page diff","change detection"],credits:i(t.diff_page),unit:"per check",notes:"Same cost as a single page extract \u2014 one scrape is performed per check, then compared against your last stored snapshot for that URL."}],Te="price_1Ta1NRS8aAcsk3TGwsRnYbix";function M(e){return e.billing_interval??"month"}function x(e){return e.billed_usd??e.monthly_usd}function P(e){return e.credits_mc/a}var p={price_1TmiHRS8aAcsk3TGwmSNfNIa:{tier:"starter",label:"Starter",price_id:"price_1TmiHRS8aAcsk3TGwmSNfNIa",monthly_usd:12,credits_mc:8e6,concurrency:3,intro_coupon:"mcp-starter-1dollar-intro-12"},price_1TrgihS8aAcsk3TG5cglrq4D:{tier:"growth",label:"Growth",price_id:"price_1TrgihS8aAcsk3TG5cglrq4D",monthly_usd:40,credits_mc:26666700,concurrency:10,intro_coupon:null},price_1TrgihS8aAcsk3TG4HnG4gbY:{tier:"scale",label:"Scale",price_id:"price_1TrgihS8aAcsk3TG4HnG4gbY",monthly_usd:100,credits_mc:8e7,concurrency:20,intro_coupon:null},price_1TwqIVS8aAcsk3TG0FE3ddDM:{tier:"sonic",label:"Sonic Annual",price_id:"price_1TwqIVS8aAcsk3TG0FE3ddDM",monthly_usd:25,billed_usd:300,credits_mc:25e7,concurrency:3,intro_coupon:null,billing_interval:"year",credits_never_expire:!0,private_offer:!0},price_1TwqIWS8aAcsk3TGbGbtlLak:{tier:"sonic-memory",label:"Sonic Annual + Memory Pro",price_id:"price_1TwqIWS8aAcsk3TGbGbtlLak",monthly_usd:34.5,billed_usd:414,credits_mc:25e7,concurrency:3,intro_coupon:null,billing_interval:"year",credits_never_expire:!0,includes_memory:!0,private_offer:!0}},E=Object.fromEntries(Object.values(p).map(e=>[e.tier,e])),R={sonic:{slug:"sonic",label:"Sonic annual partner offer",headline:"A full year of MCP Scraper, with Credits that never expire.",tier_keys:["sonic","sonic-memory"]}};function j(e){let r=Object.values(R).find(o=>o.tier_keys.includes(e));return r?`/${r.slug}/claim`:null}function z(e){return e?Object.values(R).find(r=>r.tier_keys.includes(e))??null:null}function ve(e,r){let o=z(e);return o?!o.tier_keys.includes(r):!1}function Se(e){if(!e)return null;let r=E[e];return r?{tier:r.tier,label:r.label,amount_usd:x(r),interval:M(r),monthly_equivalent_usd:r.monthly_usd,credits_per_interval:P(r),concurrency:r.concurrency,credits_never_expire:!!r.credits_never_expire,includes_memory:!!r.includes_memory,private_offer:!!r.private_offer,offer_claim_path:j(r.tier)}:null}function Ae(e){let r=R[e];if(!r)return null;let o=r.tier_keys.map(n=>E[n]).filter(n=>!!n).map(n=>({tier:n.tier,label:n.label,amount_usd:x(n),interval:M(n),monthly_equivalent_usd:n.monthly_usd,credits:P(n),credits_never_expire:!!n.credits_never_expire,includes_memory:!!n.includes_memory,concurrency:n.concurrency}));return o.length?{slug:r.slug,label:r.label,headline:r.headline,options:o}:null}function Ne(){let e=E.starter,r=X.map(({aliases:s,...c})=>({...c,...c.notes?{notes:c.notes.replace(/ via fal\.ai/g,"")}:{}})),o=Object.fromEntries(r.map(s=>[s.key,{credits:s.credits,unit:s.unit,label:s.label,...s.notes?{notes:s.notes}:{}}])),n=Object.values(p).filter(s=>!s.private_offer).map(s=>({tier:s.tier,label:s.label,monthlyUsd:s.monthly_usd,credits:s.credits_mc/a,concurrency:s.concurrency}));return{...m,operationCosts:o,publicTiers:n,concurrencyPack:{ratePolicyVersion:B,monthlyUsd:L,currency:U,interval:D,billingUnit:"pack",slotsPerPack:f},scaleCreditPack:{ratePolicyVersion:ee,eligibleTier:"scale",incrementUsd:F,creditsPerIncrement:h,maxQuantity:re,currency:"usd",expiryMonths:3},creditsPerDollarStarter:Math.round(i(e.credits_mc)/e.monthly_usd),costs:r,scheduling:m.addons.scheduling,connectedAccounts:m.addons.connectedAccounts,listingWrites:H}}var L=5,U="usd",D="month",f=2,B="2026-08-14.concurrency-pack-v1",J="$5/month for 2 extra browsers",Ie="MCP Scraper browser concurrency pack \u2014 each $5 monthly pack adds 2 browsers.",we="Billed monthly until canceled. A receipt is emailed after each successful payment.",T="npx -y -p mcp-scraper@latest mcp-scraper-cli billing concurrency checkout",ee="2026-09-21.scale-credit-pack-v1",F=10,h=8e4,ke=h*a,re=100;function Oe(){let e=process.env.CONCURRENCY_BILLING_URL??"https://mcpscraper.dev/billing";return{product:"Extra browser concurrency pack",rate_policy_version:B,price_label:J,unit_amount_usd:L,currency:U,interval:D,billing_unit:"pack",pack_quantity:1,slots_per_pack:f,extra_slots:f,billing_url:e,terminal_command:T,terminal_command_with_api_key_env:`MCP_SCRAPER_API_KEY=sk_live_your_key ${T}`}}function i(e){return e/a}var te="npx -y -p mcp-scraper@latest mcp-scraper-cli billing subscribe";function ie(){return Object.values(p).filter(e=>!e.private_offer).sort((e,r)=>e.credits_mc-r.credits_mc)}function Me(e,r){let o=process.env.TOPUP_URL??"https://mcpscraper.dev/billing",n=i(e),s=i(r),c=ie().map(u=>u.tier).join("|"),l=`${te} <${c}>`;return{error:"insufficient_balance",error_code:"insufficient_balance",message:`Insufficient credits. Balance: ${n} credits. This call requires ${s} credits. Credits refresh when your plan renews. Scale customers can buy ${h} Credits per $${F} increment; other customers can move to a larger plan at ${o} (terminal: ${l})`,balance_credits:n,required_credits:s,topup_url:o,upgrade_command:l}}var se=1e7*1,xe={price_1TnMSTS8aAcsk3TGBgiwuvqL:{plan:"pro",label:"Pro",price_id:"price_1TnMSTS8aAcsk3TGBgiwuvqL",interval:"month",monthly_usd:19,quota_bytes:5e9},price_1TnMSTS8aAcsk3TGWBVU2agY:{plan:"pro",label:"Pro",price_id:"price_1TnMSTS8aAcsk3TGWBVU2agY",interval:"year",monthly_usd:19,quota_bytes:5e9}},Pe={free:se,pro:5e9,team:5e10},ne=3;var Le=19/ne,Ue={TOPUP:"topup",SUBSCRIPTION:"subscription",SIGNUP_GRANT:"signup_grant",MONTHLY_REFRESH:"monthly_free_refresh",PAA:"paa",PAA_REFUND:"paa_refund",SERP:"serp",SERP_REFUND:"serp_refund",REFUND:"refund",TRANSCRIPTION:"transcription",TRANSCRIPTION_HOLD:"transcription_hold",TRANSCRIPTION_REFUND:"transcription_refund",YT_CHANNEL:"yt_channel",FB_AD:"fb_ad",MAPS_SEARCH:"maps_search",DIRECTORY_WORKFLOW_HOLD:"directory_workflow_hold",DIRECTORY_WORKFLOW_REFUND:"directory_workflow_refund",LEAD_LIST_ENRICHMENT_HOLD:"lead_list_enrichment_hold",LEAD_LIST_ENRICHMENT_REFUND:"lead_list_enrichment_refund",MAPS_PLACE:"maps_place",MAPS_REVIEW:"maps_review",MAPS_REVIEW_REFUND:"maps_review_refund",EXTRACT_SITE:"extract_site",EXTRACT_SITE_REFUND:"extract_site_refund",EXTRACT_URL:"page_scrape",URL_MAP:"url_map",EXTRACT_SITE_HOLD:"extract_site_hold",YT_CHANNEL_REFUND:"yt_channel_refund",FB_AD_REFUND:"fb_ad_refund",URL_MAP_REFUND:"url_map_refund",FB_SEARCH:"fb_search",FB_REELS_INVENTORY:"fb_reels_inventory",FB_REELS_INVENTORY_REFUND:"fb_reels_inventory_refund",FB_TRANSCRIBE:"fb_transcribe",TIKTOK_TRANSCRIBE:"tiktok_transcribe",FB_SEARCH_REFUND:"fb_search_refund",FB_SEARCH_RESULT:"fb_search_result",FB_SEARCH_RESULT_REFUND:"fb_search_result_refund",FB_PAGE_INTEL:"fb_page_intel",FB_PAGE_INTEL_REFUND:"fb_page_intel_refund",FB_PAGE_INTEL_AD:"fb_page_intel_ad",FB_PAGE_INTEL_AD_REFUND:"fb_page_intel_ad_refund",FB_TRANSCRIBE_REFUND:"fb_transcribe_refund",TIKTOK_TRANSCRIBE_REFUND:"tiktok_transcribe_refund",GOOGLE_ADS_SEARCH:"google_ads_search",GOOGLE_ADS_SEARCH_REFUND:"google_ads_search_refund",GOOGLE_ADS_INTEL:"google_ads_intel",GOOGLE_ADS_INTEL_REFUND:"google_ads_intel_refund",GOOGLE_ADS_TRANSCRIBE:"google_ads_transcribe",GOOGLE_ADS_TRANSCRIBE_REFUND:"google_ads_transcribe_refund",INSTAGRAM_PROFILE:"instagram_profile",INSTAGRAM_PROFILE_REFUND:"instagram_profile_refund",INSTAGRAM_MEDIA:"instagram_media",INSTAGRAM_MEDIA_REFUND:"instagram_media_refund",INSTAGRAM_TRANSCRIBE:"instagram_transcribe",INSTAGRAM_TRANSCRIBE_REFUND:"instagram_transcribe_refund",BROWSER_SESSION:"browser_session",REDDIT_THREAD:"reddit_thread",REDDIT_THREAD_REFUND:"reddit_thread_refund",REDDIT_COMMENT:"reddit_comment",REDDIT_COMMENT_REFUND:"reddit_comment_refund",VIDEO_ANALYSIS:"video_analysis",VIDEO_ANALYSIS_REFUND:"video_analysis_refund",VIDEO_ANALYSIS_ADJUST:"video_analysis_adjust",VIDEO_ANALYSIS_LLM:"video_analysis_llm",MEMORY_AI:"memory_ai",MEMORY_AI_REFUND:"memory_ai_refund",TRUSTPILOT_REVIEWS:"trustpilot_reviews",TRUSTPILOT_REVIEWS_REFUND:"trustpilot_reviews_refund",TRUSTPILOT_REVIEW:"trustpilot_review",TRUSTPILOT_REVIEW_REFUND:"trustpilot_review_refund",G2_REVIEWS:"g2_reviews",G2_REVIEWS_REFUND:"g2_reviews_refund",G2_REVIEW:"g2_review",G2_REVIEW_REFUND:"g2_review_refund",DIFF_PAGE:"diff_page",DIFF_PAGE_REFUND:"diff_page_refund",LOCAL_SOURCEBOOK_CREATE:"local_sourcebook_create",LOCAL_SOURCEBOOK_CREATE_REFUND:"local_sourcebook_create_refund",LOCAL_SOURCEBOOK_EDIT:"local_sourcebook_edit",LOCAL_SOURCEBOOK_EDIT_REFUND:"local_sourcebook_edit_refund",COMMONS_CREATE:"commons_create",COMMONS_CREATE_REFUND:"commons_create_refund",COMMONS_EDIT:"commons_edit",COMMONS_EDIT_REFUND:"commons_edit_refund",SITE_AUDIT_LLM:"site_audit_llm",SCHEDULED_RUN:"scheduled_run",CONNECTED_USAGE:"connected_usage",CONNECTED_ACCOUNT_FEE:"connected_account_fee",ADMIN_GRANT:"admin_grant",ADMIN_REVOKE:"admin_revoke"},De=3,Be=1.5,Fe=1.5,G=2e4,Y=200;function Ge(e){let r=Math.max(1,Math.ceil((e||60)/60));return G+Y*r}var Ye=G+Y*30,qe=p.price_1TmiHRS8aAcsk3TGwmSNfNIa.credits_mc/p.price_1TmiHRS8aAcsk3TGwmSNfNIa.monthly_usd;export{t as a,ce as b,le as c,_e as d,a as e,g as f,de as g,pe as h,V as i,ue as j,me as k,ge as l,H as m,y as n,W as o,be as p,Q as q,fe as r,Ee as s,Z as t,S as u,Re as v,A as w,N as x,I as y,w as z,he as A,Ce as B,ye as C,X as D,Te as E,M as F,x as G,P as H,p as I,E as J,j as K,z as L,ve as M,Se as N,Ae as O,Ne as P,L as Q,f as R,Ie as S,we as T,F as U,h as V,ke as W,re as X,Oe as Y,i as Z,Me as _,xe as $,Pe as aa,Ue as ba,De as ca,Be as da,Fe as ea,Ge as fa,Ye as ga,qe as ha};
@@ -1,4 +1,4 @@
1
- import{c as be}from"./chunk-KJQXUZ4Y.js";import{b as T,l as ve}from"./chunk-2TZBO52D.js";import{a as _e,c as ke,d as X,e as Re,f as Se}from"./chunk-WO3N5FH2.js";function xe(e){return e.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}import{mkdir as J,readFile as Ye,stat as Xe,writeFile as z}from"fs/promises";import{existsSync as Ze}from"fs";import{homedir as et,platform as tt}from"os";import{dirname as Z,join as U}from"path";import{execFile as rt}from"child_process";function ae(e){return e?.trim()||process.env.MCP_SCRAPER_OUTPUT_DIR?.trim()||U(et(),"Downloads","mcp-scraper")}function Ce(){return new Date().toISOString().replace(/[:.]/g,"-")}function se(e){return xe(e).replace(/^-+|-+$/g,"").slice(0,80)||"run"}var V=class e{constructor(t,n,r,i,s,a,l){this.workflowId=t;this.title=n;this.runId=r;this.baseDir=i;this.runDir=s;this.startedAt=a;this.input=l}workflowId;title;runId;baseDir;runDir;startedAt;input;artifacts=[];static async create(t,n,r,i,s){let a=new Date().toISOString(),l=s?.trim()||`${Ce()}-${se(t)}-${Math.random().toString(36).slice(2,8)}`,c=String(r.keyword??r.query??r.domain??r.state??t),p=ae(i),u=U(p,"workflows",t,`${Ce()}-${se(c)}-${se(l).slice(0,20)}`);return await J(u,{recursive:!0}),new e(t,n,l,p,u,a,r)}async remember(t,n,r,i){let s=await Xe(r).then(a=>a.size).catch(()=>{});return this.artifacts.push({kind:t,label:n,path:r,bytes:s,rows:i}),await ve({title:`${this.title} ${n}`,content:`artifact: ${r}`,source:`mcp-scraper-workflow:${this.workflowId}:${this.runId}`}),r}async writeJson(t,n,r){let i=U(this.runDir,n);return await J(Z(i),{recursive:!0}),await z(i,JSON.stringify(r,null,2),"utf8"),this.remember("json",t,i)}async writeText(t,n,r,i="markdown"){let s=U(this.runDir,n);return await J(Z(s),{recursive:!0}),await z(s,r,"utf8"),this.remember(i,t,s)}async writeCsv(t,n,r,i){let s=U(this.runDir,n);return await J(Z(s),{recursive:!0}),await z(s,be(r,i),"utf8"),this.remember("csv",t,s,i.length)}async writeHtml(t,n,r){return this.writeText(t,n,r,"html_report")}async writeManifest(t,n,r,i){let s={workflow:this.workflowId,title:this.title,runId:this.runId,status:t,startedAt:this.startedAt,completedAt:t==="running"?null:new Date().toISOString(),input:this.input,artifacts:this.artifacts,warnings:r,errors:i,counts:n},a=U(this.runDir,"manifest.json");return await z(a,JSON.stringify(s,null,2),"utf8"),await nt(s,a,this.baseDir),a}};function Ae(e=ae()){return U(e,"workflows","index.json")}async function Pe(e){let t=Ae(e);if(!Ze(t))return{runs:[]};try{return JSON.parse(await Ye(t,"utf8"))}catch{return{runs:[]}}}async function nt(e,t,n){if(e.status==="running")return;let r=Ae(n),i=await Pe(n),s=e.artifacts.find(l=>l.kind==="html_report")?.path??null,a={workflow:e.workflow,runId:e.runId,status:e.status,startedAt:e.startedAt,reportPath:s,manifestPath:t,summary:`${e.title} (${e.status})`};i.runs=[a,...i.runs.filter(l=>l.runId!==e.runId)].slice(0,200),await J(Z(r),{recursive:!0}),await z(r,JSON.stringify(i,null,2),"utf8")}async function $e(e){return(await Pe(ae(e))).runs}async function Ee(e,t){let n=await $e(t);return e==="last"?n[0]??null:n.find(r=>r.runId===e)??null}async function it(e,t){let n=await Ee(e,t);if(!n?.reportPath)throw new Error(`No report found for "${e}"`);return tt()==="darwin"&&await new Promise((r,i)=>{rt("open",[n.reportPath],s=>s?i(s):r())}),n.reportPath}import{readFile as At}from"fs/promises";import{z as dr}from"zod";var F=class{constructor(t,n,r=fetch,i={}){this.apiUrl=t;this.apiKey=n;this.fetchImpl=r;this.extraHeaders=i}apiUrl;apiKey;fetchImpl;extraHeaders;async post(t,n,r=18e4){let i=await this.fetchImpl(`${this.apiUrl.replace(/\/$/,"")}${t}`,{method:"POST",headers:{...this.extraHeaders,"Content-Type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:AbortSignal.timeout(r)}),s=await i.json().catch(()=>({}));if(!i.ok){let a=typeof s.error=="string"?s.error:`Workflow API ${t} failed with ${i.status}`;throw new Error(a)}return s}};import{z as D}from"zod";function I(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ot(e){let t=e.rows.map(n=>`<tr>${e.columns.map(r=>`<td>${I(n[r])}</td>`).join("")}</tr>`).join(`
1
+ import{c as be}from"./chunk-KJQXUZ4Y.js";import{b as T,j as ve}from"./chunk-Y6MKMSOC.js";import{a as _e,c as ke,d as X,e as Re,f as Se}from"./chunk-WO3N5FH2.js";function xe(e){return e.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}import{mkdir as J,readFile as Ye,stat as Xe,writeFile as z}from"fs/promises";import{existsSync as Ze}from"fs";import{homedir as et,platform as tt}from"os";import{dirname as Z,join as U}from"path";import{execFile as rt}from"child_process";function ae(e){return e?.trim()||process.env.MCP_SCRAPER_OUTPUT_DIR?.trim()||U(et(),"Downloads","mcp-scraper")}function Ce(){return new Date().toISOString().replace(/[:.]/g,"-")}function se(e){return xe(e).replace(/^-+|-+$/g,"").slice(0,80)||"run"}var V=class e{constructor(t,n,r,i,s,a,l){this.workflowId=t;this.title=n;this.runId=r;this.baseDir=i;this.runDir=s;this.startedAt=a;this.input=l}workflowId;title;runId;baseDir;runDir;startedAt;input;artifacts=[];static async create(t,n,r,i,s){let a=new Date().toISOString(),l=s?.trim()||`${Ce()}-${se(t)}-${Math.random().toString(36).slice(2,8)}`,c=String(r.keyword??r.query??r.domain??r.state??t),p=ae(i),u=U(p,"workflows",t,`${Ce()}-${se(c)}-${se(l).slice(0,20)}`);return await J(u,{recursive:!0}),new e(t,n,l,p,u,a,r)}async remember(t,n,r,i){let s=await Xe(r).then(a=>a.size).catch(()=>{});return this.artifacts.push({kind:t,label:n,path:r,bytes:s,rows:i}),await ve({title:`${this.title} ${n}`,content:`artifact: ${r}`,source:`mcp-scraper-workflow:${this.workflowId}:${this.runId}`}),r}async writeJson(t,n,r){let i=U(this.runDir,n);return await J(Z(i),{recursive:!0}),await z(i,JSON.stringify(r,null,2),"utf8"),this.remember("json",t,i)}async writeText(t,n,r,i="markdown"){let s=U(this.runDir,n);return await J(Z(s),{recursive:!0}),await z(s,r,"utf8"),this.remember(i,t,s)}async writeCsv(t,n,r,i){let s=U(this.runDir,n);return await J(Z(s),{recursive:!0}),await z(s,be(r,i),"utf8"),this.remember("csv",t,s,i.length)}async writeHtml(t,n,r){return this.writeText(t,n,r,"html_report")}async writeManifest(t,n,r,i){let s={workflow:this.workflowId,title:this.title,runId:this.runId,status:t,startedAt:this.startedAt,completedAt:t==="running"?null:new Date().toISOString(),input:this.input,artifacts:this.artifacts,warnings:r,errors:i,counts:n},a=U(this.runDir,"manifest.json");return await z(a,JSON.stringify(s,null,2),"utf8"),await nt(s,a,this.baseDir),a}};function Ae(e=ae()){return U(e,"workflows","index.json")}async function Pe(e){let t=Ae(e);if(!Ze(t))return{runs:[]};try{return JSON.parse(await Ye(t,"utf8"))}catch{return{runs:[]}}}async function nt(e,t,n){if(e.status==="running")return;let r=Ae(n),i=await Pe(n),s=e.artifacts.find(l=>l.kind==="html_report")?.path??null,a={workflow:e.workflow,runId:e.runId,status:e.status,startedAt:e.startedAt,reportPath:s,manifestPath:t,summary:`${e.title} (${e.status})`};i.runs=[a,...i.runs.filter(l=>l.runId!==e.runId)].slice(0,200),await J(Z(r),{recursive:!0}),await z(r,JSON.stringify(i,null,2),"utf8")}async function $e(e){return(await Pe(ae(e))).runs}async function Ee(e,t){let n=await $e(t);return e==="last"?n[0]??null:n.find(r=>r.runId===e)??null}async function it(e,t){let n=await Ee(e,t);if(!n?.reportPath)throw new Error(`No report found for "${e}"`);return tt()==="darwin"&&await new Promise((r,i)=>{rt("open",[n.reportPath],s=>s?i(s):r())}),n.reportPath}import{readFile as At}from"fs/promises";import{z as dr}from"zod";var F=class{constructor(t,n,r=fetch,i={}){this.apiUrl=t;this.apiKey=n;this.fetchImpl=r;this.extraHeaders=i}apiUrl;apiKey;fetchImpl;extraHeaders;async post(t,n,r=18e4){let i=await this.fetchImpl(`${this.apiUrl.replace(/\/$/,"")}${t}`,{method:"POST",headers:{...this.extraHeaders,"Content-Type":"application/json","x-api-key":this.apiKey},body:JSON.stringify(n),signal:AbortSignal.timeout(r)}),s=await i.json().catch(()=>({}));if(!i.ok){let a=typeof s.error=="string"?s.error:`Workflow API ${t} failed with ${i.status}`;throw new Error(a)}return s}};import{z as D}from"zod";function I(e){return String(e??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ot(e){let t=e.rows.map(n=>`<tr>${e.columns.map(r=>`<td>${I(n[r])}</td>`).join("")}</tr>`).join(`
2
2
  `);return["<section>",`<h2>${I(e.title)}</h2>`,'<div class="table-wrap"><table>',`<thead><tr>${e.columns.map(n=>`<th>${I(n)}</th>`).join("")}</tr></thead>`,`<tbody>${t||`<tr><td colspan="${e.columns.length}">No rows</td></tr>`}</tbody>`,"</table></div>","</section>"].join(`
3
3
  `)}function P(e){let t=e.warnings?.length?`<section class="warnings"><h2>Warnings</h2><ul>${e.warnings.map(i=>`<li>${I(i)}</li>`).join("")}</ul></section>`:"",n=(e.sections??[]).map(i=>`<section><h2>${I(i.title)}</h2><p>${I(i.body)}</p></section>`).join(`
4
4
  `),r=(e.tables??[]).map(ot).join(`
@@ -1,4 +1,4 @@
1
- import{createClient as Ve}from"@libsql/client/http";import{createHash as v,randomBytes as q,randomUUID as N,scryptSync as Ne,timingSafeEqual as ze}from"crypto";import{z as p}from"zod";var k="2026-06-26 21:58:03";var Lt="Google returned a CAPTCHA. Run with --headless=false to re-warm the browser profile, then retry.",ve="This operation is temporarily unavailable. Please retry later.",ke=["request_aborted","captcha_exhausted","captcha_or_blocked","location_mismatch","proxy_tunnel_failed","proxy_unavailable","harvest_timeout","mcp_request_timeout","mcp_http_error","extraction_failed","concurrency_limit_exceeded","unauthorized","forbidden","invalid_request","rate_limited","upstream_rate_limited","insufficient_balance","service_unavailable","response_lost","vendor_unavailable","page_not_found","page_forbidden","page_rate_limited","page_server_error","page_http_error","bot_check_unresolved","page_too_large","page_unreachable","browser_session_interrupted","site_export_not_found","site_export_format_unavailable","site_export_read_failed","site_export_image_not_found","image_url_invalid","image_url_not_https","image_host_unresolvable","image_host_blocked","image_redirect_invalid","image_source_unavailable","image_too_large","image_redirect_limit","image_base64_invalid","image_source_missing","image_source_ambiguous","image_source_type_invalid","image_artifact_not_found","image_page_too_large","page_image_not_found","page_image_candidates_unusable","image_format_unsupported","image_storage_unconfigured","featured_image_unhostable"],Xe=["request_aborted","captcha","location_mismatch","connection","timeout","extraction","concurrency_limit","unauthorized","forbidden","invalid_request","rate_limit","billing","service_unavailable"];function O(e){return e?JSON.stringify(e):null}function ae(e){if(e==null)return null;try{let t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t;if(typeof r.error_code!="string"||!oe.has(r.error_code))return null;let n=Ge({errorCode:r.error_code,errorType:r.error_type,retryable:r.retryable,retryAfterSeconds:r.retry_after_seconds,chargeStatus:r.charge_status,details:r.details});if(typeof r.message=="string"){let s=_e(r.message).trim().slice(0,1e3);s&&!/https?:\/\//i.test(s)&&(n.message=s)}return n}catch{return null}}var oe=new Set(ke),Me=new Set(Xe),Fe=new Set(["active","limit","operation","upgrade_url","topup_url","upgrade_command","slots_per_pack","pack_price_usd","balance_credits","required_credits","retry_guidance","http_status"]),Pe=12,He=500;function j(e){return typeof e=="string"&&oe.has(e)?e:"service_unavailable"}function qe(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t={};for(let[r,n]of Object.entries(e)){if(Object.keys(t).length>=Pe)break;if(Fe.has(r))if(typeof n=="string"){if((r==="upgrade_url"||r==="topup_url")&&!We(n))continue;let s=_e(n).slice(0,He);s&&(t[r]=s)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean"||n===null)&&(t[r]=n)}return Object.keys(t).length>0?t:void 0}function We(e){if(e.startsWith("/")&&!e.startsWith("//"))return!0;try{let t=new URL(e);return t.protocol==="https:"&&(t.hostname==="mcpscraper.dev"||t.hostname.endsWith(".mcpscraper.dev"))}catch{return!1}}function je(e){let t=j(e);switch(t){case"captcha_exhausted":case"captcha_or_blocked":return"captcha";case"proxy_tunnel_failed":case"proxy_unavailable":case"response_lost":return"connection";case"harvest_timeout":case"mcp_request_timeout":return"timeout";case"concurrency_limit_exceeded":return"concurrency_limit";case"rate_limited":case"upstream_rate_limited":return"rate_limit";case"extraction_failed":case"page_not_found":case"page_forbidden":case"page_rate_limited":case"page_server_error":case"page_http_error":case"bot_check_unresolved":case"page_too_large":case"page_unreachable":case"browser_session_interrupted":case"site_export_not_found":case"site_export_format_unavailable":case"site_export_read_failed":case"site_export_image_not_found":return"extraction";case"image_url_invalid":case"image_url_not_https":case"image_host_unresolvable":case"image_host_blocked":case"image_redirect_invalid":case"image_source_unavailable":case"image_too_large":case"image_redirect_limit":case"image_base64_invalid":case"image_source_missing":case"image_source_ambiguous":case"image_source_type_invalid":case"image_artifact_not_found":case"image_page_too_large":case"page_image_not_found":case"page_image_candidates_unusable":case"image_format_unsupported":case"image_storage_unconfigured":case"featured_image_unhostable":return"invalid_request";case"insufficient_balance":return"billing";case"vendor_unavailable":case"mcp_http_error":return"service_unavailable";default:return t}}function Be(e){switch(j(e)){case"request_aborted":return"The request was cancelled before it completed.";case"captcha_exhausted":case"captcha_or_blocked":return"The target site returned a verification challenge. Heavy traffic can temporarily increase these challenges; retry in a few minutes.";case"location_mismatch":return"The target site returned results for a different location. Please retry.";case"proxy_tunnel_failed":case"proxy_unavailable":return"The web request could not establish a working connection. Please retry later.";case"harvest_timeout":return"The request timed out before it completed. Please retry with a smaller request.";case"mcp_request_timeout":return"The MCP caller stopped waiting before a final response arrived. Durable work may still be running; continue with the returned Task or job handle instead of restarting it.";case"concurrency_limit_exceeded":return"The service is available, but this account has reached its parallel-operation limit. Wait for an active operation to finish or add capacity.";case"unauthorized":return"Authentication is required to perform this operation.";case"forbidden":return"This account does not have permission to perform this operation.";case"invalid_request":return"The request is invalid. Check the supplied inputs and try again.";case"rate_limited":return"This account is sending requests too quickly. Wait briefly and retry.";case"upstream_rate_limited":return"The connected provider is temporarily rate-limiting requests. Wait briefly and retry.";case"mcp_http_error":return"The API returned an unexpected HTTP response.";case"insufficient_balance":return"This account does not have enough Credits for the operation.";case"extraction_failed":return"The target could not be extracted. Please retry later.";case"response_lost":return"The connection was lost before the response arrived. The operation may have already completed and been billed on our side \u2014 check credits_info before retrying blind.";case"vendor_unavailable":return"MCP Scraper's internal browser services require MCP Scraper team attention. Servers or IPs are down until this is fixed \u2014 this is not caused by your request. Please retry in a few minutes.";case"page_not_found":return"The page could not be found. It may have been moved or deleted.";case"page_forbidden":return"The site refused the request.";case"page_rate_limited":return"The site is rate-limiting requests right now. Retrying after a short wait usually works.";case"page_server_error":return"The page's own server returned an error. This is on the target site's side, not something a retry here can fix.";case"page_http_error":return"The page returned an unexpected HTTP response.";case"bot_check_unresolved":return"This site has automated-traffic protection (a bot/CAPTCHA check) that could not be resolved in time. Some sites are simply not extractable this way.";case"page_too_large":return"The page is larger than we can safely process.";case"page_unreachable":return"The page did not respond in time, or the connection could not be completed.";case"browser_session_interrupted":return"The browser session closed before extraction completed. MCP Scraper will retry once with a fresh session; retry the request if this persists.";case"site_export_not_found":return"The site export or requested page was not found, expired, or does not belong to this account.";case"site_export_format_unavailable":return"That representation was not retained for this export page. Read the export manifest and request one of the formats marked available.";case"site_export_read_failed":return"The stored site export could not be read or did not pass its integrity check.";case"site_export_image_not_found":return"The requested site-export image was not found, expired, or does not belong to this account.";case"image_url_invalid":return"The image source is not a valid URL. Use a stable public HTTPS URL or inline image bytes.";case"image_url_not_https":return"Commons image sources must use a public HTTPS URL or inline image bytes.";case"image_host_unresolvable":return"The image host could not be resolved. Use a different stable public URL or inline image bytes.";case"image_host_blocked":return"The image source resolves to a network address Commons cannot fetch safely.";case"image_redirect_invalid":return"The image source redirected to an invalid or unsafe destination.";case"image_source_unavailable":return"The image source could not be fetched. Host a different stable public URL or provide inline image bytes.";case"image_too_large":return"The image exceeds the Commons image size limit.";case"image_redirect_limit":return"The image source exceeded the Commons redirect limit.";case"image_base64_invalid":return"The supplied inline image bytes are invalid.";case"image_source_missing":return"Provide exactly one of a public image or webpage URL, inline image bytes, or an owner-scoped image artifact.";case"image_source_ambiguous":return"Provide only one image source: sourceUrl, imageBase64, or artifactId.";case"image_source_type_invalid":return"Use sourceType only with inline image bytes or an owner-scoped image artifact.";case"image_artifact_not_found":return"The image artifact was not found, expired, or does not belong to this account.";case"image_page_too_large":return"The webpage is too large for bounded Commons image discovery.";case"page_image_not_found":return"The webpage did not expose a usable featured or content image.";case"page_image_candidates_unusable":return"The webpage exposed image candidates, but none returned supported public image bytes.";case"image_format_unsupported":return"Commons accepts JPEG, PNG, GIF, or WebP image bytes.";case"image_storage_unconfigured":return"Commons image storage is temporarily unavailable.";case"featured_image_unhostable":return"The required featured image could not be hosted for Commons publication.";default:return ve}}function Ge(e){let t=j(e.errorCode),r=typeof e.retryAfterSeconds=="number"&&Number.isFinite(e.retryAfterSeconds)?Math.max(1,Math.min(86400,Math.trunc(e.retryAfterSeconds))):void 0,n=e.chargeStatus==="not_charged"||e.chargeStatus==="refund_pending"||e.chargeStatus==="refunded"||e.chargeStatus==="charged"?e.chargeStatus:void 0,s=typeof e.errorType=="string"&&Me.has(e.errorType)?e.errorType:void 0,a=qe(e.details);return{error_code:t,error_type:s??je(t),message:Be(t),retryable:e.retryable===!0,...r?{retry_after_seconds:r}:{},...n?{charge_status:n}:{},...a?{details:a}:{}}}function _e(e){return e.replace(/https?:\/\/[^\s]*(?:brightdata|onkernel|kernel\.sh)[^\s]*/gi,"the service").replace(/bright\s*data/gi,"the service").replace(/brightdata/gi,"the service").replace(/kernel\.sh\s+sessions?/gi,"sessions").replace(/kernel\.sh\s+session/gi,"this session").replace(/kernel\.sh/gi,"the service").replace(/kernel\s+sessions?/gi,"sessions").replace(/kernel\s+session/gi,"this session").replace(/\b(?:sub|cus|sess|proxy)_[A-Za-z0-9_-]+\b/g,"[redacted]").replace(/\b(?:KERNEL|BRIGHTDATA|BRIGHT_DATA)_[A-Z0-9_]*API_KEY\b/g,"BROWSER_SERVICE_API_KEY").replace(/\bkernel\b/gi,"the service").replace(/ +/g," ").trim()}var ee=class extends Error{constructor(r){super(`CAPTCHA detected. ${r}`);this.instructions=r}instructions;name="CaptchaError"},te=class extends Error{constructor(r,n){super(r);this.cause=n}cause;name="ExtractionError"},re=class extends Error{constructor(r){super(`Google Maps search did not reach a complete result state (${r})`);this.pageState=r}pageState;name="MapsSearchIncompletePageError"},ne=class extends Error{name="RequestAbortedError";constructor(t="Request aborted before harvest completed"){super(t)}},se=class extends Error{name="PaaInteractionInterruptedError"},ie=class extends Error{name="LocationMismatchError";constructor(t="Google returned results for a different location than requested"){super(t)}};var I=["oauth_store_metadata","oauth_clients","oauth_client_redirect_uris","oauth_codes","oauth_code_exchanges","oauth_refresh_families","oauth_refresh_tokens","oauth_refresh_rotations","oauth_security_events","oauth_rate_limit_buckets"],x=["oauth_clients_inactivity_idx","oauth_clients_cleanup_idx","oauth_codes_expiry_idx","oauth_codes_client_idx","oauth_code_exchanges_replay_expiry_idx","oauth_refresh_families_lifecycle_idx","oauth_refresh_families_user_status_idx","oauth_refresh_families_client_idx","oauth_refresh_families_cleanup_idx","oauth_refresh_tokens_expiry_idx","oauth_refresh_rotations_replay_expiry_idx","oauth_security_events_retention_idx","oauth_rate_limit_buckets_expiry_idx"],ue={oauth_clients:"oauth_clients_legacy_raw",oauth_codes:"oauth_codes_legacy_raw",oauth_tokens:"oauth_tokens_legacy_raw"},L="strftime('%Y-%m-%dT%H:%M:%fZ','now')";async function y(e,t,r=!1){try{await e.execute(t)}catch(n){let s=n.code;if(!r||s!=="SQL_PARSE_ERROR")throw n}}var Ye=[`CREATE TABLE IF NOT EXISTS oauth_store_metadata (
1
+ import{createClient as Ve}from"@libsql/client/http";import{createHash as v,randomBytes as q,randomUUID as N,scryptSync as Ne,timingSafeEqual as ze}from"crypto";import{z as p}from"zod";var k="2026-06-26 21:58:03";var Lt="Google returned a CAPTCHA. Run with --headless=false to re-warm the browser profile, then retry.",ve="This operation is temporarily unavailable. Please retry later.",ke=["request_aborted","captcha_exhausted","captcha_or_blocked","location_mismatch","proxy_tunnel_failed","proxy_unavailable","harvest_timeout","mcp_request_timeout","mcp_http_error","extraction_failed","concurrency_limit_exceeded","unauthorized","forbidden","invalid_request","rate_limited","upstream_rate_limited","insufficient_balance","service_unavailable","response_lost","vendor_unavailable","page_not_found","page_forbidden","page_rate_limited","page_server_error","page_http_error","bot_check_unresolved","page_too_large","page_unreachable","browser_session_interrupted","site_export_not_found","site_export_format_unavailable","site_export_read_failed","site_export_image_not_found","image_url_invalid","image_url_not_https","image_host_unresolvable","image_host_blocked","image_redirect_invalid","image_source_unavailable","image_too_large","image_redirect_limit","image_base64_invalid","image_source_missing","image_source_ambiguous","image_source_type_invalid","image_artifact_not_found","image_page_too_large","page_image_not_found","page_image_candidates_unusable","image_format_unsupported","image_storage_unconfigured","featured_image_unhostable"],Xe=["request_aborted","captcha","location_mismatch","connection","timeout","extraction","concurrency_limit","unauthorized","forbidden","invalid_request","rate_limit","billing","service_unavailable"];function O(e){return e?JSON.stringify(e):null}function ae(e){if(e==null)return null;try{let t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object"||Array.isArray(t))return null;let r=t;if(typeof r.error_code!="string"||!oe.has(r.error_code))return null;let n=Ge({errorCode:r.error_code,errorType:r.error_type,retryable:r.retryable,retryAfterSeconds:r.retry_after_seconds,chargeStatus:r.charge_status,details:r.details});if(typeof r.message=="string"){let s=_e(r.message).trim().slice(0,1e3);s&&!/https?:\/\//i.test(s)&&(n.message=s)}return n}catch{return null}}var oe=new Set(ke),Me=new Set(Xe),Fe=new Set(["active","limit","operation","upgrade_url","topup_url","upgrade_command","slots_per_pack","pack_price_usd","balance_credits","required_credits","retry_guidance","http_status"]),Pe=12,He=500;function j(e){return typeof e=="string"&&oe.has(e)?e:"service_unavailable"}function qe(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t={};for(let[r,n]of Object.entries(e)){if(Object.keys(t).length>=Pe)break;if(Fe.has(r))if(typeof n=="string"){if((r==="upgrade_url"||r==="topup_url")&&!We(n))continue;let s=_e(n).slice(0,He);s&&(t[r]=s)}else(typeof n=="number"&&Number.isFinite(n)||typeof n=="boolean"||n===null)&&(t[r]=n)}return Object.keys(t).length>0?t:void 0}function We(e){if(e.startsWith("/")&&!e.startsWith("//"))return!0;try{let t=new URL(e);return t.protocol==="https:"&&(t.hostname==="mcpscraper.dev"||t.hostname.endsWith(".mcpscraper.dev"))}catch{return!1}}function je(e){let t=j(e);switch(t){case"captcha_exhausted":case"captcha_or_blocked":return"captcha";case"proxy_tunnel_failed":case"proxy_unavailable":case"response_lost":return"connection";case"harvest_timeout":case"mcp_request_timeout":return"timeout";case"concurrency_limit_exceeded":return"concurrency_limit";case"rate_limited":case"upstream_rate_limited":return"rate_limit";case"extraction_failed":case"page_not_found":case"page_forbidden":case"page_rate_limited":case"page_server_error":case"page_http_error":case"bot_check_unresolved":case"page_too_large":case"page_unreachable":case"browser_session_interrupted":case"site_export_not_found":case"site_export_format_unavailable":case"site_export_read_failed":case"site_export_image_not_found":return"extraction";case"image_url_invalid":case"image_url_not_https":case"image_host_unresolvable":case"image_host_blocked":case"image_redirect_invalid":case"image_source_unavailable":case"image_too_large":case"image_redirect_limit":case"image_base64_invalid":case"image_source_missing":case"image_source_ambiguous":case"image_source_type_invalid":case"image_artifact_not_found":case"image_page_too_large":case"page_image_not_found":case"page_image_candidates_unusable":case"image_format_unsupported":case"image_storage_unconfigured":case"featured_image_unhostable":return"invalid_request";case"insufficient_balance":return"billing";case"vendor_unavailable":case"mcp_http_error":return"service_unavailable";default:return t}}function Be(e){switch(j(e)){case"request_aborted":return"The request was cancelled before it completed.";case"captcha_exhausted":case"captcha_or_blocked":return"The target site returned a verification challenge. Heavy traffic can temporarily increase these challenges; retry in a few minutes.";case"location_mismatch":return"The target site returned results for a different location. Please retry.";case"proxy_tunnel_failed":case"proxy_unavailable":return"The web request could not establish a working connection. Please retry later.";case"harvest_timeout":return"The request timed out before it completed. Please retry with a smaller request.";case"mcp_request_timeout":return"The MCP caller stopped waiting before a final response arrived. Durable work may still be running; continue with the returned Task or job handle instead of restarting it.";case"concurrency_limit_exceeded":return"The service is available, but this account has reached its parallel-operation limit. Wait for an active operation to finish or add capacity.";case"unauthorized":return"Authentication is required to perform this operation.";case"forbidden":return"This account does not have permission to perform this operation.";case"invalid_request":return"The request is invalid. Check the supplied inputs and try again.";case"rate_limited":return"This account is sending requests too quickly. Wait briefly and retry.";case"upstream_rate_limited":return"The connected provider is temporarily rate-limiting requests. Wait briefly and retry.";case"mcp_http_error":return"The API returned an unexpected HTTP response.";case"insufficient_balance":return"This account does not have enough Credits for the operation.";case"extraction_failed":return"The target could not be extracted. Please retry later.";case"response_lost":return"The connection was lost before the response arrived. The operation may have already completed and been billed on our side \u2014 check credits_info before retrying blind.";case"vendor_unavailable":return"MCP Scraper's internal browser services require MCP Scraper team attention. Servers or IPs are down until this is fixed \u2014 this is not caused by your request. Please retry in a few minutes.";case"page_not_found":return"The page could not be found. It may have been moved or deleted.";case"page_forbidden":return"The site refused the request.";case"page_rate_limited":return"The site is rate-limiting requests right now. Retrying after a short wait usually works.";case"page_server_error":return"The page's own server returned an error. This is on the target site's side, not something a retry here can fix.";case"page_http_error":return"The page returned an unexpected HTTP response.";case"bot_check_unresolved":return"This site has automated-traffic protection (a bot/CAPTCHA check) that could not be resolved in time. Some sites are simply not extractable this way.";case"page_too_large":return"The page is larger than we can safely process.";case"page_unreachable":return"The page did not respond in time, or the connection could not be completed.";case"browser_session_interrupted":return"The browser session closed before extraction completed. MCP Scraper will retry once with a fresh session; retry the request if this persists.";case"site_export_not_found":return"The site export or requested page was not found, expired, or does not belong to this account.";case"site_export_format_unavailable":return"That representation was not retained for this export page. Read the export manifest and request one of the formats marked available.";case"site_export_read_failed":return"The stored site export could not be read or did not pass its integrity check.";case"site_export_image_not_found":return"The requested site-export image was not found, expired, or does not belong to this account.";case"image_url_invalid":return"The image source is not a valid URL. Use a stable public HTTPS URL or inline image bytes.";case"image_url_not_https":return"Commons image sources must use a public HTTPS URL or inline image bytes.";case"image_host_unresolvable":return"The image host could not be resolved. Use a different stable public URL or inline image bytes.";case"image_host_blocked":return"The image source resolves to a network address Commons cannot fetch safely.";case"image_redirect_invalid":return"The image source redirected to an invalid or unsafe destination.";case"image_source_unavailable":return"The image source could not be fetched. Host a different stable public URL or provide inline image bytes.";case"image_too_large":return"The image exceeds the Commons image size limit.";case"image_redirect_limit":return"The image source exceeded the Commons redirect limit.";case"image_base64_invalid":return"The supplied inline image bytes are invalid.";case"image_source_missing":return"Provide exactly one of a public image or webpage URL, inline image bytes, or an owner-scoped image artifact.";case"image_source_ambiguous":return"Provide only one image source: sourceUrl, imageBase64, or artifactId.";case"image_source_type_invalid":return"Use sourceType only with inline image bytes or an owner-scoped image artifact.";case"image_artifact_not_found":return"The image artifact was not found, expired, or does not belong to this account.";case"image_page_too_large":return"The webpage is too large for bounded Commons image discovery.";case"page_image_not_found":return"The webpage did not expose a usable featured or content image.";case"page_image_candidates_unusable":return"The webpage exposed image candidates, but none returned supported public image bytes.";case"image_format_unsupported":return"Commons accepts JPEG, PNG, GIF, or WebP image bytes.";case"image_storage_unconfigured":return"Commons image storage is temporarily unavailable.";case"featured_image_unhostable":return"The required featured image could not be hosted for Commons publication.";default:return ve}}function Ge(e){let t=j(e.errorCode),r=typeof e.retryAfterSeconds=="number"&&Number.isFinite(e.retryAfterSeconds)?Math.max(1,Math.min(86400,Math.trunc(e.retryAfterSeconds))):void 0,n=e.chargeStatus==="not_charged"||e.chargeStatus==="refund_pending"||e.chargeStatus==="refunded"||e.chargeStatus==="charged"?e.chargeStatus:void 0,s=typeof e.errorType=="string"&&Me.has(e.errorType)?e.errorType:void 0,a=qe(e.details);return{error_code:t,error_type:s??je(t),message:Be(t),retryable:e.retryable===!0,...r?{retry_after_seconds:r}:{},...n?{charge_status:n}:{},...a?{details:a}:{}}}function _e(e){return e.replace((new RegExp("https?:\\/\\/[^\\s]*(?:\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061|on\u006b\u0065\u0072\u006e\u0065\u006c|\u006b\u0065\u0072\u006e\u0065\u006c\\.sh)[^\\s]*", "gi")),"the service").replace(/bright\s*data/gi,"the service").replace((new RegExp("\u0062\u0072\u0069\u0067\u0068\u0074\u0064\u0061\u0074\u0061", "gi")),"the service").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\.sh\\s+sessions?", "gi")),"sessions").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\.sh\\s+session", "gi")),"this session").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\.sh", "gi")),"the service").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\s+sessions?", "gi")),"sessions").replace((new RegExp("\u006b\u0065\u0072\u006e\u0065\u006c\\s+session", "gi")),"this session").replace(/\b(?:sub|cus|sess|proxy)_[A-Za-z0-9_-]+\b/g,"[redacted]").replace((new RegExp("\\b(?:\u004b\u0045\u0052\u004e\u0045\u004c|\u0042\u0052\u0049\u0047\u0048\u0054\u0044\u0041\u0054\u0041|\u0042\u0052\u0049\u0047\u0048\u0054_\u0044\u0041\u0054\u0041)_[A-Z0-9_]*API_KEY\\b", "g")),"BROWSER_SERVICE_API_KEY").replace((new RegExp("\\b\u006b\u0065\u0072\u006e\u0065\u006c\\b", "gi")),"the service").replace(/ +/g," ").trim()}var ee=class extends Error{constructor(r){super(`CAPTCHA detected. ${r}`);this.instructions=r}instructions;name="CaptchaError"},te=class extends Error{constructor(r,n){super(r);this.cause=n}cause;name="ExtractionError"},re=class extends Error{constructor(r){super(`Google Maps search did not reach a complete result state (${r})`);this.pageState=r}pageState;name="MapsSearchIncompletePageError"},ne=class extends Error{name="RequestAbortedError";constructor(t="Request aborted before harvest completed"){super(t)}},se=class extends Error{name="PaaInteractionInterruptedError"},ie=class extends Error{name="LocationMismatchError";constructor(t="Google returned results for a different location than requested"){super(t)}};var I=["oauth_store_metadata","oauth_clients","oauth_client_redirect_uris","oauth_codes","oauth_code_exchanges","oauth_refresh_families","oauth_refresh_tokens","oauth_refresh_rotations","oauth_security_events","oauth_rate_limit_buckets"],x=["oauth_clients_inactivity_idx","oauth_clients_cleanup_idx","oauth_codes_expiry_idx","oauth_codes_client_idx","oauth_code_exchanges_replay_expiry_idx","oauth_refresh_families_lifecycle_idx","oauth_refresh_families_user_status_idx","oauth_refresh_families_client_idx","oauth_refresh_families_cleanup_idx","oauth_refresh_tokens_expiry_idx","oauth_refresh_rotations_replay_expiry_idx","oauth_security_events_retention_idx","oauth_rate_limit_buckets_expiry_idx"],ue={oauth_clients:"oauth_clients_legacy_raw",oauth_codes:"oauth_codes_legacy_raw",oauth_tokens:"oauth_tokens_legacy_raw"},L="strftime('%Y-%m-%dT%H:%M:%fZ','now')";async function y(e,t,r=!1){try{await e.execute(t)}catch(n){let s=n.code;if(!r||s!=="SQL_PARSE_ERROR")throw n}}var Ye=[`CREATE TABLE IF NOT EXISTS oauth_store_metadata (
2
2
  id INTEGER PRIMARY KEY CHECK (id = 1),
3
3
  store_id TEXT NOT NULL UNIQUE,
4
4
  schema_version INTEGER NOT NULL CHECK (schema_version > 0),
@@ -230,14 +230,14 @@ import{createClient as Ve}from"@libsql/client/http";import{createHash as v,rando
230
230
  max_questions INTEGER NOT NULL,
231
231
  status TEXT NOT NULL,
232
232
  outcome TEXT,
233
- kernel_session_id TEXT,
233
+ \u006b\u0065\u0072\u006e\u0065\u006c_session_id TEXT,
234
234
  question_count INTEGER,
235
235
  duration_ms INTEGER,
236
236
  error TEXT,
237
237
  will_retry INTEGER,
238
- kernel_delete_started INTEGER NOT NULL DEFAULT 0,
239
- kernel_delete_succeeded INTEGER,
240
- kernel_delete_error TEXT,
238
+ \u006b\u0065\u0072\u006e\u0065\u006c_delete_started INTEGER NOT NULL DEFAULT 0,
239
+ \u006b\u0065\u0072\u006e\u0065\u006c_delete_succeeded INTEGER,
240
+ \u006b\u0065\u0072\u006e\u0065\u006c_delete_error TEXT,
241
241
  browser_close_succeeded INTEGER,
242
242
  browser_close_error TEXT,
243
243
  debug_json TEXT,
@@ -922,8 +922,8 @@ import{createClient as Ve}from"@libsql/client/http";import{createHash as v,rando
922
922
  id TEXT PRIMARY KEY,
923
923
  user_id INTEGER NOT NULL REFERENCES users(id),
924
924
  name TEXT NOT NULL,
925
- kernel_profile_name TEXT NOT NULL,
926
- kernel_proxy_id TEXT NOT NULL,
925
+ \u006b\u0065\u0072\u006e\u0065\u006c_profile_name TEXT NOT NULL,
926
+ \u006b\u0065\u0072\u006e\u0065\u006c_proxy_id TEXT NOT NULL,
927
927
  proxy_type TEXT NOT NULL DEFAULT 'isp',
928
928
  country TEXT NOT NULL DEFAULT 'US',
929
929
  status TEXT NOT NULL DEFAULT 'ready',
@@ -982,7 +982,7 @@ import{createClient as Ve}from"@libsql/client/http";import{createHash as v,rando
982
982
  ON CONFLICT(scope, key_hash, window_start)
983
983
  DO UPDATE SET count = count + 1, updated_at = datetime('now')
984
984
  RETURNING count
985
- `,args:[e,_,a]}),c=Number(o.rows[0]?.count);if(!Number.isSafeInteger(c)||c<1)throw new Error("Rate-limit bucket mutation did not return a valid count");return{allowed:c<=r,count:c,remaining:Math.max(0,r-c),resetSeconds:Math.max(1,a+n-s)}}async function nr(e){let t=q(32).toString("hex"),r=v("sha256").update(t).digest("hex"),n=new Date(Date.now()+3600*1e3).toISOString();return await i().execute({sql:"INSERT INTO password_reset_tokens (token, user_id, expires_at) VALUES (?, ?, ?)",args:[r,e,n]}),t}async function sr(e){let t=i(),r=v("sha256").update(e).digest("hex"),s=(await t.execute({sql:"SELECT user_id, expires_at, used FROM password_reset_tokens WHERE token = ?",args:[r]})).rows[0];return!s||Number(s.used)||new Date(String(s.expires_at))<new Date?null:(await t.execute({sql:"UPDATE password_reset_tokens SET used = 1 WHERE token = ?",args:[r]}),Number(s.user_id))}async function ir(e){let t=Re();return await i().execute({sql:"UPDATE users SET api_key = ?, key_active = 1 WHERE id = ?",args:[t,e]}),t}async function ar(e){await i().execute({sql:"UPDATE users SET key_active = 0 WHERE id = ?",args:[e]})}async function or(){return(await i().execute("SELECT id, email, name, created_at, active FROM users ORDER BY created_at DESC")).rows.map(t=>S({...t,api_key:"",key_active:1}))}async function _r(e){await i().execute({sql:"UPDATE users SET active = 0 WHERE id = ?",args:[e]})}function R(e){return{id:String(e.id),user_id:Number(e.user_id),status:String(e.status),query:String(e.query),options:String(e.options),callback_url:e.callback_url!=null?String(e.callback_url):null,result:e.result!=null?String(e.result):null,error:e.error!=null?String(e.error):null,public_error_json:e.public_error_json!=null?String(e.public_error_json):null,created_at:String(e.created_at),started_at:e.started_at!=null?String(e.started_at):null,completed_at:e.completed_at!=null?String(e.completed_at):null}}function C(e){return e==null?null:Number(e)===1}function H(e){if(e==null)return null;try{return JSON.parse(String(e))}catch{return null}}function we(e){return{id:String(e.id),job_id:String(e.job_id),user_id:Number(e.user_id),attempt_number:Number(e.attempt_number),max_attempts:Number(e.max_attempts),query:String(e.query),location:e.location!=null?String(e.location):null,max_questions:Number(e.max_questions),status:String(e.status),outcome:e.outcome!=null?String(e.outcome):null,kernel_session_id:e.kernel_session_id!=null?String(e.kernel_session_id):null,question_count:e.question_count!=null?Number(e.question_count):null,duration_ms:e.duration_ms!=null?Number(e.duration_ms):null,error:e.error!=null?String(e.error):null,will_retry:C(e.will_retry),kernel_delete_started:Number(e.kernel_delete_started??0)===1,kernel_delete_succeeded:C(e.kernel_delete_succeeded),kernel_delete_error:e.kernel_delete_error!=null?String(e.kernel_delete_error):null,browser_close_succeeded:C(e.browser_close_succeeded),browser_close_error:e.browser_close_error!=null?String(e.browser_close_error):null,browser_provider:e.browser_provider!=null?String(e.browser_provider):null,provider_session_id:e.provider_session_id!=null?String(e.provider_session_id):null,provider_session_observed_at:e.provider_session_observed_at!=null?String(e.provider_session_observed_at):null,provider_lookup_status:e.provider_lookup_status!=null?String(e.provider_lookup_status):null,provider_status:e.provider_status!=null?String(e.provider_status):null,provider_error_code:e.provider_error_code!=null?String(e.provider_error_code):null,provider_error_message:e.provider_error_message!=null?String(e.provider_error_message):null,provider_reason_source:e.provider_reason_source!=null?String(e.provider_reason_source):null,provider_duration_ms:e.provider_duration_ms!=null?Number(e.provider_duration_ms):null,provider_bandwidth_bytes:e.provider_bandwidth_bytes!=null?Number(e.provider_bandwidth_bytes):null,provider_captcha:C(e.provider_captcha),provider_checked_at:e.provider_checked_at!=null?String(e.provider_checked_at):null,provider_detail:H(e.provider_detail_json),provider_disconnect_observed:C(e.provider_disconnect_observed),provider_disconnect_message:e.provider_disconnect_message!=null?String(e.provider_disconnect_message):null,debug:H(e.debug_json),created_at:String(e.created_at),completed_at:e.completed_at!=null?String(e.completed_at):null}}function h(e){let{public_error_json:t,...r}=e;return{...r,options:JSON.parse(e.options),result:e.result?JSON.parse(e.result):null,publicError:ae(t)}}async function ur(e,t,r,n){let s=N();return await it(s,e,t,r,n),s}async function it(e,t,r,n,s){if(!/^[a-zA-Z0-9-]{1,100}$/.test(e))throw new Error("job id is invalid");await i().execute({sql:"INSERT INTO jobs (id, user_id, query, options, callback_url) VALUES (?, ?, ?, ?, ?)",args:[e,t,r,JSON.stringify(n),s??null]})}async function cr(e,t,r){let n=N();return await i().execute({sql:"INSERT INTO jobs (id, user_id, query, options, status, started_at) VALUES (?, ?, ?, ?, 'running', datetime('now'))",args:[n,e,t,JSON.stringify(r)]}),n}async function dr(e,t,r,n){let s=await i().execute({sql:`INSERT INTO jobs (id, user_id, query, options, status, started_at)
985
+ `,args:[e,_,a]}),c=Number(o.rows[0]?.count);if(!Number.isSafeInteger(c)||c<1)throw new Error("Rate-limit bucket mutation did not return a valid count");return{allowed:c<=r,count:c,remaining:Math.max(0,r-c),resetSeconds:Math.max(1,a+n-s)}}async function nr(e){let t=q(32).toString("hex"),r=v("sha256").update(t).digest("hex"),n=new Date(Date.now()+3600*1e3).toISOString();return await i().execute({sql:"INSERT INTO password_reset_tokens (token, user_id, expires_at) VALUES (?, ?, ?)",args:[r,e,n]}),t}async function sr(e){let t=i(),r=v("sha256").update(e).digest("hex"),s=(await t.execute({sql:"SELECT user_id, expires_at, used FROM password_reset_tokens WHERE token = ?",args:[r]})).rows[0];return!s||Number(s.used)||new Date(String(s.expires_at))<new Date?null:(await t.execute({sql:"UPDATE password_reset_tokens SET used = 1 WHERE token = ?",args:[r]}),Number(s.user_id))}async function ir(e){let t=Re();return await i().execute({sql:"UPDATE users SET api_key = ?, key_active = 1 WHERE id = ?",args:[t,e]}),t}async function ar(e){await i().execute({sql:"UPDATE users SET key_active = 0 WHERE id = ?",args:[e]})}async function or(){return(await i().execute("SELECT id, email, name, created_at, active FROM users ORDER BY created_at DESC")).rows.map(t=>S({...t,api_key:"",key_active:1}))}async function _r(e){await i().execute({sql:"UPDATE users SET active = 0 WHERE id = ?",args:[e]})}function R(e){return{id:String(e.id),user_id:Number(e.user_id),status:String(e.status),query:String(e.query),options:String(e.options),callback_url:e.callback_url!=null?String(e.callback_url):null,result:e.result!=null?String(e.result):null,error:e.error!=null?String(e.error):null,public_error_json:e.public_error_json!=null?String(e.public_error_json):null,created_at:String(e.created_at),started_at:e.started_at!=null?String(e.started_at):null,completed_at:e.completed_at!=null?String(e.completed_at):null}}function C(e){return e==null?null:Number(e)===1}function H(e){if(e==null)return null;try{return JSON.parse(String(e))}catch{return null}}function we(e){return{id:String(e.id),job_id:String(e.job_id),user_id:Number(e.user_id),attempt_number:Number(e.attempt_number),max_attempts:Number(e.max_attempts),query:String(e.query),location:e.location!=null?String(e.location):null,max_questions:Number(e.max_questions),status:String(e.status),outcome:e.outcome!=null?String(e.outcome):null,\u006b\u0065\u0072\u006e\u0065\u006c_session_id:e.\u006b\u0065\u0072\u006e\u0065\u006c_session_id!=null?String(e.\u006b\u0065\u0072\u006e\u0065\u006c_session_id):null,question_count:e.question_count!=null?Number(e.question_count):null,duration_ms:e.duration_ms!=null?Number(e.duration_ms):null,error:e.error!=null?String(e.error):null,will_retry:C(e.will_retry),\u006b\u0065\u0072\u006e\u0065\u006c_delete_started:Number(e.\u006b\u0065\u0072\u006e\u0065\u006c_delete_started??0)===1,\u006b\u0065\u0072\u006e\u0065\u006c_delete_succeeded:C(e.\u006b\u0065\u0072\u006e\u0065\u006c_delete_succeeded),\u006b\u0065\u0072\u006e\u0065\u006c_delete_error:e.\u006b\u0065\u0072\u006e\u0065\u006c_delete_error!=null?String(e.\u006b\u0065\u0072\u006e\u0065\u006c_delete_error):null,browser_close_succeeded:C(e.browser_close_succeeded),browser_close_error:e.browser_close_error!=null?String(e.browser_close_error):null,browser_provider:e.browser_provider!=null?String(e.browser_provider):null,provider_session_id:e.provider_session_id!=null?String(e.provider_session_id):null,provider_session_observed_at:e.provider_session_observed_at!=null?String(e.provider_session_observed_at):null,provider_lookup_status:e.provider_lookup_status!=null?String(e.provider_lookup_status):null,provider_status:e.provider_status!=null?String(e.provider_status):null,provider_error_code:e.provider_error_code!=null?String(e.provider_error_code):null,provider_error_message:e.provider_error_message!=null?String(e.provider_error_message):null,provider_reason_source:e.provider_reason_source!=null?String(e.provider_reason_source):null,provider_duration_ms:e.provider_duration_ms!=null?Number(e.provider_duration_ms):null,provider_bandwidth_bytes:e.provider_bandwidth_bytes!=null?Number(e.provider_bandwidth_bytes):null,provider_captcha:C(e.provider_captcha),provider_checked_at:e.provider_checked_at!=null?String(e.provider_checked_at):null,provider_detail:H(e.provider_detail_json),provider_disconnect_observed:C(e.provider_disconnect_observed),provider_disconnect_message:e.provider_disconnect_message!=null?String(e.provider_disconnect_message):null,debug:H(e.debug_json),created_at:String(e.created_at),completed_at:e.completed_at!=null?String(e.completed_at):null}}function h(e){let{public_error_json:t,...r}=e;return{...r,options:JSON.parse(e.options),result:e.result?JSON.parse(e.result):null,publicError:ae(t)}}async function ur(e,t,r,n){let s=N();return await it(s,e,t,r,n),s}async function it(e,t,r,n,s){if(!/^[a-zA-Z0-9-]{1,100}$/.test(e))throw new Error("job id is invalid");await i().execute({sql:"INSERT INTO jobs (id, user_id, query, options, callback_url) VALUES (?, ?, ?, ?, ?)",args:[e,t,r,JSON.stringify(n),s??null]})}async function cr(e,t,r){let n=N();return await i().execute({sql:"INSERT INTO jobs (id, user_id, query, options, status, started_at) VALUES (?, ?, ?, ?, 'running', datetime('now'))",args:[n,e,t,JSON.stringify(r)]}),n}async function dr(e,t,r,n){let s=await i().execute({sql:`INSERT INTO jobs (id, user_id, query, options, status, started_at)
986
986
  VALUES (?, ?, ?, ?, 'running', datetime('now'))
987
987
  ON CONFLICT(id) DO NOTHING`,args:[e,t,r,JSON.stringify(n)]}),a=await K(e,t);if(!a)throw new Error(`getOrCreateRunningJob: row missing immediately after insert/lookup for ${e}`);return{job:a,created:s.rowsAffected===1}}async function lr(e){await i().execute({sql:`
988
988
  INSERT INTO harvest_attempts (
@@ -1017,14 +1017,14 @@ import{createClient as Ve}from"@libsql/client/http";import{createHash as v,rando
1017
1017
  UPDATE harvest_attempts SET
1018
1018
  status = 'finished',
1019
1019
  outcome = ?,
1020
- kernel_session_id = ?,
1020
+ \u006b\u0065\u0072\u006e\u0065\u006c_session_id = ?,
1021
1021
  question_count = ?,
1022
1022
  duration_ms = ?,
1023
1023
  error = ?,
1024
1024
  will_retry = ?,
1025
- kernel_delete_started = ?,
1026
- kernel_delete_succeeded = ?,
1027
- kernel_delete_error = ?,
1025
+ \u006b\u0065\u0072\u006e\u0065\u006c_delete_started = ?,
1026
+ \u006b\u0065\u0072\u006e\u0065\u006c_delete_succeeded = ?,
1027
+ \u006b\u0065\u0072\u006e\u0065\u006c_delete_error = ?,
1028
1028
  browser_close_succeeded = ?,
1029
1029
  browser_close_error = ?,
1030
1030
  browser_provider = COALESCE(browser_provider, ?),
@@ -1056,7 +1056,7 @@ import{createClient as Ve}from"@libsql/client/http";import{createHash as v,rando
1056
1056
  debug_json = ?,
1057
1057
  completed_at = ?
1058
1058
  WHERE job_id = ? AND attempt_number = ?
1059
- `,args:[e.outcome,e.kernelSessionId,e.questionCount,e.durationMs,e.error,e.willRetry?1:0,e.kernelDeleteStarted?1:0,e.kernelDeleteSucceeded==null?null:e.kernelDeleteSucceeded?1:0,e.kernelDeleteError,e.browserCloseSucceeded==null?null:e.browserCloseSucceeded?1:0,e.browserCloseError,e.browserProvider??null,e.providerSessionId??null,e.providerLookupStatus??null,e.providerStatus??null,e.providerErrorCode??null,e.providerErrorMessage??null,e.providerReasonSource??null,e.providerDurationMs??null,e.providerBandwidthBytes??null,e.providerCaptcha==null?null:e.providerCaptcha?1:0,e.providerCheckedAt??null,e.providerDetail==null?null:Oe(e.providerDetail),e.providerDisconnectObserved==null?null:e.providerDisconnectObserved?1:0,e.providerDisconnectMessage??null,e.debug==null?null:JSON.stringify(e.debug),e.completedAt,e.jobId,e.attemptNumber]})}function Oe(e,t=4096){let r=JSON.stringify(e);return r.length<=t?r:JSON.stringify({truncated:!0})}async function mr(e){return(await i().execute({sql:`
1059
+ `,args:[e.outcome,e.\u006b\u0065\u0072\u006e\u0065\u006cSessionId,e.questionCount,e.durationMs,e.error,e.willRetry?1:0,e.\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted?1:0,e.\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded==null?null:e.\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded?1:0,e.\u006b\u0065\u0072\u006e\u0065\u006cDeleteError,e.browserCloseSucceeded==null?null:e.browserCloseSucceeded?1:0,e.browserCloseError,e.browserProvider??null,e.providerSessionId??null,e.providerLookupStatus??null,e.providerStatus??null,e.providerErrorCode??null,e.providerErrorMessage??null,e.providerReasonSource??null,e.providerDurationMs??null,e.providerBandwidthBytes??null,e.providerCaptcha==null?null:e.providerCaptcha?1:0,e.providerCheckedAt??null,e.providerDetail==null?null:Oe(e.providerDetail),e.providerDisconnectObserved==null?null:e.providerDisconnectObserved?1:0,e.providerDisconnectMessage??null,e.debug==null?null:JSON.stringify(e.debug),e.completedAt,e.jobId,e.attemptNumber]})}function Oe(e,t=4096){let r=JSON.stringify(e);return r.length<=t?r:JSON.stringify({truncated:!0})}async function mr(e){return(await i().execute({sql:`
1060
1060
  UPDATE harvest_attempts SET
1061
1061
  provider_lookup_status = ?,
1062
1062
  provider_status = ?,
@@ -1071,12 +1071,12 @@ import{createClient as Ve}from"@libsql/client/http";import{createHash as v,rando
1071
1071
  WHERE id = ?
1072
1072
  AND job_id = ?
1073
1073
  AND user_id = ?
1074
- AND browser_provider = 'bright_data_browser_api'
1074
+ AND browser_provider = '\u0062\u0072\u0069\u0067\u0068\u0074_\u0064\u0061\u0074\u0061_browser_api'
1075
1075
  AND provider_session_id = ?
1076
1076
  AND COALESCE(provider_lookup_status, '') <> 'complete'
1077
1077
  `,args:[e.lookupStatus,e.providerStatus??null,e.errorCode??null,e.errorMessage??null,e.reasonSource??null,e.durationMs??null,e.bandwidthBytes??null,e.captcha==null?null:e.captcha?1:0,e.checkedAt,e.detail==null?null:Oe(e.detail),e.attemptId,e.jobId,e.userId,e.providerSessionId]})).rowsAffected===1}async function Nr(e=25){let t=Math.max(1,Math.min(100,Math.trunc(e)));return(await i().execute({sql:`
1078
1078
  SELECT * FROM harvest_attempts
1079
- WHERE browser_provider = 'bright_data_browser_api'
1079
+ WHERE browser_provider = '\u0062\u0072\u0069\u0067\u0068\u0074_\u0064\u0061\u0074\u0061_browser_api'
1080
1080
  AND provider_session_id IS NOT NULL
1081
1081
  AND provider_lookup_status IN ('pending', 'temporary_error')
1082
1082
  ORDER BY COALESCE(provider_checked_at, created_at) ASC
@@ -1,4 +1,4 @@
1
- import{A as f,Ga as T,Ia as h,Ja as w,Ka as _,La as y,Ma as C,ga as g,ia as S,va as R,wa as E,ya as v,z as u}from"./chunk-QXAXPIHM.js";import{a as P}from"./chunk-ZJZMDWDI.js";import{a as m}from"./chunk-GCLSGYYE.js";import{readFileSync as N}from"fs";import{homedir as I}from"os";import{join as A}from"path";import{serveStdio as b}from"@modelcontextprotocol/server/stdio";import{McpServer as k}from"@modelcontextprotocol/server";var x=new Map(w.map(r=>[r.upstreamName,r.id]));function O(r){let s=r.split(`
1
+ import{A as f,Ga as T,Ia as h,Ja as w,Ka as _,La as y,Ma as C,ga as g,ia as S,va as R,wa as E,ya as v,z as u}from"./chunk-OD2WLHEN.js";import{a as P}from"./chunk-5QYW4CSJ.js";import{a as m}from"./chunk-AYQSKD7D.js";import{readFileSync as N}from"fs";import{homedir as I}from"os";import{join as A}from"path";import{serveStdio as b}from"@modelcontextprotocol/server/stdio";import{McpServer as k}from"@modelcontextprotocol/server";var x=new Map(w.map(r=>[r.upstreamName,r.id]));function O(r){let s=r.split(`
2
2
  `).filter(o=>o.startsWith("data:")).map(o=>o.slice(5).trim()).filter(Boolean);if(!s.length)return JSON.parse(r);for(let o of s){let e=JSON.parse(o);if(e.result||e.error)return e}throw new Error("hosted MCP returned no JSON-RPC result")}function a(r){return{content:[{type:"text",text:JSON.stringify({ok:!1,error:r})}],isError:!0}}var c=class{baseUrl;apiKey;constructor(s,o){this.baseUrl=s.replace(/\/$/,""),this.apiKey=o}async callMemoryTool(s,o){let e=x.get(s);if(!e)return a(`unknown memory tool: ${s}`);try{let n=await fetch(`${this.baseUrl}/mcp`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json, text/event-stream","x-api-key":this.apiKey},body:JSON.stringify({jsonrpc:"2.0",id:`memory:${e}`,method:"tools/call",params:{name:e,arguments:o}})}),l=await n.text();if(!n.ok)return a(`hosted memory ${e} failed (HTTP ${n.status})`);let t=O(l);return t.error?a(t.error.message??`hosted memory ${e} failed`):t.result??a(`hosted memory ${e} returned no result`)}catch(n){return a(n instanceof Error?n.message:`hosted memory ${e} call failed`)}}};function M(r,s){if(s.length===0)throw new Error("Restricted MCP tool allowlist must contain at least one tool name");let o=new Set;for(let t of s){if(typeof t!="string"||t.trim()!==t||t.length===0)throw new Error("Restricted MCP tool allowlist contains a malformed tool name");if(o.has(t))throw new Error(`Restricted MCP tool allowlist contains duplicate tool name: ${t}`);o.add(t)}let e=new Set,n=r,l=n.registerTool.bind(r);return n.registerTool=(t,i,p)=>{if(o.has(t))return e.add(t),l(t,i,p)},{assertComplete(){let t=[...o].filter(i=>!e.has(i));if(t.length>0)throw new Error(`Restricted MCP tool allowlist contains unknown or unavailable tool names: ${t.join(", ")}`)},registeredToolNames(){return[...e]}}}var L=new Set(["paa","serp","browser-agent","scheduled-results","memory"]);function $(){let s=[process.env.MCP_SCRAPER_KEY_PATH?.trim(),A(I(),".mcp-scraper-key")].filter(Boolean);for(let o of s)try{let e=N(o,"utf8").trim();if(e)return e}catch{}}function Y(r,s={}){let o=s.toolsets??L,e=process.env.MCP_SCRAPER_BASE_URL?.trim()||process.env.MCP_BASE_URL?.trim()||"https://mcpscraper.dev",n=g(),l=S({deploymentProfile:n,transportProfile:"stdio",baseUrl:e,explicitlyEnabled:process.env.MCP_SCRAPER_ALLOW_PRIVATE_NETWORK==="1"}),t=process.env.BROWSER_AGENT_CONSOLE_URL?.trim()||e,i=new k({name:"mcp-scraper",version:m},{instructions:u,cacheHints:{"server/discover":{ttlMs:3e5,cacheScope:"private"},"tools/list":{ttlMs:3e5,cacheScope:"private"},"prompts/list":{ttlMs:3e5,cacheScope:"private"},"resources/list":{ttlMs:3e5,cacheScope:"private"},"resources/templates/list":{ttlMs:3e5,cacheScope:"private"},"resources/read":{ttlMs:6e4,cacheScope:"private"}}});f(i);let p=s.allowedToolNames?M(i,s.allowedToolNames):void 0,d=s.httpExecutor??new T(e,r,{localNetworkAccess:l});return o.has("paa")&&v(i,d,{ownerId:R(r),deploymentProfile:n,transportProfile:"stdio",baseUrl:e,localNetworkAccess:l,taskHandleSecret:r}),o.has("serp")&&E(i,d,{exposeDevelopmentDiagnostics:n==="development"||n==="test"}),o.has("browser-agent")&&h(i,{baseUrl:e,apiKey:r,consoleBaseUrl:t}),o.has("scheduled-results")&&C(i,new y(e,r)),o.has("memory")&&_(i,new c(e,r)),p?.assertComplete(),i}function se(r={}){let s=process.argv.includes("--stdio")||process.env.MCP_SCRAPER_FORCE_STDIO==="1",o=!!(process.stdin.isTTY&&process.stdout.isTTY),e=process.argv.includes("--help")||process.argv.includes("-h");if(!s&&(o||e)){let l=process.argv.includes("--no-color")||process.env.NO_COLOR!==void 0||process.env.FORCE_COLOR==="0"||!process.stdout.isTTY;process.stdout.write(P({version:m,color:!l,apiKeyConfigured:!!process.env.MCP_SCRAPER_API_KEY?.trim()})),process.exit(0)}let n=(process.env.MCP_SCRAPER_API_KEY??process.env.MCP_SCRAPER_KEY??process.env.MCP_API_KEY??$())?.trim();n||(process.stderr.write(`MCP_SCRAPER_API_KEY env var or ~/.mcp-scraper-key is required
3
3
  `),process.exit(1)),b(()=>Y(n,r),{legacy:"serve",onerror(l){process.stderr.write(`${l.message}
4
4
  `)}})}export{se as a};
@@ -0,0 +1 @@
1
+ import{z as e}from"zod";var i="none",a="none";function c(t){switch(t){case"day":return"qdr:d";case"week":return"qdr:w";case"month":return"qdr:m";case"year":return"qdr:y";default:return}}var u=e.object({businessName:e.string().min(1),location:e.string().min(1),gl:e.string().length(2).default("us"),hl:e.string().length(2).default("en"),includeReviews:e.boolean().default(!1),maxReviews:e.number().int().min(1).max(500).default(50),includeServices:e.boolean().default(!1),includeImages:e.boolean().default(!1),imageScope:e.enum(["owner","all"]).default("all"),maxImages:e.number().int().min(1).max(250).default(100),maxInlineImages:e.number().int().min(0).max(5).default(3),\u006b\u0065\u0072\u006e\u0065\u006cApiKey:e.string().optional(),\u006b\u0065\u0072\u006e\u0065\u006cProxyId:e.string().optional(),headless:e.boolean().default(!0)}),g=e.object({query:e.string().min(1),location:e.string().optional(),gl:e.string().length(2).default("us"),hl:e.string().length(2).default("en"),maxResults:e.number().int().min(1).max(50).default(10),includeServices:e.boolean().default(!1),proxyMode:e.enum(["location","configured","none"]).default(a),proxyZip:e.string().regex(/^\d{5}$/).optional(),serpRedirect:e.boolean().optional(),forceDirectEgress:e.boolean().optional(),debug:e.boolean().default(!1),\u006b\u0065\u0072\u006e\u0065\u006cApiKey:e.string().optional(),\u006b\u0065\u0072\u006e\u0065\u006cProxyId:e.string().optional(),\u006b\u0065\u0072\u006e\u0065\u006cProxyResolution:e.unknown().optional(),headless:e.boolean().default(!0)}),p=e.object({name:e.string().nullable(),rating:e.string().nullable(),reviewCount:e.string().nullable(),category:e.string().nullable(),address:e.string().nullable(),hoursSummary:e.string().nullable(),phone:e.string().nullable(),phoneDisplay:e.string().nullable(),website:e.string().nullable(),plusCode:e.string().nullable(),bookingUrl:e.string().nullable()}),d=e.object({day:e.string(),hours:e.string()}),b=e.object({reviewHistogram:e.array(e.object({stars:e.number(),count:e.string()})),reviewTopics:e.array(e.object({label:e.string(),count:e.string()}))}),m=e.object({reviewId:e.string(),author:e.string().nullable(),stars:e.string().nullable(),date:e.string().nullable(),text:e.string().nullable(),ownerResponse:e.string().nullable()}),f=e.object({section:e.string(),attribute:e.string()});async function R(t){if((process.env.NODE_ENV==="test"||process.env.VITEST)&&process.env.MCP_SCRAPER_ENABLE_MEMORY_LIBRARY_SINK_IN_TESTS!=="1")return;let r=process.env.MCP_SCRAPER_API_KEY?.trim(),s=(process.env.MCP_SCRAPER_BASE_URL??"https://mcpscraper.dev").replace(/\/$/,"");if(r)try{let n=await fetch(`${s}/memory/mcp-call`,{method:"POST",headers:{"content-type":"application/json","x-api-key":r},body:JSON.stringify({toolName:"libraryIngestTool",args:t})}),o=await n.json().catch(()=>null);(!n.ok||o?.ok===!1)&&console.warn("[memory-library-sink] ingest not accepted:",n.status,o?.error??"")}catch(n){console.warn("[memory-library-sink] ingest failed:",n?.message)}}export{i as a,a as b,c,u as d,g as e,p as f,d as g,b as h,f as i,R as j};
@@ -1,4 +1,4 @@
1
- import{c as Ge,h as ke,i as Qe,j as Ve,l as et}from"./chunk-IK5BG7MO.js";import"./chunk-XG6GCEUE.js";import{b as Ye,c as Xe,h as Ze,j as Ke}from"./chunk-QHHOKLQY.js";import"./chunk-M5QHXNFZ.js";import{c as ze,e as Fe,f as He,g as We}from"./chunk-W2BVJ7S2.js";import{c as Je}from"./chunk-RK2VCTZI.js";import"./chunk-ORB4RHCK.js";import"./chunk-TMB56NCA.js";import"./chunk-RSPA4IWH.js";import"./chunk-6DTXIZY2.js";import"./chunk-HE45FFBU.js";import{t as qe}from"./chunk-WJ4XFLS4.js";import{createWriteStream as se,mkdirSync as ie,readFileSync as xt,readdirSync as kt,rmSync as _t,statSync as Pt,writeFileSync as g}from"fs";import{createHash as G}from"crypto";import{basename as Mt,join as a}from"path";import{tmpdir as It}from"os";import{createGzip as Ct}from"zlib";import{once as Y}from"events";import{finished as ae}from"stream/promises";import{ZipFile as At}from"yazl";import Rt from"p-limit";import{createHash as _e}from"crypto";var gt=500,ht=.9,ft=1e4,yt=5e4;function ge(r,s){let n=10**s;return Math.round(r*n)/n}function wt(r,s){if(r.length===0||r.length!==s.length)throw new Error("Similarity vectors must have the same non-zero dimension.");let n=0,c=0,b=0;for(let w=0;w<r.length;w++)n+=r[w]*s[w],c+=r[w]*r[w],b+=s[w]*s[w];return c===0||b===0?0:Math.max(-1,Math.min(1,n/(Math.sqrt(c)*Math.sqrt(b))))}function St(r){let s=_e("sha256");for(let n of[...r].sort((c,b)=>c.url.localeCompare(b.url)))s.update(n.url),s.update("\0"),s.update(n.contentHash),s.update("\0");return s.digest("hex")}function tt(r){let s=r.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/https?:\/\/\S+/gi," ").replace(/&(?:amp|nbsp|quot|#39);/gi," ").replace(/[#>*_`~|\\-]+/g," ").replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim().toLowerCase();return s.length>=12?s:null}function bt(r){let s=r.map(f=>f.bodyMarkdown.split(/\n{2,}/).map(M=>M.trim()).filter(Boolean)),n=r.length>=4?Math.max(3,Math.ceil(r.length*.5)):null,c=new Map;for(let f of s){let M=new Set(f.map(tt).filter(I=>!!I));for(let I of M)c.set(I,(c.get(I)??0)+1)}let b=new Set;if(n!=null)for(let[f,M]of c)M>=n&&b.add(f);let w=0;return{texts:r.map((f,M)=>{let I=[];for(let _ of s[M]){let T=tt(_);if(T&&b.has(T)){w+=_.length;continue}I.push(_)}let A=I.join(`
1
+ import{c as Ge,h as ke,i as Qe,j as Ve,l as et}from"./chunk-IK5BG7MO.js";import"./chunk-XG6GCEUE.js";import{b as Ye,c as Xe,h as Ze,j as Ke}from"./chunk-5JKBFNYF.js";import"./chunk-M5QHXNFZ.js";import{c as ze,e as Fe,f as He,g as We}from"./chunk-W2BVJ7S2.js";import{c as Je}from"./chunk-RK2VCTZI.js";import"./chunk-ORB4RHCK.js";import"./chunk-TMB56NCA.js";import"./chunk-UN6FVDJQ.js";import"./chunk-6DTXIZY2.js";import"./chunk-HE45FFBU.js";import{t as qe}from"./chunk-WJ4XFLS4.js";import{createWriteStream as se,mkdirSync as ie,readFileSync as xt,readdirSync as kt,rmSync as _t,statSync as Pt,writeFileSync as g}from"fs";import{createHash as G}from"crypto";import{basename as Mt,join as a}from"path";import{tmpdir as It}from"os";import{createGzip as Ct}from"zlib";import{once as Y}from"events";import{finished as ae}from"stream/promises";import{ZipFile as At}from"yazl";import Rt from"p-limit";import{createHash as _e}from"crypto";var gt=500,ht=.9,ft=1e4,yt=5e4;function ge(r,s){let n=10**s;return Math.round(r*n)/n}function wt(r,s){if(r.length===0||r.length!==s.length)throw new Error("Similarity vectors must have the same non-zero dimension.");let n=0,c=0,b=0;for(let w=0;w<r.length;w++)n+=r[w]*s[w],c+=r[w]*r[w],b+=s[w]*s[w];return c===0||b===0?0:Math.max(-1,Math.min(1,n/(Math.sqrt(c)*Math.sqrt(b))))}function St(r){let s=_e("sha256");for(let n of[...r].sort((c,b)=>c.url.localeCompare(b.url)))s.update(n.url),s.update("\0"),s.update(n.contentHash),s.update("\0");return s.digest("hex")}function tt(r){let s=r.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/https?:\/\/\S+/gi," ").replace(/&(?:amp|nbsp|quot|#39);/gi," ").replace(/[#>*_`~|\\-]+/g," ").replace(/[^\p{L}\p{N}]+/gu," ").replace(/\s+/g," ").trim().toLowerCase();return s.length>=12?s:null}function bt(r){let s=r.map(f=>f.bodyMarkdown.split(/\n{2,}/).map(M=>M.trim()).filter(Boolean)),n=r.length>=4?Math.max(3,Math.ceil(r.length*.5)):null,c=new Map;for(let f of s){let M=new Set(f.map(tt).filter(I=>!!I));for(let I of M)c.set(I,(c.get(I)??0)+1)}let b=new Set;if(n!=null)for(let[f,M]of c)M>=n&&b.add(f);let w=0;return{texts:r.map((f,M)=>{let I=[];for(let _ of s[M]){let T=tt(_);if(T&&b.has(T)){w+=_.length;continue}I.push(_)}let A=I.join(`
2
2
 
3
3
  `).trim(),C=A.length>=60?A:f.bodyMarkdown;return`${f.title?.trim()||"Untitled page"}
4
4
 
@@ -1 +1 @@
1
- import{e as a,f as b,g as c,h as d,i as e,j as f,k as g,l as h}from"./chunk-T2IJVEHG.js";import"./chunk-TCLSPE3P.js";import"./chunk-QTDLZTQ7.js";import"./chunk-HUV2WTRW.js";import"./chunk-RSPA4IWH.js";import"./chunk-2SP57VCG.js";import"./chunk-6DTXIZY2.js";import"./chunk-WJ4XFLS4.js";export{d as GMAIL_ATTACHMENT_REF_TTL_MS,c as GMAIL_INLINE_BODY_BYTES,b as GMAIL_MAIN_CONTRACT_HASH,a as GMAIL_MAIN_CONTRACT_VERSION,h as GmailService,e as GmailServiceError,g as normalizeGmailMessage,f as parseGmailAddresses};
1
+ import{e as a,f as b,g as c,h as d,i as e,j as f,k as g,l as h}from"./chunk-NLKA6SHC.js";import"./chunk-IJF4VXJ7.js";import"./chunk-QTDLZTQ7.js";import"./chunk-HUV2WTRW.js";import"./chunk-UN6FVDJQ.js";import"./chunk-2SP57VCG.js";import"./chunk-6DTXIZY2.js";import"./chunk-WJ4XFLS4.js";export{d as GMAIL_ATTACHMENT_REF_TTL_MS,c as GMAIL_INLINE_BODY_BYTES,b as GMAIL_MAIN_CONTRACT_HASH,a as GMAIL_MAIN_CONTRACT_VERSION,h as GmailService,e as GmailServiceError,g as normalizeGmailMessage,f as parseGmailAddresses};