mcp-scraper 0.96.0 → 0.96.2
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 +28 -1
- package/README.md +3 -1
- package/dist/{actions-YCMJY3PF.js → actions-R4EJDLRO.js} +1 -1
- package/dist/bin/api-server.js +1 -1
- package/dist/bin/mcp-scraper-cli.js +1 -1
- package/dist/bin/mcp-scraper-core.js +1 -1
- package/dist/bin/mcp-scraper-install.js +1 -1
- package/dist/bin/mcp-stdio-server.js +1 -1
- package/dist/bin/paa-harvest.js +1 -1
- package/dist/{bundle-TTJP6DHU.js → bundle-FCXZMIRB.js} +1 -1
- package/dist/chunk-2OKQVTQ5.js +173 -0
- package/dist/{chunk-ZPQNY5TI.js → chunk-5LYINW7Z.js} +8 -1
- package/dist/{chunk-R5LJL6IR.js → chunk-6BD75VKS.js} +30 -37
- package/dist/{chunk-VAC3SQ5T.js → chunk-6K7ZJYQW.js} +3 -3
- package/dist/chunk-7H6YWD2L.js +1 -0
- package/dist/{chunk-6SNOUSSZ.js → chunk-7WPCGRD7.js} +1 -1
- package/dist/{chunk-DGAW7FD7.js → chunk-BPKTUCV7.js} +1 -1
- package/dist/{chunk-QWE7VKIX.js → chunk-CORWWDHL.js} +1 -1
- package/dist/{chunk-LFRAA3MY.js → chunk-DTVKZU5X.js} +1 -1
- package/dist/{chunk-HJIOH7HF.js → chunk-H6MODA7W.js} +2 -2
- package/dist/{chunk-JAV5V3JT.js → chunk-HVQZRQRJ.js} +19 -19
- package/dist/chunk-JHT6A4U6.js +11 -0
- package/dist/{chunk-ARSQZCTJ.js → chunk-KUEMW76G.js} +255 -245
- package/dist/{chunk-SNJR5N36.js → chunk-RYX4FJVH.js} +1 -1
- package/dist/{chunk-JW4GDY7S.js → chunk-SE4VKLEC.js} +1 -1
- package/dist/{chunk-TPN25AFZ.js → chunk-SFUOSJ3A.js} +1 -1
- package/dist/{chunk-GVYGAZV7.js → chunk-UXNR3K6I.js} +1 -1
- package/dist/{chunk-FRXKMOXI.js → chunk-ZTMQEDIB.js} +1 -1
- package/dist/{dispatch-3HY4735M.js → dispatch-P7IY75LH.js} +1 -1
- package/dist/index.cjs +36 -36
- package/dist/index.d.cts +3 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +1 -1
- package/dist/{queue-HUP2GNXF.js → queue-AC4XKD6Z.js} +1 -1
- package/dist/{reconciliation-ANXNJWME.js → reconciliation-UZUZ6B74.js} +1 -1
- package/dist/{server-VQU6S24A.js → server-AEEE7E3C.js} +600 -600
- package/dist/{settlement-6CCE2PDH.js → settlement-6CS4JZTY.js} +1 -1
- package/dist/{worker-5G5BK23B.js → worker-HHUU2ECG.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-2PRH4Z3N.js +0 -181
- package/dist/chunk-7UHDOIUE.js +0 -1
- package/dist/chunk-OB6E6UTD.js +0 -1
|
@@ -1 +1,8 @@
|
|
|
1
|
-
var
|
|
1
|
+
var t={serp:6e3,serp_headless:6e3,serp_headful:6e3,paa:1e3,paa_base:4e4,page_scrape:100,url_map:500,yt_channel:200,yt_transcription:200,fb_ad:700,maps_search:500,maps_place:6e3,maps_review:100,fb_search:800,fb_search_result:100,fb_page_intel:700,fb_page_intel_ad:50,fb_reels_inventory:400,fb_transcribe:33300,tiktok_transcribe:33300,google_ads_search:600,google_ads_intel:200,google_ads_transcribe:33300,instagram_profile:400,instagram_media:400,instagram_transcribe:33300,browser_minute:12e3,reddit_thread:3e3,reddit_comment:200,video_analysis:666700,trustpilot_reviews:500,trustpilot_review:100,g2_reviews:500,g2_review:200,diff_page:100,listing_create:1e3,listing_edit:200},o={TOPUP:"topup",SUBSCRIPTION:"subscription",SIGNUP_GRANT:"signup_grant",MONTHLY_REFRESH:"monthly_free_refresh",PAA:"paa",PAA_REFUND:"paa_refund",SERP:"serp",SERP_REFUND:"serp_refund",REFUND:"refund",TRANSCRIPTION:"transcription",TRANSCRIPTION_HOLD:"transcription_hold",TRANSCRIPTION_REFUND:"transcription_refund",YT_CHANNEL:"yt_channel",FB_AD:"fb_ad",MAPS_SEARCH:"maps_search",DIRECTORY_WORKFLOW_HOLD:"directory_workflow_hold",DIRECTORY_WORKFLOW_REFUND:"directory_workflow_refund",LEAD_LIST_ENRICHMENT_HOLD:"lead_list_enrichment_hold",LEAD_LIST_ENRICHMENT_REFUND:"lead_list_enrichment_refund",MAPS_PLACE:"maps_place",MAPS_REVIEW:"maps_review",MAPS_REVIEW_REFUND:"maps_review_refund",EXTRACT_SITE:"extract_site",EXTRACT_SITE_REFUND:"extract_site_refund",EXTRACT_URL:"page_scrape",URL_MAP:"url_map",EXTRACT_SITE_HOLD:"extract_site_hold",YT_CHANNEL_REFUND:"yt_channel_refund",FB_AD_REFUND:"fb_ad_refund",URL_MAP_REFUND:"url_map_refund",FB_SEARCH:"fb_search",FB_REELS_INVENTORY:"fb_reels_inventory",FB_REELS_INVENTORY_REFUND:"fb_reels_inventory_refund",FB_TRANSCRIBE:"fb_transcribe",TIKTOK_TRANSCRIBE:"tiktok_transcribe",FB_SEARCH_REFUND:"fb_search_refund",FB_SEARCH_RESULT:"fb_search_result",FB_SEARCH_RESULT_REFUND:"fb_search_result_refund",FB_PAGE_INTEL:"fb_page_intel",FB_PAGE_INTEL_REFUND:"fb_page_intel_refund",FB_PAGE_INTEL_AD:"fb_page_intel_ad",FB_PAGE_INTEL_AD_REFUND:"fb_page_intel_ad_refund",FB_TRANSCRIBE_REFUND:"fb_transcribe_refund",TIKTOK_TRANSCRIBE_REFUND:"tiktok_transcribe_refund",GOOGLE_ADS_SEARCH:"google_ads_search",GOOGLE_ADS_SEARCH_REFUND:"google_ads_search_refund",GOOGLE_ADS_INTEL:"google_ads_intel",GOOGLE_ADS_INTEL_REFUND:"google_ads_intel_refund",GOOGLE_ADS_TRANSCRIBE:"google_ads_transcribe",GOOGLE_ADS_TRANSCRIBE_REFUND:"google_ads_transcribe_refund",INSTAGRAM_PROFILE:"instagram_profile",INSTAGRAM_PROFILE_REFUND:"instagram_profile_refund",INSTAGRAM_MEDIA:"instagram_media",INSTAGRAM_MEDIA_REFUND:"instagram_media_refund",INSTAGRAM_TRANSCRIBE:"instagram_transcribe",INSTAGRAM_TRANSCRIBE_REFUND:"instagram_transcribe_refund",BROWSER_SESSION:"browser_session",REDDIT_THREAD:"reddit_thread",REDDIT_THREAD_REFUND:"reddit_thread_refund",REDDIT_COMMENT:"reddit_comment",REDDIT_COMMENT_REFUND:"reddit_comment_refund",VIDEO_ANALYSIS:"video_analysis",VIDEO_ANALYSIS_REFUND:"video_analysis_refund",VIDEO_ANALYSIS_ADJUST:"video_analysis_adjust",VIDEO_ANALYSIS_LLM:"video_analysis_llm",MEMORY_AI:"memory_ai",MEMORY_AI_REFUND:"memory_ai_refund",TRUSTPILOT_REVIEWS:"trustpilot_reviews",TRUSTPILOT_REVIEWS_REFUND:"trustpilot_reviews_refund",TRUSTPILOT_REVIEW:"trustpilot_review",TRUSTPILOT_REVIEW_REFUND:"trustpilot_review_refund",G2_REVIEWS:"g2_reviews",G2_REVIEWS_REFUND:"g2_reviews_refund",G2_REVIEW:"g2_review",G2_REVIEW_REFUND:"g2_review_refund",DIFF_PAGE:"diff_page",DIFF_PAGE_REFUND:"diff_page_refund",LOCAL_SOURCEBOOK_CREATE:"local_sourcebook_create",LOCAL_SOURCEBOOK_CREATE_REFUND:"local_sourcebook_create_refund",LOCAL_SOURCEBOOK_EDIT:"local_sourcebook_edit",LOCAL_SOURCEBOOK_EDIT_REFUND:"local_sourcebook_edit_refund",COMMONS_CREATE:"commons_create",COMMONS_CREATE_REFUND:"commons_create_refund",COMMONS_EDIT:"commons_edit",COMMONS_EDIT_REFUND:"commons_edit_refund",SITE_AUDIT_LLM:"site_audit_llm",SCHEDULED_RUN:"scheduled_run",CONNECTED_USAGE:"connected_usage",CONNECTED_ACCOUNT_FEE:"connected_account_fee",ADMIN_GRANT:"admin_grant",ADMIN_REVOKE:"admin_revoke"};function E(e){return e===!0?t.serp_headless:t.serp_headful}var a=100,i=20,s=35;function d(e,_){return e*a*(_==="apify"?i:s)}var n=class extends Error{constructor(){super("Current operation wallet claim and matching durable plan are required"),this.name="WalletClaimLostError"}},r=class extends Error{constructor(){super("Named operation debit plan conflicts with durable billing history"),this.name="DebitPlanConflictError"}};function l(e){if(!Number.isSafeInteger(e.userId)||e.userId<=0||!Number.isSafeInteger(e.amountMc)||e.amountMc<=0||!e.key||e.key.length>500||!e.operation||!e.description||e.description.length>500)throw new r;return{sql:`EXISTS (SELECT 1 FROM billing_debits d WHERE d.idempotency_key=? AND d.user_id=?
|
|
2
|
+
AND d.amount_mc=? AND d.operation=? AND d.description=? AND d.status='applied'
|
|
3
|
+
AND NOT EXISTS (SELECT 1 FROM billing_events b WHERE b.user_id=d.user_id
|
|
4
|
+
AND b.billing_class='wallet_hold_settlement'
|
|
5
|
+
AND json_extract(b.metadata,'$.debitIdempotencyKey')=d.idempotency_key))`,args:[e.key,e.userId,e.amountMc,e.operation,e.description]}}function c(e,_){if(!/^[a-z_]+\.[a-z_]+$/.test(e)||!/^json_extract\([a-z_]+\.[a-z_]+,'\$\.hold\.key'\)$/.test(_))throw new Error("Invalid stored hold selector");return`EXISTS (SELECT 1 FROM billing_debits d WHERE d.user_id=${e}
|
|
6
|
+
AND d.idempotency_key=${_} AND d.status='applied'
|
|
7
|
+
AND NOT EXISTS (SELECT 1 FROM billing_events b WHERE b.user_id=d.user_id
|
|
8
|
+
AND b.billing_class='wallet_hold_settlement' AND json_extract(b.metadata,'$.debitIdempotencyKey')=d.idempotency_key))`}export{n as a,r as b,l as c,c as d,t as e,o as f,E as g,a as h,i,s as j,d as k};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as u}from"./chunk-WNUXMPVX.js";var
|
|
1
|
+
import{a as _,b as N,c as I}from"./chunk-5LYINW7Z.js";import{a as u}from"./chunk-WNUXMPVX.js";var y="2026-06-26 21:58:03";var k="+3 months";function D(t){return{sql:`INSERT INTO credit_lots (user_id, amount_mc, remaining_mc, source, expires_at)
|
|
2
2
|
SELECT ?, legacy.balance_mc, legacy.balance_mc, 'migration', datetime('now', ?)
|
|
3
3
|
FROM (
|
|
4
4
|
SELECT COALESCE(SUM(amount_mc), 0) AS balance_mc
|
|
@@ -12,36 +12,29 @@ import{a as u}from"./chunk-WNUXMPVX.js";var L="2026-06-26 21:58:03";var W="+3 mo
|
|
|
12
12
|
)
|
|
13
13
|
AND NOT EXISTS (
|
|
14
14
|
SELECT 1 FROM credit_lots WHERE user_id = ?
|
|
15
|
-
)`,args:[
|
|
16
|
-
|
|
17
|
-
AND NOT EXISTS (SELECT 1 FROM billing_events b WHERE b.user_id=d.user_id
|
|
18
|
-
AND b.billing_class='wallet_hold_settlement'
|
|
19
|
-
AND json_extract(b.metadata,'$.debitIdempotencyKey')=d.idempotency_key))`,args:[e.key,e.userId,e.amountMc,e.operation,e.description]}}function v(e,t){if(!/^[a-z_]+\.[a-z_]+$/.test(e)||!/^json_extract\([a-z_]+\.[a-z_]+,'\$\.hold\.key'\)$/.test(t))throw new Error("Invalid stored hold selector");return`EXISTS (SELECT 1 FROM billing_debits d WHERE d.user_id=${e}
|
|
20
|
-
AND d.idempotency_key=${t} AND d.status='applied'
|
|
21
|
-
AND NOT EXISTS (SELECT 1 FROM billing_events b WHERE b.user_id=d.user_id
|
|
22
|
-
AND b.billing_class='wallet_hold_settlement' AND json_extract(b.metadata,'$.debitIdempotencyKey')=d.idempotency_key))`}var D="(CAST(strftime('%s', 'now') AS INTEGER) * 1000)",f="operation-debit:",w=e=>e==="execute"?"e.phase = 'effects_started' AND r.status = 'running'":"e.phase = 'unknown' AND r.status = 'unknown'";function C(e,t,r){if(!r){if(t.startsWith(f))throw new _;return}if(r.userId!==e||!r.runId||!r.token||!["execute","compensate"].includes(r.mode))throw new _}var h=e=>String(e).includes("operation_wallet_claim_current");function x(e,t,r,n){if(C(e,t,r),!r){let a=A(),c="NOT EXISTS (SELECT 1 FROM operation_debit_plans WHERE debit_key = ?)";return{before:[{sql:`INSERT INTO operation_wallet_fences (id, allowed)
|
|
23
|
-
SELECT ?, CASE WHEN ${c} THEN 1 ELSE 0 END`,args:[a,t]}],after:[{sql:"DELETE FROM operation_wallet_fences WHERE id = ?",args:[a]}],current:async p=>!!(await p.execute({sql:`SELECT ${c} AS allowed`,args:[t]})).rows[0]?.allowed}}if(n.kind==="debit"&&r.mode!=="execute"||r.mode==="compensate"&&n.amountMc!==0&&!r.settlementPlanId)throw new _;let i=r.settlementPlanId?" AND EXISTS (SELECT 1 FROM operation_final_settlements s WHERE s.id=? AND s.run_id=p.run_id AND s.user_id=r.user_id AND s.debit_key=p.debit_key AND s.final_amount_mc=? AND s.refund_operation=? AND s.source_surface=?)":"",l=`SELECT 1 FROM operation_debit_plans p
|
|
15
|
+
)`,args:[t,k,t,t,y,t]}}async function O(t){return(await u().execute(D(t))).rowsAffected}import{createHash as T,randomUUID as A}from"crypto";var R="(CAST(strftime('%s', 'now') AS INTEGER) * 1000)",f="operation-debit:",w=t=>t==="execute"?"e.phase = 'effects_started' AND r.status = 'running'":"e.phase = 'unknown' AND r.status = 'unknown'";function C(t,e,r){if(!r){if(e.startsWith(f))throw new _;return}if(r.userId!==t||!r.runId||!r.token||!["execute","compensate"].includes(r.mode))throw new _}var W=t=>String(t).includes("operation_wallet_claim_current");function h(t,e,r,i){if(C(t,e,r),!r){let a=A(),d="NOT EXISTS (SELECT 1 FROM operation_debit_plans WHERE debit_key = ?)";return{before:[{sql:`INSERT INTO operation_wallet_fences (id, allowed)
|
|
16
|
+
SELECT ?, CASE WHEN ${d} THEN 1 ELSE 0 END`,args:[a,e]}],after:[{sql:"DELETE FROM operation_wallet_fences WHERE id = ?",args:[a]}],current:async p=>!!(await p.execute({sql:`SELECT ${d} AS allowed`,args:[e]})).rows[0]?.allowed}}if(i.kind==="debit"&&r.mode!=="execute"||r.mode==="compensate"&&i.amountMc!==0&&!r.settlementPlanId)throw new _;let n=r.settlementPlanId?" AND EXISTS (SELECT 1 FROM operation_final_settlements s WHERE s.id=? AND s.run_id=p.run_id AND s.user_id=r.user_id AND s.debit_key=p.debit_key AND s.final_amount_mc=? AND s.refund_operation=? AND s.source_surface=?)":"",l=`SELECT 1 FROM operation_debit_plans p
|
|
24
17
|
JOIN operation_runs r ON r.id = p.run_id JOIN operation_executions e ON e.run_id = r.id
|
|
25
18
|
WHERE p.debit_key = ? AND r.id = ? AND r.user_id = ? AND e.claim_token = ?
|
|
26
|
-
AND e.expires_at_ms > ${
|
|
27
|
-
AND ${
|
|
19
|
+
AND e.expires_at_ms > ${R} AND ${w(r.mode)}
|
|
20
|
+
AND ${i.kind==="debit"?"p.amount_mc = ? AND p.operation = ? AND p.description = ?":"p.refund_operation = ? AND p.source_surface = ?"}${n}`,c=[e,r.runId,t,r.token,...i.kind==="debit"?[i.amountMc,i.operation,i.description]:[i.operation,i.sourceSurface],...r.settlementPlanId?[r.settlementPlanId,i.amountMc,i.operation,i.sourceSurface]:[]],o=A(),s=i.kind==="debit"?{sql:`INSERT OR IGNORE INTO operation_billing_links (run_id, billing_table, billing_key, relation, amount_mc)
|
|
28
21
|
SELECT p.run_id, 'billing_debits', d.idempotency_key, 'debit', d.amount_mc FROM operation_debit_plans p
|
|
29
22
|
JOIN billing_debits d ON d.idempotency_key = p.debit_key
|
|
30
|
-
WHERE p.debit_key = ? AND d.user_id = ? AND d.status = 'applied'`,args:[t
|
|
23
|
+
WHERE p.debit_key = ? AND d.user_id = ? AND d.status = 'applied'`,args:[e,t]}:{sql:`INSERT OR IGNORE INTO operation_billing_links (run_id, billing_table, billing_key, relation, amount_mc)
|
|
31
24
|
SELECT p.run_id, 'billing_events', b.id, 'settlement', b.amount_mc FROM operation_debit_plans p
|
|
32
25
|
JOIN billing_events b ON b.idempotency_key = ?
|
|
33
|
-
WHERE p.debit_key = ? AND b.user_id = ? AND b.status = 'settled'`,args:[`debit-settlement:${
|
|
34
|
-
SELECT ?, CASE WHEN EXISTS (${l}) THEN 1 ELSE 0 END`,args:[o,...
|
|
35
|
-
WHERE r.id = ? AND r.user_id = ? AND e.claim_token = ? AND e.expires_at_ms > ${
|
|
36
|
-
AND ${w("execute")})`,l=[
|
|
26
|
+
WHERE p.debit_key = ? AND b.user_id = ? AND b.status = 'settled'`,args:[`debit-settlement:${T("sha256").update(e).digest("hex")}`,e,t]};return{before:[{sql:`INSERT INTO operation_wallet_fences (id, allowed)
|
|
27
|
+
SELECT ?, CASE WHEN EXISTS (${l}) THEN 1 ELSE 0 END`,args:[o,...c]},D(t)],after:[s,{sql:"DELETE FROM operation_wallet_fences WHERE id = ?",args:[o]}],current:async a=>(await a.execute({sql:l,args:c})).rows.length===1}}function M(t){return{label:String(t.label),key:String(t.debit_key),amountMc:Number(t.amount_mc),operation:String(t.operation),description:String(t.description),refundOperation:String(t.refund_operation),sourceSurface:String(t.source_surface)}}async function X(t,e){if(t.mode!=="execute"||!Number.isSafeInteger(e.amountMc)||e.amountMc<=0||!e.label||e.label.length>200||!e.operation||!e.refundOperation||!e.sourceSurface)throw new N;let r=u(),i=f+A();C(t.userId,i,t);let n=`EXISTS (SELECT 1 FROM operation_runs r JOIN operation_executions e ON e.run_id = r.id
|
|
28
|
+
WHERE r.id = ? AND r.user_id = ? AND e.claim_token = ? AND e.expires_at_ms > ${R}
|
|
29
|
+
AND ${w("execute")})`,l=[t.runId,t.userId,t.token],c;try{await r.batch([{sql:`INSERT OR IGNORE INTO operation_debit_plans
|
|
37
30
|
(run_id, label, debit_key, amount_mc, operation, description, refund_operation, source_surface)
|
|
38
|
-
SELECT ?, ?, ?, ?, ?, ?, ?, ? WHERE ${
|
|
39
|
-
AND operation = ? AND description = ? AND refund_operation = ? AND source_surface = ? AND ${
|
|
31
|
+
SELECT ?, ?, ?, ?, ?, ?, ?, ? WHERE ${n}`,args:[t.runId,e.label,i,e.amountMc,e.operation,e.description,e.refundOperation,e.sourceSurface,...l]},{sql:`UPDATE operation_debit_plans SET amount_mc = ? WHERE run_id = ? AND label = ?
|
|
32
|
+
AND operation = ? AND description = ? AND refund_operation = ? AND source_surface = ? AND ${n}
|
|
40
33
|
AND EXISTS (SELECT 1 FROM billing_debits d WHERE d.idempotency_key = operation_debit_plans.debit_key
|
|
41
34
|
AND d.user_id = ? AND d.status = 'claimed' AND d.amount_mc = operation_debit_plans.amount_mc
|
|
42
|
-
AND d.operation = operation_debit_plans.operation AND d.description = operation_debit_plans.description)`,args:[
|
|
43
|
-
WHERE r.id = ? AND r.user_id = ? AND e.claim_token = ? AND e.expires_at_ms > ${
|
|
44
|
-
AND ${w(
|
|
35
|
+
AND d.operation = operation_debit_plans.operation AND d.description = operation_debit_plans.description)`,args:[e.amountMc,t.runId,e.label,e.operation,e.description,e.refundOperation,e.sourceSurface,...l,t.userId]}],"write")}catch(a){c=a}let o;try{o=(await r.execute({sql:`SELECT p.* FROM operation_debit_plans p WHERE p.run_id = ? AND p.label = ? AND ${n}`,args:[t.runId,e.label,...l]})).rows[0]}catch(a){throw c??a}if(!o)throw c||new _;let s=M(o);if(s.amountMc!==e.amountMc||s.operation!==e.operation||s.description!==e.description||s.refundOperation!==e.refundOperation||s.sourceSurface!==e.sourceSurface)throw new N;return s}async function B(t){C(t.userId,f,t);let e=u();if(!(await e.execute({sql:`SELECT 1 FROM operation_executions e JOIN operation_runs r ON r.id = e.run_id
|
|
36
|
+
WHERE r.id = ? AND r.user_id = ? AND e.claim_token = ? AND e.expires_at_ms > ${R}
|
|
37
|
+
AND ${w(t.mode)}`,args:[t.runId,t.userId,t.token]})).rows.length)throw new _;return(await e.execute({sql:"SELECT * FROM operation_debit_plans WHERE run_id = ? ORDER BY label",args:[t.runId]})).rows.map(M)}async function j(t,e){let i=(await u().execute({sql:"SELECT user_id, amount_mc, operation, description, status FROM billing_debits WHERE idempotency_key = ? AND user_id = ? LIMIT 1",args:[e,t]})).rows[0];return i?{amountMc:Number(i.amount_mc),operation:String(i.operation),description:String(i.description),status:String(i.status)}:null}async function J(t,e,r,i,n,l){if(!Number.isSafeInteger(e)||e<=0)throw new Error("idempotent debit amount must be a positive integer");if(!n||n.length>500)throw new Error("idempotent debit key is required and must be bounded");let c=u(),o=h(t,n,l,{kind:"debit",amountMc:e,operation:r,description:i});l||await O(t);let s;try{s=await c.batch([...o.before,{sql:"UPDATE billing_debits SET amount_mc = ? WHERE idempotency_key = ? AND user_id = ? AND operation = ? AND description = ? AND status = 'claimed'",args:[e,n,t,r,i]},{sql:"INSERT OR IGNORE INTO billing_debits (idempotency_key, user_id, amount_mc, operation, description, status) VALUES (?, ?, ?, ?, ?, 'claimed')",args:[n,t,e,r,i]},{sql:`UPDATE users
|
|
45
38
|
SET balance_mc = balance_mc - ?
|
|
46
39
|
WHERE id = ?
|
|
47
40
|
AND balance_mc >= ?
|
|
@@ -50,7 +43,7 @@ import{a as u}from"./chunk-WNUXMPVX.js";var L="2026-06-26 21:58:03";var W="+3 mo
|
|
|
50
43
|
WHERE user_id = ?
|
|
51
44
|
AND remaining_mc > 0
|
|
52
45
|
AND (never_expires = 1 OR expires_at > datetime('now'))) >= ?
|
|
53
|
-
AND EXISTS (SELECT 1 FROM billing_debits WHERE idempotency_key = ? AND user_id = ? AND amount_mc = ? AND operation = ? AND description = ? AND status = 'claimed')`,args:[t,e,t,e,t,
|
|
46
|
+
AND EXISTS (SELECT 1 FROM billing_debits WHERE idempotency_key = ? AND user_id = ? AND amount_mc = ? AND operation = ? AND description = ? AND status = 'claimed')`,args:[e,t,e,t,e,n,t,e,r,i]},{sql:"UPDATE billing_debits SET status = 'applying' WHERE idempotency_key = ? AND user_id = ? AND amount_mc = ? AND operation = ? AND description = ? AND status = 'claimed' AND changes() = 1",args:[n,t,e,r,i]},{sql:`INSERT OR IGNORE INTO billing_debit_allocations
|
|
54
47
|
(debit_idempotency_key, lot_id, user_id, amount_mc, expires_at)
|
|
55
48
|
WITH ordered AS MATERIALIZED (
|
|
56
49
|
SELECT id,
|
|
@@ -69,7 +62,7 @@ import{a as u}from"./chunk-WNUXMPVX.js";var L="2026-06-26 21:58:03";var W="+3 mo
|
|
|
69
62
|
SELECT ?, id, ?, take_mc, expires_at
|
|
70
63
|
FROM allocation
|
|
71
64
|
WHERE take_mc > 0
|
|
72
|
-
AND EXISTS (SELECT 1 FROM billing_debits WHERE idempotency_key = ? AND status = 'applying')`,args:[e,t,
|
|
65
|
+
AND EXISTS (SELECT 1 FROM billing_debits WHERE idempotency_key = ? AND status = 'applying')`,args:[t,e,n,t,n]},{sql:`UPDATE credit_lots
|
|
73
66
|
SET remaining_mc = remaining_mc - COALESCE((
|
|
74
67
|
SELECT amount_mc FROM billing_debit_allocations
|
|
75
68
|
WHERE debit_idempotency_key = ? AND lot_id = credit_lots.id
|
|
@@ -77,9 +70,9 @@ import{a as u}from"./chunk-WNUXMPVX.js";var L="2026-06-26 21:58:03";var W="+3 mo
|
|
|
77
70
|
WHERE id IN (
|
|
78
71
|
SELECT lot_id FROM billing_debit_allocations WHERE debit_idempotency_key = ?
|
|
79
72
|
)
|
|
80
|
-
AND EXISTS (SELECT 1 FROM billing_debits WHERE idempotency_key = ? AND status = 'applying')`,args:[
|
|
73
|
+
AND EXISTS (SELECT 1 FROM billing_debits WHERE idempotency_key = ? AND status = 'applying')`,args:[n,n,n]},{sql:"INSERT INTO ledger (user_id, amount_mc, operation, description) SELECT user_id, -amount_mc, operation, description FROM billing_debits WHERE idempotency_key = ? AND status = 'applying'",args:[n]},{sql:"UPDATE billing_debits SET status = 'applied', applied_at = datetime('now') WHERE idempotency_key = ? AND status = 'applying'",args:[n]},...o.after],"write")}catch(b){if(W(b))throw new _;try{if(!await o.current(c))throw new _;let E=(await c.execute({sql:"SELECT user_id, amount_mc, operation, description, status FROM billing_debits WHERE idempotency_key = ? AND status = 'applied' LIMIT 1",args:[n]})).rows[0];if(E&&Number(E.user_id)===t&&Number(E.amount_mc)===e&&String(E.operation)===r&&String(E.description)===i){let S=await c.execute({sql:"SELECT balance_mc FROM users WHERE id = ?",args:[t]});return{ok:!0,balance_mc:Number(S.rows[0]?.balance_mc??0),duplicate:!0}}}catch(m){if(m instanceof _)throw m}throw b}let d=(await c.execute({sql:"SELECT user_id, amount_mc, operation, description, status FROM billing_debits WHERE idempotency_key = ? LIMIT 1",args:[n]})).rows[0];if(!d||Number(d.user_id)!==t||Number(d.amount_mc)!==e||String(d.operation)!==r||String(d.description)!==i)throw new Error("idempotent debit key conflicts with another debit");let p=await c.execute({sql:"SELECT balance_mc FROM users WHERE id = ?",args:[t]});return{ok:String(d.status)==="applied",balance_mc:Number(p.rows[0]?.balance_mc??0),duplicate:s[2+o.before.length]?.rowsAffected===0&&String(d.status)==="applied"}}async function V(t,e,r,i,n,l,c){if(!Number.isSafeInteger(r)||r<0)throw new Error("idempotent debit settlement amount must be a non-negative integer");if(!e||e.length>500)throw new Error("idempotent debit settlement key is required and must be bounded");if(!i||!l)throw new Error("idempotent debit settlement operation and source are required");let o=u(),s=h(t,e,c,{kind:"settlement",amountMc:r,operation:i,description:n,sourceSurface:l});c||await O(t);let a=`debit-settlement:${T("sha256").update(e).digest("hex")}`,d="wallet_hold_settlement",p=A(),b=JSON.stringify({debitIdempotencyKey:e,refundOperation:i,description:n}),m=()=>x(t,e,l),E;try{E=await o.batch([...s.before,{sql:`INSERT OR IGNORE INTO billing_events
|
|
81
74
|
(id, user_id, idempotency_key, billing_class, source_surface, status, amount_mc, metadata)
|
|
82
|
-
VALUES (?, ?, ?, ?, ?, 'settling', ?, ?)`,args:[p,
|
|
75
|
+
VALUES (?, ?, ?, ?, ?, 'settling', ?, ?)`,args:[p,t,a,d,l,r,b]},{sql:`WITH ordered AS (
|
|
83
76
|
SELECT a.lot_id,
|
|
84
77
|
a.amount_mc,
|
|
85
78
|
a.expires_at,
|
|
@@ -120,14 +113,14 @@ import{a as u}from"./chunk-WNUXMPVX.js";var L="2026-06-26 21:58:03";var W="+3 mo
|
|
|
120
113
|
AND d.user_id = e.user_id
|
|
121
114
|
AND d.status = 'applied'
|
|
122
115
|
AND e.amount_mc BETWEEN 0 AND d.amount_mc
|
|
123
|
-
)`,args:[
|
|
116
|
+
)`,args:[e,r,t,e,a,t,d,l]},{sql:`UPDATE billing_events
|
|
124
117
|
SET status = 'applying'
|
|
125
118
|
WHERE idempotency_key = ?
|
|
126
119
|
AND user_id = ?
|
|
127
120
|
AND billing_class = ?
|
|
128
121
|
AND source_surface = ?
|
|
129
122
|
AND status = 'settling'
|
|
130
|
-
AND changes() = 1`,args:[a,
|
|
123
|
+
AND changes() = 1`,args:[a,t,d,l]},{sql:`WITH ordered AS (
|
|
131
124
|
SELECT a.lot_id,
|
|
132
125
|
a.amount_mc,
|
|
133
126
|
a.expires_at,
|
|
@@ -149,7 +142,7 @@ import{a as u}from"./chunk-WNUXMPVX.js";var L="2026-06-26 21:58:03";var W="+3 mo
|
|
|
149
142
|
SELECT lot_id FROM refunds
|
|
150
143
|
WHERE refund_mc > 0 AND expires_at > datetime('now')
|
|
151
144
|
)
|
|
152
|
-
AND EXISTS (SELECT 1 FROM billing_events WHERE idempotency_key = ? AND status = 'applying')`,args:[
|
|
145
|
+
AND EXISTS (SELECT 1 FROM billing_events WHERE idempotency_key = ? AND status = 'applying')`,args:[e,r,a]},{sql:`WITH ordered AS (
|
|
153
146
|
SELECT a.amount_mc,
|
|
154
147
|
a.expires_at,
|
|
155
148
|
COALESCE(SUM(a.amount_mc) OVER (
|
|
@@ -182,19 +175,19 @@ import{a as u}from"./chunk-WNUXMPVX.js";var L="2026-06-26 21:58:03";var W="+3 mo
|
|
|
182
175
|
?,
|
|
183
176
|
?
|
|
184
177
|
FROM credited
|
|
185
|
-
WHERE refund_mc > 0`,args:[
|
|
178
|
+
WHERE refund_mc > 0`,args:[e,r,e,a,i,n]},{sql:`UPDATE billing_events
|
|
186
179
|
SET status = 'settled', settled_at = datetime('now')
|
|
187
180
|
WHERE idempotency_key = ?
|
|
188
|
-
AND status = 'applying'`,args:[a]},...s.after],"write")}catch(
|
|
181
|
+
AND status = 'applying'`,args:[a]},...s.after],"write")}catch(L){if(W(L))throw new _;try{if(!await s.current(o))throw new _;let g=await m();if(g)return g}catch(g){if(g instanceof _)throw g}throw L}let S=await m();if(!S)throw new Error("idempotent debit settlement did not reach a durable settled state");return{...S,duplicate:E[s.before.length]?.rowsAffected===0}}async function Y(t,e){let{hold:r}=e,i=I(r);if(r.userId!==t.userId||!t.runId||!t.token||!e.label||e.label.length>200||!e.refundOperation||!e.sourceSurface||!e.tool||!e.jobId)throw new N;let n=`EXISTS (SELECT 1 FROM operation_runs r JOIN operation_executions e ON e.run_id=r.id
|
|
189
182
|
WHERE r.id=? AND r.user_id=? AND r.tool=? AND r.job_id=? AND r.status='running'
|
|
190
183
|
AND json_extract(r.normalized_flags_json,'$._storeGateRequired') IS 1
|
|
191
|
-
AND e.claim_token=? AND e.phase='claimed' AND e.expires_at_ms > ${
|
|
184
|
+
AND e.claim_token=? AND e.phase='claimed' AND e.expires_at_ms > ${R})`,l=[t.runId,t.userId,e.tool,e.jobId,t.token],c=u(),o;try{await c.batch([{sql:`INSERT OR IGNORE INTO operation_debit_plans
|
|
192
185
|
(run_id,label,debit_key,amount_mc,operation,description,refund_operation,source_surface)
|
|
193
|
-
SELECT ?,?,?,?,?,?,?,? WHERE ${
|
|
186
|
+
SELECT ?,?,?,?,?,?,?,? WHERE ${n} AND (${i.sql})`,args:[t.runId,e.label,r.key,r.amountMc,r.operation,r.description,e.refundOperation,e.sourceSurface,...l,...i.args]},{sql:`INSERT OR IGNORE INTO operation_billing_links (run_id,billing_table,billing_key,relation,amount_mc)
|
|
194
187
|
SELECT p.run_id,'billing_debits',p.debit_key,'hold',p.amount_mc FROM operation_debit_plans p
|
|
195
188
|
WHERE p.run_id=? AND p.label=? AND p.debit_key=? AND p.amount_mc=? AND p.operation=? AND p.description=?
|
|
196
|
-
AND p.refund_operation=? AND p.source_surface=? AND ${
|
|
197
|
-
WHERE p.run_id=? AND p.label=? AND ${
|
|
189
|
+
AND p.refund_operation=? AND p.source_surface=? AND ${n} AND (${i.sql})`,args:[t.runId,e.label,r.key,r.amountMc,r.operation,r.description,e.refundOperation,e.sourceSurface,...l,...i.args]}],"write")}catch(d){o=d}let s;try{s=(await c.execute({sql:`SELECT p.* FROM operation_debit_plans p
|
|
190
|
+
WHERE p.run_id=? AND p.label=? AND ${n} AND (${i.sql})`,args:[t.runId,e.label,...l,...i.args]})).rows[0]}catch(d){throw o??d}if(!s)throw o||new _;let a=M(s);if(a.key!==r.key||a.amountMc!==r.amountMc||a.operation!==r.operation||a.description!==r.description||a.refundOperation!==e.refundOperation||a.sourceSurface!==e.sourceSurface)throw new N;return a}async function x(t,e,r){if(!Number.isSafeInteger(t)||t<=0||!e||!r)throw new _;let i=u(),n=`debit-settlement:${T("sha256").update(e).digest("hex")}`,l="wallet_hold_settlement",o=(await i.execute({sql:`SELECT e.user_id,
|
|
198
191
|
e.status,
|
|
199
192
|
e.amount_mc AS final_amount_mc,
|
|
200
193
|
e.billing_class,
|
|
@@ -206,7 +199,7 @@ import{a as u}from"./chunk-WNUXMPVX.js";var L="2026-06-26 21:58:03";var W="+3 mo
|
|
|
206
199
|
WHERE e.idempotency_key = ?
|
|
207
200
|
AND d.user_id = e.user_id
|
|
208
201
|
AND d.status = 'applied'
|
|
209
|
-
LIMIT 1`,args:[
|
|
202
|
+
LIMIT 1`,args:[e,n]})).rows[0];if(!o)return null;if(Number(o.user_id)!==t||String(o.billing_class)!==l||String(o.source_surface)!==r)throw new Error("idempotent debit settlement key conflicts with another settlement");if(String(o.status)!=="settled")return null;let s=Number(o.held_amount_mc),a=Number(o.final_amount_mc);if(!Number.isSafeInteger(s)||!Number.isSafeInteger(a)||a<0||a>s)throw new Error("idempotent debit settlement receipt is invalid");let d=s-a,p=await i.execute({sql:`WITH ordered AS (
|
|
210
203
|
SELECT a.amount_mc,
|
|
211
204
|
a.expires_at,
|
|
212
205
|
COALESCE(SUM(a.amount_mc) OVER (
|
|
@@ -222,4 +215,4 @@ import{a as u}from"./chunk-WNUXMPVX.js";var L="2026-06-26 21:58:03";var W="+3 mo
|
|
|
222
215
|
)
|
|
223
216
|
SELECT (SELECT COUNT(*) FROM ordered) AS allocation_count,
|
|
224
217
|
COALESCE(SUM(CASE WHEN expires_at > ? THEN refund_mc ELSE 0 END), 0) AS credited_refund_mc
|
|
225
|
-
FROM refunds`,args:[
|
|
218
|
+
FROM refunds`,args:[e,a,String(o.settled_at)]}),m=Number(p.rows[0]?.allocation_count??0)>0?Number(p.rows[0]?.credited_refund_mc??0):0,E=await i.execute({sql:"SELECT balance_mc FROM users WHERE id = ?",args:[t]});return{balance_mc:Number(E.rows[0]?.balance_mc??0),final_amount_mc:a,refund_mc:m,expired_refund_mc:d-m,duplicate:!0}}export{k as a,O as b,X as c,B as d,j as e,J as f,V as g,Y as h,x as i};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as s}from"./chunk-WP3QS4CJ.js";var
|
|
1
|
+
import{a as s}from"./chunk-WP3QS4CJ.js";var i={message:"PAA progress checks wait at least 20 seconds, and completed captures now finish publication without a competing heartbeat. Confirmed failed SERP API requests refund the original hold without repeating acquisition. Expanded PAA answers and initial SERP previews retain their source details."};var _={reset:"\x1B[0m",cyan:"\x1B[36m",lime:"\x1B[32m",amber:"\x1B[33m",red:"\x1B[31m",muted:"\x1B[90m",bold:"\x1B[1m"};function r(t,e,n){return n?`${_[e]}${t}${_.reset}`:t}function o(t,e,n){let a=t.padEnd(9," ");return` ${r(a,"muted",n)} ${e.join(r(" . ","muted",n))}`}function b(t){let e=t.color??!0,n=t.apiKeyConfigured?"$MCP_SCRAPER_API_KEY":"sk_live_your_key",a=String.raw`
|
|
2
2
|
__ __ ____ ____
|
|
3
3
|
| \/ |/ ___| _ \
|
|
4
4
|
| |\/| | | | |_) |
|
|
@@ -10,7 +10,7 @@ import{a as s}from"./chunk-WP3QS4CJ.js";var _={message:"Read complete retained r
|
|
|
10
10
|
\___ \| | | |_) | / _ \ | |_) | _| | |_) |
|
|
11
11
|
___) | |___| _ < / ___ \| __/| |___| _ <
|
|
12
12
|
|____/ \____|_| \_\/_/ \_\_| |_____|_| \_\
|
|
13
|
-
`,
|
|
13
|
+
`,c=[`MCP_SCRAPER_API_KEY=${n} npx -y -p mcp-scraper@latest \\`," mcp-scraper-cli agent install claude --apply"].join(`
|
|
14
14
|
`),l=["[mcp_servers.mcp-scraper]",'command = "npx"','args = ["-y", "-p", "mcp-scraper@latest", "mcp-scraper"]',`env = { MCP_SCRAPER_API_KEY = "${n}" }`].join(`
|
|
15
|
-
`);return[r(`mcp-scraper v${t.version}`,"bold",e),r("> mcp-scraper-install","muted",e),r(a,"amber",e),`${r("MCP Scraper Agent","cyan",e)} . v${t.version} . mcpscraper.dev`,"1/1 install surfaces ready",r(`Newest in v${t.version}: ${
|
|
15
|
+
`);return[r(`mcp-scraper v${t.version}`,"bold",e),r("> mcp-scraper-install","muted",e),r(a,"amber",e),`${r("MCP Scraper Agent","cyan",e)} . v${t.version} . mcpscraper.dev`,"1/1 install surfaces ready",r(`Newest in v${t.version}: ${i.message}`,"lime",e),"",`${r("Tools","cyan",e)} ${r(`(${s.inventory.totalTools} MCP tools)`,"muted",e)}`,o("search",["harvest_paa","search_serp","maps_search","maps_place_intel"],e),o("extract",["extract_url","map_site_urls","extract_site","audit_site","directory_workflow"],e),o("build",["create_editorial_reading_room","rank_tracker_workflow","portable HTML"],e),o("media",["youtube_harvest","youtube_transcribe","facebook_reels_inventory","facebook_ad_search","facebook_page_intel","facebook_ad_transcribe","facebook_video_transcribe","tiktok_video_transcribe","instagram_profile_content","instagram_media_download","reddit_thread"],e),o("browser",["serp_identity_create","serp_identity_list","browser_open","browser_profile_connect","browser_profile_list","browser_close","browser_screenshot","browser_read","browser_locate","browser_replay_mark","browser_replay_annotate"],e),o("connect",["list_service_connections","describe_service_connection_tool","import_service_connection_to_memory","export_connected_service_data","renew_connected_data_download","read_service_connection","call_service_connection_action"],e),o("commons",["commons_search_entities","commons_get_entity_linkset","commons_prepare_entity","commons_submit_entity","commons_prepare_publication","commons_claim_publication","commons_publish_editorial","commons_get_publication"],e),o("account",["credits_info","reports","MCP resources"],e),o("memory",["memory-put","memory-get","memory-search","list-vaults","record-fact","list-scheduled-actions"],e),`${r("Workflows","cyan",e)} ${r("(MCP + CLI + API)","muted",e)}`,o("route",["workflow_list","workflow_suggest","workflow_run","workflow_step","workflow_status","workflow_artifact_read"],e),o("seo",["directory","agent-packet","competitive audit","map/serp comparison","PAA/AIO briefs","scheduled runs"],e),"",r("Usage tips:","amber",e),"Run mcp-scraper-install for this visible card. Run mcp-scraper-cli for setup utilities and subcommands.","Run mcp-scraper in a human terminal to print this card; MCP clients get the same command as a silent stdio server.","Explicit card command: npx -y -p mcp-scraper@latest mcp-scraper-install","Hosted browser sessions use direct/no-proxy egress by default.","Customer auth setup: run browser_profile_connect, send the watch_url, let the user sign in, then call browser_profile_list until AUTHENTICATED.","Connected account ranges: call export_connected_service_data once. It handles Gmail, Calendar, Zoom, and Resend pagination; do not loop read_service_connection over individual records.","Connected account RAG: call import_service_connection_to_memory for one bounded approved read. It writes a redacted, untrusted snapshot to a stable Memory path and embeds it for search.","Stack logins / reconnect: run browser_profile_connect again with the same profile name and another domain to add accounts or refresh a login.","Start with workflow_suggest for broad jobs like market analysis, ICP research, CRO audits, brand briefs, content gaps, and AI visibility.","For MCP clients, use mcp-scraper so one install can mix SERP, Maps, browser, reports, and saved MCP resources.","If you hit the concurrency limit, add 2 browsers for $5/month with mcp-scraper-cli billing concurrency checkout.","",`${r("Ready.","lime",e)} Install the combined MCP server with one command:`,"",r("Setup doctor","amber",e),"npx -y -p mcp-scraper@latest mcp-scraper-cli doctor","",r("Hosted profile setup","amber",e),'In your MCP client, call browser_profile_connect with email="seo@example.com" and domain="chatgpt.com".',"Give the returned watch_url to the user. After they sign in, call browser_profile_list, then browser_open with the returned profile. Add more logins by calling browser_profile_connect again with the same profile and a new domain.","",r("Claude Code one-command setup","amber",e),c,"Then fully exit Claude Code and open a new Claude terminal. Check with: claude mcp list","",r("Codex config","amber",e),l,"",r("Claude Desktop Extension","amber",e),"Download: https://mcpscraper.dev/downloads/mcp-scraper.mcpb","",r("Safety note:","muted",e),"mcp-scraper prints this card only when stdin/stdout are an interactive TTY. In MCP clients it writes only JSON-RPC to stdout.","Use --stdio or MCP_SCRAPER_FORCE_STDIO=1 to force server mode from a terminal.",""].join(`
|
|
16
16
|
`)}export{b as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var o="0.96.2";export{o as a};
|
|
@@ -175,7 +175,7 @@ import{i as j,m as T}from"./chunk-KXJCGV3H.js";import{m as f,q as b}from"./chunk
|
|
|
175
175
|
public_error_json = CASE WHEN json_valid(public_error_json) THEN json_set(public_error_json, '$.charge_status', ?) ELSE public_error_json END,
|
|
176
176
|
updated_at = datetime('now')
|
|
177
177
|
WHERE id = ? AND user_id = ? AND execution_generation = ? AND status = ?
|
|
178
|
-
AND billed_mc IS NULL AND settlement_plan_json = ?`,args:[e.netChargeMc,JSON.stringify(e),n,t.jobId,t.userId,t.generation,t.status,JSON.stringify(t)]})}async function jt(t,e,n,r,a,s=0){let{settleExtractJobCharge:i}=await import("./settlement-
|
|
178
|
+
AND billed_mc IS NULL AND settlement_plan_json = ?`,args:[e.netChargeMc,JSON.stringify(e),n,t.jobId,t.userId,t.generation,t.status,JSON.stringify(t)]})}async function jt(t,e,n,r,a,s=0){let{settleExtractJobCharge:i}=await import("./settlement-6CS4JZTY.js");return i(t,e,n,r,a,s)}var B=25;async function*Tt(t){let e=o(),n=0;for(;;){let r=await e.execute({sql:`SELECT rowid AS cursor_id, page
|
|
179
179
|
FROM site_extract_pages
|
|
180
180
|
WHERE job_id = ? AND rowid > ?
|
|
181
181
|
ORDER BY rowid
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as D,
|
|
1
|
+
import{a as D,c as A,d as T,e as C,f as w,g as p}from"./chunk-6BD75VKS.js";import{B as k,C as x,D as v,b as E,g,x as I}from"./chunk-7WPCGRD7.js";import{e as P,f as S}from"./chunk-5LYINW7Z.js";import{a as _}from"./chunk-WNUXMPVX.js";import{randomUUID as O}from"crypto";var L=class{constructor(t,r,i){this.userId=t;this.sourceSurface=r;this.fence=i;if(i&&i.userId!==t)throw Error("Billing scope principal differs from execution claim")}userId;sourceSurface;fence;identity=`debit:${O()}`;charges=new Map;pending=new Map;compensating=new Set;closing=!1;async debit(t,r,i,c,a){if(this.closing||this.compensating.has(t))throw Error("Billing scope is compensating; new charges are forbidden");let s=this.charges.get(t);if(s?.outcome==="pending")throw Error("Named debit outcome is pending; reconcile before retrying");if(s?.outcome==="funded"&&s.amountMc!==r)throw Error("An applied debit amount cannot change");let o={key:s?.key??`${this.identity}:${t}`,amountMc:r,operation:i,description:c,refundOperation:a,outcome:"pending"};if(s&&(s.operation!==i||s.description!==c||s.refundOperation!==a))throw Error("Named charge identity cannot change");this.charges.set(t,o);let u=(async()=>{if(this.fence){let f=await A(this.fence,{label:t,amountMc:r,operation:i,description:c,refundOperation:a,sourceSurface:this.sourceSurface});if(o.key=f.key,this.closing||this.compensating.has(t))throw Error("Billing scope began compensating while planning")}return this.fence?w(this.userId,r,i,c,o.key,this.fence):w(this.userId,r,i,c,o.key)})();this.pending.set(t,u);try{let f=await u;return o.outcome=f.ok?"funded":"unfunded",{...f,billingKey:o.key}}finally{this.pending.delete(t)}}async compensate(t){this.compensating.add(t),await this.pending.get(t)?.catch(()=>{});try{this.fence&&await this.loadDurablePlans();let r=this.charges.get(t);if(!r)return"not_charged";let i=await C(this.userId,r.key);return i?i.amountMc!==r.amountMc||i.operation!==r.operation||i.description!==r.description?"refund_pending":i.status==="claimed"?this.fence?.mode==="compensate"||r.outcome==="unfunded"?"not_charged":"refund_pending":i.status!=="applied"?"refund_pending":(this.fence?await p(this.userId,r.key,0,r.refundOperation,`${this.sourceSurface} failed`,this.sourceSurface,this.fence):await p(this.userId,r.key,0,r.refundOperation,`${this.sourceSurface} failed`,this.sourceSurface)).final_amount_mc===0?"refunded":"refund_pending":this.fence?.mode==="compensate"||r.outcome==="unfunded"?"not_charged":"refund_pending"}catch{return"refund_pending"}}async compensateAll(){if(this.closing=!0,await Promise.allSettled([...this.pending.values()]),this.fence)try{await this.loadDurablePlans()}catch{return"refund_pending"}let t=await Promise.all([...this.charges.keys()].map(r=>this.compensate(r)));return t.includes("refund_pending")?"refund_pending":t.includes("refunded")?"refunded":"not_charged"}async loadDurablePlans(){if(this.fence)for(let t of await T(this.fence)){let r=this.charges.get(t.label);if(t.sourceSurface!==this.sourceSurface)throw Error("Persisted billing source differs from scope");this.charges.set(t.label,{key:t.key,amountMc:t.amountMc,operation:t.operation,description:t.description,refundOperation:t.refundOperation,outcome:r?.key===t.key?r.outcome:"pending"})}}};async function H(e){if(!Number.isSafeInteger(e.userId)||e.userId<=0||!Number.isSafeInteger(e.refundMc)||e.refundMc<0)throw Error("invalid_legacy_refund");await _().batch([e.admission,{sql:`INSERT INTO credit_lots (user_id, amount_mc, remaining_mc, source, expires_at)
|
|
2
2
|
SELECT ?, ?, ?, ?, ? WHERE changes() = 1 AND ? > 0 AND datetime(?) > datetime('now')`,args:[e.userId,e.refundMc,e.refundMc,e.operation,e.expiresAt,e.refundMc,e.expiresAt]},{sql:"UPDATE users SET balance_mc = balance_mc + ? WHERE id = ? AND ? > 0 AND changes() = 1",args:[e.refundMc,e.userId,e.refundMc]},{sql:`INSERT INTO ledger (user_id, amount_mc, operation, description)
|
|
3
3
|
SELECT ?, ?, ?, ? WHERE ? > 0 AND changes() = 1`,args:[e.userId,e.refundMc,e.operation,e.description,e.refundMc]},e.acknowledgment],"write")}function J(e){return e.status==="complete"||e.status==="partial"||e.status==="failed"}function y(e,t,r){return e.userId===t&&(e.executionGeneration??0)===r&&J(e)}function W(e){let t=e.options.xraySetupReceipt;return e.options.heldMc===0&&e.options.debitKey==null&&t?.billingClass===E&&t.consumesMcpScraperCredits===!1&&t.heldMc===0&&t.billedMc===0}function b(e,t){if(!e||!y(e,t.userId,t.generation)||JSON.stringify(e.settlementPlan)!==JSON.stringify(t))return null;let r=e.settlementReceipt;return!r||r.jobId!==t.jobId||r.userId!==t.userId||r.generation!==t.generation||e.billedMc!==r.netChargeMc?null:r}async function Q(e,t,r,i,c,a=0){let s=await g(e);if(!s||!y(s,t,a))throw Error("extract_settlement_identity_or_terminal_conflict");if(s.billedMc!=null)return s.settlementReceipt??null;let o=Number(s.options.heldMc??0);if(![o,r,i].every(d=>Number.isSafeInteger(d)&&d>=0)||r+i!==o)throw Error("extract_settlement_amount_conflict");let u=String(s.options.billingClass??"credits");if(u===E&&!W(s))throw Error("xray_extract_zero_charge_finalization_rejected");let f={version:1,jobId:e,userId:t,generation:a,status:s.status,heldMc:o,debitKey:typeof s.options.debitKey=="string"?s.options.debitKey:null,billingClass:u,netChargeMc:i,refundMc:r,reference:c},l;try{l=await k(f)}catch(d){if(l=await g(e).catch(()=>null),!l?.settlementPlan||!y(l,t,a))throw d}if(!l||!y(l,t,a)||!l.settlementPlan)throw Error("extract_settlement_admission_conflict");let n=l.settlementPlan;if(n.jobId!==e||n.userId!==t||n.generation!==a||n.status!==l.status||n.heldMc!==o||n.debitKey!==f.debitKey||n.billingClass!==u)throw Error("extract_settlement_plan_conflict");let N=b(l,n);if(N)return N;let m={version:1,jobId:e,userId:t,generation:a,netChargeMc:n.netChargeMc,refundMc:0,expiredRefundMc:0};try{if(u===E)await x(n,m);else if(n.debitKey){let d=await p(t,n.debitKey,n.netChargeMc,S.EXTRACT_SITE_REFUND,n.reference,"extract_site");m.netChargeMc=d.final_amount_mc,m.refundMc=d.refund_mc,m.expiredRefundMc=d.expired_refund_mc??0,await x(n,m)}else{let h=await _().execute({sql:"SELECT datetime(created_at, ?) AS expires_at FROM site_extract_jobs WHERE id = ?",args:[D,e]}),R=[e,t,a,n.status,JSON.stringify(n)];await H({userId:t,refundMc:n.refundMc,expiresAt:String(h.rows[0]?.expires_at),operation:S.EXTRACT_SITE_REFUND,description:n.reference,admission:{sql:`UPDATE site_extract_jobs SET billed_mc = -1
|
|
4
4
|
WHERE id = ? AND user_id = ? AND execution_generation = ? AND status = ?
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as t,d as o,e as _,f as l}from"./chunk-ZPQNY5TI.js";import{a as g}from"./chunk-WP3QS4CJ.js";var F=t.browser_minute/6e4;function de(e){return Math.round(e*F)}var pe=1e3,ue=_,$=t.serp_headful/o,me=t.paa_base/o,ge=t.paa/o,be=t.page_scrape/o,V={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},H=2e6,K=3,v=1e4,y=1e9,j=75,fe=j*o,Q=15e3,Ce=Q/v,Ee=5e3,W="2026-08-03.connected-usage-v3",S=15e3,Re=S*o,I=2,A=2,x=5,N=I*o,k=A*o,M=x*o,he={schemaVersion:2,ratePolicyVersion:W,effectiveAt:"2026-08-03T00:00:00.000Z",provider:"nango",entitlement:"paid_plan_add_on",connection:{billingMode:"flat_recurring_credits",amountCredits:S,interval:"month",unit:"active_connection",proration:"none"},usage:{billingMode:"credits",settlementMode:"authoritative_receipt",rounding:"aggregate_then_ceil_to_mc",functionRun:{credits:I,mc:N,unit:"per_function_run"},proxyRequest:{credits:A,mc:k,unit:"per_proxy_request"},compute:{creditsPerSecond:x,mcPerSecond:M,sourceUnit:"millisecond",unit:"per_compute_second",formula:"ceil(computeMilliseconds * mcPerSecond / 1000)"}}};function b(e,r){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${r} must be a non-negative safe integer`);return BigInt(e)}function p(e){if(e>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("connected usage charge exceeds the safe integer range");return Number(e)}function ye(e){let r=b(e.functionRuns,"functionRuns"),a=b(e.proxyRequests,"proxyRequests"),s=b(e.computeMilliseconds,"computeMilliseconds"),n=r*BigInt(N),c=a*BigInt(k),d=s*BigInt(M),m=d===0n?0n:(d+999n)/1000n,h=n+c+m;return{functionRunMc:p(n),proxyRequestMc:p(c),computeMc:p(m),amountMc:p(h),credits:p(h)/o}}function Te(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*y))*BigInt(r)*BigInt(H),n=BigInt(y)*BigInt(v)*BigInt(K),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 Z=[{key:"serp",label:"SERP search",aliases:["search_serp","serp","google search","organic results"],credits:_,unit:"per page (ordinary search)",notes:`search_serp light mode returns one page of organic positions, URLs, titles, and descriptions by default. Unfiltered one-page full mode returns available same-page SERP features. Either mode requests two pages only when pages:2 is explicit. Unfiltered light searches cost ${_} credits per delivered page, or ${l} credits per delivered page if the backup supplies the result. One-page full searches cost ${l} credits. Setting recency to week or month applies Google's date filter through a managed browser and returns organic results only. It costs ${l} credits for one page; filtered pages:2 follows Google's page-two control and costs ${l*2} credits when both pages are delivered. Unfiltered searches use the managed browser only as the last backup. Unfiltered two-page full searches return organic results only for ${_*2} credits, with rich features marked unsupported. If only page 1 is delivered, the search is marked partial and billed for one delivered page. A temporary ${l}-credit-per-requested-page hold is settled to the delivered rate. Location, language, device, and optional module fields do not change ordinary searches. Saved browser identity and capture_serp_snapshot searches retain their ${$}-credit base price; optional page snapshots add ${i(t.page_scrape)} credit per attempted URL.`},{key:"paa",label:"PAA harvest",aliases:["harvest_paa","paa","people also ask","questions"],credits:i(t.paa),unit:`per question (+${i(t.paa_base)} credit base)`,notes:`Returns original-query PAA questions with answers and sources plus organic results and Google entity IDs. Optional same-page SERP modules are flag-controlled. Billed ${i(t.paa_base)} credit base + ${i(t.paa)} per question actually returned (unused estimate refunded).`},{key:"page_scrape",label:"Page crawl / extract",aliases:["extract_url","extract_site","page scrape","url scrape","single page","site crawl"],credits:i(t.page_scrape),unit:"per page",notes:"Applies to both single-URL extraction and per-page site crawls."},{key:"listing_create",label:"Directory or wiki listing creation",aliases:["local-sourcebook-capture","commons_submit_entity","directory listing","wiki listing"],credits:i(t.listing_create),unit:"per new listing",notes:"Fixed total price for a new Local Sourcebook directory listing or Transparent Commons wiki entity. Sourcebook acquisition is included."},{key:"listing_edit",label:"Directory or wiki listing edit",aliases:["local_sourcebook_refresh","commons_submit_entity","listing refresh","wiki edit"],credits:i(t.listing_edit),unit:"per existing listing revision",notes:"Fixed total price for refreshing an existing Local Sourcebook listing or revising an existing Transparent Commons entity."},{key:"url_map",label:"Site URL mapping",aliases:["map_site_urls","url map","site map","crawl urls"],credits:i(t.url_map),unit:"per mapping operation",notes:"Flat rate for the full /map-urls call regardless of URL count discovered."},{key:"yt_channel",label:"YouTube search / channel harvest",aliases:["youtube_harvest","youtube search","youtube channel","yt_channel"],credits:i(t.yt_channel),unit:"per call"},{key:"yt_transcription",label:"YouTube transcription",aliases:["youtube_transcribe","youtube transcript","transcription","yt_transcription"],credits:i(2e4),unit:"base + 2/min of video",notes:"Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},{key:"fb_ad",label:"Facebook search / ad lookup",aliases:["facebook_page_intel","facebook_ad_search","facebook_ad","facebook ads","fb ads"],credits:i(t.fb_ad),unit:"per call"},{key:"maps_search",label:"Maps business search",aliases:["maps_search","google maps search","gmb search","gbp search","business profiles"],credits:i(t.maps_search),unit:"per search",notes:"Returns up to 50 Google Maps business/profile candidates. Use maps_place_intel to hydrate selected businesses."},{key:"maps_place",label:"Maps business lookup",aliases:["maps_place_intel","google maps","maps place","place intel"],credits:i(t.maps_place),unit:"per business",notes:"Maps place runs reserve the 60-credit base plus the declared review maximum before browsing. Completed runs settle to the base plus unique saved reviews; stopped attempts are refunded."},{key:"maps_review",label:"Maps review",aliases:["maps_reviews","google reviews","review cards","reviews"],credits:i(t.maps_review),unit:"per review card",notes:"One credit per unique saved review on a completed Maps place run. The declared maximum is held before browsing; unused credits are refunded."},{key:"fb_search",label:"Facebook ad library search",aliases:["facebook_search","fb_search","fb ad search"],credits:i(t.fb_search),unit:"per search",notes:"Browser automation to search Facebook Ads Library by keyword."},{key:"google_ads_search",label:"Google Ads Transparency search",aliases:["google_ads_search","google ads search","ads transparency search"],credits:i(t.google_ads_search),unit:"per search",notes:"Browser automation to find advertisers in Google Ads Transparency Center by domain or name."},{key:"google_ads_intel",label:"Google Ads Transparency advertiser intel",aliases:["google_ads_page_intel","google ads intel","ads transparency intel"],credits:i(t.google_ads_intel),unit:"per call",notes:"Lists and hydrates an advertiser's creatives with image URLs and video references."},{key:"google_ads_transcribe",label:"Google ad video transcription",aliases:["google_ads_transcribe","google ad transcript"],credits:i(2e4),unit:"base + 2/min of video",notes:"Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},{key:"fb_transcribe",label:"Facebook video / ad transcription",aliases:["facebook_transcribe","facebook_video_transcribe","fb_transcribe","fb ad transcript"],credits:i(2e4),unit:"base + 2/min of video",notes:"Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},{key:"fb_reels_inventory",label:"Facebook Reel URL inventory",aliases:["facebook_reels_inventory","facebook reels","facebook reel urls","facebook profile reels"],credits:i(t.fb_reels_inventory),unit:"per profile scan",notes:"Collects canonical Reel URLs from a Facebook profile. Logged-out scans are capped at 60 URLs; saved browser profiles can request larger inventories."},{key:"tiktok_transcribe",label:"TikTok video transcription",aliases:["tiktok_video_transcribe","tiktok transcript"],credits:i(2e4),unit:"base + 2/min of video",notes:"Transcribes a public TikTok video from its playback media. Flat 200-credit base plus 2 credits per minute, reconciled after transcription."},{key:"instagram_profile",label:"Instagram profile content discovery",aliases:["instagram_profile_content","instagram profile","instagram content list","ig profile"],credits:i(t.instagram_profile),unit:"per profile scan",notes:"Browser extraction of public Instagram profile grid links. Complete history may require a logged-in profile."},{key:"instagram_media",label:"Instagram media download",aliases:["instagram_media_download","instagram reel download","instagram post download","ig media"],credits:i(t.instagram_media),unit:"per post or reel",notes:"Extracts post text, image URLs, and reel audio/video tracks, with local downloads when the server can write files."},{key:"instagram_transcribe",label:"Instagram media transcription",aliases:["instagram transcript","instagram reel transcript","ig transcribe"],credits:i(2e4),unit:"base + 2/min of video",notes:"Whisper transcription of selected Instagram audio/video media. Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},{key:"browser_minute",label:"Interactive browser session",aliases:["browser_open","browser agent","browser_agent","live browser","browse","browser control","interactive browser"],credits:i(t.browser_minute),unit:"per minute of use",notes:"Metered per minute of use for the whole time the browser session is open. Close the session to stop the meter; abandoned sessions are auto-closed after a short idle window."},{key:"reddit_thread",label:"Reddit thread base lookup",aliases:["reddit","reddit_thread","reddit comments","subreddit","reddit post"],credits:i(t.reddit_thread),unit:"per thread",notes:"Base lookup for the post itself. Comments billed separately per comment at reddit_comment rate. Refunded if the thread cannot be retrieved."},{key:"reddit_comment",label:"Reddit comment",aliases:["reddit_comment","reddit comments"],credits:i(t.reddit_comment),unit:"per comment",notes:"Charged per comment actually extracted, billed down automatically if the balance runs out mid-thread."},{key:"video_analysis",label:"Video breakdown (frame-by-frame + transcript)",aliases:["video_frame_analysis","video breakdown","video analysis","analyze video"],credits:i(t.video_analysis),unit:"per 120 frames (max 480)",notes:`Full video breakdown: samples frames across a video up to 60 minutes, analyzes visuals and audio, then produces a summary, pacing, topic outline, key points, hook, style, and replication guidance. Reserves ${i(t.video_analysis)} Credits per requested 120-frame tier, up to 480 frames. Unused frame tiers and failed-run frame charges are refunded. Incurred analysis-model usage is billed separately, including usage before a failure; terminal status checks settle the original run.`},{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."}],ve="price_1Ta1NRS8aAcsk3TGwsRnYbix";function w(e){return e.billing_interval??"month"}function P(e){return e.billed_usd??e.monthly_usd}function O(e){return e.credits_mc/o}var u={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}},C=Object.fromEntries(Object.values(u).map(e=>[e.tier,e])),E={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 X(e){let r=Object.values(E).find(a=>a.tier_keys.includes(e));return r?`/${r.slug}/claim`:null}function z(e){return e?Object.values(E).find(r=>r.tier_keys.includes(e))??null:null}function Se(e,r){let a=z(e);return a?!a.tier_keys.includes(r):!1}function Ie(e){if(!e)return null;let r=C[e];return r?{tier:r.tier,label:r.label,amount_usd:P(r),interval:w(r),monthly_equivalent_usd:r.monthly_usd,credits_per_interval:O(r),concurrency:r.concurrency,credits_never_expire:!!r.credits_never_expire,includes_memory:!!r.includes_memory,private_offer:!!r.private_offer,offer_claim_path:X(r.tier)}:null}function Ae(e){let r=E[e];if(!r)return null;let a=r.tier_keys.map(s=>C[s]).filter(s=>!!s).map(s=>({tier:s.tier,label:s.label,amount_usd:P(s),interval:w(s),monthly_equivalent_usd:s.monthly_usd,credits:O(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 xe(){let e=C.starter,r=Z.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(u).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{...g,operationCosts:a,publicTiers:s,concurrencyPack:{ratePolicyVersion:B,monthlyUsd:U,currency:L,interval:D,billingUnit:"pack",slotsPerPack:f},scaleCreditPack:{ratePolicyVersion:ee,eligibleTier:"scale",incrementUsd:G,creditsPerIncrement:R,maxQuantity:re,currency:"usd",expiryMonths:3},creditsPerDollarStarter:Math.round(i(e.credits_mc)/e.monthly_usd),costs:r,scheduling:g.addons.scheduling,connectedAccounts:g.addons.connectedAccounts,listingWrites:V}}var U=5,L="usd",D="month",f=2,B="2026-08-14.concurrency-pack-v1",J="$5/month for 2 extra browsers",Ne="MCP Scraper browser concurrency pack \u2014 each $5 monthly pack adds 2 browsers.",ke="Billed monthly until canceled. A receipt is emailed after each successful payment.",T="npx -y -p mcp-scraper@latest mcp-scraper-cli billing concurrency checkout",ee="2026-09-21.scale-credit-pack-v1",G=10,R=8e4,Me=R*o,re=100;function we(){let e=process.env.CONCURRENCY_BILLING_URL??"https://mcpscraper.dev/billing";return{product:"Extra browser concurrency pack",rate_policy_version:B,price_label:J,unit_amount_usd:U,currency:L,interval:D,billing_unit:"pack",pack_quantity:1,slots_per_pack:f,extra_slots:f,billing_url:e,terminal_command:T,terminal_command_with_api_key_env:`MCP_SCRAPER_API_KEY=sk_live_your_key ${T}`}}function i(e){return e/o}var te="npx -y -p mcp-scraper@latest mcp-scraper-cli billing subscribe";function ie(){return Object.values(u).filter(e=>!e.private_offer).sort((e,r)=>e.credits_mc-r.credits_mc)}function Pe(e,r){let a=process.env.TOPUP_URL??"https://mcpscraper.dev/billing",s=i(e),n=i(r),c=ie().map(m=>m.tier).join("|"),d=`${te} <${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. Scale customers can buy ${R} Credits per $${G} increment; other customers can move to a larger plan at ${a} (terminal: ${d})`,balance_credits:s,required_credits:n,topup_url:a,upgrade_command:d}}var ne=1e7*1,Oe={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}},Ue={free:ne,pro:5e9,team:5e10},se=3;var Le=19/se,De=3,Be=1.5,Ge=1.5,Y=2e4,q=200;function Ye(e){let r=Math.max(1,Math.ceil((e||60)/60));return Y+q*r}var qe=Y+q*30,Fe=u.price_1TmiHRS8aAcsk3TGwmSNfNIa.credits_mc/u.price_1TmiHRS8aAcsk3TGwmSNfNIa.monthly_usd;export{de as a,pe as b,ue as c,$ as d,me as e,ge as f,be as g,V as h,y as i,j,fe as k,Q as l,Ce as m,Ee as n,W as o,S as p,Re as q,I as r,A as s,x as t,N as u,he as v,ye as w,Te as x,Z as y,ve as z,w as A,P as B,O as C,u as D,C as E,X as F,z as G,Se as H,Ie as I,Ae as J,xe as K,U as L,f as M,Ne as N,ke as O,G as P,R as Q,Me as R,re as S,we as T,i as U,Pe as V,Oe as W,Ue as X,De as Y,Be as Z,Ge as _,Y as $,q as aa,Ye as ba,qe as ca,Fe as da};
|
|
1
|
+
import{e as t,h as o,i as _,j as l}from"./chunk-5LYINW7Z.js";import{a as g}from"./chunk-WP3QS4CJ.js";var F=t.browser_minute/6e4;function de(e){return Math.round(e*F)}var pe=1e3,ue=_,$=t.serp_headful/o,me=t.paa_base/o,ge=t.paa/o,be=t.page_scrape/o,V={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},H=2e6,K=3,v=1e4,y=1e9,j=75,fe=j*o,Q=15e3,Ce=Q/v,Ee=5e3,W="2026-08-03.connected-usage-v3",S=15e3,Re=S*o,I=2,A=2,x=5,N=I*o,k=A*o,M=x*o,he={schemaVersion:2,ratePolicyVersion:W,effectiveAt:"2026-08-03T00:00:00.000Z",provider:"nango",entitlement:"paid_plan_add_on",connection:{billingMode:"flat_recurring_credits",amountCredits:S,interval:"month",unit:"active_connection",proration:"none"},usage:{billingMode:"credits",settlementMode:"authoritative_receipt",rounding:"aggregate_then_ceil_to_mc",functionRun:{credits:I,mc:N,unit:"per_function_run"},proxyRequest:{credits:A,mc:k,unit:"per_proxy_request"},compute:{creditsPerSecond:x,mcPerSecond:M,sourceUnit:"millisecond",unit:"per_compute_second",formula:"ceil(computeMilliseconds * mcPerSecond / 1000)"}}};function b(e,r){if(!Number.isSafeInteger(e)||e<0)throw new Error(`${r} must be a non-negative safe integer`);return BigInt(e)}function p(e){if(e>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("connected usage charge exceeds the safe integer range");return Number(e)}function ye(e){let r=b(e.functionRuns,"functionRuns"),a=b(e.proxyRequests,"proxyRequests"),s=b(e.computeMilliseconds,"computeMilliseconds"),n=r*BigInt(N),c=a*BigInt(k),d=s*BigInt(M),m=d===0n?0n:(d+999n)/1000n,h=n+c+m;return{functionRunMc:p(n),proxyRequestMc:p(c),computeMc:p(m),amountMc:p(h),credits:p(h)/o}}function Te(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*y))*BigInt(r)*BigInt(H),n=BigInt(y)*BigInt(v)*BigInt(K),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 Z=[{key:"serp",label:"SERP search",aliases:["search_serp","serp","google search","organic results"],credits:_,unit:"per page (ordinary search)",notes:`search_serp light mode returns one page of organic positions, URLs, titles, and descriptions by default. Unfiltered one-page full mode returns available same-page SERP features. Either mode requests two pages only when pages:2 is explicit. Unfiltered light searches cost ${_} credits per delivered page, or ${l} credits per delivered page if the backup supplies the result. One-page full searches cost ${l} credits. Setting recency to week or month applies Google's date filter through a managed browser and returns organic results only. It costs ${l} credits for one page; filtered pages:2 follows Google's page-two control and costs ${l*2} credits when both pages are delivered. Unfiltered searches use the managed browser only as the last backup. Unfiltered two-page full searches return organic results only for ${_*2} credits, with rich features marked unsupported. If only page 1 is delivered, the search is marked partial and billed for one delivered page. A temporary ${l}-credit-per-requested-page hold is settled to the delivered rate. Location, language, device, and optional module fields do not change ordinary searches. Saved browser identity and capture_serp_snapshot searches retain their ${$}-credit base price; optional page snapshots add ${i(t.page_scrape)} credit per attempted URL.`},{key:"paa",label:"PAA harvest",aliases:["harvest_paa","paa","people also ask","questions"],credits:i(t.paa),unit:`per question (+${i(t.paa_base)} credit base)`,notes:`Returns original-query PAA questions with answers and sources plus organic results and Google entity IDs. Optional same-page SERP modules are flag-controlled. Billed ${i(t.paa_base)} credit base + ${i(t.paa)} per question actually returned (unused estimate refunded).`},{key:"page_scrape",label:"Page crawl / extract",aliases:["extract_url","extract_site","page scrape","url scrape","single page","site crawl"],credits:i(t.page_scrape),unit:"per page",notes:"Applies to both single-URL extraction and per-page site crawls."},{key:"listing_create",label:"Directory or wiki listing creation",aliases:["local-sourcebook-capture","commons_submit_entity","directory listing","wiki listing"],credits:i(t.listing_create),unit:"per new listing",notes:"Fixed total price for a new Local Sourcebook directory listing or Transparent Commons wiki entity. Sourcebook acquisition is included."},{key:"listing_edit",label:"Directory or wiki listing edit",aliases:["local_sourcebook_refresh","commons_submit_entity","listing refresh","wiki edit"],credits:i(t.listing_edit),unit:"per existing listing revision",notes:"Fixed total price for refreshing an existing Local Sourcebook listing or revising an existing Transparent Commons entity."},{key:"url_map",label:"Site URL mapping",aliases:["map_site_urls","url map","site map","crawl urls"],credits:i(t.url_map),unit:"per mapping operation",notes:"Flat rate for the full /map-urls call regardless of URL count discovered."},{key:"yt_channel",label:"YouTube search / channel harvest",aliases:["youtube_harvest","youtube search","youtube channel","yt_channel"],credits:i(t.yt_channel),unit:"per call"},{key:"yt_transcription",label:"YouTube transcription",aliases:["youtube_transcribe","youtube transcript","transcription","yt_transcription"],credits:i(2e4),unit:"base + 2/min of video",notes:"Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},{key:"fb_ad",label:"Facebook search / ad lookup",aliases:["facebook_page_intel","facebook_ad_search","facebook_ad","facebook ads","fb ads"],credits:i(t.fb_ad),unit:"per call"},{key:"maps_search",label:"Maps business search",aliases:["maps_search","google maps search","gmb search","gbp search","business profiles"],credits:i(t.maps_search),unit:"per search",notes:"Returns up to 50 Google Maps business/profile candidates. Use maps_place_intel to hydrate selected businesses."},{key:"maps_place",label:"Maps business lookup",aliases:["maps_place_intel","google maps","maps place","place intel"],credits:i(t.maps_place),unit:"per business",notes:"Maps place runs reserve the 60-credit base plus the declared review maximum before browsing. Completed runs settle to the base plus unique saved reviews; stopped attempts are refunded."},{key:"maps_review",label:"Maps review",aliases:["maps_reviews","google reviews","review cards","reviews"],credits:i(t.maps_review),unit:"per review card",notes:"One credit per unique saved review on a completed Maps place run. The declared maximum is held before browsing; unused credits are refunded."},{key:"fb_search",label:"Facebook ad library search",aliases:["facebook_search","fb_search","fb ad search"],credits:i(t.fb_search),unit:"per search",notes:"Browser automation to search Facebook Ads Library by keyword."},{key:"google_ads_search",label:"Google Ads Transparency search",aliases:["google_ads_search","google ads search","ads transparency search"],credits:i(t.google_ads_search),unit:"per search",notes:"Browser automation to find advertisers in Google Ads Transparency Center by domain or name."},{key:"google_ads_intel",label:"Google Ads Transparency advertiser intel",aliases:["google_ads_page_intel","google ads intel","ads transparency intel"],credits:i(t.google_ads_intel),unit:"per call",notes:"Lists and hydrates an advertiser's creatives with image URLs and video references."},{key:"google_ads_transcribe",label:"Google ad video transcription",aliases:["google_ads_transcribe","google ad transcript"],credits:i(2e4),unit:"base + 2/min of video",notes:"Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},{key:"fb_transcribe",label:"Facebook video / ad transcription",aliases:["facebook_transcribe","facebook_video_transcribe","fb_transcribe","fb ad transcript"],credits:i(2e4),unit:"base + 2/min of video",notes:"Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},{key:"fb_reels_inventory",label:"Facebook Reel URL inventory",aliases:["facebook_reels_inventory","facebook reels","facebook reel urls","facebook profile reels"],credits:i(t.fb_reels_inventory),unit:"per profile scan",notes:"Collects canonical Reel URLs from a Facebook profile. Logged-out scans are capped at 60 URLs; saved browser profiles can request larger inventories."},{key:"tiktok_transcribe",label:"TikTok video transcription",aliases:["tiktok_video_transcribe","tiktok transcript"],credits:i(2e4),unit:"base + 2/min of video",notes:"Transcribes a public TikTok video from its playback media. Flat 200-credit base plus 2 credits per minute, reconciled after transcription."},{key:"instagram_profile",label:"Instagram profile content discovery",aliases:["instagram_profile_content","instagram profile","instagram content list","ig profile"],credits:i(t.instagram_profile),unit:"per profile scan",notes:"Browser extraction of public Instagram profile grid links. Complete history may require a logged-in profile."},{key:"instagram_media",label:"Instagram media download",aliases:["instagram_media_download","instagram reel download","instagram post download","ig media"],credits:i(t.instagram_media),unit:"per post or reel",notes:"Extracts post text, image URLs, and reel audio/video tracks, with local downloads when the server can write files."},{key:"instagram_transcribe",label:"Instagram media transcription",aliases:["instagram transcript","instagram reel transcript","ig transcribe"],credits:i(2e4),unit:"base + 2/min of video",notes:"Whisper transcription of selected Instagram audio/video media. Flat 200-credit base plus 2 credits per minute of video, reconciled to the real video length after transcription (e.g. a 10-minute video is about 220 credits)."},{key:"browser_minute",label:"Interactive browser session",aliases:["browser_open","browser agent","browser_agent","live browser","browse","browser control","interactive browser"],credits:i(t.browser_minute),unit:"per minute of use",notes:"Metered per minute of use for the whole time the browser session is open. Close the session to stop the meter; abandoned sessions are auto-closed after a short idle window."},{key:"reddit_thread",label:"Reddit thread base lookup",aliases:["reddit","reddit_thread","reddit comments","subreddit","reddit post"],credits:i(t.reddit_thread),unit:"per thread",notes:"Base lookup for the post itself. Comments billed separately per comment at reddit_comment rate. Refunded if the thread cannot be retrieved."},{key:"reddit_comment",label:"Reddit comment",aliases:["reddit_comment","reddit comments"],credits:i(t.reddit_comment),unit:"per comment",notes:"Charged per comment actually extracted, billed down automatically if the balance runs out mid-thread."},{key:"video_analysis",label:"Video breakdown (frame-by-frame + transcript)",aliases:["video_frame_analysis","video breakdown","video analysis","analyze video"],credits:i(t.video_analysis),unit:"per 120 frames (max 480)",notes:`Full video breakdown: samples frames across a video up to 60 minutes, analyzes visuals and audio, then produces a summary, pacing, topic outline, key points, hook, style, and replication guidance. Reserves ${i(t.video_analysis)} Credits per requested 120-frame tier, up to 480 frames. Unused frame tiers and failed-run frame charges are refunded. Incurred analysis-model usage is billed separately, including usage before a failure; terminal status checks settle the original run.`},{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."}],ve="price_1Ta1NRS8aAcsk3TGwsRnYbix";function w(e){return e.billing_interval??"month"}function P(e){return e.billed_usd??e.monthly_usd}function O(e){return e.credits_mc/o}var u={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}},C=Object.fromEntries(Object.values(u).map(e=>[e.tier,e])),E={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 X(e){let r=Object.values(E).find(a=>a.tier_keys.includes(e));return r?`/${r.slug}/claim`:null}function z(e){return e?Object.values(E).find(r=>r.tier_keys.includes(e))??null:null}function Se(e,r){let a=z(e);return a?!a.tier_keys.includes(r):!1}function Ie(e){if(!e)return null;let r=C[e];return r?{tier:r.tier,label:r.label,amount_usd:P(r),interval:w(r),monthly_equivalent_usd:r.monthly_usd,credits_per_interval:O(r),concurrency:r.concurrency,credits_never_expire:!!r.credits_never_expire,includes_memory:!!r.includes_memory,private_offer:!!r.private_offer,offer_claim_path:X(r.tier)}:null}function Ae(e){let r=E[e];if(!r)return null;let a=r.tier_keys.map(s=>C[s]).filter(s=>!!s).map(s=>({tier:s.tier,label:s.label,amount_usd:P(s),interval:w(s),monthly_equivalent_usd:s.monthly_usd,credits:O(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 xe(){let e=C.starter,r=Z.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(u).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{...g,operationCosts:a,publicTiers:s,concurrencyPack:{ratePolicyVersion:B,monthlyUsd:U,currency:L,interval:D,billingUnit:"pack",slotsPerPack:f},scaleCreditPack:{ratePolicyVersion:ee,eligibleTier:"scale",incrementUsd:G,creditsPerIncrement:R,maxQuantity:re,currency:"usd",expiryMonths:3},creditsPerDollarStarter:Math.round(i(e.credits_mc)/e.monthly_usd),costs:r,scheduling:g.addons.scheduling,connectedAccounts:g.addons.connectedAccounts,listingWrites:V}}var U=5,L="usd",D="month",f=2,B="2026-08-14.concurrency-pack-v1",J="$5/month for 2 extra browsers",Ne="MCP Scraper browser concurrency pack \u2014 each $5 monthly pack adds 2 browsers.",ke="Billed monthly until canceled. A receipt is emailed after each successful payment.",T="npx -y -p mcp-scraper@latest mcp-scraper-cli billing concurrency checkout",ee="2026-09-21.scale-credit-pack-v1",G=10,R=8e4,Me=R*o,re=100;function we(){let e=process.env.CONCURRENCY_BILLING_URL??"https://mcpscraper.dev/billing";return{product:"Extra browser concurrency pack",rate_policy_version:B,price_label:J,unit_amount_usd:U,currency:L,interval:D,billing_unit:"pack",pack_quantity:1,slots_per_pack:f,extra_slots:f,billing_url:e,terminal_command:T,terminal_command_with_api_key_env:`MCP_SCRAPER_API_KEY=sk_live_your_key ${T}`}}function i(e){return e/o}var te="npx -y -p mcp-scraper@latest mcp-scraper-cli billing subscribe";function ie(){return Object.values(u).filter(e=>!e.private_offer).sort((e,r)=>e.credits_mc-r.credits_mc)}function Pe(e,r){let a=process.env.TOPUP_URL??"https://mcpscraper.dev/billing",s=i(e),n=i(r),c=ie().map(m=>m.tier).join("|"),d=`${te} <${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. Scale customers can buy ${R} Credits per $${G} increment; other customers can move to a larger plan at ${a} (terminal: ${d})`,balance_credits:s,required_credits:n,topup_url:a,upgrade_command:d}}var ne=1e7*1,Oe={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}},Ue={free:ne,pro:5e9,team:5e10},se=3;var Le=19/se,De=3,Be=1.5,Ge=1.5,Y=2e4,q=200;function Ye(e){let r=Math.max(1,Math.ceil((e||60)/60));return Y+q*r}var qe=Y+q*30,Fe=u.price_1TmiHRS8aAcsk3TGwmSNfNIa.credits_mc/u.price_1TmiHRS8aAcsk3TGwmSNfNIa.monthly_usd;export{de as a,pe as b,ue as c,$ as d,me as e,ge as f,be as g,V as h,y as i,j,fe as k,Q as l,Ce as m,Ee as n,W as o,S as p,Re as q,I as r,A as s,x as t,N as u,he as v,ye as w,Te as x,Z as y,ve as z,w as A,P as B,O as C,u as D,C as E,X as F,z as G,Se as H,Ie as I,Ae as J,xe as K,U as L,f as M,Ne as N,ke as O,G as P,R as Q,Me as R,re as S,we as T,i as U,Pe as V,Oe as W,Ue as X,De as Y,Be as Z,Ge as _,Y as $,q as aa,Ye as ba,qe as ca,Fe as da};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$ as E,B as R,D as S,La as C,Ma as P,Y as v,_ as h,ha as T,ja as w,ka as _,la as y,x as u,y as f,z as g}from"./chunk-
|
|
1
|
+
import{$ as E,B as R,D as S,La as C,Ma as P,Y as v,_ as h,ha as T,ja as w,ka as _,la as y,x as u,y as f,z as g}from"./chunk-KUEMW76G.js";import{a as x}from"./chunk-6K7ZJYQW.js";import{a as c}from"./chunk-7H6YWD2L.js";import{readFileSync as L}from"fs";import{homedir as B}from"os";import{join as U}from"path";import{serveStdio as Y}from"@modelcontextprotocol/server/stdio";import{McpServer as J}from"@modelcontextprotocol/server";var I=new Map(_.map(r=>[r.upstreamName,r.id]));function N(r){let s=r.split(`
|
|
2
2
|
`).filter(t=>t.startsWith("data:")).map(t=>t.slice(5).trim()).filter(Boolean);if(!s.length)return JSON.parse(r);for(let t of s){let e=JSON.parse(t);if(e.result||e.error)return e}throw new Error("hosted MCP returned no JSON-RPC result")}function l(r){return{content:[{type:"text",text:JSON.stringify({ok:!1,error:r})}],isError:!0}}var p=class{baseUrl;apiKey;constructor(s,t){this.baseUrl=s.replace(/\/$/,""),this.apiKey=t}async callMemoryTool(s,t){let e=I.get(s);if(!e)return l(`unknown memory tool: ${s}`);try{let n=await fetch(`${this.baseUrl}/mcp`,{method:"POST",headers:{"content-type":"application/json",accept:"application/json, text/event-stream","x-api-key":this.apiKey},body:JSON.stringify({jsonrpc:"2.0",id:`memory:${e}`,method:"tools/call",params:{name:e,arguments:t}})}),i=await n.text();if(!n.ok)return l(`hosted memory ${e} failed (HTTP ${n.status})`);let o=N(i);return o.error?l(o.error.message??`hosted memory ${e} failed`):o.result??l(`hosted memory ${e} returned no result`)}catch(n){return l(n instanceof Error?n.message:`hosted memory ${e} call failed`)}}};function M(r,s){if(s.length===0)throw new Error("Restricted MCP tool allowlist must contain at least one tool name");let t=new Set;for(let o of s){if(typeof o!="string"||o.trim()!==o||o.length===0)throw new Error("Restricted MCP tool allowlist contains a malformed tool name");if(t.has(o))throw new Error(`Restricted MCP tool allowlist contains duplicate tool name: ${o}`);t.add(o)}let e=new Set,n=r,i=n.registerTool.bind(r);return n.registerTool=(o,a,m)=>{if(t.has(o))return e.add(o),i(o,a,m)},{assertComplete(){let o=[...t].filter(a=>!e.has(a));if(o.length>0)throw new Error(`Restricted MCP tool allowlist contains unknown or unavailable tool names: ${o.join(", ")}`)},registeredToolNames(){return[...e]}}}import{Client as b,StreamableHTTPClientTransport as k}from"@modelcontextprotocol/client";var $=new Set(["artifact_read","artifact_describe","artifact_download","report_artifact_read"]),A=()=>({content:[{type:"text",text:"Retained file storage is unavailable. Preserve the artifactId and retry retrieval; do not repeat acquisition."}],isError:!0});function O(r,s,t={}){return async(e,n)=>{if(!$.has(e))return A();let i=new b({name:"mcp-scraper-artifact-client",version:c},{versionNegotiation:{mode:"auto"}}),o=AbortSignal.timeout(3e4);try{let a=new k(new URL(`${r.replace(/\/$/,"")}/mcp`),{requestInit:{signal:o,headers:{Authorization:`Bearer ${s}`,"x-api-key":s,...t.localNetworkAccess?{"x-mcp-scraper-local-network":"1"}:{}}}});return await i.connect(a,{signal:o,timeout:3e4}),await i.callTool({name:e,arguments:n},{signal:o,timeout:3e4})}catch{return A()}finally{await i.close().catch(()=>{})}}}var G=new Set(["paa","serp","browser-agent","scheduled-results","memory"]);function K(){let s=[process.env.MCP_SCRAPER_KEY_PATH?.trim(),U(B(),".mcp-scraper-key")].filter(Boolean);for(let t of s)try{let e=L(t,"utf8").trim();if(e)return e}catch{}}function j(r,s={}){let t=s.toolsets??G,e=process.env.MCP_SCRAPER_BASE_URL?.trim()||process.env.MCP_BASE_URL?.trim()||"https://mcpscraper.dev",n=R(),i=S({deploymentProfile:n,transportProfile:"stdio",baseUrl:e,explicitlyEnabled:process.env.MCP_SCRAPER_ALLOW_PRIVATE_NETWORK==="1"}),o=process.env.BROWSER_AGENT_CONSOLE_URL?.trim()||e,a=new J({name:"mcp-scraper",version:c},{instructions:f,cacheHints:{"server/discover":{ttlMs:3e5,cacheScope:"private"},"tools/list":{ttlMs:3e5,cacheScope:"private"},"prompts/list":{ttlMs:3e5,cacheScope:"private"},"resources/list":{ttlMs:3e5,cacheScope:"private"},"resources/templates/list":{ttlMs:3e5,cacheScope:"private"},"resources/read":{ttlMs:6e4,cacheScope:"private"}}});g(a);let m=s.allowedToolNames?M(a,s.allowedToolNames):void 0,d=s.httpExecutor??new T(e,r,{localNetworkAccess:i,analyticsIdentity:()=>E(a.server.getClientVersion()?.name)});return t.has("paa")&&h(a,d,{ownerId:v(r),deploymentProfile:n,transportProfile:"stdio",baseUrl:e,localNetworkAccess:i,taskHandleSecret:r,remoteArtifactAccess:O(e,r,{localNetworkAccess:i})}),t.has("serp")&&u(a,d,{exposeDevelopmentDiagnostics:n==="development"||n==="test"}),t.has("browser-agent")&&w(a,{baseUrl:e,apiKey:r,consoleBaseUrl:o}),t.has("scheduled-results")&&P(a,new C(e,r)),t.has("memory")&&y(a,new p(e,r)),m?.assertComplete(),a}function Re(r={}){let s=process.argv.includes("--stdio")||process.env.MCP_SCRAPER_FORCE_STDIO==="1",t=!!(process.stdin.isTTY&&process.stdout.isTTY),e=process.argv.includes("--help")||process.argv.includes("-h");if(!s&&(t||e)){let i=process.argv.includes("--no-color")||process.env.NO_COLOR!==void 0||process.env.FORCE_COLOR==="0"||!process.stdout.isTTY;process.stdout.write(x({version:c,color:!i,apiKeyConfigured:!!process.env.MCP_SCRAPER_API_KEY?.trim()})),process.exit(0)}let n=(process.env.MCP_SCRAPER_API_KEY??process.env.MCP_SCRAPER_KEY??process.env.MCP_API_KEY??K())?.trim();n||(process.stderr.write(`MCP_SCRAPER_API_KEY env var or ~/.mcp-scraper-key is required
|
|
3
3
|
`),process.exit(1)),Y(()=>j(n,r),{legacy:"serve",onerror(i){process.stderr.write(`${i.message}
|
|
4
4
|
`)}})}export{Re as a};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{H as sn,_ as an,c as Yt,j as ut,k as je,m as nn,z as rn}from"./chunk-
|
|
1
|
+
import{H as sn,_ as an,c as Yt,j as ut,k as je,m as nn,z as rn}from"./chunk-SFUOSJ3A.js";import{B as gn,a as f,b as v,c as ue,d as Oe,e as yt,f as ln,g as un,h as U,i as $,l as _n,m as mn,n as pn,p as gt,u as B,v as Q,z as yn}from"./chunk-NNOX3FYG.js";import{a as qe}from"./chunk-NALXKTUU.js";import{a as Kt,b as Jt,f as zt}from"./chunk-6BD75VKS.js";import{d as on,g as He,i as We,k as _t,m as mt,o as cn,r as Be,t as dn,u as pt}from"./chunk-2IATUJO6.js";import{D as L,E as Qt,N as Zt,O as en,P as Re,Q as dt,R as tn,S as lt,U as te,W as le,p as Fe,q as Gt,v as Xt,z as ct}from"./chunk-CORWWDHL.js";import{f as Ue}from"./chunk-5LYINW7Z.js";import{a as I}from"./chunk-WNUXMPVX.js";import{randomUUID as Fi}from"crypto";async function fn(e,t,n){return(await I().execute({sql:`INSERT OR IGNORE INTO stripe_events
|
|
2
2
|
(event_id, event_type, stripe_created_at, status, attempt_count, received_at, next_attempt_at, processed_at, updated_at)
|
|
3
3
|
VALUES (?, ?, ?, 'pending', 0, datetime('now'), datetime('now'), datetime('now'), datetime('now'))`,args:[e,t,n]})).rowsAffected===1?"queued":"duplicate"}async function ra(e=50,t=300){let n=Math.max(1,Math.min(500,Math.trunc(e))),i=await I().execute({sql:`SELECT event_id
|
|
4
4
|
FROM stripe_events
|
|
@@ -932,4 +932,4 @@ MCowBQYDK2VwAyEAi2HR1srL4o18O8BRa7gVJY7G7bupbN3H9AwJrHCDiOg=
|
|
|
932
932
|
)
|
|
933
933
|
ORDER BY edge.confidence DESC, edge.last_seen_at DESC
|
|
934
934
|
LIMIT 1
|
|
935
|
-
FOR SHARE OF p, ns, cs, receipt`,[t.siteId,$("customer_id",t.stableUserId)])).rows[0]??null}async function Wt(e,t){let n=process.env.MCP_SCRAPER_XRAY_SITE_ID?.trim();if(!n)return{status:"skipped",eventName:Pe,reason:"site_not_configured"};if(!Ws(n))return{status:"skipped",eventName:Pe,reason:"site_id_invalid"};let i=String(e.userId).trim();if(!i||!e.invoiceId.trim()||!Number.isSafeInteger(e.amountPaidMinor)||e.amountPaidMinor<0||!/^[a-z]{3}$/i.test(e.currency)||!Number.isFinite(new Date(e.occurredAt).getTime()))throw new Error("analytics_first_party_outcome_invalid");let r=t??{db:v(),record:(a,o)=>Ai({...a,transactionClient:o})},s=await r.db.connect();try{await s.query("BEGIN");let a=await Bs(s,{siteId:n,stableUserId:i});if(!a)return await s.query("ROLLBACK"),{status:"skipped",eventName:Pe,reason:"identity_or_consent_unavailable"};let o={schemaVersion:1,eventId:`mcp_invoice_${e.invoiceId}`.slice(0,200),sourceEventId:`stripe:invoice:${e.invoiceId}`.slice(0,300),source:"mcp_scraper",sourceAccountRef:"first_party_billing",eventKind:"transaction",eventName:Pe,occurredAt:e.occurredAt,personRef:i,orderId:e.invoiceId,valueMinor:e.amountPaidMinor,currency:e.currency.toUpperCase(),consent:{analytics:"granted",adUserData:"granted",adPersonalization:a.advertising_measurement?"granted":"denied",globalPrivacyControl:!1,occurredAt:new Date(a.effective_at).toISOString(),receiptId:a.receipt_id,policyVersion:a.policy_version,purposes:{site_analytics:"granted",enhanced_matching:"granted",advertising_measurement:a.advertising_measurement?"granted":"denied"}},properties:{product:"mcp_scraper",billingKind:"base_plan_paid_invoice",revenueProvenance:"stripe_paid_invoice"}},c=await r.record({siteId:n,event:o},s);return await s.query("COMMIT"),{status:"recorded",eventName:Pe,reason:"recorded",created:c.created,conversionIds:c.conversionIds}}catch(a){throw await s.query("ROLLBACK").catch(()=>{}),a}finally{s.release()}}function Si(e,t){return e&&(t??0)>0}function hi(e){let t=e;return t?.price?.id??t?.pricing?.price_details?.price??t?.plan?.id}function Ce(e){if(typeof e=="string")return e;if(e&&typeof e=="object"&&"id"in e)return String(e.id)}function Vs(e){let t=e.subscription;if(t)return Ce(t);let n=e.parent;return Ce(n?.subscription_details?.subscription)}async function Ks(e,t){let n=await P(e);return n||!t||(n=await je(t),n&&await Ve(n.id,e)),n}async function Js(e,t,n){let i=t.memory_subscription_id;if(!(!i||i===n))try{let r=await e.subscriptions.retrieve(i);r.status!=="canceled"&&!r.cancel_at_period_end&&await e.subscriptions.update(i,{cancel_at_period_end:!0})}catch(r){console.error("[stripe] could not wind down standalone memory subscription",i,r instanceof Error?r.message:r)}}async function Bt(e,t,n){if(!t.id||t.status!=="paid")return{status:"not_applicable",invoiceId:t.id??null};let i=t.lines.data.some(p=>{let E=hi(p);return!!E&&E in L});if(!Si(i,t.total))return{status:"not_applicable",invoiceId:t.id};let r=Vs(t),a=(r?me(await e.subscriptions.retrieve(r))?.price?.id:void 0)??t.lines.data.map(hi).find(p=>!!p&&p in L),o=a?L[a]:void 0;if(!o)return{status:"not_applicable",invoiceId:t.id};let c=Ce(t.customer);if(!c)throw new Error("Paid subscription invoice has no Stripe customer");let l=await Ks(c,t.customer_email);if(!l)throw new Error("Paid subscription invoice does not map to an MCP Scraper account");let _=await vn({invoiceId:t.id,userId:l.id,subscriptionId:r??l.subscription_id,tier:o.tier,concurrency:o.concurrency,creditsMc:o.credits_mc,description:`${o.label} subscription credits`,neverExpires:!!o.credits_never_expire,includedMemoryPlan:o.includes_memory?"pro":null});o.includes_memory&&(await Js(e,l,r??l.subscription_id),await Z(l,V({...l,memory_plan:"pro",subscription_tier:o.tier})));let d=await Je(l);d.ok||console.warn("[stripe] scheduled-action credential sync failed:",d.error??"unknown error");try{await Wt({userId:l.id,invoiceId:t.id,amountPaidMinor:t.amount_paid,currency:t.currency,occurredAt:new Date(((t.status_transitions?.paid_at??n)||Math.floor(Date.now()/1e3))*1e3).toISOString()})}catch(p){console.error("[stripe] X-Ray paid outcome failed",{invoiceId:t.id,error:p instanceof Error?p.message:String(p)})}return{status:_.granted?"fulfilled":"already_fulfilled",invoiceId:t.id,userId:l.id,tier:o.tier}}async function Ni(e,t,n){let i=await e.checkout.sessions.retrieve(t,{expand:["invoice"]});if(i.mode!=="subscription")throw new Error("Checkout session is not a subscription purchase");if(i.payment_status!=="paid"&&i.payment_status!=="no_payment_required")return{status:"not_applicable",invoiceId:Ce(i.invoice)??null};let r=Ce(i.customer);if(n&&r!==n)throw new Error("Checkout session does not belong to this billing account");let s=typeof i.invoice=="object"&&i.invoice&&!("deleted"in i.invoice)?i.invoice:await e.invoices.retrieve(Ce(i.invoice)??"");if(!s?.id)throw new Error("Paid subscription checkout has no invoice");return Bt(e,s,i.created)}var Ci="scale_credit_pack";function ot(e){if(typeof e=="string")return e;if(e&&typeof e=="object"&&"id"in e)return String(e.id)}function wi(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>lt)throw new Error(`quantity must be a whole number from 1 to ${lt}`);return t}function Vd(e){return e.subscription_tier==="scale"}function Kd(e,t){let n=wi(t);return{purchase_kind:Ci,account_user_id:String(e),eligible_tier:"scale",increment_quantity:String(n),increment_usd:String(Re),credits_per_increment:String(dt)}}async function Ri(e,t,n){let i=await e.checkout.sessions.retrieve(t);if(i.mode!=="payment"||i.metadata?.purchase_kind!==Ci)return{status:"not_applicable",paymentIntentId:ot(i.payment_intent)??null};if(i.payment_status!=="paid")return{status:"not_applicable",paymentIntentId:ot(i.payment_intent)??null};let r=ot(i.customer);if(!r)throw new Error("Paid Scale credit-pack checkout has no Stripe customer");if(n&&r!==n)throw new Error("Checkout session does not belong to this billing account");let s=wi(i.metadata.increment_quantity),a=s*Re*100;if(i.currency!=="usd"||i.amount_subtotal!==a)throw new Error("Scale credit-pack checkout amount does not match the product contract");let o=await e.checkout.sessions.listLineItems(i.id,{limit:2}),c=o.data[0];if(o.data.length!==1||c?.quantity!==s||c.price?.currency!=="usd"||c.price?.unit_amount!==Re*100)throw new Error("Scale credit-pack checkout line item does not match the product contract");let l=await P(r);if(!l)throw new Error("Paid Scale credit-pack checkout does not map to an MCP Scraper account");if(i.metadata.account_user_id!==String(l.id)||i.metadata.eligible_tier!=="scale")throw new Error("Scale credit-pack checkout account metadata does not match the billing account");let _=ot(i.payment_intent);if(!_)throw new Error("Paid Scale credit-pack checkout has no payment intent");let d=s*dt;return{status:(await Yt(l.id,s*tn,Ue.TOPUP,`$${s*Re} Scale credit pack (${d.toLocaleString("en-US")} credits)`,`stripe-payment-intent:${_}`,{neverExpires:!1})).duplicate?"already_fulfilled":"fulfilled",paymentIntentId:_,userId:l.id,quantity:s,credits:d}}var M=new zs(process.env.STRIPE_SECRET_KEY,{apiVersion:"2026-02-25.clover"});async function Xs(e,t){if(!(!e||e===t))try{let n=await M.subscriptions.retrieve(e),i=n.items.data[0]?.price?.id,r=n.status!=="canceled"&&!n.cancel_at_period_end;i&&i in le&&r&&await M.subscriptions.update(e,{cancel_at_period_end:!0})}catch(n){console.error("[stripe] could not wind down standalone memory subscription",e,n instanceof Error?n.message:n)}}var Qs=new Ys;Qs.post("/webhooks",async e=>{let t=e.req.header("stripe-signature"),n=await e.req.text(),i;try{i=M.webhooks.constructEvent(n,t,process.env.STRIPE_WEBHOOK_SECRET)}catch{return e.json({error:"Invalid signature"},400)}try{let r=await fn(i.id,i.type,i.created);return r==="queued"&&Zs(),e.json({received:!0,disposition:r})}catch(r){let s=r instanceof Error?r.message:String(r);return console.error("[stripe] webhook enqueue failed",i.id,s),e.json({error:"Webhook enqueue failed"},500)}});function Zs(){let e=import("./queue-HUP2GNXF.js").then(({drainStripeEventQueue:t})=>t({limit:10,leaseSeconds:300})).catch(t=>{console.error("[stripe] immediate queue drain failed; the scheduled drain will retry",t instanceof Error?t.message:String(t))});Gs(e)}async function ol(e){if(e.type==="checkout.session.completed"||e.type==="checkout.session.async_payment_succeeded"){let t=e.data.object;t.mode==="payment"?await Ri(M,t.id):await Ni(M,t.id);return}if(e.type==="invoice.created"){let t=e.data.object;Oi(t)&&t.status==="draft"&&await M.invoices.update(t.id,{description:Zt,footer:en,custom_fields:[{name:"Pack benefit",value:"2 browsers per $5 monthly pack"},{name:"Billing cadence",value:"Monthly"}]});return}if(e.type==="invoice.paid"||e.type==="invoice.payment_succeeded"){let t=e.data.object;if(Oi(t)){let i=t.customer_email?void 0:await Ti(t.customer,void 0),r=t.customer_email??i?.email;if(!r)throw new Error("Paid concurrency invoice has no customer receipt email");await ea(t.id,r);return}if(t.lines.data.map(xi).find(i=>i&&i in le))return;await Bt(M,t,e.created)}if(e.type==="customer.subscription.created"||e.type==="customer.subscription.updated"){let t=e.data.object,n=Di(t);if(n){let s=await P(t.customer);if(!s)return;let a=De(t.status);await ft(s.id,a?ta(n):0),await vt(s.id,a?t.id:null);return}let i=me(t)?.price?.id??t.items.data[0]?.price?.id;if(i&&i in le){let s=le[i],a=await Ti(t.customer,t.customer_email);if(a){let o=De(t.status),c=o?s.plan:"free";await _e(a.id,c,o?t.id:null),await Z(a,V({...a,memory_plan:c}))}return}let r=await P(t.customer);if(!r)return;if(i&&i in L){let s=L[i],a=De(t.status),o=a?s.tier:null;if(await Et(r.id,o,a?s.concurrency:0,a?t.id:null),s.includes_memory){let c=a?"pro":"free";a&&await Xs(r.memory_subscription_id,t.id),await _e(r.id,c,null),await Z(r,V({...r,memory_plan:c}))}else r.memory_subscription_id===t.id&&(await _e(r.id,"free",null),await Z(r,V({...r,memory_plan:"free"})));if(a){let c=await Je(r);c.ok||console.warn("[stripe] scheduled-action credential sync failed:",c.error??"unknown error")}}}if(e.type==="customer.subscription.deleted"){let t=e.data.object;if(Di(t)){let i=await P(t.customer);i&&(await ft(i.id,0),await vt(i.id,null));return}let n=me(t)?.price?.id??t.items.data[0]?.price?.id;if(n&&n in L){let i=L[n],r=await P(t.customer);r&&(await Et(r.id,null,0,null),(i.includes_memory||r.memory_subscription_id===t.id)&&(await _e(r.id,"free",null),await Z(r,V({...r,memory_plan:"free"}))));return}if(n&&n in le||await bt(t.id)){let i=await bt(t.id)??await P(t.customer);i&&(await _e(i.id,"free",null),await Z(i,V({...i,memory_plan:"free"})));return}}}function Oi(e){return e.lines.data.some(t=>xi(t)===ct)}async function ea(e,t){let i=(await M.invoicePayments.list({invoice:e,status:"paid",limit:10})).data.find(a=>a.status==="paid");if(!i)throw new Error("Paid concurrency invoice has no paid Stripe payment");let r;if(i.payment.type==="charge")r=i.payment.charge;else if(i.payment.type==="payment_intent"&&i.payment.payment_intent){let a=typeof i.payment.payment_intent=="string"?i.payment.payment_intent:i.payment.payment_intent.id;r=(await M.paymentIntents.retrieve(a,{expand:["latest_charge"]})).latest_charge}if(!r)throw new Error("Paid concurrency invoice has no receipt-capable charge");let s=typeof r=="string"?await M.charges.retrieve(r):r;s.receipt_email!==t&&await M.charges.update(s.id,{receipt_email:t})}function Di(e){return e.items.data.find(t=>t.price?.id===ct)}function ta(e){let t=e.quantity??1;if(!Number.isSafeInteger(t)||t<1)throw new Error("Stripe concurrency pack quantity must be a positive safe integer");return t}function xi(e){let t=e;return t?.price?.id??t?.pricing?.price_details?.price??t?.plan?.id}async function Ti(e,t){let n=await P(e);if(n)return n;if(t)return n=await je(t),n&&await Ve(n.id,e),n}export{Ve as a,ft as b,vt as c,Et as d,_e as e,ma as f,Ki as g,fa as h,In as i,It as j,Na as k,Ca as l,Sn as m,ir as n,wa as o,Ra as p,rr as q,Nn as r,Je as s,ra as t,sa as u,aa as v,oa as w,ca as x,ht as y,K as z,me as A,Ma as B,Ua as C,Fa as D,Xe as E,Qe as F,Ln as G,Cr as H,Rr as I,Ct as J,Ga as K,Xa as L,Qa as M,Za as N,oo as O,Un as P,po as Q,yo as R,go as S,fo as T,vo as U,Eo as V,bo as W,Io as X,Ao as Y,So as Z,ho as _,No as $,Co as aa,jn as ba,wo as ca,Lr as da,Ro as ea,se as fa,nt as ga,F as ha,Oo as ia,Pr as ja,Lo as ka,$o as la,ko as ma,zn as na,Yn as oa,Po as pa,jo as qa,Zn as ra,qo as sa,Hr as ta,Xo as ua,fe as va,Qo as wa,uc as xa,si as ya,ai as za,yc as Aa,gc as Ba,oi as Ca,Ec as Da,ci as Ea,di as Fa,li as Ga,ui as Ha,_i as Ia,mi as Ja,at as Ka,Lc as La,$c as Ma,kc as Na,Pc as Oa,Mc as Pa,Uc as Qa,yi as Ra,gi as Sa,Ft as Ta,fi as Ua,vi as Va,Ds as Wa,cd as Xa,dd as Ya,ld as Za,ud as _a,_d as $a,md as ab,pd as bb,yd as cb,gd as db,fd as eb,vd as fb,Ed as gb,bd as hb,Id as ib,Ad as jb,Sd as kb,Ei as lb,hd as mb,Nd as nb,Ai as ob,Cd as pb,wd as qb,Bt as rb,Ni as sb,wi as tb,Vd as ub,Kd as vb,Ri as wb,M as xb,Qs as yb,ol as zb};
|
|
935
|
+
FOR SHARE OF p, ns, cs, receipt`,[t.siteId,$("customer_id",t.stableUserId)])).rows[0]??null}async function Wt(e,t){let n=process.env.MCP_SCRAPER_XRAY_SITE_ID?.trim();if(!n)return{status:"skipped",eventName:Pe,reason:"site_not_configured"};if(!Ws(n))return{status:"skipped",eventName:Pe,reason:"site_id_invalid"};let i=String(e.userId).trim();if(!i||!e.invoiceId.trim()||!Number.isSafeInteger(e.amountPaidMinor)||e.amountPaidMinor<0||!/^[a-z]{3}$/i.test(e.currency)||!Number.isFinite(new Date(e.occurredAt).getTime()))throw new Error("analytics_first_party_outcome_invalid");let r=t??{db:v(),record:(a,o)=>Ai({...a,transactionClient:o})},s=await r.db.connect();try{await s.query("BEGIN");let a=await Bs(s,{siteId:n,stableUserId:i});if(!a)return await s.query("ROLLBACK"),{status:"skipped",eventName:Pe,reason:"identity_or_consent_unavailable"};let o={schemaVersion:1,eventId:`mcp_invoice_${e.invoiceId}`.slice(0,200),sourceEventId:`stripe:invoice:${e.invoiceId}`.slice(0,300),source:"mcp_scraper",sourceAccountRef:"first_party_billing",eventKind:"transaction",eventName:Pe,occurredAt:e.occurredAt,personRef:i,orderId:e.invoiceId,valueMinor:e.amountPaidMinor,currency:e.currency.toUpperCase(),consent:{analytics:"granted",adUserData:"granted",adPersonalization:a.advertising_measurement?"granted":"denied",globalPrivacyControl:!1,occurredAt:new Date(a.effective_at).toISOString(),receiptId:a.receipt_id,policyVersion:a.policy_version,purposes:{site_analytics:"granted",enhanced_matching:"granted",advertising_measurement:a.advertising_measurement?"granted":"denied"}},properties:{product:"mcp_scraper",billingKind:"base_plan_paid_invoice",revenueProvenance:"stripe_paid_invoice"}},c=await r.record({siteId:n,event:o},s);return await s.query("COMMIT"),{status:"recorded",eventName:Pe,reason:"recorded",created:c.created,conversionIds:c.conversionIds}}catch(a){throw await s.query("ROLLBACK").catch(()=>{}),a}finally{s.release()}}function Si(e,t){return e&&(t??0)>0}function hi(e){let t=e;return t?.price?.id??t?.pricing?.price_details?.price??t?.plan?.id}function Ce(e){if(typeof e=="string")return e;if(e&&typeof e=="object"&&"id"in e)return String(e.id)}function Vs(e){let t=e.subscription;if(t)return Ce(t);let n=e.parent;return Ce(n?.subscription_details?.subscription)}async function Ks(e,t){let n=await P(e);return n||!t||(n=await je(t),n&&await Ve(n.id,e)),n}async function Js(e,t,n){let i=t.memory_subscription_id;if(!(!i||i===n))try{let r=await e.subscriptions.retrieve(i);r.status!=="canceled"&&!r.cancel_at_period_end&&await e.subscriptions.update(i,{cancel_at_period_end:!0})}catch(r){console.error("[stripe] could not wind down standalone memory subscription",i,r instanceof Error?r.message:r)}}async function Bt(e,t,n){if(!t.id||t.status!=="paid")return{status:"not_applicable",invoiceId:t.id??null};let i=t.lines.data.some(p=>{let E=hi(p);return!!E&&E in L});if(!Si(i,t.total))return{status:"not_applicable",invoiceId:t.id};let r=Vs(t),a=(r?me(await e.subscriptions.retrieve(r))?.price?.id:void 0)??t.lines.data.map(hi).find(p=>!!p&&p in L),o=a?L[a]:void 0;if(!o)return{status:"not_applicable",invoiceId:t.id};let c=Ce(t.customer);if(!c)throw new Error("Paid subscription invoice has no Stripe customer");let l=await Ks(c,t.customer_email);if(!l)throw new Error("Paid subscription invoice does not map to an MCP Scraper account");let _=await vn({invoiceId:t.id,userId:l.id,subscriptionId:r??l.subscription_id,tier:o.tier,concurrency:o.concurrency,creditsMc:o.credits_mc,description:`${o.label} subscription credits`,neverExpires:!!o.credits_never_expire,includedMemoryPlan:o.includes_memory?"pro":null});o.includes_memory&&(await Js(e,l,r??l.subscription_id),await Z(l,V({...l,memory_plan:"pro",subscription_tier:o.tier})));let d=await Je(l);d.ok||console.warn("[stripe] scheduled-action credential sync failed:",d.error??"unknown error");try{await Wt({userId:l.id,invoiceId:t.id,amountPaidMinor:t.amount_paid,currency:t.currency,occurredAt:new Date(((t.status_transitions?.paid_at??n)||Math.floor(Date.now()/1e3))*1e3).toISOString()})}catch(p){console.error("[stripe] X-Ray paid outcome failed",{invoiceId:t.id,error:p instanceof Error?p.message:String(p)})}return{status:_.granted?"fulfilled":"already_fulfilled",invoiceId:t.id,userId:l.id,tier:o.tier}}async function Ni(e,t,n){let i=await e.checkout.sessions.retrieve(t,{expand:["invoice"]});if(i.mode!=="subscription")throw new Error("Checkout session is not a subscription purchase");if(i.payment_status!=="paid"&&i.payment_status!=="no_payment_required")return{status:"not_applicable",invoiceId:Ce(i.invoice)??null};let r=Ce(i.customer);if(n&&r!==n)throw new Error("Checkout session does not belong to this billing account");let s=typeof i.invoice=="object"&&i.invoice&&!("deleted"in i.invoice)?i.invoice:await e.invoices.retrieve(Ce(i.invoice)??"");if(!s?.id)throw new Error("Paid subscription checkout has no invoice");return Bt(e,s,i.created)}var Ci="scale_credit_pack";function ot(e){if(typeof e=="string")return e;if(e&&typeof e=="object"&&"id"in e)return String(e.id)}function wi(e){let t=Number(e);if(!Number.isSafeInteger(t)||t<1||t>lt)throw new Error(`quantity must be a whole number from 1 to ${lt}`);return t}function Vd(e){return e.subscription_tier==="scale"}function Kd(e,t){let n=wi(t);return{purchase_kind:Ci,account_user_id:String(e),eligible_tier:"scale",increment_quantity:String(n),increment_usd:String(Re),credits_per_increment:String(dt)}}async function Ri(e,t,n){let i=await e.checkout.sessions.retrieve(t);if(i.mode!=="payment"||i.metadata?.purchase_kind!==Ci)return{status:"not_applicable",paymentIntentId:ot(i.payment_intent)??null};if(i.payment_status!=="paid")return{status:"not_applicable",paymentIntentId:ot(i.payment_intent)??null};let r=ot(i.customer);if(!r)throw new Error("Paid Scale credit-pack checkout has no Stripe customer");if(n&&r!==n)throw new Error("Checkout session does not belong to this billing account");let s=wi(i.metadata.increment_quantity),a=s*Re*100;if(i.currency!=="usd"||i.amount_subtotal!==a)throw new Error("Scale credit-pack checkout amount does not match the product contract");let o=await e.checkout.sessions.listLineItems(i.id,{limit:2}),c=o.data[0];if(o.data.length!==1||c?.quantity!==s||c.price?.currency!=="usd"||c.price?.unit_amount!==Re*100)throw new Error("Scale credit-pack checkout line item does not match the product contract");let l=await P(r);if(!l)throw new Error("Paid Scale credit-pack checkout does not map to an MCP Scraper account");if(i.metadata.account_user_id!==String(l.id)||i.metadata.eligible_tier!=="scale")throw new Error("Scale credit-pack checkout account metadata does not match the billing account");let _=ot(i.payment_intent);if(!_)throw new Error("Paid Scale credit-pack checkout has no payment intent");let d=s*dt;return{status:(await Yt(l.id,s*tn,Ue.TOPUP,`$${s*Re} Scale credit pack (${d.toLocaleString("en-US")} credits)`,`stripe-payment-intent:${_}`,{neverExpires:!1})).duplicate?"already_fulfilled":"fulfilled",paymentIntentId:_,userId:l.id,quantity:s,credits:d}}var M=new zs(process.env.STRIPE_SECRET_KEY,{apiVersion:"2026-02-25.clover"});async function Xs(e,t){if(!(!e||e===t))try{let n=await M.subscriptions.retrieve(e),i=n.items.data[0]?.price?.id,r=n.status!=="canceled"&&!n.cancel_at_period_end;i&&i in le&&r&&await M.subscriptions.update(e,{cancel_at_period_end:!0})}catch(n){console.error("[stripe] could not wind down standalone memory subscription",e,n instanceof Error?n.message:n)}}var Qs=new Ys;Qs.post("/webhooks",async e=>{let t=e.req.header("stripe-signature"),n=await e.req.text(),i;try{i=M.webhooks.constructEvent(n,t,process.env.STRIPE_WEBHOOK_SECRET)}catch{return e.json({error:"Invalid signature"},400)}try{let r=await fn(i.id,i.type,i.created);return r==="queued"&&Zs(),e.json({received:!0,disposition:r})}catch(r){let s=r instanceof Error?r.message:String(r);return console.error("[stripe] webhook enqueue failed",i.id,s),e.json({error:"Webhook enqueue failed"},500)}});function Zs(){let e=import("./queue-AC4XKD6Z.js").then(({drainStripeEventQueue:t})=>t({limit:10,leaseSeconds:300})).catch(t=>{console.error("[stripe] immediate queue drain failed; the scheduled drain will retry",t instanceof Error?t.message:String(t))});Gs(e)}async function ol(e){if(e.type==="checkout.session.completed"||e.type==="checkout.session.async_payment_succeeded"){let t=e.data.object;t.mode==="payment"?await Ri(M,t.id):await Ni(M,t.id);return}if(e.type==="invoice.created"){let t=e.data.object;Oi(t)&&t.status==="draft"&&await M.invoices.update(t.id,{description:Zt,footer:en,custom_fields:[{name:"Pack benefit",value:"2 browsers per $5 monthly pack"},{name:"Billing cadence",value:"Monthly"}]});return}if(e.type==="invoice.paid"||e.type==="invoice.payment_succeeded"){let t=e.data.object;if(Oi(t)){let i=t.customer_email?void 0:await Ti(t.customer,void 0),r=t.customer_email??i?.email;if(!r)throw new Error("Paid concurrency invoice has no customer receipt email");await ea(t.id,r);return}if(t.lines.data.map(xi).find(i=>i&&i in le))return;await Bt(M,t,e.created)}if(e.type==="customer.subscription.created"||e.type==="customer.subscription.updated"){let t=e.data.object,n=Di(t);if(n){let s=await P(t.customer);if(!s)return;let a=De(t.status);await ft(s.id,a?ta(n):0),await vt(s.id,a?t.id:null);return}let i=me(t)?.price?.id??t.items.data[0]?.price?.id;if(i&&i in le){let s=le[i],a=await Ti(t.customer,t.customer_email);if(a){let o=De(t.status),c=o?s.plan:"free";await _e(a.id,c,o?t.id:null),await Z(a,V({...a,memory_plan:c}))}return}let r=await P(t.customer);if(!r)return;if(i&&i in L){let s=L[i],a=De(t.status),o=a?s.tier:null;if(await Et(r.id,o,a?s.concurrency:0,a?t.id:null),s.includes_memory){let c=a?"pro":"free";a&&await Xs(r.memory_subscription_id,t.id),await _e(r.id,c,null),await Z(r,V({...r,memory_plan:c}))}else r.memory_subscription_id===t.id&&(await _e(r.id,"free",null),await Z(r,V({...r,memory_plan:"free"})));if(a){let c=await Je(r);c.ok||console.warn("[stripe] scheduled-action credential sync failed:",c.error??"unknown error")}}}if(e.type==="customer.subscription.deleted"){let t=e.data.object;if(Di(t)){let i=await P(t.customer);i&&(await ft(i.id,0),await vt(i.id,null));return}let n=me(t)?.price?.id??t.items.data[0]?.price?.id;if(n&&n in L){let i=L[n],r=await P(t.customer);r&&(await Et(r.id,null,0,null),(i.includes_memory||r.memory_subscription_id===t.id)&&(await _e(r.id,"free",null),await Z(r,V({...r,memory_plan:"free"}))));return}if(n&&n in le||await bt(t.id)){let i=await bt(t.id)??await P(t.customer);i&&(await _e(i.id,"free",null),await Z(i,V({...i,memory_plan:"free"})));return}}}function Oi(e){return e.lines.data.some(t=>xi(t)===ct)}async function ea(e,t){let i=(await M.invoicePayments.list({invoice:e,status:"paid",limit:10})).data.find(a=>a.status==="paid");if(!i)throw new Error("Paid concurrency invoice has no paid Stripe payment");let r;if(i.payment.type==="charge")r=i.payment.charge;else if(i.payment.type==="payment_intent"&&i.payment.payment_intent){let a=typeof i.payment.payment_intent=="string"?i.payment.payment_intent:i.payment.payment_intent.id;r=(await M.paymentIntents.retrieve(a,{expand:["latest_charge"]})).latest_charge}if(!r)throw new Error("Paid concurrency invoice has no receipt-capable charge");let s=typeof r=="string"?await M.charges.retrieve(r):r;s.receipt_email!==t&&await M.charges.update(s.id,{receipt_email:t})}function Di(e){return e.items.data.find(t=>t.price?.id===ct)}function ta(e){let t=e.quantity??1;if(!Number.isSafeInteger(t)||t<1)throw new Error("Stripe concurrency pack quantity must be a positive safe integer");return t}function xi(e){let t=e;return t?.price?.id??t?.pricing?.price_details?.price??t?.plan?.id}async function Ti(e,t){let n=await P(e);if(n)return n;if(t)return n=await je(t),n&&await Ve(n.id,e),n}export{Ve as a,ft as b,vt as c,Et as d,_e as e,ma as f,Ki as g,fa as h,In as i,It as j,Na as k,Ca as l,Sn as m,ir as n,wa as o,Ra as p,rr as q,Nn as r,Je as s,ra as t,sa as u,aa as v,oa as w,ca as x,ht as y,K as z,me as A,Ma as B,Ua as C,Fa as D,Xe as E,Qe as F,Ln as G,Cr as H,Rr as I,Ct as J,Ga as K,Xa as L,Qa as M,Za as N,oo as O,Un as P,po as Q,yo as R,go as S,fo as T,vo as U,Eo as V,bo as W,Io as X,Ao as Y,So as Z,ho as _,No as $,Co as aa,jn as ba,wo as ca,Lr as da,Ro as ea,se as fa,nt as ga,F as ha,Oo as ia,Pr as ja,Lo as ka,$o as la,ko as ma,zn as na,Yn as oa,Po as pa,jo as qa,Zn as ra,qo as sa,Hr as ta,Xo as ua,fe as va,Qo as wa,uc as xa,si as ya,ai as za,yc as Aa,gc as Ba,oi as Ca,Ec as Da,ci as Ea,di as Fa,li as Ga,ui as Ha,_i as Ia,mi as Ja,at as Ka,Lc as La,$c as Ma,kc as Na,Pc as Oa,Mc as Pa,Uc as Qa,yi as Ra,gi as Sa,Ft as Ta,fi as Ua,vi as Va,Ds as Wa,cd as Xa,dd as Ya,ld as Za,ud as _a,_d as $a,md as ab,pd as bb,yd as cb,gd as db,fd as eb,vd as fb,Ed as gb,bd as hb,Id as ib,Ad as jb,Sd as kb,Ei as lb,hd as mb,Nd as nb,Ai as ob,Cd as pb,wd as qb,Bt as rb,Ni as sb,wi as tb,Vd as ub,Kd as vb,Ri as wb,M as xb,Qs as yb,ol as zb};
|