mcp-scraper 0.90.5 → 0.90.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +2 -2
  3. package/dist/bin/api-server.js +2 -2
  4. package/dist/bin/mcp-scraper-cli.js +1 -1
  5. package/dist/bin/mcp-scraper-core.js +1 -1
  6. package/dist/bin/mcp-scraper-install.js +1 -1
  7. package/dist/bin/mcp-stdio-server.js +1 -1
  8. package/dist/bin/paa-harvest.js +1 -1
  9. package/dist/{chunk-W4QBJ7WW.js → chunk-5MMN27Q6.js} +2 -2
  10. package/dist/{chunk-PNDXAOZD.js → chunk-AQSMJCTF.js} +1 -1
  11. package/dist/{chunk-ZJOD3YKH.js → chunk-AQXYXVOP.js} +8 -8
  12. package/dist/{chunk-YEFXVTMJ.js → chunk-CTX3NMZQ.js} +1 -1
  13. package/dist/{chunk-5RTZPHIY.js → chunk-MADTJXNI.js} +1 -1
  14. package/dist/chunk-NOUHD54C.js +48 -0
  15. package/dist/{chunk-XSYLDTMI.js → chunk-NWRRVZKW.js} +1 -1
  16. package/dist/chunk-UM4WSLKQ.js +1 -0
  17. package/dist/{chunk-NC32JCZT.js → chunk-WDB5CTRY.js} +1 -1
  18. package/dist/chunk-XARSC34L.js +1279 -0
  19. package/dist/{chunk-IRWULJS5.js → chunk-YDOBZMLS.js} +1 -1
  20. package/dist/{extract-bundle-MQM3P7VS.js → extract-bundle-CP6WBOJI.js} +1 -1
  21. package/dist/{gmail-service-DTUP6EWC.js → gmail-service-5NH2GVQ5.js} +1 -1
  22. package/dist/index.cjs +45 -45
  23. package/dist/index.js +1 -1
  24. package/dist/server-TQJ6Z3ZF.js +4931 -0
  25. package/dist/{site-extract-repository-IZT3NTWY.js → site-extract-repository-KG6FQU55.js} +1 -1
  26. package/dist/{stripe-event-worker-5QNWGHVK.js → stripe-event-worker-ZNNQEVK4.js} +1 -1
  27. package/dist/{worker-Z27YG7TE.js → worker-4LFWAEX2.js} +1 -1
  28. package/package.json +1 -1
  29. package/dist/chunk-5JCPVCBT.js +0 -1280
  30. package/dist/chunk-ARKQYLKU.js +0 -1
  31. package/dist/chunk-X4YCWF4B.js +0 -48
  32. package/dist/server-NTIME7TQ.js +0 -6520
@@ -1 +0,0 @@
1
- var o="0.90.5";export{o as a};
@@ -1,48 +0,0 @@
1
- import{a as P}from"./chunk-XG6GCEUE.js";import{d as k,g as L}from"./chunk-56UT5M5Y.js";import{b as y,g as c,h as v,ha as O,ia as N,j as R,ka as x,m as I,o as A,t as a}from"./chunk-KKHTMYCD.js";import{createHash as j,randomUUID as b}from"crypto";var w=class extends Error{constructor(){super("This idempotency key was already used with different normalized inputs."),this.name="OperationIdempotencyConflictError"}};function g(e){return j("sha256").update(e).digest("hex")}function S(e){return Array.isArray(e)?e.map(S):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([r],[o])=>r.localeCompare(o)).map(([r,o])=>[r,S(o)])):e}function T(e){return JSON.stringify(S(e??{}))}function l(e,r){let o=e.trim();if(!o)throw new Error(`${r} is required`);return o}function p(e,r=2e3){return e==null?null:e.slice(0,r)}async function C(e){let r=a(),o=l(e.tool,"tool"),s=l(e.ownerScope,"ownerScope"),i=e.idempotencyKey?.trim()||null,t=e.requestFingerprint?.trim()||null;if(i==null!=(t==null))throw new Error("idempotencyKey and requestFingerprint must be supplied together");let n=i?g(`${s}\0${o}\0${i}`):null,d=e.id??b(),u=[d,e.userId??null,g(s),o,n,t,e.jobId??null,e.requestId??null,e.deploymentCommit??null,T(e.normalizedFlags),e.startedAt??new Date().toISOString()];if(n){await r.execute({sql:`INSERT OR IGNORE INTO operation_runs
2
- (id, user_id, owner_scope_hash, tool, idempotency_scope_hash, request_fingerprint,
3
- job_id, request_id, deployment_commit, normalized_flags_json, started_at)
4
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,args:u});let f=(await r.execute({sql:"SELECT id, request_fingerprint FROM operation_runs WHERE idempotency_scope_hash = ?",args:[n]})).rows[0];if(!f)throw new Error("Operation run insert did not produce an idempotency receipt");if(String(f.request_fingerprint)!==t)throw new w;return{id:String(f.id),replayed:String(f.id)!==d}}return await r.execute({sql:`INSERT INTO operation_runs
5
- (id, user_id, owner_scope_hash, tool, idempotency_scope_hash, request_fingerprint,
6
- job_id, request_id, deployment_commit, normalized_flags_json, started_at)
7
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,args:u}),{id:d,replayed:!1}}async function U(e){let r=e.endedAt??new Date().toISOString();if((await a().execute({sql:`UPDATE operation_runs
8
- SET status = ?, failure_class = ?, ended_at = ?, updated_at = ?
9
- WHERE id = ? AND status = 'running'`,args:[e.status,p(e.failureClass,200),r,r,e.runId]})).rowsAffected===1)return;let s=p(e.failureClass,200),i=await a().execute({sql:"SELECT status, failure_class FROM operation_runs WHERE id = ?",args:[e.runId]});if(i.rows.length===0)throw new Error(`Unknown operation run: ${e.runId}`);let t=i.rows[0]?.failure_class==null?null:String(i.rows[0]?.failure_class);if(String(i.rows[0]?.status)!==e.status||t!==s)throw new Error(`Operation run ${e.runId} is already terminal as ${String(i.rows[0]?.status)}`)}async function q(e){if(!Number.isInteger(e.attemptNumber)||e.attemptNumber<1)throw new Error("attemptNumber must be a positive integer");if(e.attemptNumber===1&&(e.parentAttemptId||e.edgeKind||e.retryKind))throw new Error("The first attempt cannot have a parent or retry edge");if(e.attemptNumber>1&&(!e.parentAttemptId||!e.edgeKind))throw new Error("Every non-first attempt requires a parentAttemptId and edgeKind");if(e.retryKind&&!["same_method_retry","provider_fallback","durable_resume","reconciliation"].includes(e.edgeKind??""))throw new Error("retryKind requires a retry or reconciliation edgeKind");let r=e.id??b();return await a().execute({sql:`INSERT INTO operation_attempts
10
- (id, run_id, parent_attempt_id, attempt_number, edge_kind, retry_kind, retry_reason, retry_owner,
11
- method, provider, normalized_flags_json, started_at)
12
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,args:[r,e.runId,e.parentAttemptId??null,e.attemptNumber,e.edgeKind??null,e.retryKind??null,p(e.retryReason,500),p(e.retryOwner,100),l(e.method,"method"),e.provider??null,T(e.normalizedFlags),e.startedAt??new Date().toISOString()]}),r}async function D(e){if(!Number.isInteger(e.durationMs)||e.durationMs<0)throw new Error("durationMs must be a non-negative integer");let r=e.endedAt??new Date().toISOString();if((await a().execute({sql:`UPDATE operation_attempts SET
13
- status = ?, error_code = ?, error_message = ?, ended_at = ?, duration_ms = ?, updated_at = ?
14
- WHERE id = ? AND status = 'running'`,args:[e.status,p(e.errorCode,200),p(e.errorMessage),r,e.durationMs,r,e.attemptId]})).rowsAffected===1)return;let s=await a().execute({sql:"SELECT status, duration_ms FROM operation_attempts WHERE id = ?",args:[e.attemptId]});if(s.rows.length===0)throw new Error(`Unknown operation attempt: ${e.attemptId}`);if(String(s.rows[0]?.status)!==e.status||Number(s.rows[0]?.duration_ms)!==e.durationMs)throw new Error(`Operation attempt ${e.attemptId} is already terminal as ${String(s.rows[0]?.status)}`)}async function H(e){let r=l(e.provider,"provider"),o=l(e.method,"method"),s=g(l(e.accountScope,"accountScope")),i=e.providerSourceKey?.trim()||null,t=i?g(i):null,n=e.id??b(),d=await a().execute({sql:`INSERT OR IGNORE INTO provider_usage_receipts
15
- (id, attempt_id, provider, account_scope_hash, method, provider_source_key,
16
- provider_source_key_hash, provider_status)
17
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,args:[n,e.attemptId,r,s,o,i,t,e.providerStatus??null]});if(!t){if(d.rowsAffected===1)return{id:n,replayed:!1};let _=(await a().execute({sql:"SELECT attempt_id, provider, method FROM provider_usage_receipts WHERE id = ?",args:[n]})).rows[0];if(!_||String(_.attempt_id)!==e.attemptId||String(_.provider)!==r||String(_.method)!==o)throw new Error("Provider receipt ID is already used by a different receipt");return{id:n,replayed:!0}}let m=(await a().execute({sql:`SELECT id, attempt_id FROM provider_usage_receipts
18
- WHERE provider = ? AND account_scope_hash = ? AND method = ? AND provider_source_key_hash = ?`,args:[r,s,o,t]})).rows[0];if(!m)throw new Error("Provider receipt insert did not produce a source receipt");if(String(m.attempt_id)!==e.attemptId)throw new Error("Provider source identity is already attached to a different attempt");return{id:String(m.id),replayed:String(m.id)!==n}}async function M(e,r){let o=l(r,"providerSourceKey"),s=g(o);if((await a().execute({sql:`UPDATE provider_usage_receipts
19
- SET provider_source_key = ?, provider_source_key_hash = ?, updated_at = datetime('now')
20
- WHERE id = ? AND provider_source_key IS NULL`,args:[o,s,e]})).rowsAffected===1)return;let t=await a().execute({sql:"SELECT provider_source_key_hash FROM provider_usage_receipts WHERE id = ?",args:[e]});if(!t.rows[0])throw new Error(`Unknown provider receipt: ${e}`);if(String(t.rows[0].provider_source_key_hash)!==s)throw new Error(`Provider receipt ${e} already has a different source identity`)}async function h(e){if(e.units!=null&&(!Number.isFinite(e.units)||e.units<0))throw new Error("units must be non-negative");if(e.amountUsdNanos!=null&&(!Number.isSafeInteger(e.amountUsdNanos)||e.amountUsdNanos<0))throw new Error("amountUsdNanos must be a non-negative safe integer");if(e.costState==="actual"&&e.amountUsdNanos==null)throw new Error("actual receipts require amountUsdNanos");if(e.costState==="actual"&&e.amountUsdNanos===0&&!e.zeroCostReason?.trim())throw new Error("actual zero-cost receipts require zeroCostReason");let r=e.checkedAt??new Date().toISOString(),o=e.finalizedAt??r;if((await a().execute({sql:`UPDATE provider_usage_receipts SET
21
- cost_state = ?, units = ?, unit_type = ?, amount_usd_nanos = ?, rate_source = ?, zero_cost_reason = ?,
22
- provider_status = ?, provider_duration_ms = ?, provider_captcha = ?, error_code = ?, error_message = ?,
23
- checked_at = ?, finalized_at = ?, updated_at = ?
24
- WHERE id = ? AND (cost_state = 'pending' OR (cost_state = 'estimated' AND ? = 'actual'))`,args:[e.costState,e.units??null,e.unitType??null,e.amountUsdNanos??null,e.rateSource??null,e.zeroCostReason??null,e.providerStatus??null,e.providerDurationMs??null,e.providerCaptcha==null?null:e.providerCaptcha?1:0,p(e.errorCode,200),p(e.errorMessage),r,o,o,e.receiptId,e.costState]})).rowsAffected===1)return;let i=await a().execute({sql:"SELECT cost_state, units, unit_type, amount_usd_nanos FROM provider_usage_receipts WHERE id = ?",args:[e.receiptId]});if(i.rows.length===0)throw new Error(`Unknown provider receipt: ${e.receiptId}`);let t=i.rows[0],n=t?.units==null&&e.units==null||Number(t?.units)===e.units,d=t?.amount_usd_nanos==null&&e.amountUsdNanos==null||Number(t?.amount_usd_nanos)===e.amountUsdNanos,u=t?.unit_type==null&&e.unitType==null||String(t?.unit_type)===e.unitType;if(String(t?.cost_state)!==e.costState||!n||!d||!u)throw new Error(`Provider receipt ${e.receiptId} is already finalized as ${String(i.rows[0]?.cost_state)}`)}async function ie(e){let o=(await a().execute({sql:`SELECT id FROM provider_usage_receipts
25
- WHERE provider = ? AND account_scope_hash = ? AND method = ? AND provider_source_key_hash = ?`,args:[l(e.provider,"provider"),g(l(e.accountScope,"accountScope")),l(e.method,"method"),g(l(e.providerSourceKey,"providerSourceKey"))]})).rows[0];if(!o)return!1;let{provider:s,accountScope:i,method:t,providerSourceKey:n,...d}=e;return await h({...d,receiptId:String(o.id)}),!0}async function se(e=30){if(!Number.isInteger(e)||e<1||e>365)throw new Error("retentionDays must be an integer between 1 and 365");let r=`-${e} days`,o=a(),[s,i,t]=await Promise.all([o.execute({sql:`UPDATE operation_attempts
26
- SET error_message = NULL, updated_at = datetime('now')
27
- WHERE ended_at < datetime('now', ?) AND error_message IS NOT NULL`,args:[r]}),o.execute({sql:`UPDATE provider_usage_receipts
28
- SET provider_source_key = NULL, error_message = NULL, updated_at = datetime('now')
29
- WHERE finalized_at < datetime('now', ?)
30
- AND (provider_source_key IS NOT NULL OR error_message IS NOT NULL)`,args:[r]}),o.execute({sql:`UPDATE harvest_attempts
31
- SET provider_session_id = NULL, \u006b\u0065\u0072\u006e\u0065\u006c_session_id = NULL, error = NULL,
32
- \u006b\u0065\u0072\u006e\u0065\u006c_delete_error = NULL, browser_close_error = NULL,
33
- provider_error_message = NULL, provider_detail_json = NULL,
34
- provider_disconnect_message = NULL, debug_json = NULL
35
- WHERE completed_at < datetime('now', ?)
36
- AND (provider_session_id IS NOT NULL OR \u006b\u0065\u0072\u006e\u0065\u006c_session_id IS NOT NULL OR error IS NOT NULL
37
- OR \u006b\u0065\u0072\u006e\u0065\u006c_delete_error IS NOT NULL OR browser_close_error IS NOT NULL
38
- OR provider_error_message IS NOT NULL OR provider_detail_json IS NOT NULL
39
- OR provider_disconnect_message IS NOT NULL OR debug_json IS NOT NULL)`,args:[r]})]);return{operationAttempts:s.rowsAffected,providerReceipts:i.rowsAffected,legacyHarvestAttempts:t.rowsAffected}}async function F(e){let o={billing_authorizations:{column:"id"},billing_events:{column:"id"},billing_debits:{column:"idempotency_key"},billing_credits:{column:"idempotency_key"},ledger:{column:"id"}}[e.billingTable],s=l(e.billingKey,"billingKey"),i=await a().execute({sql:`SELECT b.user_id AS billing_user_id, r.user_id AS run_user_id
40
- FROM operation_runs r
41
- JOIN ${e.billingTable} b ON CAST(b.${o.column} AS TEXT) = ?
42
- WHERE r.id = ?`,args:[s,e.runId]});if(!i.rows[0])throw new Error("Billing link target or operation run does not exist");let t=i.rows[0].billing_user_id,n=i.rows[0].run_user_id;if(n!=null&&t!=null&&String(n)!==String(t))throw new Error("Billing link owner does not match operation run owner");await a().execute({sql:`INSERT OR IGNORE INTO operation_billing_links
43
- (run_id, billing_table, billing_key, relation, amount_mc) VALUES (?, ?, ?, ?, ?)`,args:[e.runId,e.billingTable,s,e.relation,e.amountMc??null]})}async function ae(e,r=new Date().toISOString()){let o=b();return await a().execute({sql:"INSERT INTO provider_reconciliation_runs (id, provider, started_at) VALUES (?, ?, ?)",args:[o,l(e,"provider"),r]}),o}async function de(e){if([e.checkedCount,e.completedCount,e.pendingCount,e.unavailableCount,e.failedCount].some(i=>!Number.isInteger(i)||i<0))throw new Error("Reconciliation counts must be non-negative integers");if(e.completedCount+e.pendingCount+e.unavailableCount+e.failedCount>e.checkedCount)throw new Error("Reconciliation outcome counts cannot exceed checkedCount");let o=e.completedAt??new Date().toISOString();if((await a().execute({sql:`UPDATE provider_reconciliation_runs SET
44
- status = ?, checked_count = ?, completed_count = ?, pending_count = ?, unavailable_count = ?,
45
- failed_count = ?, error_code = ?, completed_at = ?
46
- WHERE id = ? AND status = 'running'`,args:[e.status,e.checkedCount,e.completedCount,e.pendingCount,e.unavailableCount,e.failedCount,p(e.errorCode,200),o,e.id]})).rowsAffected!==1)throw new Error(`Unknown or terminal provider reconciliation run: ${e.id}`)}async function K(e){let r=a(),[o,s,i,t]=await Promise.all([r.execute({sql:"SELECT * FROM operation_runs WHERE id = ?",args:[e]}),r.execute({sql:"SELECT * FROM operation_attempts WHERE run_id = ? ORDER BY attempt_number",args:[e]}),r.execute({sql:`SELECT r.* FROM provider_usage_receipts r
47
- JOIN operation_attempts a ON a.id = r.attempt_id
48
- WHERE a.run_id = ? ORDER BY a.attempt_number, r.created_at, r.id`,args:[e]}),r.execute({sql:"SELECT * FROM operation_billing_links WHERE run_id = ? ORDER BY created_at, billing_table, billing_key",args:[e]})]);return o.rows[0]?{run:o.rows[0],attempts:[...s.rows],providerReceipts:[...i.rows],billingLinks:[...t.rows]}:null}function W(e){return e instanceof Error?e.message:String(e)}function B(e,r){return e instanceof DOMException&&(e.name==="TimeoutError"||e.name==="AbortError")?!0:/timeout|timed out|Timeout \d+ms exceeded|deadline/i.test(r)}function V(e){return/captcha|recaptcha|unusual traffic|google\.com\/sorry|blocked/i.test(e)}function J(e){return/ERR_TUNNEL_CONNECTION_FAILED|ERR_PROXY_CONNECTION_FAILED|ERR_SOCKS_CONNECTION_FAILED|tunnel connection failed|proxy connection failed|transport error: proxy/i.test(e)}function G(e){return/proxy unavailable|proxy_unavailable|connection_test_failed|did not return a proxy id|configured fallback/i.test(e)}function Q(e){return/(?:spending|billing|organization|account).{0,80}(?:cap|limit|blocked|disabled)|(?:quota|capacity).{0,40}(?:reached|exceeded)|https?:\/\/\S*dashboard/i.test(e)}function Y(e){return/browser (?:has been )?closed|context (?:has been )?closed|target page, context or browser has been closed|session closed|page has been closed/i.test(e)}function X(e){let r=W(e);return e instanceof I?{error_code:"request_aborted",error_type:"request_aborted",message:c("request_aborted"),retryable:!0,httpStatus:408,terminalStatus:"cancelled"}:e instanceof R||V(r)?{error_code:"captcha_exhausted",error_type:"captcha",message:c("captcha_exhausted"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:P(e,r)?{error_code:"vendor_unavailable",error_type:"service_unavailable",message:c("vendor_unavailable"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:e instanceof A?{error_code:"location_mismatch",error_type:"location_mismatch",message:c("location_mismatch"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:J(r)?{error_code:"proxy_tunnel_failed",error_type:"connection",message:c("proxy_tunnel_failed"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:G(r)?{error_code:"proxy_unavailable",error_type:"connection",message:c("proxy_unavailable"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:Y(r)?{error_code:"browser_session_interrupted",error_type:"extraction",message:c("browser_session_interrupted"),retryable:!0,httpStatus:503,terminalStatus:"failed"}:B(e,r)?{error_code:"harvest_timeout",error_type:"timeout",message:c("harvest_timeout"),retryable:!0,httpStatus:504,terminalStatus:"failed"}:Q(r)?{error_code:"service_unavailable",error_type:"service_unavailable",message:y,retryable:!0,httpStatus:503,terminalStatus:"failed"}:{error_code:"extraction_failed",error_type:"extraction",message:y,retryable:!1,httpStatus:500,terminalStatus:"failed"}}function pe(e){return JSON.stringify({error_code:e.error_code,error_type:e.error_type,message:e.message,retryable:e.retryable})}function z(e,r={}){let o=v({errorCode:e.error_code,errorType:e.error_type,retryable:e.retryable,retryAfterSeconds:r.retryAfterSeconds,chargeStatus:r.chargeStatus,details:r.details});return{error:o.message,...o}}function me(e,r={}){let{error:o,...s}=z(e,r);return s}function _e(e,r={}){let o=X(e);return{body:z(o,r),status:o.httpStatus}}import{createHash as Z}from"crypto";var ee=1e9;function re(e){return Z("sha256").update(JSON.stringify(e)).digest("hex")}function te(e){return`harvest:${e}`}async function we(e){let r=te(e.jobId);try{return(await C({id:r,userId:e.userId,ownerScope:`user:${e.userId}`,tool:e.tool,normalizedFlags:e.normalizedFlags,idempotencyKey:`job:${e.jobId}`,requestFingerprint:re(e.normalizedFlags),jobId:e.jobId,requestId:e.requestId??null,deploymentCommit:process.env.VERCEL_GIT_COMMIT_SHA?.trim()||process.env.GIT_COMMIT_SHA?.trim()||null})).id}catch(o){return console.warn(JSON.stringify({event:"operation_run_start_failed",job_id:e.jobId,tool:e.tool,message:o instanceof Error?o.message:String(o)})),null}}async function Se(e,r,o){if(e)try{await U({runId:e,status:r,failureClass:o})}catch(s){console.warn(JSON.stringify({event:"operation_run_finish_failed",operation_run_id:e,message:s instanceof Error?s.message:String(s)}))}}async function he(e,r,o,s){if(!(!e||!r))try{await F({runId:e,billingTable:"billing_debits",billingKey:r,relation:o,amountMc:s})}catch(i){console.warn(JSON.stringify({event:"operation_billing_link_failed",operation_run_id:e,relation:o,message:i instanceof Error?i.message:String(i)}))}}function E(e){return e==="timeout"?"timed_out":e==="request_aborted"?"cancelled":e==="browser_session_interrupted"?"interrupted":e==="captcha"||e==="proxy_tunnel_failed"||e==="proxy_unavailable"||e==="location_mismatch"||e==="error"?"failed":"succeeded"}function $(e,r,o=0){let s=new Map,i=null;return async t=>{if(e)try{if(t.type==="started"){let d=o+t.attemptNumber;if(d>1&&!i){let _=(await K(e))?.attempts.at(-1);i=_?.id==null?null:String(_.id)}let u=await q({runId:e,attemptNumber:d,method:t.method,provider:t.provider,parentAttemptId:d===1?null:i,edgeKind:d===1?null:o>0&&t.attemptNumber===1?"durable_resume":t.retryKind==="provider_fallback"?"provider_fallback":"same_method_retry",retryKind:d===1?null:o>0&&t.attemptNumber===1?"durable_resume":t.retryKind,retryReason:d===1?null:o>0&&t.attemptNumber===1?"durable_worker_resume":t.retryReason,retryOwner:d===1?null:o>0&&t.attemptNumber===1?"durable_reconciler":"harvest",normalizedFlags:{maxAttempts:t.maxAttempts,maxQuestions:t.maxQuestions,hasLocation:!!t.location},startedAt:t.startedAt}),m=await H({attemptId:u,provider:t.provider,accountScope:r,method:t.method,providerStatus:"started"});s.set(t.attemptNumber,{attemptId:u,receiptId:m.id,provider:t.provider,method:t.method,startedAtMs:Date.parse(t.startedAt)}),i=u;return}let n=s.get(t.attemptNumber);if(!n)throw new Error(`Missing operation attempt state for attempt ${t.attemptNumber}`);if(t.type==="provider_session_started"){await M(n.receiptId,t.providerSessionId);return}if(await D({attemptId:n.attemptId,status:E(t.outcome),errorCode:E(t.outcome)==="succeeded"?null:t.outcome,errorMessage:t.error,durationMs:t.durationMs,endedAt:t.completedAt}),n.provider==="\u006b\u0065\u0072\u006e\u0065\u006c"){let d=L(t.durationMs,!0);await h({receiptId:n.receiptId,costState:"estimated",units:t.durationMs/1e3,unitType:"browser_second",amountUsdNanos:Math.round(d*ee),rateSource:`\u006b\u0065\u0072\u006e\u0065\u006c_headful_usd_per_second:${k}`,providerStatus:t.outcome,providerDurationMs:t.durationMs,errorCode:E(t.outcome)==="succeeded"?null:t.outcome,errorMessage:t.error,finalizedAt:t.completedAt})}}catch(n){console.warn(JSON.stringify({event:"operation_attempt_telemetry_failed",operation_run_id:e,attempt_number:t.attemptNumber,message:n instanceof Error?n.message:String(n)}))}}}function Ie(e,r,o=null,s="production-default",i=0){let t=$(o,s,i);return async n=>{if(await t(n),n.type==="started"){await O({jobId:e,userId:r,attemptNumber:n.attemptNumber,maxAttempts:n.maxAttempts,query:n.query,location:n.location,maxQuestions:n.maxQuestions,startedAt:n.startedAt});return}if(n.type==="provider_session_started"){await N({jobId:e,attemptNumber:n.attemptNumber,browserProvider:n.provider,providerSessionId:n.providerSessionId,observedAt:n.observedAt});return}await x({jobId:e,attemptNumber:n.attemptNumber,outcome:n.outcome,\u006b\u0065\u0072\u006e\u0065\u006cSessionId:n.\u006b\u0065\u0072\u006e\u0065\u006cSessionId,questionCount:n.questionCount,durationMs:n.durationMs,error:n.error,willRetry:n.willRetry,\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted:n.cleanup.\u006b\u0065\u0072\u006e\u0065\u006cDeleteStarted,\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded:n.cleanup.\u006b\u0065\u0072\u006e\u0065\u006cDeleteSucceeded,\u006b\u0065\u0072\u006e\u0065\u006cDeleteError:n.cleanup.\u006b\u0065\u0072\u006e\u0065\u006cDeleteError,browserCloseSucceeded:n.cleanup.browserCloseSucceeded,browserCloseError:n.cleanup.browserCloseError,browserProvider:n.cleanup.provider??null,providerSessionId:n.cleanup.providerSessionId??null,providerLookupStatus:n.cleanup.providerSessionId?"pending":"not_applicable",providerErrorCode:n.cleanup.providerDisconnectObserved?"browser_session_interrupted":null,providerErrorMessage:n.cleanup.providerDisconnectMessage??null,providerReasonSource:n.cleanup.providerDisconnectObserved?"client_runtime":null,providerDisconnectObserved:n.cleanup.providerDisconnectObserved??!1,providerDisconnectMessage:n.cleanup.providerDisconnectMessage??null,debug:n.debug,completedAt:n.completedAt})}}async function Oe(e,r,o=3){for(let s=1;s<=o;s++){try{let i=await fetch(e,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(r),signal:AbortSignal.timeout(1e4)});if(i.ok)return;console.warn(`[webhook] attempt ${s} \u2192 ${i.status} from ${e}`)}catch(i){console.warn(`[webhook] attempt ${s} failed:`,i instanceof Error?i.message:i)}s<o&&await new Promise(i=>setTimeout(i,1e3*s*2))}console.error(`[webhook] gave up after ${o} attempts for ${e}`)}export{q as a,D as b,H as c,M as d,h as e,ie as f,se as g,ae as h,de as i,X as j,pe as k,z as l,me as m,_e as n,te as o,we as p,Se as q,he as r,Ie as s,Oe as t};