mcp-scraper 0.88.2 → 0.89.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.
- package/CHANGELOG.md +41 -2
- package/README.md +6 -3
- package/dist/analytics-repository-J25XR5E7.js +1 -0
- package/dist/bin/api-server.js +2 -41
- package/dist/bin/mcp-scraper-cli.js +39 -756
- package/dist/bin/mcp-scraper-core.js +1 -60
- package/dist/bin/mcp-scraper-install.js +2 -25
- package/dist/bin/mcp-stdio-server.js +1 -19
- package/dist/bin/paa-harvest.js +1 -41
- package/dist/chunk-3GP5CYZX.js +1 -0
- package/dist/chunk-4FROKQJN.js +1 -0
- package/dist/chunk-57AHYL2O.js +20 -0
- package/dist/chunk-5H3MCTTP.js +1 -0
- package/dist/chunk-63T4W2LX.js +1271 -0
- package/dist/chunk-645LQBE7.js +2595 -0
- package/dist/chunk-6QO4F2KC.js +21710 -0
- package/dist/chunk-CCYWSJNG.js +16 -0
- package/dist/chunk-D6IQJP64.js +84 -0
- package/dist/chunk-DGBLGFNJ.js +182 -0
- package/dist/chunk-FFPD2DOF.js +59 -0
- package/dist/chunk-FXEWHK54.js +1 -0
- package/dist/chunk-HE45FFBU.js +1 -0
- package/dist/chunk-HUV2WTRW.js +1 -0
- package/dist/chunk-IJ2AO7AO.js +102 -0
- package/dist/chunk-KJQXUZ4Y.js +4 -0
- package/dist/chunk-MEM4D2QN.js +1280 -0
- package/dist/chunk-MZN4U5BL.js +1 -0
- package/dist/chunk-PRWZNHQB.js +1 -0
- package/dist/chunk-QPWPR5XG.js +10 -0
- package/dist/chunk-RYNHNEF3.js +73 -0
- package/dist/chunk-TMB56NCA.js +1 -0
- package/dist/chunk-W2BVJ7S2.js +13 -0
- package/dist/chunk-WO3N5FH2.js +5 -0
- package/dist/chunk-XLWNEVUZ.js +27 -0
- package/dist/chunk-YQZGZBB4.js +1 -0
- package/dist/chunk-YUPLOOTB.js +4 -0
- package/dist/chunk-ZHORX44A.js +100 -0
- package/dist/db-JJWJLAVQ.js +1 -0
- package/dist/extract-bundle-TTSEGWYF.js +26 -0
- package/dist/gmail-service-34PIJRLK.js +1 -0
- package/dist/index.cjs +21838 -6034
- package/dist/index.js +18 -315
- package/dist/lead-list-enrichment-repository-VJBBMBCG.js +1 -0
- package/dist/location-data-repository-W3LPT6G3.js +1 -0
- package/dist/server-UEY5YQL6.js +7329 -0
- package/dist/site-extract-repository-7W5ZUNPR.js +1 -0
- package/dist/worker-ZOTOKG56.js +1 -0
- package/package.json +11 -4
- package/dist/analytics-repository-GGJJCVVP.js +0 -194
- package/dist/chunk-4QMUF6XM.js +0 -1013
- package/dist/chunk-6HAV7LCE.js +0 -265
- package/dist/chunk-ABF2CGOZ.js +0 -113
- package/dist/chunk-C5Z4OFKW.js +0 -404
- package/dist/chunk-DNM65UCK.js +0 -299
- package/dist/chunk-EQGTEHLZ.js +0 -592
- package/dist/chunk-F5GQJWZU.js +0 -732
- package/dist/chunk-GGZEC22A.js +0 -215
- package/dist/chunk-GXBZXWXB.js +0 -184
- package/dist/chunk-IHXAXYIS.js +0 -843
- package/dist/chunk-K3Z5AQYE.js +0 -683
- package/dist/chunk-K45K75OF.js +0 -6
- package/dist/chunk-LFW2FRPJ.js +0 -224
- package/dist/chunk-MZDNZQWT.js +0 -2078
- package/dist/chunk-NVUKO5NN.js +0 -256
- package/dist/chunk-OM7HVEJ3.js +0 -26
- package/dist/chunk-OPQIGAFB.js +0 -286
- package/dist/chunk-OZJMVCDK.js +0 -16
- package/dist/chunk-P7FWOMU7.js +0 -505
- package/dist/chunk-PGJQDMC2.js +0 -383
- package/dist/chunk-PKZS6SHW.js +0 -33139
- package/dist/chunk-RJ7JVYKU.js +0 -68
- package/dist/chunk-S24LFPL7.js +0 -5262
- package/dist/chunk-T3MZISOF.js +0 -240
- package/dist/chunk-UZPTGUDV.js +0 -1915
- package/dist/chunk-X623GTBV.js +0 -8290
- package/dist/chunk-YXNDOQXN.js +0 -4018
- package/dist/db-Z34LPZNR.js +0 -284
- package/dist/extract-bundle-565SBZCR.js +0 -1003
- package/dist/gmail-service-E6ALS7JG.js +0 -25
- package/dist/lead-list-enrichment-repository-36RPVV6N.js +0 -67
- package/dist/location-data-repository-WPRG62GE.js +0 -34
- package/dist/server-SQZ3A7SY.js +0 -86606
- package/dist/site-extract-repository-VYFZASPU.js +0 -69
- package/dist/worker-LDCAULWL.js +0 -146
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var p={schemaVersion:1,ratePolicy:{version:"serp-paa-2026-08-11",effectiveDate:"2026-08-11T00:00:00.000Z"},costEvidence:{id:"serp-paa-rate-basis-2026-08",status:"provisional",minimumRevenueCostRatio:2.5,observedRevenueCostRatio:2.5160607750756583},operationCosts:{serp:{credits:60,unit:"per search",label:"SERP search",notes:"Returns organic results and Google entity IDs by default; optional same-page local pack, forums, videos, AI surfaces, and What People Are Saying are enabled with flags at the same product price. search_serp and the base capture_serp_snapshot search are billed 60 credits per search. Optional SERP Intelligence 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."},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:376,scraperTools:250,memoryTools:126},concurrencyPack:{ratePolicyVersion:"2026-08-14.concurrency-pack-v1",monthlyUsd:5,currency:"usd",interval:"month",billingUnit:"pack",slotsPerPack:2},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,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 re(e){return e===!0?t.serp_headless:t.serp_headful}var B=t.browser_minute/6e4;function te(e){return Math.round(e*B)}var ie=1e3,o=100,ne=t.serp_headful/o,se=t.paa_base/o,ae=t.paa/o,oe=t.page_scrape/o,F={billingMode:"credits",chargeEvent:"accepted_write",validationCredits:0,create:{credits:t.listing_create/o,mc:t.listing_create},edit:{credits:t.listing_edit/o,mc:t.listing_edit},surfaces:["local_sourcebook","transparent_commons"],sourcebookAcquisitionIncluded:!0},G=2e6,Y=3,C=1e4,E=1e9,q=75,ce=q*o,V=15e3,le=V/C,_e=5e3,H="2026-08-03.connected-usage-v3",y=15e3,de=y*o,T=2,v=2,S=5,A=T*o,N=v*o,I=S*o,ue={schemaVersion:2,ratePolicyVersion:H,effectiveAt:"2026-08-03T00:00:00.000Z",provider:"nango",entitlement:"paid_plan_add_on",connection:{billingMode:"flat_recurring_credits",amountCredits:y,interval:"month",unit:"active_connection",proration:"none"},usage:{billingMode:"credits",settlementMode:"authoritative_receipt",rounding:"aggregate_then_ceil_to_mc",functionRun:{credits:T,mc:A,unit:"per_function_run"},proxyRequest:{credits:v,mc:N,unit:"per_proxy_request"},compute:{creditsPerSecond:S,mcPerSecond:I,sourceUnit:"millisecond",unit:"per_compute_second",formula:"ceil(computeMilliseconds * mcPerSecond / 1000)"}}};function m(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 pe(e){let r=m(e.functionRuns,"functionRuns"),a=m(e.proxyRequests,"proxyRequests"),s=m(e.computeMilliseconds,"computeMilliseconds"),n=r*BigInt(A),c=a*BigInt(N),l=s*BigInt(I),u=l===0n?0n:(l+999n)/1000n,R=n+c+u;return{functionRunMc:_(n),proxyRequestMc:_(c),computeMc:_(u),amountMc:_(R),credits:_(R)/o}}function me(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 s=BigInt(Math.round(e*E))*BigInt(r)*BigInt(G),n=BigInt(E)*BigInt(C)*BigInt(Y),c=s===0n?0n:(s+n-1n)/n;if(c>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("calculated mc exceeds the safe integer range");return Number(c)}var W=[{key:"serp",label:"SERP search",aliases:["search_serp","serp","google search","organic results"],credits:i(t.serp_headful),unit:"per search",notes:`Returns organic results and Google entity IDs by default; optional same-page local pack, forums, videos, AI surfaces, and What People Are Saying are enabled with flags at the same product price. search_serp and the base capture_serp_snapshot search are billed ${i(t.serp_headful)} credits per search. Optional SERP Intelligence 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:"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."}],ge="price_1Ta1NRS8aAcsk3TGwsRnYbix";function w(e){return e.billing_interval??"month"}function O(e){return e.billed_usd??e.monthly_usd}function M(e){return e.credits_mc/o}var d={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}},b=Object.fromEntries(Object.values(d).map(e=>[e.tier,e])),f={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 $(e){let r=Object.values(f).find(a=>a.tier_keys.includes(e));return r?`/${r.slug}/claim`:null}function K(e){return e?Object.values(f).find(r=>r.tier_keys.includes(e))??null:null}function be(e,r){let a=K(e);return a?!a.tier_keys.includes(r):!1}function fe(e){if(!e)return null;let r=b[e];return r?{tier:r.tier,label:r.label,amount_usd:O(r),interval:w(r),monthly_equivalent_usd:r.monthly_usd,credits_per_interval:M(r),concurrency:r.concurrency,credits_never_expire:!!r.credits_never_expire,includes_memory:!!r.includes_memory,private_offer:!!r.private_offer,offer_claim_path:$(r.tier)}:null}function Re(e){let r=f[e];if(!r)return null;let a=r.tier_keys.map(s=>b[s]).filter(s=>!!s).map(s=>({tier:s.tier,label:s.label,amount_usd:O(s),interval:w(s),monthly_equivalent_usd:s.monthly_usd,credits:M(s),credits_never_expire:!!s.credits_never_expire,includes_memory:!!s.includes_memory,concurrency:s.concurrency}));return a.length?{slug:r.slug,label:r.label,headline:r.headline,options:a}:null}function Ee(){let e=b.starter,r=W.map(({aliases:n,...c})=>({...c,...c.notes?{notes:c.notes.replace(/ via fal\.ai/g,"")}:{}})),a=Object.fromEntries(r.map(n=>[n.key,{credits:n.credits,unit:n.unit,label:n.label,...n.notes?{notes:n.notes}:{}}])),s=Object.values(d).filter(n=>!n.private_offer).map(n=>({tier:n.tier,label:n.label,monthlyUsd:n.monthly_usd,credits:n.credits_mc/o,concurrency:n.concurrency}));return{...p,operationCosts:a,publicTiers:s,concurrencyPack:{ratePolicyVersion:L,monthlyUsd:x,currency:k,interval:U,billingUnit:"pack",slotsPerPack:g},creditsPerDollarStarter:Math.round(i(e.credits_mc)/e.monthly_usd),costs:r,scheduling:p.addons.scheduling,connectedAccounts:p.addons.connectedAccounts,listingWrites:F}}var x=5,k="usd",U="month",g=2,L="2026-08-14.concurrency-pack-v1",Z="$5/month for 2 extra browsers",he="MCP Scraper browser concurrency pack \u2014 each $5 monthly pack adds 2 browsers.",Ce="Billed monthly until canceled. A receipt is emailed after each successful payment.",h="npx -y -p mcp-scraper@latest mcp-scraper-cli billing concurrency checkout";function ye(){let e=process.env.CONCURRENCY_BILLING_URL??"https://mcpscraper.dev/billing";return{product:"Extra browser concurrency pack",rate_policy_version:L,price_label:Z,unit_amount_usd:x,currency:k,interval:U,billing_unit:"pack",pack_quantity:1,slots_per_pack:g,extra_slots:g,billing_url:e,terminal_command:h,terminal_command_with_api_key_env:`MCP_SCRAPER_API_KEY=sk_live_your_key ${h}`}}function i(e){return e/o}var Q="npx -y -p mcp-scraper@latest mcp-scraper-cli billing subscribe";function j(){return Object.values(d).filter(e=>!e.private_offer).sort((e,r)=>e.credits_mc-r.credits_mc)}function Te(e,r){let a=process.env.TOPUP_URL??"https://mcpscraper.dev/billing",s=i(e),n=i(r),c=j().map(u=>u.tier).join("|"),l=`${Q} <${c}>`;return{error:"insufficient_balance",error_code:"insufficient_balance",message:`Insufficient credits. Balance: ${s} credits. This call requires ${n} credits. Credits refresh when your plan renews; for more now, move to a larger plan at ${a} (terminal: ${l})`,balance_credits:s,required_credits:n,topup_url:a,upgrade_command:l}}var X=1e7*1,ve={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}},Se={free:X,pro:5e9,team:5e10},z=3;var Ae=19/z,Ne={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",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",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"},Ie=3,we=1.5,Oe=1.5,P=2e4,D=200;function Me(e){let r=Math.max(1,Math.ceil((e||60)/60));return P+D*r}var xe=P+D*30,ke=d.price_1TmiHRS8aAcsk3TGwmSNfNIa.credits_mc/d.price_1TmiHRS8aAcsk3TGwmSNfNIa.monthly_usd;export{t as a,re as b,te as c,ie as d,o as e,ne as f,se as g,ae as h,oe as i,F as j,E as k,q as l,ce as m,V as n,le as o,_e as p,H as q,y as r,de as s,T as t,v as u,S as v,A as w,ue as x,pe as y,me as z,W as A,ge as B,w as C,O as D,M as E,d as F,b as G,$ as H,K as I,be as J,fe as K,Re as L,Ee as M,x as N,g as O,he as P,Ce as Q,ye as R,i as S,Te as T,ve as U,Se as V,Ne as W,Ie as X,we as Y,Oe as Z,Me as _,xe as $,ke as aa};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as m}from"./chunk-YQZGZBB4.js";import{b as n,da as p,ea as d,g as o,ga as b,h as i,j as l,m as u,o as c}from"./chunk-63T4W2LX.js";function f(e){return e instanceof Error?e.message:String(e)}function y(e,t){return e instanceof DOMException&&(e.name==="TimeoutError"||e.name==="AbortError")?!0:/timeout|timed out|Timeout \d+ms exceeded|deadline/i.test(t)}function g(e){return/captcha|recaptcha|unusual traffic|google\.com\/sorry|blocked/i.test(e)}function S(e){return/ERR_TUNNEL_CONNECTION_FAILED|ERR_PROXY_CONNECTION_FAILED|ERR_SOCKS_CONNECTION_FAILED|tunnel connection failed|proxy connection failed|transport error: proxy/i.test(e)}function E(e){return/proxy unavailable|proxy_unavailable|connection_test_failed|did not return a proxy id|configured fallback/i.test(e)}function h(e){return/(?:spending|billing|organization|account).{0,80}(?:cap|limit|blocked|disabled)|(?:quota|capacity).{0,40}(?:reached|exceeded)|https?:\/\/\S*dashboard/i.test(e)}function v(e){return/browser (?:has been )?closed|context (?:has been )?closed|target page, context or browser has been closed|session closed|page has been closed/i.test(e)}function x(e){let t=f(e);return e instanceof u?{error_code:"request_aborted",error_type:"request_aborted",message:o("request_aborted"),retryable:!0,httpStatus:408,terminalStatus:"cancelled"}:e instanceof l||g(t)?{error_code:"captcha_exhausted",error_type:"captcha",message:o("captcha_exhausted"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:m(e,t)?{error_code:"vendor_unavailable",error_type:"service_unavailable",message:o("vendor_unavailable"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:e instanceof c?{error_code:"location_mismatch",error_type:"location_mismatch",message:o("location_mismatch"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:S(t)?{error_code:"proxy_tunnel_failed",error_type:"connection",message:o("proxy_tunnel_failed"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:E(t)?{error_code:"proxy_unavailable",error_type:"connection",message:o("proxy_unavailable"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:v(t)?{error_code:"browser_session_interrupted",error_type:"extraction",message:o("browser_session_interrupted"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:y(e,t)?{error_code:"harvest_timeout",error_type:"timeout",message:o("harvest_timeout"),retryable:!0,httpStatus:504,terminalStatus:"failed"}:h(t)?{error_code:"service_unavailable",error_type:"service_unavailable",message:n,retryable:!0,httpStatus:503,terminalStatus:"failed"}:{error_code:"extraction_failed",error_type:"extraction",message:n,retryable:!1,httpStatus:500,terminalStatus:"failed"}}function w(e){return JSON.stringify({error_code:e.error_code,error_type:e.error_type,message:e.message,retryable:e.retryable})}function _(e,t={}){let r=i({errorCode:e.error_code,errorType:e.error_type,retryable:e.retryable,retryAfterSeconds:t.retryAfterSeconds,chargeStatus:t.chargeStatus,details:t.details});return{error:r.message,...r}}function A(e,t={}){let{error:r,...a}=_(e,t);return a}function C(e,t={}){let r=x(e);return{body:_(r,t),status:r.httpStatus}}function D(e,t){return async r=>{if(r.type==="started"){await p({jobId:e,userId:t,attemptNumber:r.attemptNumber,maxAttempts:r.maxAttempts,query:r.query,location:r.location,maxQuestions:r.maxQuestions,startedAt:r.startedAt});return}if(r.type==="provider_session_started"){await d({jobId:e,attemptNumber:r.attemptNumber,browserProvider:r.provider,providerSessionId:r.providerSessionId,observedAt:r.observedAt});return}await b({jobId:e,attemptNumber:r.attemptNumber,outcome:r.outcome,kernelSessionId:r.kernelSessionId,questionCount:r.questionCount,durationMs:r.durationMs,error:r.error,willRetry:r.willRetry,kernelDeleteStarted:r.cleanup.kernelDeleteStarted,kernelDeleteSucceeded:r.cleanup.kernelDeleteSucceeded,kernelDeleteError:r.cleanup.kernelDeleteError,browserCloseSucceeded:r.cleanup.browserCloseSucceeded,browserCloseError:r.cleanup.browserCloseError,browserProvider:r.cleanup.provider??null,providerSessionId:r.cleanup.providerSessionId??null,providerLookupStatus:r.cleanup.providerSessionId?"pending":"not_applicable",providerErrorCode:r.cleanup.providerDisconnectObserved?"browser_session_interrupted":null,providerErrorMessage:r.cleanup.providerDisconnectMessage??null,providerReasonSource:r.cleanup.providerDisconnectObserved?"client_runtime":null,providerDisconnectObserved:r.cleanup.providerDisconnectObserved??!1,providerDisconnectMessage:r.cleanup.providerDisconnectMessage??null,debug:r.debug,completedAt:r.completedAt})}}async function I(e,t,r=3){for(let a=1;a<=r;a++){try{let s=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t),signal:AbortSignal.timeout(1e4)});if(s.ok)return;console.warn(`[webhook] attempt ${a} \u2192 ${s.status} from ${e}`)}catch(s){console.warn(`[webhook] attempt ${a} failed:`,s instanceof Error?s.message:s)}a<r&&await new Promise(s=>setTimeout(s,1e3*a*2))}console.error(`[webhook] gave up after ${r} attempts for ${e}`)}export{x as a,w as b,_ as c,A as d,C as e,D as f,I as g};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
function S(r,e,t,n,o){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!o:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?o.call(r,t):o?o.value=t:e.set(r,t),t}function _(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}var ct=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return ct=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};function Ue(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var ve=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};var x=class extends Error{},I=class r extends x{constructor(e,t,n,o){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=o,this.error=t}static makeMessage(e,t,n){let o=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,t,n,o){if(!e||!o)return new K({message:n,cause:ve(t)});let s=t;return e===400?new fe(e,s,n,o):e===401?new de(e,s,n,o):e===403?new pe(e,s,n,o):e===404?new he(e,s,n,o):e===409?new me(e,s,n,o):e===422?new ye(e,s,n,o):e===429?new ge(e,s,n,o):e>=500?new we(e,s,n,o):new r(e,s,n,o)}},T=class extends I{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},K=class extends I{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},D=class extends K{constructor({message:e}={}){super({message:e??"Request timed out."})}},fe=class extends I{},de=class extends I{},pe=class extends I{},he=class extends I{},me=class extends I{},ye=class extends I{},ge=class extends I{},we=class extends I{};var Er=/^[a-z][a-z0-9+.-]*:/i,vt=r=>Er.test(r),$=r=>($=Array.isArray,$(r)),lt=$;function ut(r){return typeof r!="object"?{}:r??{}}function ft(r){if(!r)return!0;for(let e in r)return!1;return!0}function Dt(r,e){return Object.prototype.hasOwnProperty.call(r,e)}var Nt=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new x(`${r} must be an integer`);if(e<0)throw new x(`${r} must be a positive integer`);return e},Sr=r=>{if(typeof r=="number")return Math.round(r);if(typeof r=="string")return parseInt(r,10);throw new x(`Could not coerce ${r} (type: ${typeof r}) into a number`)};var Ir=r=>typeof r=="boolean"?r:typeof r=="string"?r==="true":!!r,Ht=r=>{if(r!=null)return Sr(r)};var dt=r=>{if(r!=null)return Ir(r)},Bt=r=>{try{return JSON.parse(r)}catch{return}};var Mt=r=>new Promise(e=>setTimeout(e,r));var W="0.93.0";function $r(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var Lr=()=>{let r=$r();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":Kt(Deno.build.os),"X-Stainless-Arch":qt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":Kt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":qt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Tr();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":W,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Tr(){if(typeof navigator>"u"||!navigator)return null;let r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let o=n[1]||0,s=n[2]||0,a=n[3]||0;return{browser:e,version:`${o}.${s}.${a}`}}}return null}var qt=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",Kt=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),Wt,Xt=()=>Wt??(Wt=Lr());function zt(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Kernel({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function pt(...r){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}function ze(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return pt({start(){},async pull(t){let{done:n,value:o}=await e.next();n?t.close():t.enqueue(o)},async cancel(){await e.return?.()}})}function ht(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Vt(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}var Jt=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var mt="RFC3986",yt=r=>String(r),gt={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:yt},Gt="RFC1738";var Ve=(r,e)=>(Ve=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ve(r,e)),v=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})();var wt=1024,Qt=(r,e,t,n,o)=>{if(r.length===0)return r;let s=r;if(typeof r=="symbol"?s=Symbol.prototype.toString.call(r):typeof r!="string"&&(s=String(r)),t==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let a="";for(let c=0;c<s.length;c+=wt){let f=s.length>=wt?s.slice(c,c+wt):s,d=[];for(let m=0;m<f.length;++m){let l=f.charCodeAt(m);if(l===45||l===46||l===95||l===126||l>=48&&l<=57||l>=65&&l<=90||l>=97&&l<=122||o===Gt&&(l===40||l===41)){d[d.length]=f.charAt(m);continue}if(l<128){d[d.length]=v[l];continue}if(l<2048){d[d.length]=v[192|l>>6]+v[128|l&63];continue}if(l<55296||l>=57344){d[d.length]=v[224|l>>12]+v[128|l>>6&63]+v[128|l&63];continue}m+=1,l=65536+((l&1023)<<10|f.charCodeAt(m)&1023),d[d.length]=v[240|l>>18]+v[128|l>>12&63]+v[128|l>>6&63]+v[128|l&63]}a+=d.join("")}return a};function Yt(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function bt(r,e){if($(r)){let t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}var er={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},tr=function(r,e){Array.prototype.push.apply(r,$(e)?e:[e])},Zt,R={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Qt,encodeValuesOnly:!1,format:mt,formatter:yt,indices:!1,serializeDate(r){return(Zt??(Zt=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function Cr(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var xt={};function rr(r,e,t,n,o,s,a,c,f,d,m,l,g,h,A,E,U,k){let b=r,J=k,G=0,it=!1;for(;(J=J.get(xt))!==void 0&&!it;){let L=J.get(r);if(G+=1,typeof L<"u"){if(L===G)throw new RangeError("Cyclic object value");it=!0}typeof J.get(xt)>"u"&&(G=0)}if(typeof d=="function"?b=d(e,b):b instanceof Date?b=g?.(b):t==="comma"&&$(b)&&(b=bt(b,function(L){return L instanceof Date?g?.(L):L})),b===null){if(s)return f&&!E?f(e,R.encoder,U,"key",h):e;b=""}if(Cr(b)||Yt(b)){if(f){let L=E?e:f(e,R.encoder,U,"key",h);return[A?.(L)+"="+A?.(f(b,R.encoder,U,"value",h))]}return[A?.(e)+"="+A?.(String(b))]}let q=[];if(typeof b>"u")return q;let Fe;if(t==="comma"&&$(b))E&&f&&(b=bt(b,f)),Fe=[{value:b.length>0?b.join(",")||null:void 0}];else if($(d))Fe=d;else{let L=Object.keys(b);Fe=m?L.sort(m):L}let kt=c?String(e).replace(/\./g,"%2E"):String(e),Xe=n&&$(b)&&b.length===1?kt+"[]":kt;if(o&&$(b)&&b.length===0)return Xe+"[]";for(let L=0;L<Fe.length;++L){let ue=Fe[L],Ft=typeof ue=="object"&&typeof ue.value<"u"?ue.value:b[ue];if(a&&Ft===null)continue;let at=l&&c?ue.replace(/\./g,"%2E"):ue,Rr=$(b)?typeof t=="function"?t(Xe,at):Xe:Xe+(l?"."+at:"["+at+"]");k.set(r,G);let Ut=new WeakMap;Ut.set(xt,k),tr(q,rr(Ft,Rr,t,n,o,s,a,c,t==="comma"&&E&&$(b)?null:f,d,m,l,g,h,A,E,U,Ut))}return q}function kr(r=R){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||R.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=mt;if(typeof r.format<"u"){if(!Ve(gt,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=gt[t],o=R.filter;(typeof r.filter=="function"||$(r.filter))&&(o=r.filter);let s;if(r.arrayFormat&&r.arrayFormat in er?s=r.arrayFormat:"indices"in r?s=r.indices?"indices":"repeat":s=R.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:R.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:R.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:R.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:R.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?R.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:R.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:R.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:R.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:R.encodeValuesOnly,filter:o,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:R.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:R.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:R.strictNullHandling}}function nr(r,e={}){let t=r,n=kr(e),o,s;typeof n.filter=="function"?(s=n.filter,t=s("",t)):$(n.filter)&&(s=n.filter,o=s);let a=[];if(typeof t!="object"||t===null)return"";let c=er[n.arrayFormat],f=c==="comma"&&n.commaRoundTrip;o||(o=Object.keys(t)),n.sort&&o.sort(n.sort);let d=new WeakMap;for(let g=0;g<o.length;++g){let h=o[g];n.skipNulls&&t[h]===null||tr(a,rr(t[h],h,c,f,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,d))}let m=a.join(n.delimiter),l=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?l+="utf8=%26%2310003%3B&":l+="utf8=%E2%9C%93&"),m.length>0?l+m:""}function or(r){return nr(r,{arrayFormat:"comma"})}function ar(r){let e=0;for(let o of r)e+=o.length;let t=new Uint8Array(e),n=0;for(let o of r)t.set(o,n),n+=o.length;return t}var sr;function De(r){let e;return(sr??(e=new globalThis.TextEncoder,sr=e.encode.bind(e)))(r)}var ir;function _t(r){let e;return(ir??(e=new globalThis.TextDecoder,ir=e.decode.bind(e)))(r)}var j,C,Q=class{constructor(){j.set(this,void 0),C.set(this,void 0),S(this,j,new Uint8Array,"f"),S(this,C,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?De(e):e;S(this,j,ar([_(this,j,"f"),t]),"f");let n=[],o;for(;(o=Ur(_(this,j,"f"),_(this,C,"f")))!=null;){if(o.carriage&&_(this,C,"f")==null){S(this,C,o.index,"f");continue}if(_(this,C,"f")!=null&&(o.index!==_(this,C,"f")+1||o.carriage)){n.push(_t(_(this,j,"f").subarray(0,_(this,C,"f")-1))),S(this,j,_(this,j,"f").subarray(_(this,C,"f")),"f"),S(this,C,null,"f");continue}let s=_(this,C,"f")!==null?o.preceding-1:o.preceding,a=_t(_(this,j,"f").subarray(0,s));n.push(a),S(this,j,_(this,j,"f").subarray(o.index),"f"),S(this,C,null,"f")}return n}flush(){return _(this,j,"f").length?this.decode(`
|
|
2
|
+
`):[]}};j=new WeakMap,C=new WeakMap;Q.NEWLINE_CHARS=new Set([`
|
|
3
|
+
`,"\r"]);Q.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ur(r,e){for(let o=e??0;o<r.length;o++){if(r[o]===10)return{preceding:o,index:o+1,carriage:!1};if(r[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function cr(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}var Ge={off:0,error:200,warn:300,info:400,debug:500},At=(r,e,t)=>{if(r){if(Dt(Ge,r))return r;P(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(Ge))}`)}};function Ne(){}function Je(r,e,t){return!e||Ge[r]>Ge[t]?Ne:e[r].bind(e)}var vr={error:Ne,warn:Ne,info:Ne,debug:Ne},lr=new WeakMap;function P(r){let e=r.logger,t=r.logLevel??"off";if(!e)return vr;let n=lr.get(e);if(n&&n[0]===t)return n[1];let o={error:Je("error",e,t),warn:Je("warn",e,t),info:Je("info",e,t),debug:Je("debug",e,t)};return lr.set(e,[t,o]),o}var N=r=>(r.options&&(r.options={...r.options},delete r.options.headers),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r);var He,Qe=class r{constructor(e,t,n){this.iterator=e,He.set(this,void 0),this.controller=t,S(this,He,n,"f")}static fromSSEResponse(e,t,n){let o=!1,s=n?P(n):console;async function*a(){if(o)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let c=!1;try{for await(let f of Dr(e,t))try{yield JSON.parse(f.data)}catch(d){throw s.error("Could not parse message into JSON:",f.data),s.error("From chunk:",f.raw),d}c=!0}catch(f){if(Ue(f))return;throw f}finally{c||t.abort()}}return new r(a,t,n)}static fromReadableStream(e,t,n){let o=!1;async function*s(){let c=new Q,f=ht(e);for await(let d of f)for(let m of c.decode(d))yield m;for(let d of c.flush())yield d}async function*a(){if(o)throw new x("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let c=!1;try{for await(let f of s())c||f&&(yield JSON.parse(f));c=!0}catch(f){if(Ue(f))return;throw f}finally{c||t.abort()}}return new r(a,t,n)}[(He=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],n=this.iterator(),o=s=>({next:()=>{if(s.length===0){let a=n.next();e.push(a),t.push(a)}return s.shift()}});return[new r(()=>o(e),this.controller,_(this,He,"f")),new r(()=>o(t),this.controller,_(this,He,"f"))]}toReadableStream(){let e=this,t;return pt({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:s}=await t.next();if(s)return n.close();let a=De(JSON.stringify(o)+`
|
|
4
|
+
`);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await t.return?.()}})}};async function*Dr(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new x("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new x("Attempted to iterate over a response with no body");let t=new Rt,n=new Q,o=ht(r.body);for await(let s of Nr(o))for(let a of n.decode(s)){let c=t.decode(a);c&&(yield c)}for(let s of n.flush()){let a=t.decode(s);a&&(yield a)}}async function*Nr(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?De(t):t,o=new Uint8Array(e.length+n.length);o.set(e),o.set(n,e.length),e=o;let s;for(;(s=cr(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var Rt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let s={event:this.event,data:this.data.join(`
|
|
5
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,o]=Hr(e,":");return o.startsWith(" ")&&(o=o.substring(1)),t==="event"?this.event=o:t==="data"&&this.data.push(o),null}};function Hr(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}async function Ye(r,e){let{response:t,requestLogID:n,retryOfRequestLogID:o,startTime:s}=e,a=await(async()=>{if(e.options.stream)return P(r).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,r):Qe.fromSSEResponse(t,e.controller,r);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let f=t.headers.get("content-type")?.split(";")[0]?.trim();return f?.includes("application/json")||f?.endsWith("+json")?t.headers.get("content-length")==="0"?void 0:await t.json():await t.text()})();return P(r).debug(`[${n}] response parsed`,N({retryOfRequestLogID:o,url:t.url,status:t.status,body:a,durationMs:Date.now()-s})),a}var Be,Y=class r extends Promise{constructor(e,t,n=Ye){super(o=>{o(null)}),this.responsePromise=t,this.parseResponse=n,Be.set(this,void 0),S(this,Be,e,"f")}_thenUnwrap(e){return new r(_(this,Be,"f"),this.responsePromise,async(t,n)=>e(await this.parseResponse(t,n),n))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(_(this,Be,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Be=new WeakMap;var Ze,et=class{constructor(e,t,n,o){Ze.set(this,void 0),S(this,Ze,e,"f"),this.options=o,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new x("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await _(this,Ze,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ze=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Me=class extends Y{constructor(e,t,n){super(e,t,async(o,s)=>new n(o,s.response,await Ye(o,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},tt=class extends et{constructor(e,t,n,o){super(e,t,n,o),this.items=n||[],this.next_page_token=this.response.headers.get("x-next-page-token")??null,this.has_more=dt(this.response.headers.get("x-has-more"))??null}getPaginatedItems(){return this.items??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next_page_token;return e?{...this.options,query:{...ut(this.options.query),page_token:e}}:null}},w=class extends et{constructor(e,t,n,o){super(e,t,n,o),this.items=n||[],this.has_more=dt(this.response.headers.get("x-has-more"))??null,this.next_offset=Ht(this.response.headers.get("x-next-offset"))??null}getPaginatedItems(){return this.items??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next_offset;if(e==null){if(this.has_more)throw new x("Server reported X-Has-More: true without an X-Next-Offset header; refusing to silently truncate pagination");return null}return e===0?null:{...this.options,query:{...ut(this.options.query),offset:e}}}};var St=()=>{if(typeof File>"u"){let{process:r}=globalThis,e=typeof r?.versions?.node=="string"&&parseInt(r.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function be(r,e,t){return St(),new File(r,e??"unknown_file",t)}function qe(r){return(typeof r=="object"&&r!==null&&("name"in r&&r.name&&String(r.name)||"url"in r&&r.url&&String(r.url)||"filename"in r&&r.filename&&String(r.filename)||"path"in r&&r.path&&String(r.path))||"").split(/[\\/]/).pop()||void 0}var rt=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function";var H=async(r,e)=>({...r,body:await qr(r.body,e)}),ur=new WeakMap;function Mr(r){let e=typeof r=="function"?r:r.fetch,t=ur.get(e);if(t)return t;let n=(async()=>{try{let o="Response"in e?e.Response:(await e("data:,")).constructor,s=new FormData;return s.toString()!==await new o(s).text()}catch{return!0}})();return ur.set(e,n),n}var qr=async(r,e)=>{if(!await Mr(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let t=new FormData;return await Promise.all(Object.entries(r||{}).map(([n,o])=>Et(t,n,o))),t},fr=r=>r instanceof Blob&&"name"in r,Kr=r=>typeof r=="object"&&r!==null&&(r instanceof Response||rt(r)||fr(r)),Pt=r=>{if(Kr(r))return!0;if(Array.isArray(r))return r.some(Pt);if(r&&typeof r=="object"){for(let e in r)if(Pt(r[e]))return!0}return!1},Et=async(r,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")r.append(e,String(t));else if(t instanceof Response)r.append(e,be([await t.blob()],qe(t)));else if(rt(t))r.append(e,be([await new Response(ze(t)).blob()],qe(t)));else if(fr(t))r.append(e,t,qe(t));else if(Array.isArray(t))await Promise.all(t.map((n,o)=>Et(r,`${e}[${o}]`,n)));else if(typeof t=="object")!(e==="env_vars")&&!Pt(t)?Object.entries(t).filter(([s,a])=>a!==void 0).length>0&&r.append(e,JSON.stringify(t)):await Promise.all(Object.entries(t).map(([o,s])=>Et(r,`${e}[${o}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var dr=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function",Wr=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&dr(r),Xr=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function";async function nt(r,e,t){if(St(),r=await r,Wr(r))return r instanceof File?r:be([await r.arrayBuffer()],r.name);if(Xr(r)){let o=await r.blob();return e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()),be(await It(o),e,t)}let n=await It(r);if(e||(e=qe(r)),!t?.type){let o=n.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof o=="string"&&(t={...t,type:o})}return be(n,e,t)}async function It(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(dr(r))e.push(r instanceof Blob?r:await r.arrayBuffer());else if(rt(r))for await(let t of r)e.push(...await It(t));else{let t=r?.constructor?.name;throw new Error(`Unexpected data type: ${typeof r}${t?`; constructor: ${t}`:""}${zr(r)}`)}return e}function zr(r){return typeof r!="object"||r===null?"":`; props: [${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}var p=class{constructor(e){this._client=e}};var pr=Symbol("brand.privateNullableHeaders");function*Jr(r){if(!r)return;if(pr in r){let{values:n,nulls:o}=r;yield*n.entries();for(let s of o)yield[s,null];return}let e=!1,t;r instanceof Headers?t=r.entries():lt(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let n of t){let o=n[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let s=lt(n[1])?n[1]:[n[1]],a=!1;for(let c of s)c!==void 0&&(e&&!a&&(a=!0,yield[o,null]),yield[o,c])}}var u=r=>{let e=new Headers,t=new Set;for(let n of r){let o=new Set;for(let[s,a]of Jr(n)){let c=s.toLowerCase();o.has(c)||(e.delete(s),o.add(c)),a===null?(e.delete(s),t.add(c)):(e.append(s,a),t.delete(c))}}return{[pr]:!0,values:e,nulls:t}};function mr(r){return r.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var hr=Object.freeze(Object.create(null)),Gr=(r=mr)=>function(t,...n){if(t.length===1)return t[0];let o=!1,s=[],a=t.reduce((m,l,g)=>{/[?#]/.test(l)&&(o=!0);let h=n[g],A=(o?encodeURIComponent:r)(""+h);return g!==n.length&&(h==null||typeof h=="object"&&h.toString===Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??hr)??hr)?.toString)&&(A=h+"",s.push({start:m.length+l.length,length:A.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),m+l+(g===n.length?"":A)},""),c=a.split(/[?#]/,1)[0],f=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,d;for(;(d=f.exec(c))!==null;)s.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(s.sort((m,l)=>m.start-l.start),s.length>0){let m=0,l=s.reduce((g,h)=>{let A=" ".repeat(h.start-m),E="^".repeat(h.length);return m=h.start+h.length,g+A+E},"");throw new x(`Path parameters result in path with invalid segments:
|
|
6
|
+
${s.map(g=>g.error).join(`
|
|
7
|
+
`)}
|
|
8
|
+
${a}
|
|
9
|
+
${l}`)}return a},i=Gr(mr);var Z=class extends p{create(e,t){return this._client.post("/org/api_keys",{body:e,...t})}retrieve(e,t={},n){return this._client.get(i`/org/api_keys/${e}`,{query:t,...n})}update(e,t,n){return this._client.patch(i`/org/api_keys/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/org/api_keys",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/org/api_keys/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}rotate(e,t={},n){return this._client.post(i`/org/api_keys/${e}/rotate`,{body:t,...n})}};var ee=class extends p{list(e={},t){return this._client.getAPIList("/apps",w,{query:e,...t})}};var xe=class extends p{create(e,t){return this._client.post("/audit-logs/export/destinations",{body:e,...t})}retrieve(e,t){return this._client.get(i`/audit-logs/export/destinations/${e}`,t)}update(e,t,n){return this._client.patch(i`/audit-logs/export/destinations/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/audit-logs/export/destinations",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/audit-logs/export/destinations/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}test(e,t){return this._client.post(i`/audit-logs/export/destinations/${e}/test`,t)}};var Yr=6,Zr=5e4,en=8e3,F=class extends x{};async function gr(r,e,t,n,o={}){if(!t||typeof t.write!="function")throw new TypeError("audit log download destination must provide write()");let{onProgress:s,maxTransferRetries:a=Yr,...c}=o;if(!Number.isInteger(a)||a<0)throw new TypeError("maxTransferRetries must be a non-negative integer");let f=c.timeout??n,d,m={bytesWritten:0,chunks:0,rows:0},l=new Set;for(;;){let g=await tn(r,d?{...e,cursor:d}:e,c,a,f),{nextCursor:h,hasMore:A,rows:E}=rn(g.headers,d);if(A&&h){if(l.has(h))throw new F("response repeated X-Next-Cursor header");l.add(h)}if(await sn(t,g.body),d=h,m.bytesWritten+=g.body.byteLength,m.chunks+=1,m.rows+=E,s&&await s({...m,chunkRows:E}),!A)return m}}async function tn(r,e,t,n,o){for(let s=0;;s+=1){let a=new AbortController,c=()=>a.abort();t.signal?.aborted?a.abort():t.signal?.addEventListener("abort",c,{once:!0});let f;try{f=await r(e,{...t,signal:a.signal})}catch(l){throw t.signal?.removeEventListener("abort",c),l}let d=!1,m=setTimeout(()=>{d=!0,a.abort()},o);try{let l=new Uint8Array(await f.arrayBuffer());if(clearTimeout(m),t.signal?.aborted)throw new T;if(d)throw new D;let g=f.headers.get("x-content-sha256");if(!g)throw new F("response missing X-Content-Sha256 header");let h=await nn(l);if(t.signal?.aborted)throw new T;if(h!==g)throw new F(`audit log chunk checksum mismatch (got ${h}, want ${g})`);return{body:l,headers:f.headers}}catch(l){if(t.signal?.aborted&&!(l instanceof T)?l=new T:d&&(l=new D),s===n||l instanceof T)throw l;await on(s+1,t.signal)}finally{clearTimeout(m),t.signal?.removeEventListener("abort",c)}}}function rn(r,e){let t=r.get("x-has-more");if(t!=="true"&&t!=="false")throw new F("response missing or invalid X-Has-More header");let n=t==="true",o=r.get("x-row-count");if(o===null||!/^[0-9]+$/.test(o))throw new F("response missing or invalid X-Row-Count header");let s=Number(o);if(!Number.isSafeInteger(s)||s>Zr)throw new F("response missing or invalid X-Row-Count header");let a=r.get("x-next-cursor")||void 0;if(n&&(!a||a===e))throw new F("response has invalid X-Next-Cursor header");if(!n&&a)throw new F("response returned a cursor after the final chunk");return{rows:s,nextCursor:a,hasMore:n}}async function nn(r){let e=await globalThis.crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(e),t=>t.toString(16).padStart(2,"0")).join("")}async function on(r,e){let t=Math.min(1e3*2**(r-1),en);await new Promise((n,o)=>{if(e?.aborted){o(new T);return}let s=()=>{clearTimeout(a),o(new T)},a=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t);e?.addEventListener("abort",s,{once:!0})})}async function sn(r,e){let t=0;for(;t<e.byteLength;){let n=await r.write(t===0?e:e.subarray(t));if(typeof n=="number"){t+=yr(n,e.byteLength-t);continue}if(n&&typeof n=="object"&&"bytesWritten"in n){let o=n.bytesWritten;t+=yr(o,e.byteLength-t);continue}return}}function yr(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new F("audit log download destination performed a short write");return r}var X=class extends p{constructor(){super(...arguments),this.exportDestinations=new xe(this._client)}list(e,t){return this._client.getAPIList("/audit-logs",tt,{query:e,...t})}exportChunk(e,t){return this._client.get("/audit-logs/export/chunk",{query:e,...t,headers:u([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}download(e,t,n){return gr((o,s)=>this.exportChunk(o,s),e,t,this._client.timeout,n)}};X.ExportDestinations=xe;var _e=class extends p{create(e,t){return this._client.post("/auth/connections",{body:e,...t})}retrieve(e,t){return this._client.get(i`/auth/connections/${e}`,t)}update(e,t,n){return this._client.patch(i`/auth/connections/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/auth/connections",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/auth/connections/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}follow(e,t){return this._client.get(i`/auth/connections/${e}/events`,{...t,headers:u([{Accept:"text/event-stream"},t?.headers]),stream:!0})}login(e,t={},n){return this._client.post(i`/auth/connections/${e}/login`,{body:t,...n})}submit(e,t,n){return this._client.post(i`/auth/connections/${e}/submit`,{body:t,...n})}timeline(e,t={},n){return this._client.getAPIList(i`/auth/connections/${e}/timeline`,w,{query:t,...n})}};var Ae=class extends p{retrieve(e){return this._client.get("/auth/context",e)}};var B=class extends p{constructor(){super(...arguments),this.context=new Ae(this._client),this.connections=new _e(this._client)}};B.Context=Ae;B.Connections=_e;var te=class extends p{create(e,t){return this._client.post("/browser_pools",{body:e,...t})}retrieve(e,t){return this._client.get(i`/browser_pools/${e}`,t)}update(e,t,n){return this._client.patch(i`/browser_pools/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/browser_pools",w,{query:e,...t})}delete(e,t={},n){return this._client.delete(i`/browser_pools/${e}`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}acquire(e,t,n){return this._client.post(i`/browser_pools/${e}/acquire`,{body:t,...n})}flush(e,t){return this._client.post(i`/browser_pools/${e}/flush`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}release(e,t,n){return this._client.post(i`/browser_pools/${e}/release`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}};var Re=class extends p{batch(e,t,n){return this._client.post(i`/browsers/${e}/computer/batch`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}captureScreenshot(e,t={},n){return this._client.post(i`/browsers/${e}/computer/screenshot`,{body:t,...n,headers:u([{Accept:"image/png"},n?.headers]),__binaryResponse:!0})}clickMouse(e,t,n){return this._client.post(i`/browsers/${e}/computer/click_mouse`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}dragMouse(e,t,n){return this._client.post(i`/browsers/${e}/computer/drag_mouse`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}getMousePosition(e,t){return this._client.post(i`/browsers/${e}/computer/get_mouse_position`,t)}moveMouse(e,t,n){return this._client.post(i`/browsers/${e}/computer/move_mouse`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}pressKey(e,t,n){return this._client.post(i`/browsers/${e}/computer/press_key`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}readClipboard(e,t){return this._client.post(i`/browsers/${e}/computer/clipboard/read`,t)}scroll(e,t,n){return this._client.post(i`/browsers/${e}/computer/scroll`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}setCursorVisibility(e,t,n){return this._client.post(i`/browsers/${e}/computer/cursor`,{body:t,...n})}typeText(e,t,n){return this._client.post(i`/browsers/${e}/computer/type`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}writeClipboard(e,t,n){return this._client.post(i`/browsers/${e}/computer/clipboard/write`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}};var Pe=class extends p{stream(e,t,n){return this._client.get(i`/browsers/${e}/logs/stream`,{query:t,...n,headers:u([{Accept:"text/event-stream"},n?.headers]),stream:!0})}};var Ee=class extends p{execute(e,t,n){return this._client.post(i`/browsers/${e}/playwright/execute`,{body:t,...n})}};var Se=class extends p{exec(e,t,n){return this._client.post(i`/browsers/${e}/process/exec`,{body:t,...n})}kill(e,t,n){let{id:o,...s}=t;return this._client.post(i`/browsers/${o}/process/${e}/kill`,{body:s,...n})}resize(e,t,n){let{id:o,...s}=t;return this._client.post(i`/browsers/${o}/process/${e}/resize`,{body:s,...n})}spawn(e,t,n){return this._client.post(i`/browsers/${e}/process/spawn`,{body:t,...n})}status(e,t,n){let{id:o}=t;return this._client.get(i`/browsers/${o}/process/${e}/status`,n)}stdin(e,t,n){let{id:o,...s}=t;return this._client.post(i`/browsers/${o}/process/${e}/stdin`,{body:s,...n})}stdoutStream(e,t,n){let{id:o}=t;return this._client.get(i`/browsers/${o}/process/${e}/stdout/stream`,{...n,headers:u([{Accept:"text/event-stream"},n?.headers]),stream:!0})}};var Ie=class extends p{list(e,t){return this._client.get(i`/browsers/${e}/replays`,t)}download(e,t,n){let{id:o}=t;return this._client.get(i`/browsers/${o}/replays/${e}`,{...n,headers:u([{Accept:"video/mp4"},n?.headers]),__binaryResponse:!0})}start(e,t={},n){return this._client.post(i`/browsers/${e}/replays`,{body:t,...n})}stop(e,t,n){let{id:o}=t;return this._client.post(i`/browsers/${o}/replays/${e}/stop`,{...n,headers:u([{Accept:"*/*"},n?.headers])})}};var $e=class extends p{events(e,t={},n){return this._client.getAPIList(i`/browsers/${e}/telemetry/events`,w,{query:t,...n})}stream(e,t={},n){let{"Last-Event-ID":o,...s}=t??{};return this._client.get(i`/browsers/${e}/telemetry/stream`,{query:s,...n,headers:u([{Accept:"text/event-stream",...o!=null?{"Last-Event-ID":o}:void 0},n?.headers]),stream:!0})}};var Le=class extends p{events(e,t,n){let{id:o}=t;return this._client.get(i`/browsers/${o}/fs/watch/${e}/events`,{...n,headers:u([{Accept:"text/event-stream"},n?.headers]),stream:!0})}start(e,t,n){return this._client.post(i`/browsers/${e}/fs/watch`,{body:t,...n})}stop(e,t,n){let{id:o}=t;return this._client.delete(i`/browsers/${o}/fs/watch/${e}`,{...n,headers:u([{Accept:"*/*"},n?.headers])})}};var re=class extends p{constructor(){super(...arguments),this.watch=new Le(this._client)}createDirectory(e,t,n){return this._client.put(i`/browsers/${e}/fs/create_directory`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}deleteDirectory(e,t,n){return this._client.put(i`/browsers/${e}/fs/delete_directory`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}deleteFile(e,t,n){return this._client.put(i`/browsers/${e}/fs/delete_file`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}downloadDirZip(e,t,n){return this._client.get(i`/browsers/${e}/fs/download_dir_zip`,{query:t,...n,headers:u([{Accept:"application/zip"},n?.headers]),__binaryResponse:!0})}fileInfo(e,t,n){return this._client.get(i`/browsers/${e}/fs/file_info`,{query:t,...n})}listFiles(e,t,n){return this._client.get(i`/browsers/${e}/fs/list_files`,{query:t,...n})}move(e,t,n){return this._client.put(i`/browsers/${e}/fs/move`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}readFile(e,t,n){return this._client.get(i`/browsers/${e}/fs/read_file`,{query:t,...n,headers:u([{Accept:"application/octet-stream"},n?.headers]),__binaryResponse:!0})}setFilePermissions(e,t,n){return this._client.put(i`/browsers/${e}/fs/set_file_permissions`,{body:t,...n,headers:u([{Accept:"*/*"},n?.headers])})}upload(e,t,n){return this._client.post(i`/browsers/${e}/fs/upload`,H({body:t,...n,headers:u([{Accept:"*/*"},n?.headers])},this._client))}uploadZip(e,t,n){return this._client.post(i`/browsers/${e}/fs/upload_zip`,H({body:t,...n,headers:u([{Accept:"*/*"},n?.headers])},this._client))}writeFile(e,t,n,o){let{path:s,mode:a}=n;return this._client.put(i`/browsers/${e}/fs/write_file`,{body:t,query:{path:s,mode:a},...o,headers:u([{"Content-Type":"application/octet-stream",Accept:"*/*"},o?.headers])})}};re.Watch=Le;function ot(r,e){return`${r.replace(/\/+$/,"")}${e.startsWith("/")?e:`/${e}`}`}async function wr(r,e,t,n){let o=r.browserRouteCache.get(e);if(!o)throw new x(`browser route cache does not contain session ${e}; create, retrieve, or list the browser before calling browser.fetch`);let{url:s,method:a,headers:c,body:f,signal:d,duplex:m,timeout_ms:l}=wn(t,n);bn(s);let g={url:s,jwt:o.jwt};l!==void 0&&(g.timeout_ms=l);let h=c.get("accept"),A={method:gn(a),path:ot(o.baseURL,"/curl/raw"),query:g,body:f,headers:u([{Authorization:null},h?{Accept:h}:{Accept:"*/*"},xn(c)]),signal:d??null,__binaryResponse:!0};return m&&(A.fetchOptions={duplex:m}),r.request(A).asResponse()}function gn(r){let e=r.toLowerCase();if(!new Set(["get","post","put","patch","delete"]).has(e))throw new x(`browser.fetch unsupported HTTP method: ${r}`);return e}function wn(r,e){let t=e&&"timeout_ms"in e?e.timeout_ms:void 0;if(r instanceof Request){let o=new Headers(r.headers);e?.headers&&new Headers(e.headers).forEach((d,m)=>{o.set(m,d)});let s={url:r.url,method:(e?.method??r.method)?.toUpperCase()||"GET",headers:o},a=e?.body??r.body;a!=null&&(s.body=a);let c=e?.signal??r.signal;return c!==void 0&&(s.signal=c),e?.duplex!==void 0&&(s.duplex=e.duplex),t!==void 0&&(s.timeout_ms=t),s}let n={url:r instanceof URL?r.href:String(r),method:(e?.method??"GET").toUpperCase(),headers:new Headers(e?.headers)};return e?.body!==void 0&&(n.body=e.body),e?.signal!==void 0&&(n.signal=e.signal),e?.duplex!==void 0&&(n.duplex=e.duplex),t!==void 0&&(n.timeout_ms=t),n}function bn(r){let e;try{e=new URL(r)}catch{throw new x(`browser.fetch target must be an absolute URL; received: ${r}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new x(`browser.fetch only supports http(s) URLs; received: ${e.protocol}`)}function xn(r){let e={};return r.forEach((t,n)=>{switch(n.toLowerCase()){case"accept":case"content-length":case"connection":case"keep-alive":case"proxy-authenticate":case"proxy-authorization":case"te":case"trailers":case"transfer-encoding":case"upgrade":return;default:e[n]=t}}),e}var O=class extends p{constructor(){super(...arguments),this.telemetry=new $e(this._client),this.replays=new Ie(this._client),this.fs=new re(this._client),this.process=new Se(this._client),this.logs=new Pe(this._client),this.computer=new Re(this._client),this.playwright=new Ee(this._client)}create(e={},t){return this._client.post("/browsers",{body:e,...t})}retrieve(e,t={},n){return this._client.get(i`/browsers/${e}`,{query:t,...n})}update(e,t,n){return this._client.patch(i`/browsers/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/browsers",w,{query:e,...t})}curl(e,t,n){return this._client.post(i`/browsers/${e}/curl`,{body:t,...n})}fetch(e,t,n){return wr(this._client,e,t,n)}deleteByID(e,t){return this._client.delete(i`/browsers/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}loadExtensions(e,t,n){return this._client.post(i`/browsers/${e}/extensions`,H({body:t,...n,headers:u([{Accept:"*/*"},n?.headers])},this._client))}};O.Telemetry=$e;O.Replays=Ie;O.Fs=re;O.Process=Se;O.Logs=Pe;O.Computer=Re;O.Playwright=Ee;var ne=class extends p{create(e,t){return this._client.post("/org/credential_providers",{body:e,...t})}retrieve(e,t){return this._client.get(i`/org/credential_providers/${e}`,t)}update(e,t,n){return this._client.patch(i`/org/credential_providers/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/org/credential_providers",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/org/credential_providers/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}listItems(e,t){return this._client.get(i`/org/credential_providers/${e}/items`,t)}test(e,t){return this._client.post(i`/org/credential_providers/${e}/test`,t)}};var oe=class extends p{create(e,t){return this._client.post("/credentials",{body:e,...t})}retrieve(e,t){return this._client.get(i`/credentials/${e}`,t)}update(e,t,n){return this._client.patch(i`/credentials/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/credentials",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/credentials/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}totpCode(e,t){return this._client.get(i`/credentials/${e}/totp-code`,t)}};var se=class extends p{create(e,t){return this._client.post("/deployments",H({body:e,...t},this._client))}retrieve(e,t){return this._client.get(i`/deployments/${e}`,t)}list(e={},t){return this._client.getAPIList("/deployments",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/deployments/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}follow(e,t={},n){return this._client.get(i`/deployments/${e}/events`,{query:t,...n,headers:u([{Accept:"text/event-stream"},n?.headers]),stream:!0})}};var ie=class extends p{list(e={},t){return this._client.getAPIList("/extensions",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/extensions/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}download(e,t){return this._client.get(i`/extensions/${e}`,{...t,headers:u([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}downloadFromChromeStore(e,t){return this._client.get("/extensions/from_chrome_store",{query:e,...t,headers:u([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}get(e,t){return this._client.get(i`/extensions/${e}/metadata`,t)}upload(e,t){return this._client.post("/extensions",H({body:e,...t},this._client))}};var ae=class extends p{create(e,t){return this._client.post("/invocations",{body:e,...t})}retrieve(e,t){return this._client.get(i`/invocations/${e}`,t)}update(e,t,n){return this._client.patch(i`/invocations/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/invocations",w,{query:e,...t})}deleteBrowsers(e,t){return this._client.delete(i`/invocations/${e}/browsers`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}follow(e,t={},n){return this._client.get(i`/invocations/${e}/events`,{query:t,...n,headers:u([{Accept:"text/event-stream"},n?.headers]),stream:!0})}listBrowsers(e,t){return this._client.get(i`/invocations/${e}/browsers`,t)}};var Te=class extends p{retrieve(e){return this._client.get("/org/entitlements",e)}};var Oe=class extends p{retrieve(e){return this._client.get("/org/limits",e)}update(e,t){return this._client.patch("/org/limits",{body:e,...t})}};var M=class extends p{constructor(){super(...arguments),this.entitlements=new Te(this._client),this.limits=new Oe(this._client)}};M.Entitlements=Te;M.Limits=Oe;var ce=class extends p{create(e,t){return this._client.post("/profiles",{body:e,...t})}retrieve(e,t){return this._client.get(i`/profiles/${e}`,t)}update(e,t,n){return this._client.patch(i`/profiles/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/profiles",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/profiles/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}download(e,t={},n){return this._client.get(i`/profiles/${e}/download`,{query:t,...n,headers:u([{Accept:"application/octet-stream"},n?.headers]),__binaryResponse:!0})}};var je=class extends p{retrieve(e,t){return this._client.get(i`/org/projects/${e}/limits`,t)}update(e,t,n){return this._client.patch(i`/org/projects/${e}/limits`,{body:t,...n})}};var z=class extends p{constructor(){super(...arguments),this.limits=new je(this._client)}create(e,t){return this._client.post("/org/projects",{body:e,...t})}retrieve(e,t){return this._client.get(i`/org/projects/${e}`,t)}update(e,t,n){return this._client.patch(i`/org/projects/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/org/projects",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/org/projects/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}};z.Limits=je;var le=class extends p{create(e,t){return this._client.post("/proxies",{body:e,...t})}retrieve(e,t){return this._client.get(i`/proxies/${e}`,t)}update(e,t,n){return this._client.patch(i`/proxies/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/proxies",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/proxies/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}check(e,t={},n){return this._client.post(i`/proxies/${e}/check`,{body:t,...n})}};var Ce=class extends p{create(e,t){return this._client.post("/telemetry/destinations",{body:e,...t})}retrieve(e,t){return this._client.get(i`/telemetry/destinations/${e}`,t)}update(e,t,n){return this._client.patch(i`/telemetry/destinations/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/telemetry/destinations",w,{query:e,...t})}delete(e,t){return this._client.delete(i`/telemetry/destinations/${e}`,{...t,headers:u([{Accept:"*/*"},t?.headers])})}};var V=class extends p{constructor(){super(...arguments),this.destinations=new Ce(this._client)}};V.Destinations=Ce;var Ke=class{constructor(){this.entries=new Map}get(e){return this.entries.get(e)}set(e){this.entries.set(e.sessionId,e)}delete(e){this.entries.delete(e)}clear(){this.entries.clear()}},br="KERNEL_BROWSER_ROUTING_SUBRESOURCES",Sn=["curl","telemetry/stream"],In=/^\/(?:v\d+\/)?browsers(?:\/[^/]+)?\/?$/,$n=/^\/(?:v\d+\/)?browser_pools\/[^/]+\/acquire\/?$/,Ln=/^\/(?:v\d+\/)?browsers\/([^/]+)\/?$/,Tn=/^\/(?:v\d+\/)?browser_pools\/[^/]+\/release\/?$/;function Lt(){let r=qn();return r===void 0?[...Sn]:r.trim()===""?[]:r.split(",").map(e=>e.trim()).filter(Boolean)}function Tt(r,{apiBaseURL:e,subresources:t,cache:n}){let o=[...t].map(a=>a.trim().replace(/^\/+|\/+$/g,"")).filter(Boolean),s=new URL(e).origin;return async(a,c)=>{let f=new Request(a,c),d=On(f,s),m=await Dn(r,{input:a,init:c,request:f},s,o,n);return d&&await Un(m,n),await jn(f,m,s,n),m}}function On(r,e){let t=new URL(r.url);return t.origin===e&&(In.test(t.pathname)||$n.test(t.pathname))}async function jn(r,e,t,n){if(!e.ok)return;let o=new URL(r.url);if(o.origin!==t)return;let s=Cn(r,o.pathname)??await kn(r,o.pathname);s&&n.delete(s)}function Cn(r,e){if(r.method.toUpperCase()!=="DELETE")return;let t=e.match(Ln);return t&&decodeURIComponent(t[1]??"")||void 0}async function kn(r,e){if(!(r.method.toUpperCase()!=="POST"||!Tn.test(e)))try{let t=await r.clone().json();if(!t||typeof t!="object")return;let n=t.session_id;return typeof n=="string"&&n.trim()?n.trim():void 0}catch{return}}function Fn(r){if(!r||typeof r!="object")return;let e=r,t=typeof e.session_id=="string"?e.session_id.trim():"",n=typeof e.base_url=="string"?e.base_url.trim():"";if(!t||!n)return;let o=typeof e.jwt=="string"?e.jwt.trim():"",s=typeof e.cdp_ws_url=="string"?e.cdp_ws_url:void 0,a=o||Mn(s)||"";if(a)return{sessionId:t,baseURL:n,jwt:a}}async function Un(r,e){if((r.headers.get("content-type")?.toLowerCase()??"").includes("application/json"))try{$t(await r.clone().json(),e)}catch{}}function $t(r,e){let t=Fn(r);if(t&&e.set(t),Array.isArray(r)){for(let n of r)$t(n,e);return}if(!(!r||typeof r!="object"))for(let n of Object.values(r))typeof n=="object"&&n!==null&&$t(n,e)}function vn(r,e){let t=r.replace(/^\/+|\/+$/g,"");return e.some(n=>t===n||t.startsWith(n+"/"))}async function Dn(r,{input:e,init:t,request:n},o,s,a){let c=new URL(n.url);if(c.origin!==o)return r(e,t);let f=c.pathname.match(/^\/(?:v\d+\/)?browsers\/([^/]+)\/([^/]+)(\/.*)?$/);if(!f)return r(e,t);let d=decodeURIComponent(f[1]??""),m=f[2]??"";if(!d||!vn(m+(f[3]??""),s))return r(e,t);let l=a.get(d);if(l===void 0)return r(e,t);let g=new URL(ot(l.baseURL,`/${m}${f[3]??""}`));c.searchParams.forEach((A,E)=>{E!=="jwt"&&g.searchParams.append(E,A)}),g.searchParams.get("jwt")||g.searchParams.set("jwt",l.jwt);let h=new Headers(n.headers);return h.delete("authorization"),r(g.toString(),Nn(e,n,t,h))}function Nn(r,e,t,n){let o=e.method.toUpperCase(),s={...t??{},method:o,headers:n,redirect:e.redirect,signal:t?.signal??(r instanceof Request?r.signal:void 0)};if(delete s.body,delete s.duplex,o!=="GET"&&o!=="HEAD"){let a=Hn(e,t);a!==void 0&&(s.body=a),t?.duplex!==void 0?s.duplex=t.duplex:Bn(a)&&(s.duplex="half")}return s}function Hn(r,e){return e?.body!==void 0&&e.body!==null?e.body:r.body??void 0}function Bn(r){return globalThis.ReadableStream&&r instanceof globalThis.ReadableStream||typeof r=="object"&&r!==null&&Symbol.asyncIterator in r}function Mn(r){if(r)try{return new URL(r).searchParams.get("jwt")??void 0}catch{return}}function qn(){if(typeof globalThis.process<"u"){let r=globalThis.process.env?.[br];return typeof r=="string"?r:void 0}if(typeof globalThis.Deno<"u"){let r=globalThis.Deno.env?.get?.(br);return typeof r=="string"?r:void 0}}var st=class{constructor(e){this.actions=new Map,this.name=e,xr.registerApp(this)}action(e,t){let n;if(t.length===0)throw new Error("Action handlers must accept at least the context parameter");if(t.length===1){let o=t;n=async(s,a)=>o(s)}else n=t;return this.actions.set(e,{name:e,handler:n}),n}getActions(){return Array.from(this.actions.values())}getAction(e){return this.actions.get(e)}toJSON(){return{name:this.name,actions:this.getActions().map(e=>({name:e.name}))}}},Ot=class{constructor(){this.apps=new Map}registerApp(e){this.apps.set(e.name,e)}getApps(){return Array.from(this.apps.values())}getAppByName(e){return this.apps.get(e)}export(){return{apps:this.getApps().map(e=>e.toJSON())}}exportJSON(){return JSON.stringify(this.export(),null,2)}},xr=new Ot;var ke=r=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()||void 0};var jt,Ct,We,_r,Ar={production:"https://api.onkernel.com/",development:"https://localhost:3001/"},y=class{constructor({baseURL:e=ke("KERNEL_BASE_URL"),apiKey:t=ke("KERNEL_API_KEY"),projectID:n=null,project:o=null,...s}={}){if(jt.add(this),We.set(this,void 0),this.deployments=new se(this),this.apps=new ee(this),this.invocations=new ae(this),this.browsers=new O(this),this.profiles=new ce(this),this.auth=new B(this),this.telemetry=new V(this),this.proxies=new le(this),this.extensions=new ie(this),this.browserPools=new te(this),this.credentials=new oe(this),this.projects=new z(this),this.organization=new M(this),this.auditLogs=new X(this),this.apiKeys=new Z(this),this.credentialProviders=new ne(this),typeof globalThis<"u"&&typeof globalThis.Bun<"u"&&globalThis.Bun.version&&!ke("KERNEL_SUPPRESS_BUN_WARNING")&&P(this).warn("The Bun runtime was detected. Playwright may have CDP connection issues, proceed with caution. Suppress this warning by setting the KERNEL_SUPPRESS_BUN_WARNING environment variable to true"),t===void 0)throw new x("The KERNEL_API_KEY environment variable is missing or empty; either provide it, or instantiate the Kernel client with an apiKey option, like new Kernel({ apiKey: 'My API Key' }).");let a={apiKey:t,projectID:n,project:o,...s,baseURL:e,environment:s.environment??"production"};if(e&&s.environment)throw new x("Ambiguous URL; The `baseURL` option (or KERNEL_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null");this.baseURL=a.baseURL||Ar[a.environment||"production"],this.timeout=a.timeout??Ct.DEFAULT_TIMEOUT,this.logger=a.logger??console;let c="warn";this.logLevel=c,this.logLevel=At(a.logLevel,"ClientOptions.logLevel",this)??At(ke("KERNEL_LOG"),"process.env['KERNEL_LOG']",this)??c,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.rawFetch=a.fetch??zt(),this.browserRouteCache=new Ke,this.fetch=Tt(this.rawFetch,{apiBaseURL:this.baseURL,subresources:Lt(),cache:this.browserRouteCache}),S(this,We,Jt,"f");let f=ke("KERNEL_CUSTOM_HEADERS");if(f){let d={};for(let m of f.split(`
|
|
10
|
+
`)){let l=m.indexOf(":");l>=0&&(d[m.substring(0,l).trim()]=m.substring(l+1).trim())}a.defaultHeaders={...d,...a.defaultHeaders}}this._options=a,this.apiKey=t,this.projectID=n,this.project=o}withOptions(e){let t=new this.constructor({...this._options,environment:e.environment?e.environment:void 0,baseURL:e.environment?void 0:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.rawFetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,projectID:this.projectID,project:this.project,...e});return t.browserRouteCache=this.browserRouteCache,t.fetch=Tt(t.rawFetch,{apiBaseURL:t.baseURL,subresources:Lt(),cache:t.browserRouteCache}),t}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return u([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return or(e)}getUserAgent(){return`${this.constructor.name}/JS ${W}`}defaultIdempotencyKey(){return`stainless-node-retry-${ct()}`}makeStatusError(e,t,n,o){return I.generate(e,t,n,o)}buildURL(e,t,n){let o=!_(this,jt,"m",_r).call(this)&&n||this.baseURL,s=vt(e)?new URL(e):new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),c=Object.fromEntries(s.searchParams);return(!ft(a)||!ft(c))&&(t={...c,...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(s.search=this.stringifyQuery(t)),s.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(o=>({method:e,path:t,...o})))}request(e,t=null){return new Y(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let o=await e,s=o.maxRetries??this.maxRetries;t==null&&(t=s),await this.prepareOptions(o);let{req:a,url:c,timeout:f}=await this.buildRequest(o,{retryCount:s-t});await this.prepareRequest(a,{url:c,options:o});let d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=n===void 0?"":`, retryOf: ${n}`,l=Date.now();if(P(this).debug(`[${d}] sending request`,N({retryOfRequestLogID:n,method:o.method,url:c,options:o,headers:a.headers})),o.signal?.aborted)throw new T;let g=new AbortController,h=await this.fetchWithTimeout(c,a,f,g).catch(ve),A=Date.now();if(h instanceof globalThis.Error){let U=`retrying, ${t} attempts remaining`;if(o.signal?.aborted)throw new T;let k=Ue(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return P(this).info(`[${d}] connection ${k?"timed out":"failed"} - ${U}`),P(this).debug(`[${d}] connection ${k?"timed out":"failed"} (${U})`,N({retryOfRequestLogID:n,url:c,durationMs:A-l,message:h.message})),this.retryRequest(o,t,n??d);throw P(this).info(`[${d}] connection ${k?"timed out":"failed"} - error; no more retries left`),P(this).debug(`[${d}] connection ${k?"timed out":"failed"} (error; no more retries left)`,N({retryOfRequestLogID:n,url:c,durationMs:A-l,message:h.message})),k?new D:new K({cause:h})}let E=`[${d}${m}] ${a.method} ${c} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${A-l}ms`;if(!h.ok){let U=await this.shouldRetry(h);if(t&&U){let q=`retrying, ${t} attempts remaining`;return await Vt(h.body),P(this).info(`${E} - ${q}`),P(this).debug(`[${d}] response error (${q})`,N({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:A-l})),this.retryRequest(o,t,n??d,h.headers)}let k=U?"error; no more retries left":"error; not retryable";P(this).info(`${E} - ${k}`);let b=await h.text().catch(q=>ve(q).message),J=Bt(b),G=J?void 0:b;throw P(this).debug(`[${d}] response error (${k})`,N({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,message:G,durationMs:Date.now()-l})),this.makeStatusError(h.status,J,G,h.headers)}return P(this).info(E),P(this).debug(`[${d}] response start`,N({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:A-l})),{response:h,options:o,controller:g,requestLogID:d,retryOfRequestLogID:n,startTime:l}}getAPIList(e,t,n){return this.requestAPIList(t,n&&"then"in n?n.then(o=>({method:"get",path:e,...o})):{method:"get",path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new Me(this,n,e)}async fetchWithTimeout(e,t,n,o){let{signal:s,method:a,...c}=t||{},f=this._makeAbort(o);s&&s.addEventListener("abort",f,{once:!0});let d=setTimeout(f,n),m=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,l={signal:o.signal,...m?{duplex:"half"}:{},method:"GET",...c};a&&(l.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,l)}finally{clearTimeout(d)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,o){let s,a=o?.get("retry-after-ms");if(a){let f=parseFloat(a);Number.isNaN(f)||(s=f)}let c=o?.get("retry-after");if(c&&!s){let f=parseFloat(c);Number.isNaN(f)?s=Date.parse(c)-Date.now():s=f*1e3}if(s===void 0){let f=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,f)}return await Mt(s),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let s=t-e,a=Math.min(.5*Math.pow(2,s),8),c=1-Math.random()*.25;return a*c*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:o,path:s,query:a,defaultBaseURL:c}=n,f=this.buildURL(s,a,c);"timeout"in n&&Nt("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:d,body:m}=this.buildBody({options:n}),l=await this.buildHeaders({options:e,method:o,bodyHeaders:d,retryCount:t});return{req:{method:o,headers:l,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"},...m&&{body:m},...this.fetchOptions??{},...n.fetchOptions??{}},url:f,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:o}){let s={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let a=u([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(o),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Xt(),"X-Kernel-Project-Id":this.projectID,"X-Kernel-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:n}=e;if(!t)return t==null&&"body"in e?_(this,We,"f").call(this,{body:t,headers:u([n])}):{bodyHeaders:void 0,body:void 0};let o=u([n]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&o.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:ze(t)}:typeof t=="object"&&o.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(t)}:_(this,We,"f").call(this,{body:t,headers:o})}app(e){return new st(e)}};Ct=y,We=new WeakMap,jt=new WeakSet,_r=function(){return this.baseURL!==Ar[this._options.environment||"production"]};y.Kernel=Ct;y.DEFAULT_TIMEOUT=6e4;y.KernelError=x;y.APIError=I;y.APIConnectionError=K;y.APIConnectionTimeoutError=D;y.APIUserAbortError=T;y.NotFoundError=he;y.ConflictError=me;y.RateLimitError=ge;y.BadRequestError=fe;y.AuthenticationError=de;y.InternalServerError=we;y.PermissionDeniedError=pe;y.UnprocessableEntityError=ye;y.toFile=nt;y.Deployments=se;y.Apps=ee;y.Invocations=ae;y.Browsers=O;y.Profiles=ce;y.Auth=B;y.Telemetry=V;y.Proxies=le;y.Extensions=ie;y.BrowserPools=te;y.Credentials=oe;y.Projects=z;y.Organization=M;y.AuditLogs=X;y.APIKeys=Z;y.CredentialProviders=ne;export{K as a,D as b,de as c,pe as d,we as e,y as f};
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import{s as _}from"./chunk-63T4W2LX.js";import{AsyncLocalStorage as N}from"async_hooks";var C="MCP_SCRAPER_ALLOW_HEADLESS_HARVEST_TEST",d=new N;function D(e,t){return d.run(e,t)}function l(){return d.getStore()}import{randomUUID as T}from"crypto";var p=166667e-10,L=.0001333336,h=new Set(["serp","fb_search","fb_ad","instagram"]),A=.00111,R=4,g=4e-4;function n(e,t){let r=process.env[e]?.trim();if(!r)return t;let o=Number(r);return Number.isFinite(o)&&o>=0?o:t}var m=n("NANGO_USD_PER_CONNECTION_MONTH",1),U=n("NANGO_USD_PER_FUNCTION_RUN",1e-4),O=n("NANGO_USD_PER_PROXY_REQUEST",1e-4),S=n("NANGO_USD_PER_COMPUTE_SEC",2e-4),b=n("BRIGHTDATA_BROWSER_USD_PER_GB",8);function u(e,t){return Math.max(0,e)/1e3*(t?L:p)}function i(e,t){return e==="fal_wizper"?Math.max(0,t)/R*A:e==="deepinfra_qwen"?Math.max(0,t)/1e3*g:e==="openrouter"||e==="mcp_memory_video"||e==="mcp_memory_ai"?Math.max(0,t):e==="nango_connection"?Math.max(0,t)*m:e==="nango_function_run"?Math.max(0,t)*U:e==="nango_proxy_request"?Math.max(0,t)*O:e==="nango_compute"?Math.max(0,t)*S:e==="brightdata_browser_api"?Math.max(0,t)/1e9*b:0}var E=!1,s=null;async function c(){if(!E)return s||(s=x().finally(()=>{s=null}),s)}async function x(){let e=_(),t=await e.execute(`
|
|
2
|
+
SELECT
|
|
3
|
+
(SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name IN ('kernel_session_log', 'vendor_usage_log', 'cost_probe_runs')) = 3
|
|
4
|
+
AND (SELECT COUNT(*) FROM pragma_table_info('kernel_session_log') WHERE name IN ('proxy_source', 'proxy_type', 'method')) = 3
|
|
5
|
+
AND (SELECT COUNT(*) FROM pragma_table_info('vendor_usage_log') WHERE name IN ('method', 'source_key', 'provider_duration_ms', 'provider_captcha', 'provider_status')) = 5
|
|
6
|
+
AND (SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'vendor_usage_log_vendor_source_key') = 1
|
|
7
|
+
AND (SELECT COUNT(*) FROM pragma_table_info('cost_probe_runs') WHERE name IN ('units', 'unit_type', 'mode')) = 3
|
|
8
|
+
AS ready
|
|
9
|
+
`);if(Number(t.rows[0]?.ready??0)===1){E=!0;return}await e.execute(`
|
|
10
|
+
CREATE TABLE IF NOT EXISTS kernel_session_log (
|
|
11
|
+
id TEXT PRIMARY KEY,
|
|
12
|
+
kernel_session_id TEXT,
|
|
13
|
+
op TEXT,
|
|
14
|
+
source TEXT NOT NULL,
|
|
15
|
+
probe_run_id TEXT,
|
|
16
|
+
user_id INTEGER,
|
|
17
|
+
stealth INTEGER,
|
|
18
|
+
headless_sent INTEGER,
|
|
19
|
+
proxy_used INTEGER,
|
|
20
|
+
fallback INTEGER NOT NULL DEFAULT 0,
|
|
21
|
+
opened_at TEXT,
|
|
22
|
+
closed_at TEXT,
|
|
23
|
+
duration_ms INTEGER NOT NULL DEFAULT 0,
|
|
24
|
+
est_cost_usd_headless REAL NOT NULL DEFAULT 0,
|
|
25
|
+
est_cost_usd_headful REAL NOT NULL DEFAULT 0,
|
|
26
|
+
error TEXT,
|
|
27
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
28
|
+
)
|
|
29
|
+
`),await e.execute("CREATE INDEX IF NOT EXISTS kernel_session_log_op ON kernel_session_log(op)"),await e.execute("CREATE INDEX IF NOT EXISTS kernel_session_log_probe ON kernel_session_log(probe_run_id)"),await e.execute("CREATE INDEX IF NOT EXISTS kernel_session_log_created ON kernel_session_log(created_at)");try{await e.execute("ALTER TABLE kernel_session_log ADD COLUMN proxy_source TEXT")}catch{}try{await e.execute("ALTER TABLE kernel_session_log ADD COLUMN proxy_type TEXT")}catch{}try{await e.execute("ALTER TABLE kernel_session_log ADD COLUMN method TEXT")}catch{}await e.execute(`
|
|
30
|
+
CREATE TABLE IF NOT EXISTS vendor_usage_log (
|
|
31
|
+
id TEXT PRIMARY KEY,
|
|
32
|
+
op TEXT,
|
|
33
|
+
probe_run_id TEXT,
|
|
34
|
+
user_id INTEGER,
|
|
35
|
+
vendor TEXT NOT NULL,
|
|
36
|
+
model TEXT,
|
|
37
|
+
units REAL NOT NULL DEFAULT 0,
|
|
38
|
+
unit_type TEXT,
|
|
39
|
+
est_cost_usd REAL NOT NULL DEFAULT 0,
|
|
40
|
+
error TEXT,
|
|
41
|
+
source_key TEXT,
|
|
42
|
+
provider_duration_ms INTEGER,
|
|
43
|
+
provider_captcha INTEGER,
|
|
44
|
+
provider_status TEXT,
|
|
45
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
46
|
+
)
|
|
47
|
+
`),await e.execute("CREATE INDEX IF NOT EXISTS vendor_usage_log_op ON vendor_usage_log(op)"),await e.execute("CREATE INDEX IF NOT EXISTS vendor_usage_log_probe ON vendor_usage_log(probe_run_id)"),await e.execute("CREATE INDEX IF NOT EXISTS vendor_usage_log_created ON vendor_usage_log(created_at)");try{await e.execute("ALTER TABLE vendor_usage_log ADD COLUMN method TEXT")}catch{}try{await e.execute("ALTER TABLE vendor_usage_log ADD COLUMN source_key TEXT")}catch{}try{await e.execute("ALTER TABLE vendor_usage_log ADD COLUMN provider_duration_ms INTEGER")}catch{}try{await e.execute("ALTER TABLE vendor_usage_log ADD COLUMN provider_captcha INTEGER")}catch{}try{await e.execute("ALTER TABLE vendor_usage_log ADD COLUMN provider_status TEXT")}catch{}await e.execute("CREATE UNIQUE INDEX IF NOT EXISTS vendor_usage_log_vendor_source_key ON vendor_usage_log(vendor, source_key) WHERE source_key IS NOT NULL"),await e.execute(`
|
|
48
|
+
CREATE TABLE IF NOT EXISTS cost_probe_runs (
|
|
49
|
+
id TEXT PRIMARY KEY,
|
|
50
|
+
tool TEXT NOT NULL,
|
|
51
|
+
target TEXT,
|
|
52
|
+
started_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
53
|
+
wall_ms INTEGER NOT NULL DEFAULT 0,
|
|
54
|
+
success INTEGER NOT NULL DEFAULT 0,
|
|
55
|
+
error TEXT,
|
|
56
|
+
http_only INTEGER NOT NULL DEFAULT 0,
|
|
57
|
+
kernel_used INTEGER NOT NULL DEFAULT 0,
|
|
58
|
+
kernel_sessions INTEGER NOT NULL DEFAULT 0,
|
|
59
|
+
kernel_seconds_total REAL NOT NULL DEFAULT 0,
|
|
60
|
+
kernel_tier_observed TEXT,
|
|
61
|
+
est_kernel_cost_usd_headless REAL NOT NULL DEFAULT 0,
|
|
62
|
+
est_kernel_cost_usd_headful REAL NOT NULL DEFAULT 0,
|
|
63
|
+
vendor_cost_usd REAL NOT NULL DEFAULT 0,
|
|
64
|
+
charged_credits REAL NOT NULL DEFAULT 0,
|
|
65
|
+
margin_usd_headless_starter REAL NOT NULL DEFAULT 0,
|
|
66
|
+
margin_usd_headful_starter REAL NOT NULL DEFAULT 0,
|
|
67
|
+
notes TEXT
|
|
68
|
+
)
|
|
69
|
+
`),await e.execute("CREATE INDEX IF NOT EXISTS cost_probe_runs_tool ON cost_probe_runs(tool)");try{await e.execute("ALTER TABLE cost_probe_runs ADD COLUMN units REAL")}catch{}try{await e.execute("ALTER TABLE cost_probe_runs ADD COLUMN unit_type TEXT")}catch{}try{await e.execute("ALTER TABLE cost_probe_runs ADD COLUMN mode TEXT")}catch{}E=!0}async function w(e){try{await c();let t=l(),r=Math.max(0,e.closedAtMs-e.openedAtMs);await _().execute({sql:`INSERT INTO kernel_session_log
|
|
70
|
+
(id, kernel_session_id, op, source, probe_run_id, user_id, stealth, headless_sent, proxy_used, proxy_source, proxy_type, fallback, opened_at, closed_at, duration_ms, est_cost_usd_headless, est_cost_usd_headful, error, method)
|
|
71
|
+
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,args:[T(),e.kernelSessionId??null,t?.op??null,e.source,t?.probeRunId??null,t?.userId??null,a(e.stealth),a(e.headlessSent),a(e.proxyUsed),e.proxySource??null,e.proxyType??null,e.fallback?1:0,new Date(e.openedAtMs).toISOString(),new Date(e.closedAtMs).toISOString(),r,u(r,!1),u(r,!0),e.error??null,t?.subOp??null]})}catch(t){console.warn("[cost-telemetry] recordKernelSession failed:",t instanceof Error?t.message:String(t))}}async function F(e){try{await c();let t=l();return(await _().execute({sql:`INSERT OR IGNORE INTO vendor_usage_log
|
|
72
|
+
(id, op, probe_run_id, user_id, vendor, model, units, unit_type, est_cost_usd, error, method, source_key, provider_duration_ms, provider_captcha, provider_status)
|
|
73
|
+
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,args:[T(),e.op??t?.op??null,e.probeRunId??t?.probeRunId??null,e.userId??t?.userId??null,e.vendor,e.model??null,e.units,e.unitType,i(e.vendor,e.units),e.error??null,e.method??t?.subOp??null,e.sourceKey??null,e.providerDurationMs??null,a(e.providerCaptcha),e.providerStatus??null]})).rowsAffected===1}catch(t){return console.warn("[cost-telemetry] recordVendorUsage failed:",t instanceof Error?t.message:String(t)),!1}}function a(e){return e==null?null:e?1:0}export{C as a,D as b,l as c,h as d,i as e,c as f,w as g,F as h};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash as M}from"crypto";import{mkdir as D,readFile as $,writeFile as O}from"fs/promises";import{createWriteStream as C}from"fs";import{homedir as N}from"os";import{dirname as _,join as x}from"path";import{Transform as K}from"stream";import{pipeline as E}from"stream/promises";var b="9999-12-31T23:59:59.999Z";function L(){return process.env.VERCEL==="1"||process.env.NODE_ENV==="production"}function T(t){return t.hosted??L()}function v(t){return t.localBaseDir?.trim()||process.env.MCP_SCRAPER_OUTPUT_DIR?.trim()||x(N(),"Downloads","mcp-scraper")}function P(t){let e=t.replace(/^\/+/,"").replace(/\/+$/,"");if(!e||e.includes("..")||!/^[a-zA-Z0-9/_-]+$/.test(e))throw new Error("private artifact prefix is invalid");return`${e}/`}function y(t,e){let r=t.trim();if(!/^[a-zA-Z0-9_-]{1,160}$/.test(r))throw new Error(`${e} must contain only letters, numbers, underscores, or hyphens`);return r}function U(t){let e=t.trim();if(!/^[a-zA-Z0-9_.-]{1,200}$/.test(e)||e==="."||e==="..")throw new Error("private artifact key is invalid");return e}function k(t){return(t.trim().replace(/[^a-zA-Z0-9_.-]+/g,"-").replace(/^-+|-+$/g,"")||"artifact").slice(0,160)}function R(t){let e=typeof t=="string"&&/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(t)?`${t.replace(" ","T")}Z`:t,r=e instanceof Date?e.getTime():typeof e=="number"?e:new Date(e).getTime();if(!Number.isSafeInteger(r)||r<=0)throw new Error("private artifact createdAt is invalid");return r}function I(t){if(t.artifactTtlMs!==null&&(!Number.isSafeInteger(t.artifactTtlMs)||t.artifactTtlMs<=0))throw new Error("private artifact TTL must be a positive integer");if(!Number.isSafeInteger(t.downloadTtlMs)||t.downloadTtlMs<=0)throw new Error("private artifact download TTL must be a positive integer");return{prefix:P(t.prefix),artifactTtlMs:t.artifactTtlMs,downloadTtlMs:t.downloadTtlMs}}function W(t,e){let r=P(e);if(!t.startsWith(r))return null;let n=(t.split("/").at(-1)??"").match(/^(\d{13})-/);if(!n)return null;let o=Number(n[1]);return Number.isSafeInteger(o)&&o>0?o:null}function g(t,e){let r=P(e);if(!t.startsWith(r)||t.includes(".."))return null;let n=t.slice(r.length).split("/");if(n.length<2)return null;try{return y(n[0]??"","ownerId")}catch{return null}}function S(t,e){let r=I(e);if(g(t,r.prefix)===null||r.artifactTtlMs===null)return null;let i=W(t,r.prefix);return i===null?null:new Date(i+r.artifactTtlMs)}async function B(t,e,r){let i=r.token?.trim();if(!i)return null;let n=e?Math.min(Date.now()+r.downloadTtlMs,e.getTime()):Date.now()+r.downloadTtlMs;if(n<=Date.now())return null;let{issueSignedToken:o,presignUrl:c}=await import("@vercel/blob"),a=await o({token:i,pathname:t,operations:["get"],validUntil:n}),{presignedUrl:u}=await c(a,{access:"private",operation:"get",pathname:t,validUntil:n});return{url:u,expiresAt:new Date(n).toISOString()}}async function J(t){let e={...t.policy,...I(t.policy)},r=y(t.ownerId,"ownerId"),i=U(t.artifactKey),n=(t.scopeSegments??[]).map((f,l)=>y(f,`scopeSegments[${l}]`)),o=R(t.createdAt),c=`${e.prefix}${r}/${n.length?`${n.join("/")}/`:""}${o}-${i}`,a=Buffer.isBuffer(t.content)?t.content:Buffer.from(t.content),u=a.length,A=M("sha256").update(a).digest("hex"),m=e.artifactTtlMs===null?null:new Date(o+e.artifactTtlMs),d=e.token?.trim()||null,p=c;if(d){let{put:f}=await import("@vercel/blob");p=(await f(c,a,{access:"private",token:d,contentType:t.contentType,addRandomSuffix:!1,allowOverwrite:!0,cacheControlMaxAge:60,multipart:u>100*1024*1024})).pathname}else{if(T(e))throw new Error("private_artifact_blob_not_configured");let f=x(v(e),"blobs",c);await D(_(f),{recursive:!0}),await O(f,a)}let h=await B(p,m,e);return{artifactId:p,filename:k(t.filename),contentType:t.contentType,bytes:u,sha256:A,expiresAt:m?.toISOString()??b,downloadUrl:h?.url??null,downloadUrlExpiresAt:h?.expiresAt??null}}async function Q(t){let e={...t.policy,...I(t.policy)},r=y(t.ownerId,"ownerId"),i=U(t.artifactKey),n=(t.scopeSegments??[]).map((l,w)=>y(l,`scopeSegments[${w}]`)),o=R(t.createdAt),c=`${e.prefix}${r}/${n.length?`${n.join("/")}/`:""}${o}-${i}`,a=e.artifactTtlMs===null?null:new Date(o+e.artifactTtlMs),u=e.token?.trim()||null,A=M("sha256"),m=0,d=new K({transform(l,w,s){m+=l.length,A.update(l),s(null,l)}}),p=c;if(u){let{put:l}=await import("@vercel/blob"),w=E(t.content,d);try{let s=await l(c,d,{access:"private",token:u,contentType:t.contentType,addRandomSuffix:!1,allowOverwrite:!0,cacheControlMaxAge:60,multipart:!0});await w,p=s.pathname}catch(s){throw t.content.destroy(s instanceof Error?s:new Error(String(s))),d.destroy(s instanceof Error?s:new Error(String(s))),await w.catch(()=>{}),s}}else{if(T(e))throw new Error("private_artifact_blob_not_configured");let l=x(v(e),"blobs",c);await D(_(l),{recursive:!0}),await E(t.content,d,C(l))}let h=A.digest("hex"),f=await B(p,a,e);return{artifactId:p,filename:k(t.filename),contentType:t.contentType,bytes:m,sha256:h,expiresAt:a?.toISOString()??b,downloadUrl:f?.url??null,downloadUrlExpiresAt:f?.expiresAt??null}}async function Y(t){if(g(t.artifactId,t.policy.prefix)!==t.ownerId)return null;let e=S(t.artifactId,t.policy);if(t.policy.artifactTtlMs!==null&&(!e||e.getTime()<=Date.now()))return null;let r=await B(t.artifactId,e,t.policy);return r?{downloadUrl:r.url,downloadUrlExpiresAt:r.expiresAt,expiresAt:e?.toISOString()??b}:null}async function z(t){let e=t.getReader(),r=[];try{for(;;){let{done:i,value:n}=await e.read();if(i)break;n&&r.push(Buffer.from(n))}}finally{e.releaseLock()}return Buffer.concat(r)}async function tt(t){if(g(t.artifactId,t.policy.prefix)===null)return null;let e=S(t.artifactId,t.policy);if(t.policy.artifactTtlMs!==null&&(!e||e.getTime()<=Date.now()))return null;if(!Number.isSafeInteger(t.offset)||t.offset<0)throw new Error("private artifact offset is invalid");if(!Number.isSafeInteger(t.maxBytes)||t.maxBytes<=0)throw new Error("private artifact maxBytes is invalid");let r=t.policy.token?.trim()||null,i;if(r){let{get:c}=await import("@vercel/blob"),a=await c(t.artifactId,{access:"private",token:r,useCache:!1});if(!a||a.statusCode!==200)return null;i=await z(a.stream)}else{if(T(t.policy))return null;try{i=await $(x(v(t.policy),"blobs",t.artifactId))}catch{return null}}let n=i.length,o=Math.min(n,t.offset+t.maxBytes);return{text:i.subarray(t.offset,o).toString("utf8"),totalBytes:n,nextOffset:o<n?o:null}}async function et(t){if(g(t.artifactId,t.policy.prefix)===null)return null;let e=S(t.artifactId,t.policy);if(t.policy.artifactTtlMs!==null&&(!e||e.getTime()<=Date.now()))return null;if(!Number.isSafeInteger(t.maxBytes)||t.maxBytes<=0)throw new Error("private artifact maxBytes is invalid");let r=t.policy.token?.trim()||null,i;if(r){let{get:n}=await import("@vercel/blob"),o=await n(t.artifactId,{access:"private",token:r,useCache:!1});if(!o||o.statusCode!==200)return null;i=await z(o.stream)}else{if(T(t.policy))return null;try{i=await $(x(v(t.policy),"blobs",t.artifactId))}catch{return null}}if(i.length>t.maxBytes)throw new Error("private artifact exceeds read limit");return i}export{g as a,J as b,Q as c,Y as d,tt as e,et as f};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import{b as y}from"./chunk-HE45FFBU.js";var $=100*1024,L=new Set(["webp","avif","svg","svg+xml"]);function w(s){return s==null?null:s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(1)} KB`:`${(s/(1024*1024)).toFixed(2)} MB`}var R=s=>s.replace(/&/g,"&").replace(/�?38;/g,"&").replace(/&/gi,"&").trim(),M=s=>s.replace(/^https?:\/\//i,"//").replace(/\/$/,""),E=(s,r)=>{if(s){let c=s.split(";")[0].trim().toLowerCase();if(c.startsWith("image/"))return c.replace("image/","")}return(r.split("?")[0].match(/\.([a-z0-9]+)$/i)?.[1]||"unknown").toLowerCase()};function T(s){let r=new Map;for(let c of s)for(let n of c.imageLinks||[]){let e=R(n);if(!/^https?:\/\//i.test(e)||/[{}]|%7[bd]/i.test(e))continue;let a=M(e),i=r.get(a);(!i||/^https:/i.test(e)&&/^http:/i.test(i))&&r.set(a,e)}return[...r.values()]}async function D(s,r){let c=new AbortController,n=setTimeout(()=>c.abort(),r),e=i=>({len:i.headers.get("content-length"),cr:i.headers.get("content-range"),ct:i.headers.get("content-type"),status:i.status}),a=async i=>{let g=s;for(let p=0;p<=5;p++){let m=await y(g,{field:"image URL"});if(m.error||!m.parsed)throw new Error(m.error??"Image URL was rejected");let u=await fetch(m.parsed.href,{method:i,...i==="GET"?{headers:{Range:"bytes=0-0"}}:{},redirect:"manual",signal:c.signal});if(u.status>=300&&u.status<400){let t=u.headers.get("location");if(!t)throw new Error(`HTTP ${u.status} redirect did not include Location`);g=new URL(t,m.parsed.href).href;continue}return u}throw new Error("Image request exceeded five redirects")};try{let i=null,g=null,p=null;try{let m=e(await a("HEAD"));p=m.status,g=m.ct,m.len&&(i=Number(m.len))}catch{}if(i==null){let m=await a("GET"),u=e(m);if(p=p??u.status,g=g??u.ct,u.cr&&u.cr.includes("/")){let t=u.cr.split("/")[1];t&&t!=="*"&&(i=Number(t))}else u.len&&(i=Number(u.len));try{await m.body?.cancel()}catch{}}return{url:s,status:p,bytes:Number.isFinite(i)?i:null,contentType:g}}catch(i){return{url:s,status:null,bytes:null,contentType:null,error:String(i.message||i)}}finally{clearTimeout(n)}}async function v(s,r,c){let n=new Array(s.length),e=0;return await Promise.all(Array.from({length:Math.min(r,s.length)},async()=>{for(;e<s.length;){let a=e++;n[a]=await c(s[a])}})),n}async function S(s,r={}){return A(T(s),r)}async function A(s,r={}){let c=r.concurrency??12,n=r.timeoutMs??12e3,e=r.max??5e3,a=T([{imageLinks:s}]).slice(0,e),g=(await v(a,c,t=>D(t,n))).map(t=>{let f=E(t.contentType,t.url);return{...t,size:w(t.bytes),format:f,over100kb:t.bytes!=null&&t.bytes>$,legacyFormat:f!=="unknown"&&!L.has(f)}}),p=g.filter(t=>t.bytes!=null),m=p.reduce((t,f)=>t+f.bytes,0),u={};for(let t of g)u[t.format]=(u[t.format]||0)+1;return{rows:g.sort((t,f)=>(f.bytes??0)-(t.bytes??0)),summary:{unique:g.length,sized:p.length,totalBytes:m,totalSize:w(m)??"0 B",avgSize:w(Math.round(m/(p.length||1)))??"0 B",over100kb:g.filter(t=>t.over100kb).length,legacyFormat:g.filter(t=>t.legacyFormat).length,formatCounts:u,...r.sampleTruncated?{sampleTruncated:!0,sampleCap:e}:{}}}}function _(s){let r=s.summary,c=Object.entries(r.formatCounts).sort((a,i)=>i[1]-a[1]).map(([a,i])=>`${a}:${i}`).join(" "),n=s.rows.filter(a=>a.over100kb).slice(0,15),e=["## Images",`**${r.unique} unique images** \xB7 ${r.totalSize} total \xB7 ${r.avgSize} avg \xB7 ${r.over100kb} over 100 KB \xB7 ${r.legacyFormat} legacy format`,`Formats: ${c}`];if(n.length){e.push("","| Size | Format | URL |","|------|--------|-----|");for(let a of n)e.push(`| ${a.size} | ${a.format} | ${a.url} |`)}return e.join(`
|
|
2
|
+
`)}function I(s){let r=s.replace(/^www\./,"").toLowerCase(),c=r.split(".");return c.length<=2?r:c.slice(-2).join(".")}function U(s,r,c){let n="";try{n=I(new URL(c).hostname)}catch{n=""}let e=s.filter(l=>l.internal),a=r.length,i=r.filter(l=>l.orphan).length,g=e.filter(l=>l.targetStatus!=null&&l.targetStatus>=400).length,p=r.reduce((l,h)=>l+h.inlinks,0),m=r.reduce((l,h)=>l+h.outlinksInternal+h.outlinksExternal,0),u={zero:0,oneToTwo:0,threeToTen:0,elevenPlus:0};for(let l of r)l.inlinks===0?u.zero++:l.inlinks<=2?u.oneToTwo++:l.inlinks<=10?u.threeToTen++:u.elevenPlus++;let t=[...r].sort((l,h)=>h.inlinks-l.inlinks).slice(0,20).map(l=>({url:l.url,inlinks:l.inlinks,outlinksInternal:l.outlinksInternal,outlinksExternal:l.outlinksExternal})),f=new Map,d=0;for(let l of s){let h;try{h=I(new URL(l.to).hostname)}catch{continue}if(!h||h===n)continue;d++;let k=f.get(h)??{links:0,nofollow:0,pages:new Set};k.links++,l.nofollow&&k.nofollow++,k.pages.add(l.from),f.set(h,k)}let o=[...f.entries()].map(([l,h])=>({domain:l,links:h.links,nofollow:h.nofollow,pages:h.pages.size})).sort((l,h)=>h.links-l.links),b=l=>Math.round(l*10)/10;return{summary:{internal:{totalLinks:e.length,pages:a,orphans:i,brokenInternal:g,avgInlinks:a?b(p/a):0,avgOutlinks:a?b(m/a):0,distribution:u,topByInlinks:t},external:{totalLinks:d,uniqueDomains:o.length,topDomains:o.slice(0,20)}},externalDomains:o}}function X(s){let r=s.summary;return["## Link analysis",`**Internal:** ${r.internal.totalLinks} links \xB7 ${r.internal.pages} pages \xB7 avg ${r.internal.avgInlinks} inlinks/page \xB7 ${r.internal.orphans} orphans \xB7 ${r.internal.brokenInternal} broken`,`**External:** ${r.external.totalLinks} links to ${r.external.uniqueDomains} domains`,"","### Inlink distribution",`- 0 inlinks (orphans): ${r.internal.distribution.zero}`,`- 1\u20132: ${r.internal.distribution.oneToTwo}`,`- 3\u201310: ${r.internal.distribution.threeToTen}`,`- 11+: ${r.internal.distribution.elevenPlus}`,"","### Top 20 internal pages by inlinks","| inlinks | out (int/ext) | URL |","|---|---|---|",...r.internal.topByInlinks.map(n=>`| ${n.inlinks} | ${n.outlinksInternal}/${n.outlinksExternal} | ${n.url} |`),"","### Top 20 external domains by links","| links | nofollow | from pages | domain |","|---|---|---|---|",...r.external.topDomains.map(n=>`| ${n.links} | ${n.nofollow} | ${n.pages} | ${n.domain} |`)].join(`
|
|
3
|
+
`)}function x(s,r){let c=new Map;for(let n of s){let e=r(n);if(e==null||e==="")continue;let a=String(e);c.has(a)||c.set(a,[]),c.get(a).push(n.url)}return[...c.values()].filter(n=>n.length>1).flat()}function B(s,r,c){let n=t=>({count:t.length,urls:t.slice(0,200)}),e=t=>s.filter(t).map(f=>f.url),a=t=>t.extractionStatus!=="failed",i=t=>a(t)&&t.status===200,g=new Set(s.filter(a).map(t=>t.url)),p=t=>{try{return new URL(t).pathname}catch{return""}},m={"title.missing":n(e(t=>i(t)&&!t.title)),"title.duplicate":n(x(s.filter(i),t=>t.title)),"title.tooLong":n(e(t=>(t.titleLength??0)>60||(t.titlePixels??0)>561)),"title.tooShort":n(e(t=>t.title!=null&&(t.titleLength??0)<30)),"title.sameAsH1":n(e(t=>!!t.title&&!!t.h1&&t.title.trim()===t.h1.trim())),"meta.missing":n(e(t=>i(t)&&!t.metaDescription)),"meta.duplicate":n(x(s.filter(i),t=>t.metaDescription)),"meta.tooLong":n(e(t=>(t.metaDescLength??0)>155)),"meta.tooShort":n(e(t=>t.metaDescription!=null&&(t.metaDescLength??0)<70)),"h1.missing":n(e(t=>i(t)&&!t.h1)),"h1.multiple":n(e(t=>!!t.h1_2)),"h1.duplicate":n(x(s.filter(i),t=>t.h1)),"h1.tooLong":n(e(t=>(t.h1?.length??0)>70)),"h2.missing":n(e(t=>i(t)&&t.h2Count===0)),"crawl.extractionFailed":n(e(t=>!a(t))),"indexability.nonIndexable":n(e(t=>a(t)&&!t.indexable)),"indexability.noindex":n(e(t=>t.indexabilityReason==="noindex")),"canonical.missing":n(e(t=>i(t)&&!t.canonicalUrl)),"canonical.canonicalised":n(e(t=>t.indexabilityReason==="canonicalised")),"response.broken4xx":n(e(t=>(t.status??0)>=400&&(t.status??0)<500)),"response.error5xx":n(e(t=>(t.status??0)>=500)),"response.redirect3xx":n(e(t=>(t.status??0)>=300&&(t.status??0)<400)),"response.noResponse":n(e(t=>t.status===null)),"content.thin":n(e(t=>i(t)&&t.wordCount>0&&t.wordCount<200)),"content.exactDuplicate":n(x(s.filter(t=>i(t)&&t.contentHash),t=>t.contentHash)),"images.missingAlt":n(e(t=>a(t)&&t.imagesMissingAlt>0)),"schema.missing":n(e(t=>i(t)&&t.schemaTypes.length===0)),"url.tooLong":n(e(t=>t.url.length>115)),"url.uppercase":n(e(t=>/[A-Z]/.test(p(t.url)))),"url.underscores":n(e(t=>p(t.url).includes("_"))),"links.orphan":n([...r.values()].filter(t=>t.orphan&&g.has(t.url)).map(t=>t.url))},u=c;if(!u){let t=d=>{try{let o=new URL(d);return o.hash="",(o.origin+o.pathname).replace(/\/+$/,"")+o.search}catch{return d.replace(/#.*$/,"").replace(/\/+$/,"")}},f=new Map(s.map(d=>[t(d.url),d.status]));u=new Set;for(let d of s)for(let o of d.outlinks??[]){if(!o.internal)continue;let b=f.get(t(o.href));b!=null&&b>=400&&u.add(d.url)}}return m["links.brokenInternal"]=n([...u]),m}function C(s,r,c,n){let e=r.length,a=r.filter(o=>o.extractionStatus!=="failed").length,i=e-a,g=o=>o.startsWith("response.broken")||o.startsWith("response.error")||o.startsWith("links.broken")?"\u{1F534}":o.startsWith("title.missing")||o.startsWith("h1.missing")||o.startsWith("indexability")||o.startsWith("canonical.missing")?"\u{1F7E0}":"\u{1F7E1}",p=Object.entries(c).filter(([,o])=>o.count>0).sort((o,b)=>b[1].count-o[1].count).map(([o,b])=>`| ${g(o)} | \`${o}\` | ${b.count} | ${b.urls.slice(0,3).join(" \xB7 ")}${b.urls.length>3?" \u2026":""} |`),m=[...n.values()].map(o=>o.crawlDepth).filter(o=>o!=null),u=m.length?Math.max(...m):0,t=new Set(r.filter(o=>o.extractionStatus!=="failed").map(o=>o.url)),f=[...n.values()].filter(o=>o.orphan&&t.has(o.url)).length,d=[...n.values()].sort((o,b)=>b.inlinks-o.inlinks).slice(0,5);return[`# SEO Crawl Report: ${s}`,`**${e} pages attempted** \xB7 ${a} extracted \xB7 ${i} failed \xB7 max crawl depth ${u} \xB7 ${f} orphan page(s)`,`
|
|
4
|
+
## Issues
|
|
5
|
+
| | Issue | Count | Examples |
|
|
6
|
+
|---|-------|-------|----------|
|
|
7
|
+
${p.join(`
|
|
8
|
+
`)||"| \u2705 | none | 0 | \u2014 |"}`,`
|
|
9
|
+
## Most-linked pages
|
|
10
|
+
${d.map(o=>`- ${o.inlinks} inlinks \xB7 depth ${o.crawlDepth??"\u2014"} \xB7 ${o.url}`).join(`
|
|
11
|
+
`)}`,`
|
|
12
|
+
_Thresholds: title 60ch/561px, meta 155ch, H1 70ch, thin <200 words, URL 115ch. Pixel widths are estimates._`].join(`
|
|
13
|
+
`)}export{S as a,A as b,_ as c,U as d,X as e,B as f,C as g};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{a as P,c as S}from"./chunk-HE45FFBU.js";var N=20,U=20,H=10,j=20,E=280,q=/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,D=[".png",".jpg",".jpeg",".gif",".svg",".webp",".ico","@2x","sentry","wix.com","wixpress","example.","godaddy","squarespace","schema.org","u003e","core-js"],W=/\b(?:website|site|web)\s+(?:by|built|design(?:ed)?|develop(?:ed)?|powered)\b|\b(?:developer|webmaster)\b/i,z=/(?:^|\/)(?:about|bio|contact|contact-us|meet|our-team|people|profile|staff|team)(?:\/|$)/i,Y={"facebook.com":"facebook","fb.com":"facebook","instagram.com":"instagram","linkedin.com":"linkedin","twitter.com":"twitter","x.com":"x","youtube.com":"youtube","youtu.be":"youtube","tiktok.com":"tiktok","pinterest.com":"pinterest"},F=/(?:\/shar(?:e|er)|\/intent\/|\/dialog\/|\/plugins\/|\/share\?|\/developers?\/|platform\.)/i;function x(t){return(t??"").replace(/\s+/g," ").trim()}function _(t,e){try{let r=new URL(t,e);return!["http:","https:"].includes(r.protocol)||r.username||r.password?null:r}catch{return null}}function g(t){let e=t;try{e=decodeURIComponent(t)}catch{}let r=e.split("?")[0].trim().toLowerCase().replace(/[),.;:]+$/,"");return r.length>254||r.split("@").length!==2||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9.-]+\.[a-z]{2,}$/i.test(r)||D.some(n=>r.includes(n))?null:r}function f(t){let e=t.closest("p,li,address,section,article,div").first();return x(e.length?e.text():t.text()).slice(0,E)}function k(t,e,r,n){let s=g(e);!s||W.test(n)||t.has(s)||t.set(s,{value:s,sourceUrl:r,context:x(n).slice(0,E),sourceType:"first_party_page"})}function G(t){t.hash="";for(let e of[...t.searchParams.keys()])/^(?:utm_|fbclid|gclid)/i.test(e)&&t.searchParams.delete(e);return t.href}function J(t){let e=t.toLowerCase().replace(/^www\./,"");return Object.entries(Y).find(([n])=>e===n||e.endsWith(`.${n}`))?.[1]??null}function V(t,e){let r=_(e);if(!r)throw new Error("pageUrl must be a public HTTP(S) URL");let{$:n}=S(t),s=new Map,p=new Map,o=new Map,c=new Map;return n('a[href^="mailto:" i]').each((u,a)=>{let i=n(a);k(s,(i.attr("href")??"").slice(7),r.href,f(i))}),n("body").find("*").addBack().contents().filter((u,a)=>a.type==="text").each((u,a)=>{let i=n(a.parent??a),l=String(a.data??"");for(let d of l.match(q)??[])k(s,d,r.href,f(i))}),n("a[href]").each((u,a)=>{let i=n(a),l=_(i.attr("href")??"",r.href);if(!l)return;let d=x(`${i.text()} ${f(i)}`).slice(0,E),T=J(l.hostname);if(T&&!F.test(`${l.pathname}${l.search}`)){let v=G(l);p.has(v)||p.set(v,{url:v,network:T,sourceUrl:r.href,context:d});return}if(l.origin!==r.origin||!z.test(l.pathname))return;l.hash="";let y=l.href;c.has(y)||c.set(y,{url:y,sourceUrl:r.href,context:d})}),n("form").each((u,a)=>{let i=n(a),l=_(i.attr("action")||r.href,r.href);if(!l||l.origin!==r.origin)return;l.hash="";let d=l.href;o.has(d)||o.set(d,{url:d,sourceUrl:r.href,context:f(i)})}),{emails:[...s.values()].slice(0,N),socialProfiles:[...p.values()].slice(0,U),contactForms:[...o.values()].slice(0,H),candidatePageUrls:[...c.values()].slice(0,j)}}import{createHash as K}from"crypto";var I="3.0.0",w="analytics_setup_site",B="Install X-Ray",R="Install X-Ray and tell me what drives customers",m=`Call ${w} with { "startUrl": "<site URL>", "goal": "${R}" }; on every later call, reuse the returned setupId and revision.`,C=JSON.stringify({mcpServers:{"mcp-scraper":{command:"npx",args:["-y","--package","mcp-scraper@latest","mcp-scraper"],env:{MCP_SCRAPER_API_KEY:"${env:MCP_SCRAPER_API_KEY}"}}}},null,2),Z=JSON.stringify({mcpServers:{"mcp-scraper":{url:"https://mcpscraper.dev/mcp"}}},null,2),O={schema:"https://mcpscraper.dev/schemas/xray-install-contract-v1.json",protocolVersion:I,product:"Thorbit X-Ray",triggerPhrases:[B,"Install X-Ray on this site and tell me what drives customers"],canonicalUrls:{markdown:"https://mcpscraper.dev/agent-install.md",json:"https://mcpscraper.dev/.well-known/xray-install.json",hostedMcp:"https://mcpscraper.dev/mcp"},facade:{tool:w,initialCall:{startUrl:"<site URL>",goal:R},continuationRule:"Treat setupId plus revision as the durable continuation handle. Reuse both after approval, runtime publication, verification, retry, or return."},topologies:{local_stdio:{label:"Local npm MCP process",authority:"The client starts MCP Scraper locally. After the one-time Pixel insertion, X-Ray setup publishes only owner-confirmed runtime configuration.",secretHandling:"Set MCP_SCRAPER_API_KEY in the local environment or client secret field. Never paste it into chat or commit it."},hosted_remote:{label:"Hosted authenticated MCP",authority:"The hosted MCP inspects approved public pages and publishes owner-confirmed X-Ray runtime configuration. It cannot read or write a caller-local path.",secretHandling:"Use the MCP OAuth/connection flow. Never put a credential in a URL, prompt, or config shown in chat."}},hosts:[{id:"codex",label:"Codex",supportedTopologies:["local_stdio","hosted_remote"],mcpConfigMode:"toml",workspaceRead:!0,workspaceWrite:!0,restartRequired:!0,exactConfig:`[mcp_servers.mcp-scraper]
|
|
2
|
+
command = "npx"
|
|
3
|
+
args = ["-y", "--package", "mcp-scraper@latest", "mcp-scraper"]
|
|
4
|
+
env_vars = ["MCP_SCRAPER_API_KEY"]`,continuation:m,rollback:"Remove the mcp_servers.mcp-scraper table, then restart Codex. Pixel removal is a separate owner-controlled site action."},{id:"claude-code",label:"Claude Code",supportedTopologies:["local_stdio","hosted_remote"],mcpConfigMode:"command",workspaceRead:!0,workspaceWrite:!0,restartRequired:!0,exactConfig:'claude mcp add mcp-scraper --scope user --env MCP_SCRAPER_API_KEY="$MCP_SCRAPER_API_KEY" -- npx -y --package mcp-scraper@latest mcp-scraper',continuation:m,rollback:"Run: claude mcp remove mcp-scraper -s user. Pixel removal is a separate owner-controlled site action."},{id:"claude-desktop",label:"Claude Desktop",supportedTopologies:["local_stdio"],mcpConfigMode:"desktop_extension",workspaceRead:!1,workspaceWrite:!1,restartRequired:!0,exactConfig:"Install https://mcpscraper.dev/downloads/mcp-scraper.mcpb and enter the API key only in Claude Desktop's protected configuration field.",continuation:m,rollback:"Remove the MCP Scraper extension in Claude Desktop. Pixel removal is a separate owner-controlled site action."},{id:"cursor",label:"Cursor",supportedTopologies:["local_stdio","hosted_remote"],mcpConfigMode:"json",workspaceRead:!0,workspaceWrite:!0,restartRequired:!0,exactConfig:C,continuation:m,rollback:"Remove mcp-scraper from .cursor/mcp.json (or the user MCP settings), then restart Cursor."},{id:"windsurf",label:"Windsurf",supportedTopologies:["local_stdio"],mcpConfigMode:"json",workspaceRead:!0,workspaceWrite:!0,restartRequired:!0,exactConfig:C,continuation:m,rollback:"Remove mcp-scraper from the Windsurf MCP configuration, then restart Windsurf."},{id:"cline",label:"Cline",supportedTopologies:["local_stdio"],mcpConfigMode:"json",workspaceRead:!0,workspaceWrite:!0,restartRequired:!0,exactConfig:C,continuation:m,rollback:"Remove mcp-scraper from Cline MCP Servers, then restart the extension host."},{id:"user-action-only",label:"User-action-only MCP host",supportedTopologies:["hosted_remote"],mcpConfigMode:"handoff_only",workspaceRead:!1,workspaceWrite:!1,restartRequired:!1,exactConfig:Z,continuation:m,rollback:"Disconnect MCP Scraper from the host. Pixel removal remains an owner-controlled site action."}],tagBootstrap:{requirement:"one_global_pixel_once",ongoingConfiguration:"xray_runtime_manifest",sourceAccessRequiredAfterInstall:!1,supportedInsertionPaths:["manual","tag_manager","cms_plugin","coding_host"]},workflow:["Resolve Thorbit X-Ray entitlement and the target site without consuming MCP Scraper Credits.","Inspect the whole approved public site; enumerate distinct renderers, routes, and Pixel coverage.","Infer the business model and customer outcome, then propose one privacy-safe measurement plan.","If the Pixel is absent, return the canonical one-time tag and exact uncovered surfaces; do not claim ongoing control there.","Publish an approved measurement revision as a digest-bound runtime manifest; source or repository access is not required.","For SaaS, verify the measurement foundation: global tag coverage, ad-source capture, lifecycle events, currency and timezone, consent, and observed outcome events.","Optionally publish a structured post-purchase survey after approved disclosure evidence; reported influence remains separate from deterministic touches.","Compare observed attribution with customer-reported influence only with explicit weights totaling 1,000,000 micros and a named methodology version.","Keep view-through reporting unavailable until event-level provider evidence can join to an eligible X-Ray subject; aggregate impressions never qualify.","Verify route coverage, consent, PageViews, manifest convergence, bounded rule matches, and persisted definition/version evidence.","Require a separate exact-revision approval before any canary or real-visitor experiment activation.","Return first customer-journey answers when sufficient, or exact evidence-readiness thresholds when not.","On \u201Cimprove\u201D, propose one highest-value uncovered outcome, require approval when needed, and reverify."],safetyRules:["Never invent or hand-author tracking code; use the canonical product-authored Pixel snippet returned by analytics_setup_site.","Never ask for or print API keys, OAuth tokens, signed URLs, cookies, or other credentials.","Never call ad platforms directly or silently activate events, definitions, funnels, or delivery destinations.","Never treat a CTA click as a customer, sale, or revenue event without verified outcome evidence.","Never claim full-domain installation while an in-scope route or renderer is missing, excluded without approval, or unverifiable.","Never treat event-name presence as verification; require persisted definition ID and version evidence.","Never accept survey invitation tokens or exchange codes through MCP inputs or prompts.","Never treat customer-reported influence as identity, CRM mutation authority, ad-activation evidence, or a deterministic touch."],terminalStates:["complete","tag_required","input_required","approval_required","runtime_convergence_required","not_ready","error"]};function b(t){return Array.isArray(t)?`[${t.map(b).join(",")}]`:t&&typeof t=="object"?`{${Object.entries(t).sort(([e],[r])=>e.localeCompare(r)).map(([e,r])=>`${JSON.stringify(e)}:${b(r)}`).join(",")}}`:JSON.stringify(t)}function Q(){return b(O)}var L=`sha256:${K("sha256").update(Q(),"utf8").digest("hex")}`,X={...O,protocolDigest:L};function fe(t){let e=X.hosts.find(r=>r.id===t);if(!e)throw new Error(`Unknown X-Ray host: ${t}`);return e}function ge(){return["# Install X-Ray","",`Protocol: ${I} (${L})`,"",`Use ${w} as the single conversational setup facade. Ask for the target site URL if it is missing, then call it with the goal \u201C${R}\u201D.`,"","Continue the same setup with its setupId and revision. Confirm one global Pixel across all public rendering surfaces; present one measurement plan; publish it as a digest-bound runtime manifest after exact-revision approval; verify manifest and rule versions; then return first customer-journey answers or explicit readiness thresholds. For SaaS, verify the provider-neutral measurement foundation. Browser events never prove paid revenue. GitHub or repository access is not required after the tag is installed.","","Do not request pasted credentials, invent tracking code, silently activate measurement, call ad platforms directly, or claim customers/revenue from CTA clicks."].join(`
|
|
5
|
+
`)}function he(t=X){return JSON.parse(JSON.stringify(t))}var ee=new Set(["admin","contact","customerservice","hello","help","info","inquiries","mail","office","reception","sales","service","support","team"]),te=/(?:^|\/)(?:about|bio|contact|contact-us|meet|our-team|people|profile|staff|team)(?:\/|$)/i,re=/\b(?:our team|meet the team|staff|agents?|brokers?|realtors?|people)\b/i,oe=/\b(?:brokerage|company|corporate|front desk|main office|office|organization|reception)\b/i;function M(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim().split(/\s+/).filter(Boolean)}function A(t,e){try{let r=new URL(t,e);return!["http:","https:"].includes(r.protocol)||r.username||r.password?null:r}catch{return null}}function ne(t,e){let r=t.value.split("@")[0].toLowerCase().replace(/[^a-z0-9]+/g," "),n=M(e.name).filter(a=>a.length>1),s=A(t.sourceUrl)?.pathname.toLowerCase()??"",p=`${t.context} ${s}`.toLowerCase(),o=ee.has(r.replace(/\s+/g,"")),c=n.filter(a=>new RegExp(`(?:^|[^a-z0-9])${a}(?:$|[^a-z0-9])`,"i").test(`${r} ${p}`)).length,u=e.entityType==="person"&&n.length>=2&&c>=Math.min(2,n.length)&&(r.includes(n[0])||s.includes(n.join("-"))||s.includes(n.join("/")));return!o&&u?{scope:"person",reasons:["named_person_page_context"]}:o||oe.test(p)?{scope:"office",reasons:o?["generic_mailbox_prefix"]:["organization_page_context"]}:re.test(p)?{scope:"team",reasons:["team_page_context"]}:e.entityType==="business"&&M(e.organization||e.name).filter(i=>i.length>2).some(i=>p.includes(i))?{scope:"team",reasons:["business_context"]}:{scope:"unknown",reasons:["public_occurrence_without_identity_evidence"]}}function ve(t,e){let r=t.map(o=>({...o,...ne(o,e)})),n=e.entityType==="person"?["person","team"]:["person","team","office"],s=["provided","first_party_page","structured_data","serp_snippet"],p=["person","team","office"];return r.filter(o=>n.includes(o.scope)).sort((o,c)=>s.indexOf(o.sourceType)-s.indexOf(c.sourceType)||p.indexOf(o.scope)-p.indexOf(c.scope))[0]??null}function _e(t,e,r){if(!Number.isInteger(r)||r<1||r>4)throw new Error("maxPages must be an integer from 1 to 4");let n=A(t);if(!n)return[];n.hash="";let s=new Set([n.href]),p=e.map(o=>typeof o=="string"?o:o.url).map(o=>A(o,n.href)).filter(o=>!!(o&&o.origin===n.origin&&te.test(o.pathname)));for(let o of p)o.hash="",s.add(o.href);for(let o of["/contact","/contact-us"])s.add(new URL(o,n.origin).href);return[...s].slice(0,r)}var se=/[A-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,ie=/\b(?:website|site|web)\s+(?:by|built|design(?:ed)?|develop(?:ed)?|powered)\b|\b(?:developer|webmaster)\b/i,ae=280,ce=10;function h(t){return t.toLowerCase().replace(/^www\./,"").replace(/\.$/,"")}function le(t){let e=h(t);return e==="localhost"||e.endsWith(".localhost")||e.endsWith(".local")||!e.includes(".")&&!e.includes(":")}function $(t){try{let e=new URL(t.trim());return!["http:","https:"].includes(e.protocol)||e.username||e.password||le(e.hostname)||P(e.hostname)?null:e}catch{return null}}function pe(t,e){return`${t} ${e??""}`.replace(/\s+/g," ").trim().slice(0,ae)}function we(t){let e=$(t);return e?(e.hostname=h(e.hostname),`email for ${e.protocol}//${e.host}/`):null}function Re({websiteUrl:t,results:e}){let r=$(t);if(!r)return[];let n=h(r.hostname),s=new Map,p=e.map((o,c)=>({result:o,index:c})).sort((o,c)=>{let u=Number.isFinite(o.result.position)?o.result.position:Number.MAX_SAFE_INTEGER,a=Number.isFinite(c.result.position)?c.result.position:Number.MAX_SAFE_INTEGER;return u-a||o.index-c.index});for(let{result:o}of p){let c=`${o.title} ${o.snippet??""}`,u=pe(o.title,o.snippet);for(let a of c.match(se)??[]){let i=g(a);!i||ie.test(c)||h(i.slice(i.lastIndexOf("@")+1))!==n||s.has(i)||s.set(i,{value:i,sourceUrl:o.url,sourceTitle:o.title,sourcePosition:o.position,context:u,sourceType:"serp_snippet"})}}return[...s.values()].slice(0,ce)}export{V as a,ne as b,ve as c,_e as d,we as e,Re as f,I as g,w as h,R as i,L as j,X as k,fe as l,ge as m,he as n};
|