mcp-scraper 0.89.5 → 0.89.8

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 (57) hide show
  1. package/CHANGELOG.md +65 -15
  2. package/README.md +5 -5
  3. package/dist/{analytics-repository-RG7CFK6W.js → analytics-repository-UX6VU22H.js} +1 -1
  4. package/dist/bin/api-server.js +1 -1
  5. package/dist/bin/mcp-scraper-cli.js +1 -1
  6. package/dist/bin/mcp-scraper-core.js +1 -1
  7. package/dist/bin/mcp-scraper-install.js +1 -1
  8. package/dist/bin/mcp-stdio-server.js +1 -1
  9. package/dist/bin/paa-harvest.js +1 -1
  10. package/dist/{chunk-DBDMD7V7.js → chunk-2BS7MMOS.js} +2 -2
  11. package/dist/{chunk-NGQYSQQA.js → chunk-2GRE4BAO.js} +1 -1
  12. package/dist/chunk-2TZBO52D.js +1 -0
  13. package/dist/chunk-4FROKQJN.js +1 -1
  14. package/dist/chunk-52XUWR3X.js +820 -0
  15. package/dist/chunk-5B42QVDC.js +19 -0
  16. package/dist/chunk-7AC66V3T.js +1 -0
  17. package/dist/{chunk-7JAMFXNL.js → chunk-7BEWBRMT.js} +153 -86
  18. package/dist/{chunk-4A5F7IUA.js → chunk-AGK756UE.js} +210 -210
  19. package/dist/chunk-D6BTAT5Y.js +1 -0
  20. package/dist/{chunk-53HIX3X7.js → chunk-DKQZNSYM.js} +15 -15
  21. package/dist/{chunk-MZN4U5BL.js → chunk-E4ME7J6G.js} +1 -1
  22. package/dist/{chunk-A2CZ7WRV.js → chunk-HR2A2WTL.js} +1 -1
  23. package/dist/{chunk-XLWNEVUZ.js → chunk-JHMI6HEO.js} +3 -3
  24. package/dist/{chunk-UB5N2ICD.js → chunk-JSNFZPPB.js} +1 -1
  25. package/dist/{chunk-WYCXAFID.js → chunk-JVU2THSY.js} +1 -1
  26. package/dist/{chunk-SEHBXTMX.js → chunk-KX72IORC.js} +6 -6
  27. package/dist/{chunk-RZSJC7FX.js → chunk-LZTDANNZ.js} +1 -1
  28. package/dist/{chunk-QPWPR5XG.js → chunk-M5QHXNFZ.js} +3 -3
  29. package/dist/chunk-MM6QBDPC.js +1 -0
  30. package/dist/{chunk-3UPA3XHF.js → chunk-PHBU6X5B.js} +1 -1
  31. package/dist/chunk-Q4A2KIPZ.js +41 -0
  32. package/dist/{chunk-4SQ4RKDX.js → chunk-TI3KH3YW.js} +1 -1
  33. package/dist/{chunk-JJDYKM5I.js → chunk-VT6SLBOU.js} +1 -1
  34. package/dist/{chunk-YQZGZBB4.js → chunk-XG6GCEUE.js} +1 -1
  35. package/dist/chunk-Z3WXA4ZU.js +1 -0
  36. package/dist/db-UKQ74OVT.js +1 -0
  37. package/dist/{extract-bundle-RVOBMGU2.js → extract-bundle-DI7OVLT5.js} +5 -5
  38. package/dist/gmail-service-ASX7YBC3.js +1 -0
  39. package/dist/index.cjs +47 -47
  40. package/dist/index.d.cts +14 -14
  41. package/dist/index.d.ts +14 -14
  42. package/dist/index.js +1 -1
  43. package/dist/{lead-list-enrichment-repository-GKVCX7BM.js → lead-list-enrichment-repository-GPDHJVM3.js} +1 -1
  44. package/dist/{location-data-repository-WK27TSHZ.js → location-data-repository-MXUNVDHW.js} +1 -1
  45. package/dist/{server-7TSXB24M.js → server-PQB2EITA.js} +732 -1551
  46. package/dist/{site-extract-repository-FAHOTQGX.js → site-extract-repository-WADCAIYB.js} +1 -1
  47. package/dist/stripe-event-worker-ZPNWXX2T.js +1 -0
  48. package/dist/worker-GTIKQJIN.js +1 -0
  49. package/package.json +137 -17
  50. package/THIRD_PARTY_NOTICES.html +0 -203
  51. package/dist/chunk-2ICI4TIX.js +0 -59
  52. package/dist/chunk-3GP5CYZX.js +0 -1
  53. package/dist/chunk-O2QKRYLS.js +0 -1
  54. package/dist/chunk-SCHTLEMZ.js +0 -1
  55. package/dist/db-DV4HHCYP.js +0 -1
  56. package/dist/gmail-service-FJTBCZPH.js +0 -1
  57. package/dist/worker-ROG7SO3R.js +0 -1
@@ -1 +1 @@
1
- import{A as s,B as t,C as u,D as v,E as w,F as x,G as y,H as z,I as A,J as B,K as C,L as D,M as E,i as a,j as b,k as c,l as d,m as e,n as f,o as g,p as h,q as i,r as j,s as k,t as l,u as m,v as n,w as o,x as p,y as q,z as r}from"./chunk-JJDYKM5I.js";import"./chunk-TMB56NCA.js";import"./chunk-MZN4U5BL.js";import"./chunk-7JAMFXNL.js";export{a as XRAY_ENTITLED_EXTRACT_BILLING_CLASS,q as abandonExtractSettlement,p as claimFailedExtractJobForRefinalize,z as completeExtractJob,w as countSuccessfulPages,d as createExtractJob,f as createOrGetExtractJob,b as extractJobLimitInfo,A as failExtractJob,o as failStaleRunningExtractJob,B as failUnfundedExtractJob,E as finalizeXRayEntitledExtractJobCharge,y as finishExtractJob,g as getExtractJob,e as getExtractJobByIdempotencyKey,v as getExtractedImageLinks,u as getExtractedPages,x as getExtractedUrls,h as listExtractJobs,t as listExtractPages,j as listFundedPendingExtractJobs,n as listStaleRunningExtractJobs,i as listUnsettledExtractJobs,k as markExtractJobDispatchAttempt,l as recordExtractJobDispatchFailure,m as recordExtractSettlementFailure,s as saveExtractPages,C as setExtractJobPublicError,r as setExtractJobTotal,D as settleExtractJob,c as terminalExtractJobStatus};
1
+ import{A as s,B as t,C as u,D as v,E as w,F as x,G as y,H as z,I as A,J as B,K as C,L as D,M as E,i as a,j as b,k as c,l as d,m as e,n as f,o as g,p as h,q as i,r as j,s as k,t as l,u as m,v as n,w as o,x as p,y as q,z as r}from"./chunk-VT6SLBOU.js";import"./chunk-TMB56NCA.js";import"./chunk-E4ME7J6G.js";import"./chunk-7BEWBRMT.js";export{a as XRAY_ENTITLED_EXTRACT_BILLING_CLASS,q as abandonExtractSettlement,p as claimFailedExtractJobForRefinalize,z as completeExtractJob,w as countSuccessfulPages,d as createExtractJob,f as createOrGetExtractJob,b as extractJobLimitInfo,A as failExtractJob,o as failStaleRunningExtractJob,B as failUnfundedExtractJob,E as finalizeXRayEntitledExtractJobCharge,y as finishExtractJob,g as getExtractJob,e as getExtractJobByIdempotencyKey,v as getExtractedImageLinks,u as getExtractedPages,x as getExtractedUrls,h as listExtractJobs,t as listExtractPages,j as listFundedPendingExtractJobs,n as listStaleRunningExtractJobs,i as listUnsettledExtractJobs,k as markExtractJobDispatchAttempt,l as recordExtractJobDispatchFailure,m as recordExtractSettlementFailure,s as saveExtractPages,C as setExtractJobPublicError,r as setExtractJobTotal,D as settleExtractJob,c as terminalExtractJobStatus};
@@ -0,0 +1 @@
1
+ import{ab as S,cb as h}from"./chunk-52XUWR3X.js";import"./chunk-5B42QVDC.js";import"./chunk-HR2A2WTL.js";import"./chunk-2GRE4BAO.js";import"./chunk-D6BTAT5Y.js";import"./chunk-E4ME7J6G.js";import"./chunk-DKQZNSYM.js";import{H as d,I as u,J as l,K as f,L as v}from"./chunk-7BEWBRMT.js";var g=12;function b(e){return e&&typeof e=="object"&&"code"in e&&typeof e.code=="string"?e.code:e instanceof Error?e.name:"unknown_error"}function k(e){return Math.min(21600,30*2**Math.max(0,e-1))}async function x(e={}){let w=e.stripeClient??S,E=Math.max(1,Math.min(100,e.limit??100)),r=500,i=0,s=0,c=0,m=0;for(;i<r;){let a=await d(Math.min(E,r-i),e.leaseSeconds??300);if(a.length===0)break;i+=a.length;for(let t of a)try{let n=await w.events.retrieve(t.eventId);await h(n),await u(t.eventId,t.token)&&(s+=1)}catch(n){let p=n instanceof Error?n.message:String(n),o=b(n);t.attemptCount>=g||o==="resource_missing"?await f(t.eventId,t.token,p,o)&&(m+=1):await l(t.eventId,t.token,p,o,k(t.attemptCount))&&(c+=1)}}return{claimed:i,processed:s,retried:c,deadLettered:m,capped:i>=r,health:await v()}}export{x as drainStripeEventQueue};
@@ -0,0 +1 @@
1
+ import{a as O,b as y,c as D,d as g,f as A,g as _}from"./chunk-PHBU6X5B.js";import"./chunk-XG6GCEUE.js";import{u as k}from"./chunk-KX72IORC.js";import"./chunk-M5QHXNFZ.js";import{b as f,c as H}from"./chunk-7AC66V3T.js";import{a as m,b}from"./chunk-E4ME7J6G.js";import{a as v}from"./chunk-4FROKQJN.js";import{b as M}from"./chunk-DKQZNSYM.js";import"./chunk-2TZBO52D.js";import"./chunk-MM6QBDPC.js";import{Mb as l,Qb as p,Sb as d,Ua as u,gb as h,ib as c,na as o}from"./chunk-7BEWBRMT.js";var P=2,w=0;function C(e){if(!e||typeof e!="object")return 0;let t=e;return typeof t.totalQuestions=="number"?t.totalQuestions:Array.isArray(t.flat)?t.flat.length:0}function R(e){return m.paa_base+Math.max(1,e)*m.paa}async function N(e){w++;try{let t=typeof e.options=="string"?JSON.parse(e.options):e.options,r={value:null},i=await M({op:t.serpOnly?"serp":"paa",userId:Number(e.user_id),headlessSentOut:r},()=>k({...t,kernelApiKey:v(),headless:!0,format:"json",outputDir:"/tmp/paa-output-api",onAttemptEvent:A(e.id,e.user_id)}));await h(e.id,i);let s=await o(e.id,e.user_id);if(typeof t.billingHoldMc=="number"&&t.billingDebitKey){let n=t.serpOnly?b(r.value):R(C(i));await d(Number(e.user_id),t.billingDebitKey,n,t.serpOnly?"serp_refund":"paa_refund",t.serpOnly?"SERP search settlement":"PAA harvest settlement",t.serpOnly?"serp_search":"paa_harvest")}else if(!t.serpOnly&&typeof t.billingHoldMc=="number"){let n=R(C(i)),a=t.billingHoldMc-n;a>0?await l(e.user_id,a,"paa_refund","overestimate refund"):a<0&&await p(e.user_id,-a,"paa",t.query??e.query)}else if(t.serpOnly&&typeof t.billingHoldMc=="number"){let n=b(r.value),a=t.billingHoldMc-n;a>0?await l(e.user_id,a,"serp_refund","headless-mode pricing settle"):a<0&&await p(e.user_id,-a,"serp",t.query??e.query)}e.callback_url&&await _(e.callback_url,{job_id:e.id,status:"done",result:H(i),attempts:f(s)})}catch(t){console.error("[harvest/worker] failed",{jobId:e.id,error:t instanceof Error?t.message:String(t)});let r=O(t),i=typeof e.options=="string"?JSON.parse(e.options):e.options,s=typeof i.billingHoldMc=="number"&&i.billingHoldMc>0;await c(e.id,y(r),g(r,{chargeStatus:s?"refund_pending":"not_charged"}));let n=await o(e.id,e.user_id);try{s&&(i.billingDebitKey?await d(Number(e.user_id),i.billingDebitKey,0,i.serpOnly?"serp_refund":"paa_refund","failed call",i.serpOnly?"serp_search":"paa_harvest"):await l(e.user_id,i.billingHoldMc,"refund","failed call"),await c(e.id,y(r),g(r,{chargeStatus:"refunded"})))}catch{}e.callback_url&&await _(e.callback_url,{job_id:e.id,status:"failed",...D(r),attempts:f(n)})}finally{w--}}async function x(){let e=await u();if(!e)return{claimed:!1};let t=Date.now();return await N(e),{claimed:!0,jobId:e.id,completed:!0,durationMs:Date.now()-t}}async function W(e){let t=[];for(let r=0;r<e.maxJobs&&!(Date.now()>=e.deadlineMs);r++){let i=await x();if(t.push(i),!i.claimed)break}return t}function B(){setInterval(async()=>{if(w>=P)return;let e=await u();e&&N(e)},2e3),console.log(`[worker] started \u2014 polling every 2s, max ${P} concurrent`)}export{W as drainQueue,B as startWorker,x as tickOnce};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-scraper",
3
- "version": "0.89.5",
3
+ "version": "0.89.8",
4
4
  "description": "MCP server for MCP Scraper web intelligence tools",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -23,11 +23,110 @@
23
23
  "mcp-scraper-install": "dist/bin/mcp-scraper-install.js",
24
24
  "mcp-scraper-cli": "dist/bin/mcp-scraper-cli.js"
25
25
  },
26
+ "files": [
27
+ "dist/*.js",
28
+ "dist/*.cjs",
29
+ "dist/*.d.ts",
30
+ "dist/*.d.cts",
31
+ "dist/bin/*.js",
32
+ "dist/editorial-reading-room/assets",
33
+ "public/agent-install.md",
34
+ "public/.well-known/xray-install.json",
35
+ "README.md",
36
+ "CHANGELOG.md"
37
+ ],
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/VilovietaSEO/mcp-scraper.git"
41
+ },
26
42
  "homepage": "https://mcpscraper.dev",
27
- "engines": {
28
- "node": ">=20.18.1"
43
+ "bugs": {
44
+ "url": "https://github.com/VilovietaSEO/mcp-scraper/issues"
45
+ },
46
+ "scripts": {
47
+ "build": "tsup",
48
+ "build:md": "node scripts/build-md-mirror.mjs",
49
+ "build:mcpb": "npm run build && node scripts/build-mcpb.mjs",
50
+ "build:mcpb:candidate": "npm run build && node scripts/build-mcpb.mjs --candidate",
51
+ "build:rates": "node --import tsx scripts/gen-rates.ts",
52
+ "build:geotargets": "node --import tsx scripts/gen-geotargets.ts",
53
+ "build:blog": "node scripts/run-ts-sandbox-safe.mjs scripts/build-blog.ts",
54
+ "mcp:manifest": "node scripts/run-ts-sandbox-safe.mjs scripts/generate-mcp-tool-manifest.ts",
55
+ "contracts:memory": "node --import tsx scripts/generate-memory-tool-contract.ts",
56
+ "contracts:memory-governed": "node --import tsx scripts/generate-governed-memory-mcp-schemas.ts",
57
+ "verify:crm-authority": "node --import tsx scripts/verify-crm-authority-boundary.ts",
58
+ "contracts:openapi": "node --import tsx scripts/generate-personal-assistant-openapi.ts",
59
+ "contracts:assistant": "npm run mcp:manifest && npm run contracts:memory && npm run contracts:openapi",
60
+ "contracts:assistant:verify": "node --import tsx scripts/verify-personal-assistant-contract.ts",
61
+ "contracts:assistant:verify:release": "node --import tsx scripts/verify-personal-assistant-contract.ts --release",
62
+ "mcp:memory-image-schemas": "node scripts/generate-memory-image-mcp-schemas.mjs",
63
+ "mcp:measure-catalog": "node scripts/run-ts-sandbox-safe.mjs scripts/measure-mcp-catalog.ts",
64
+ "mcp:lint-tools": "node scripts/run-ts-sandbox-safe.mjs scripts/lint-mcp-tool-craft.ts",
65
+ "mcp:lint-tools:write": "node scripts/run-ts-sandbox-safe.mjs scripts/lint-mcp-tool-craft.ts --write",
66
+ "xray:install-contract": "node --import tsx scripts/generate-xray-install-contract.ts",
67
+ "xray:install-contract:check": "node --import tsx scripts/generate-xray-install-contract.ts --check",
68
+ "api": "node scripts/run-ts-sandbox-safe.mjs bin/api-server.ts",
69
+ "dev": "node scripts/run-ts-sandbox-safe.mjs src/cli.ts",
70
+ "test": "vitest run tests/unit tests/contract",
71
+ "test:live": "vitest run --config vitest.live.config.ts",
72
+ "test:site-similarity": "node --import tsx scripts/run-site-similarity-live.ts",
73
+ "reanalyze:site-similarity": "node --import tsx scripts/reanalyze-site-similarity-zip.ts",
74
+ "test:headless-harvest": "node scripts/run-ts-sandbox-safe.mjs tests/live/harness/headless-harvest-canary.ts",
75
+ "test:integration": "node scripts/run-integration-tests.mjs",
76
+ "test:smoke": "vitest run tests/smoke",
77
+ "test:stripe": "node scripts/stripe-setup-smoke.mjs",
78
+ "typecheck": "tsc --noEmit",
79
+ "test:kernel": "vitest run tests/integration/kernel.smoke.test.ts",
80
+ "sync:env": "bash scripts/push-env.sh",
81
+ "sync:env:apply": "bash scripts/push-env.sh --apply",
82
+ "locations:publish-geonames": "node --import tsx scripts/publish-geonames-location-data.ts",
83
+ "locations:sync": "node --import tsx scripts/sync-hosted-location-data.ts",
84
+ "integrations:migrate-scheduler": "node --import tsx scripts/migrate-scheduler-integrations.ts",
85
+ "test:webhook": "node scripts/test-webhook.mjs",
86
+ "test:e2e": "playwright test",
87
+ "email:preview": "node scripts/run-ts-sandbox-safe.mjs scripts/email/render-previews.ts",
88
+ "email:preflight": "node --import tsx scripts/email/preflight.ts",
89
+ "email:avatar": "node --import tsx scripts/email/generate-sender-avatar.ts",
90
+ "email:inbound:setup": "node --import tsx scripts/email/setup-resend-inbound.ts",
91
+ "email:audience": "node scripts/run-ts-sandbox-safe.mjs scripts/email/sync-resend-audience.ts",
92
+ "email:drafts": "node scripts/run-ts-sandbox-safe.mjs scripts/email/create-resend-drafts.ts",
93
+ "email:workshop-reminders": "node --import tsx scripts/email/refresh-workshop-reminders.ts",
94
+ "email:workshop-reminders:apply": "node --import tsx scripts/email/refresh-workshop-reminders.ts --apply",
95
+ "billing:preview-credit-lot-repair": "node --import tsx scripts/billing/preview-credit-lot-repair.ts",
96
+ "billing:apply-credit-lot-repair": "node --import tsx scripts/billing/apply-credit-lot-repair.ts",
97
+ "brightdata:usage": "node scripts/brightdata-usage-report.mjs",
98
+ "brightdata:test:bandwidth": "node --import tsx scripts/brightdata-paa-bandwidth-test.ts",
99
+ "db:migrate": "node --import tsx scripts/run-core-migration.ts",
100
+ "db:verify": "node --import tsx scripts/verify-core-schema.ts",
101
+ "release:server:predeploy": "npm run db:migrate && npm run db:verify && npm run version:check:core",
102
+ "oauth-store:migrate": "node --import tsx scripts/migrate-oauth-store.ts --apply-schema",
103
+ "oauth-store:verify": "node --import tsx scripts/migrate-oauth-store.ts --verify",
104
+ "oauth-store:test": "vitest run tests/unit/oauth-store.test.ts",
105
+ "oauth-store:test-remote": "OAUTH_STORE_REMOTE_REQUIRED=1 vitest run --config vitest.live.config.ts tests/live/oauth-store-remote.live.test.ts",
106
+ "oauth:prepare-production-canary": "node --import tsx scripts/prepare-mcp-oauth-production-canary.ts",
107
+ "oauth:verify-live": "node scripts/verify-mcp-oauth-live.mjs",
108
+ "analytics:migrate": "node --import tsx scripts/run-analytics-migration.ts",
109
+ "analytics:contract": "node --import tsx scripts/analytics/export-analytics-rest-contract.ts",
110
+ "analytics:contract:check": "node --import tsx scripts/analytics/export-analytics-rest-contract.ts --check",
111
+ "assistant:migrate": "node --import tsx scripts/run-personal-assistant-migration.ts",
112
+ "assistant:schema:verify": "vitest run tests/unit/personal-assistant-db.test.ts tests/unit/personal-assistant-production-stores.test.ts tests/integration/personal-assistant-db.test.ts",
113
+ "assistant:deployment:preflight": "node --import tsx scripts/verify-personal-assistant-deployment-config.ts",
114
+ "analytics:rollups": "node --import tsx scripts/run-analytics-rollups.ts",
115
+ "test:mcp-output-contract": "vitest run --config vitest.mcp-output-contract.config.ts tests/unit/golden-payloads.test.ts tests/unit/mcp-formatter-structured.test.ts tests/unit/mcp-2026-stdio.test.ts",
116
+ "version:check": "node scripts/verify-release-version-sync.mjs",
117
+ "version:check:core": "node scripts/verify-release-version-sync.mjs --core",
118
+ "prebuild": "npm run version:check:core",
119
+ "mcp:verify": "npm run xray:install-contract:check && npm run build && npm run mcp:manifest && npm run version:check && npm run build:rates && npm run mcp:measure-catalog && npm run mcp:lint-tools && npm run test:mcp-output-contract && npm run typecheck && npm test && npm run package:verify-entrypoints",
120
+ "prepack": "npm run mcp:verify",
121
+ "package:verify-entrypoints": "node scripts/verify-package-entrypoints.mjs",
122
+ "product:install": "node scripts/run-product-command.mjs install",
123
+ "product:build": "node scripts/run-product-command.mjs build",
124
+ "product:typecheck": "node scripts/run-product-command.mjs typecheck",
125
+ "product:test": "node scripts/run-product-command.mjs test",
126
+ "product:verify-layout": "node scripts/verify-product-repository-layout.mjs",
127
+ "package:public": "npm run mcp:verify && node scripts/build-public-package.mjs",
128
+ "prepublishOnly": "node -e \"throw new Error('Publish the verified archive produced by npm run package:public')\""
29
129
  },
30
- "license": "ISC",
31
130
  "dependencies": {
32
131
  "@anthropic-ai/sdk": "^0.96.0",
33
132
  "@fal-ai/client": "^1.10.1",
@@ -66,17 +165,38 @@
66
165
  "youtube-transcript": "^1.3.1",
67
166
  "zod": "4.4.3"
68
167
  },
69
- "files": [
70
- "dist/*.js",
71
- "dist/*.cjs",
72
- "dist/*.d.ts",
73
- "dist/*.d.cts",
74
- "dist/bin/*.js",
75
- "dist/editorial-reading-room/assets",
76
- "public/agent-install.md",
77
- "public/.well-known/xray-install.json",
78
- "README.md",
79
- "CHANGELOG.md",
80
- "THIRD_PARTY_NOTICES.html"
81
- ]
168
+ "devDependencies": {
169
+ "@onkernel/cli": "^0.19.2",
170
+ "@playwright/test": "^1.60.0",
171
+ "@types/better-sqlite3": "^7.6.13",
172
+ "@types/jsdom": "^28.0.3",
173
+ "@types/node": "^20.0.0",
174
+ "@types/papaparse": "^5.3.0",
175
+ "@types/pg": "^8.23.1",
176
+ "@types/turndown": "^5.0.6",
177
+ "@types/yauzl": "^2.10.3",
178
+ "axe-core": "^4.13.0",
179
+ "better-sqlite3": "^12.9.0",
180
+ "bgutils-js": "^3.2.0",
181
+ "dotenv": "^17.4.2",
182
+ "esbuild": "^0.27.7",
183
+ "fflate": "^0.7.4",
184
+ "jsdom": "^29.1.1",
185
+ "tsup": "^8.0.0",
186
+ "tsx": "^4.0.0",
187
+ "typescript": "^5.4.0",
188
+ "vitest": "^1.6.0",
189
+ "youtubei.js": "^17.0.1",
190
+ "@onkernel/sdk": "^0.93.0"
191
+ },
192
+ "engines": {
193
+ "node": ">=20.18.1"
194
+ },
195
+ "directories": {
196
+ "doc": "docs",
197
+ "test": "tests"
198
+ },
199
+ "keywords": [],
200
+ "author": "",
201
+ "license": "ISC"
82
202
  }
@@ -1,203 +0,0 @@
1
- <!doctype html>
2
- <html lang="en"><meta charset="utf-8"><title>Third-party notices</title><body><h1>Browser control library</h1><p>This distribution bundles the browser control library with build-time minification and literal-name encoding. Its license follows.</p><pre> Apache License
3
- Version 2.0, January 2004
4
- http://www.apache.org/licenses/
5
-
6
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
-
8
- 1. Definitions.
9
-
10
- "License" shall mean the terms and conditions for use, reproduction,
11
- and distribution as defined by Sections 1 through 9 of this document.
12
-
13
- "Licensor" shall mean the copyright owner or entity authorized by
14
- the copyright owner that is granting the License.
15
-
16
- "Legal Entity" shall mean the union of the acting entity and all
17
- other entities that control, are controlled by, or are under common
18
- control with that entity. For the purposes of this definition,
19
- "control" means (i) the power, direct or indirect, to cause the
20
- direction or management of such entity, whether by contract or
21
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
- outstanding shares, or (iii) beneficial ownership of such entity.
23
-
24
- "You" (or "Your") shall mean an individual or Legal Entity
25
- exercising permissions granted by this License.
26
-
27
- "Source" form shall mean the preferred form for making modifications,
28
- including but not limited to software source code, documentation
29
- source, and configuration files.
30
-
31
- "Object" form shall mean any form resulting from mechanical
32
- transformation or translation of a Source form, including but
33
- not limited to compiled object code, generated documentation,
34
- and conversions to other media types.
35
-
36
- "Work" shall mean the work of authorship, whether in Source or
37
- Object form, made available under the License, as indicated by a
38
- copyright notice that is included in or attached to the work
39
- (an example is provided in the Appendix below).
40
-
41
- "Derivative Works" shall mean any work, whether in Source or Object
42
- form, that is based on (or derived from) the Work and for which the
43
- editorial revisions, annotations, elaborations, or other modifications
44
- represent, as a whole, an original work of authorship. For the purposes
45
- of this License, Derivative Works shall not include works that remain
46
- separable from, or merely link (or bind by name) to the interfaces of,
47
- the Work and Derivative Works thereof.
48
-
49
- "Contribution" shall mean any work of authorship, including
50
- the original version of the Work and any modifications or additions
51
- to that Work or Derivative Works thereof, that is intentionally
52
- submitted to Licensor for inclusion in the Work by the copyright owner
53
- or by an individual or Legal Entity authorized to submit on behalf of
54
- the copyright owner. For the purposes of this definition, "submitted"
55
- means any form of electronic, verbal, or written communication sent
56
- to the Licensor or its representatives, including but not limited to
57
- communication on electronic mailing lists, source code control systems,
58
- and issue tracking systems that are managed by, or on behalf of, the
59
- Licensor for the purpose of discussing and improving the Work, but
60
- excluding communication that is conspicuously marked or otherwise
61
- designated in writing by the copyright owner as "Not a Contribution."
62
-
63
- "Contributor" shall mean Licensor and any individual or Legal Entity
64
- on behalf of whom a Contribution has been received by Licensor and
65
- subsequently incorporated within the Work.
66
-
67
- 2. Grant of Copyright License. Subject to the terms and conditions of
68
- this License, each Contributor hereby grants to You a perpetual,
69
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
- copyright license to reproduce, prepare Derivative Works of,
71
- publicly display, publicly perform, sublicense, and distribute the
72
- Work and such Derivative Works in Source or Object form.
73
-
74
- 3. Grant of Patent License. Subject to the terms and conditions of
75
- this License, each Contributor hereby grants to You a perpetual,
76
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
- (except as stated in this section) patent license to make, have made,
78
- use, offer to sell, sell, import, and otherwise transfer the Work,
79
- where such license applies only to those patent claims licensable
80
- by such Contributor that are necessarily infringed by their
81
- Contribution(s) alone or by combination of their Contribution(s)
82
- with the Work to which such Contribution(s) was submitted. If You
83
- institute patent litigation against any entity (including a
84
- cross-claim or counterclaim in a lawsuit) alleging that the Work
85
- or a Contribution incorporated within the Work constitutes direct
86
- or contributory patent infringement, then any patent licenses
87
- granted to You under this License for that Work shall terminate
88
- as of the date such litigation is filed.
89
-
90
- 4. Redistribution. You may reproduce and distribute copies of the
91
- Work or Derivative Works thereof in any medium, with or without
92
- modifications, and in Source or Object form, provided that You
93
- meet the following conditions:
94
-
95
- (a) You must give any other recipients of the Work or
96
- Derivative Works a copy of this License; and
97
-
98
- (b) You must cause any modified files to carry prominent notices
99
- stating that You changed the files; and
100
-
101
- (c) You must retain, in the Source form of any Derivative Works
102
- that You distribute, all copyright, patent, trademark, and
103
- attribution notices from the Source form of the Work,
104
- excluding those notices that do not pertain to any part of
105
- the Derivative Works; and
106
-
107
- (d) If the Work includes a "NOTICE" text file as part of its
108
- distribution, then any Derivative Works that You distribute must
109
- include a readable copy of the attribution notices contained
110
- within such NOTICE file, excluding those notices that do not
111
- pertain to any part of the Derivative Works, in at least one
112
- of the following places: within a NOTICE text file distributed
113
- as part of the Derivative Works; within the Source form or
114
- documentation, if provided along with the Derivative Works; or,
115
- within a display generated by the Derivative Works, if and
116
- wherever such third-party notices normally appear. The contents
117
- of the NOTICE file are for informational purposes only and
118
- do not modify the License. You may add Your own attribution
119
- notices within Derivative Works that You distribute, alongside
120
- or as an addendum to the NOTICE text from the Work, provided
121
- that such additional attribution notices cannot be construed
122
- as modifying the License.
123
-
124
- You may add Your own copyright statement to Your modifications and
125
- may provide additional or different license terms and conditions
126
- for use, reproduction, or distribution of Your modifications, or
127
- for any such Derivative Works as a whole, provided Your use,
128
- reproduction, and distribution of the Work otherwise complies with
129
- the conditions stated in this License.
130
-
131
- 5. Submission of Contributions. Unless You explicitly state otherwise,
132
- any Contribution intentionally submitted for inclusion in the Work
133
- by You to the Licensor shall be under the terms and conditions of
134
- this License, without any additional terms or conditions.
135
- Notwithstanding the above, nothing herein shall supersede or modify
136
- the terms of any separate license agreement you may have executed
137
- with Licensor regarding such Contributions.
138
-
139
- 6. Trademarks. This License does not grant permission to use the trade
140
- names, trademarks, service marks, or product names of the Licensor,
141
- except as required for reasonable and customary use in describing the
142
- origin of the Work and reproducing the content of the NOTICE file.
143
-
144
- 7. Disclaimer of Warranty. Unless required by applicable law or
145
- agreed to in writing, Licensor provides the Work (and each
146
- Contributor provides its Contributions) on an "AS IS" BASIS,
147
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
- implied, including, without limitation, any warranties or conditions
149
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
- PARTICULAR PURPOSE. You are solely responsible for determining the
151
- appropriateness of using or redistributing the Work and assume any
152
- risks associated with Your exercise of permissions under this License.
153
-
154
- 8. Limitation of Liability. In no event and under no legal theory,
155
- whether in tort (including negligence), contract, or otherwise,
156
- unless required by applicable law (such as deliberate and grossly
157
- negligent acts) or agreed to in writing, shall any Contributor be
158
- liable to You for damages, including any direct, indirect, special,
159
- incidental, or consequential damages of any character arising as a
160
- result of this License or out of the use or inability to use the
161
- Work (including but not limited to damages for loss of goodwill,
162
- work stoppage, computer failure or malfunction, or any and all
163
- other commercial damages or losses), even if such Contributor
164
- has been advised of the possibility of such damages.
165
-
166
- 9. Accepting Warranty or Additional Liability. While redistributing
167
- the Work or Derivative Works thereof, You may choose to offer,
168
- and charge a fee for, acceptance of support, warranty, indemnity,
169
- or other liability obligations and/or rights consistent with this
170
- License. However, in accepting such obligations, You may act only
171
- on Your own behalf and on Your sole responsibility, not on behalf
172
- of any other Contributor, and only if You agree to indemnify,
173
- defend, and hold each Contributor harmless for any liability
174
- incurred by, or claims asserted against, such Contributor by reason
175
- of your accepting any such warranty or additional liability.
176
-
177
- END OF TERMS AND CONDITIONS
178
-
179
- APPENDIX: How to apply the Apache License to your work.
180
-
181
- To apply the Apache License to your work, attach the following
182
- boilerplate notice, with the fields enclosed by brackets "[]"
183
- replaced with your own identifying information. (Don't include
184
- the brackets!) The text should be enclosed in the appropriate
185
- comment syntax for the file format. We also recommend that a
186
- file or class name and description of purpose be included on the
187
- same "printed page" as the copyright notice for easier
188
- identification within third-party archives.
189
-
190
- Copyright 2026 &#75;&#101;&#114;&#110;&#101;&#108;
191
-
192
- Licensed under the Apache License, Version 2.0 (the "License");
193
- you may not use this file except in compliance with the License.
194
- You may obtain a copy of the License at
195
-
196
- http://www.apache.org/licenses/LICENSE-2.0
197
-
198
- Unless required by applicable law or agreed to in writing, software
199
- distributed under the License is distributed on an "AS IS" BASIS,
200
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
- See the License for the specific language governing permissions and
202
- limitations under the License.
203
- </pre></body></html>
@@ -1,59 +0,0 @@
1
- import{a as Ge,f as de,h as le,i as De,j as Ue,l as ue}from"./chunk-NGQYSQQA.js";import{c as Pe,d as Me}from"./chunk-HUV2WTRW.js";import{W as G,e as V,q as C,t as ce,u as Re,v as ke,w as W,y as Oe}from"./chunk-MZN4U5BL.js";import{b as ae,h as se}from"./chunk-53HIX3X7.js";import{Kb as re,N as Ne,Pb as X,t as y}from"./chunk-7JAMFXNL.js";import{createHash as Te,createHmac as pt,timingSafeEqual as on}from"crypto";import{createHash as D,randomUUID as He}from"crypto";import{Client as Mt,StreamableHTTPClientTransport as Gt}from"@modelcontextprotocol/client";import{createHash as vt,randomUUID as St}from"crypto";import{z as b}from"zod";async function _n(e,t){!Number.isFinite(t)||t<=0||await ae({op:G.CONNECTED_ACCOUNT_FEE,userId:Number(e)},()=>se({vendor:"nango_connection",units:t,unitType:"connection_month"}))}async function qe(e,t){let n=[{vendor:"nango_function_run",units:t.functionRuns,unitType:"function_run"},{vendor:"nango_proxy_request",units:t.proxyRequests,unitType:"proxy_request"},{vendor:"nango_compute",units:t.computeMilliseconds/1e3,unitType:"compute_second"}];await ae({op:G.CONNECTED_USAGE,userId:Number(e)},async()=>{for(let i of n)!Number.isFinite(i.units)||i.units<=0||await se(i)})}var R="connected_usage",Ct="mastra_scheduler",xt=b.object({toolName:b.string().trim().min(1).max(200).optional(),operationKind:b.enum(["read","action","sync","export","proxy","other"]).optional(),outcome:b.enum(["success","error","partial"]).optional(),requestId:b.string().trim().min(1).max(200).optional(),occurrenceId:b.string().trim().min(1).max(200).optional(),scheduleId:b.string().trim().min(1).max(200).optional(),nangoOperationId:b.string().trim().min(1).max(200).optional(),startedAt:b.string().datetime({offset:!0}).optional(),completedAt:b.string().datetime({offset:!0}).optional()}).strict(),Tt=b.object({identity:b.string().trim().min(1).max(320),idempotencyKey:b.string().trim().min(1).max(500),ratePolicyVersion:b.string().trim().min(1).max(100),connectionId:b.string().trim().min(1).max(500),providerConfigKey:b.string().trim().min(1).max(200),functionRuns:b.number().int().safe().nonnegative(),proxyRequests:b.number().int().safe().nonnegative(),computeMilliseconds:b.number().int().safe().nonnegative(),sourceSurface:b.enum(["main_mcp","mastra_scheduler","nango_reconciliation"]).default(Ct),metadata:xt.optional()}).strict(),Et=b.object({identity:b.string().trim().min(1).max(320),ratePolicyVersion:b.string().trim().min(1).max(100)}).strict(),x=class extends Error{constructor(n,i,r,o={}){super(i);this.code=n;this.httpStatus=r;this.details=o;this.name="ConnectedUsageBillingError"}code;httpStatus;details};function ge(e){return vt("sha256").update(e).digest("hex")}function At(e){return`connected-usage:${ge(e)}`}function Nt(e){return`connected-usage-debit:${ge(e)}`}function Rt(e){return e.trim().toLowerCase()}async function Le(e){let t=await Ne(Rt(e));if(!t)throw new x("user_not_found","billing identity was not found",404);return t}function kt(e){let t={toolName:e.metadata.toolName??null,operationKind:e.metadata.operationKind??null,outcome:e.metadata.outcome??null,requestId:e.metadata.requestId??null,occurrenceId:e.metadata.occurrenceId??null,scheduleId:e.metadata.scheduleId??null,nangoOperationId:e.metadata.nangoOperationId??null,startedAt:e.metadata.startedAt??null,completedAt:e.metadata.completedAt??null};return ge(JSON.stringify({ratePolicyVersion:C,connectionId:e.connectionId,providerConfigKey:e.providerConfigKey,usage:e.usage,sourceSurface:e.sourceSurface,metadata:t}))}function K(e){let t=JSON.stringify(e);if(t.length>4e3)throw new x("invalid_request","connected usage metadata is too large",400);return t}function ye(e){try{let t=JSON.parse(e.metadata??"");if(t.contract!=="connected_usage_receipt"||t.ratePolicyVersion!==C||typeof t.fingerprint!="string"||typeof t.connectionId!="string"||typeof t.providerConfigKey!="string"||!t.usage||!t.charge)throw new Error("invalid connected usage receipt metadata");return t}catch{throw new x("idempotency_key_conflict","the idempotency key is already bound to an incompatible billing receipt",409)}}async function me(e){let t=await y().execute({sql:"SELECT id, user_id, billing_class, source_surface, status, amount_mc, metadata FROM billing_events WHERE idempotency_key = ? LIMIT 1",args:[e]});return t.rows[0]?t.rows[0]:null}async function Ke(e,t){return(await y().execute({sql:`SELECT 1
2
- FROM billing_events
3
- WHERE user_id = ?
4
- AND billing_class = ?
5
- AND status = 'cost_pending'
6
- ${t?"AND idempotency_key <> ?":""}
7
- LIMIT 1`,args:t?[e,R,t]:[e,R]})).rows.length>0}function Ot(e){let t="connected-usage:",n=e.startsWith(t)?e.slice(t.length):"";return/^[a-f0-9]{64}$/.test(n)?`connected-usage-debit:${n}`:null}async function Pt(e){let t=await y().execute({sql:`SELECT id, user_id, idempotency_key, billing_class, source_surface, status, amount_mc, metadata
8
- FROM billing_events
9
- WHERE user_id = ? AND billing_class = ? AND status = 'cost_pending'
10
- ORDER BY created_at ASC
11
- LIMIT 10`,args:[e.id,R]});for(let n of t.rows){let i=n,r=String(i.idempotency_key??""),o=Ot(r),a;try{a=ye(i)}catch{return}if(!o||Number(i.user_id)!==e.id||i.billing_class!==R||Number(i.amount_mc)!==a.charge.amountMc||a.charge.amountMc>0&&!(await re(e.id,a.charge.amountMc,G.CONNECTED_USAGE,`connected-usage:${a.providerConfigKey}`,o)).ok)return;let s={...a};delete s.reason,await y().execute({sql:`UPDATE billing_events
12
- SET status = 'settled', metadata = ?, settled_at = datetime('now')
13
- WHERE idempotency_key = ? AND user_id = ? AND billing_class = ? AND status = 'cost_pending'`,args:[K(s),r,e.id,R]})}}function $e(e){if(e!==C)throw new x("rate_policy_mismatch","connected usage receipt rate policy does not match the active policy",409,{expectedRatePolicyVersion:C})}async function he(e){let t=Et.safeParse(e);if(!t.success)throw new x("invalid_request","invalid connected usage preflight request",400);$e(t.data.ratePolicyVersion);let n=await Le(t.data.identity);if(await Pt(n),await Ke(n.id))throw new x("pending_cost","a previous connected usage receipt has unresolved cost",409);let i=await X(n.id,n.balance_mc);if(i<W)throw new x("insufficient_credits","the wallet cannot cover the minimum connected function charge",402,{balanceMc:i,requiredMc:W});return{allowed:!0,ratePolicyVersion:C,minimumMc:W,minimumCredits:ce,balanceMc:i}}function pe(e,t,n,i,r){let o=ye(e);if(Number(e.user_id)!==t||e.billing_class!==R||e.source_surface!==n||Number(e.amount_mc)!==r||o.fingerprint!==i)throw new x("idempotency_key_conflict","the idempotency key is already bound to different connected usage",409);return o}function je(e,t){return[{key:"function_runs",label:"Connected function runs",quantity:e.functionRuns,quantityUnit:"function_run",rateCredits:ce,rateUnit:"function_run",amountMc:t.functionRunMc,credits:t.functionRunMc/V},{key:"proxy_requests",label:"Connected proxy requests",quantity:e.proxyRequests,quantityUnit:"proxy_request",rateCredits:Re,rateUnit:"proxy_request",amountMc:t.proxyRequestMc,credits:t.proxyRequestMc/V},{key:"compute",label:"Connected function compute",quantity:e.computeMilliseconds,quantityUnit:"millisecond",rateCredits:ke,rateUnit:"compute_second",amountMc:t.computeMc,credits:t.computeMc/V}]}function fe(e,t,n,i){let r=e.status==="cost_pending"?t.reason:void 0;return{id:e.id,status:e.status==="settled"?"settled":"cost_pending",ratePolicyVersion:C,connectionId:t.connectionId,providerConfigKey:t.providerConfigKey,amountMc:t.charge.amountMc,credits:t.charge.credits,functionRunMc:t.charge.functionRunMc,proxyRequestMc:t.charge.proxyRequestMc,computeMc:t.charge.computeMc,usage:t.usage,costBreakdown:je(t.usage,t.charge),balanceMc:n,...r?{reason:r}:{},duplicate:i}}async function we(e){let t=Tt.safeParse(e);if(!t.success)throw new x("invalid_request","invalid connected usage settlement request",400,{fields:[...new Set(t.error.issues.map(I=>I.path.join(".")).filter(Boolean))]});let n=t.data;$e(n.ratePolicyVersion);let i=await Le(n.identity),r={functionRuns:n.functionRuns,proxyRequests:n.proxyRequests,computeMilliseconds:n.computeMilliseconds},o=Oe(r),a=n.metadata??{},s=kt({connectionId:n.connectionId,providerConfigKey:n.providerConfigKey,usage:r,sourceSurface:n.sourceSurface,metadata:a}),c={contract:"connected_usage_receipt",ratePolicyVersion:C,fingerprint:s,connectionId:n.connectionId,providerConfigKey:n.providerConfigKey,usage:r,charge:o,safeMetadata:a},d=At(n.idempotencyKey);if(await Ke(i.id,d))throw new x("pending_cost","a previous connected usage receipt has unresolved cost",409);let l=await y().execute({sql:`INSERT OR IGNORE INTO billing_events
14
- (id, user_id, idempotency_key, billing_class, source_surface, status, amount_mc, metadata)
15
- VALUES (?, ?, ?, ?, ?, 'settling', ?, ?)`,args:[St(),i.id,d,R,n.sourceSurface,o.amountMc,K(c)]}),u=await me(d);if(!u)throw new Error("connected usage receipt insert completed without a readable event");let p=pe(u,i.id,n.sourceSurface,s,o.amountMc),_=l.rowsAffected===0;if(u.status==="settled")return fe(u,p,await X(i.id,i.balance_mc),!0);if(!["settling","cost_pending"].includes(u.status))throw new x("idempotency_key_conflict","the connected usage receipt has an incompatible status",409);if(u.status==="cost_pending"&&await y().execute({sql:"UPDATE billing_events SET status = 'settling', metadata = ? WHERE idempotency_key = ? AND status = 'cost_pending'",args:[K(c),d]}),o.amountMc===0)await y().execute({sql:"UPDATE billing_events SET status = 'settled', settled_at = datetime('now') WHERE idempotency_key = ? AND status = 'settling'",args:[d]});else{let I=await re(i.id,o.amountMc,G.CONNECTED_USAGE,`connected-usage:${n.providerConfigKey}`,Nt(n.idempotencyKey));if(!I.ok){let M={...c,reason:"insufficient_credits"};if(await y().execute({sql:"UPDATE billing_events SET status = 'cost_pending', metadata = ? WHERE idempotency_key = ? AND status = 'settling'",args:[K(M),d]}),u=await me(d),!u)throw new Error("connected usage pending receipt was lost");return p=pe(u,i.id,n.sourceSurface,s,o.amountMc),fe(u,p,I.balance_mc,_||I.duplicate)}await y().execute({sql:"UPDATE billing_events SET status = 'settled', metadata = ?, settled_at = datetime('now') WHERE idempotency_key = ? AND status IN ('settling', 'cost_pending')",args:[K(c),d]}),I.duplicate||await qe(i.id,r)}if(u=await me(d),!u)throw new Error("connected usage settlement completed without an event receipt");return p=pe(u,i.id,n.sourceSurface,s,o.amountMc),fe(u,p,await X(i.id,i.balance_mc),_)}async function Tn(e,t=100){let n=await y().execute({sql:`SELECT id, user_id, billing_class, source_surface, status, amount_mc, metadata, created_at
16
- FROM billing_events
17
- WHERE user_id = ? AND billing_class = ? AND status IN ('settled', 'cost_pending')
18
- ORDER BY created_at DESC
19
- LIMIT ?`,args:[e,R,Math.max(1,Math.min(250,Math.round(t)))]}),i=[];for(let r of n.rows){let o=r;try{let a=ye(o);i.push({id:o.id,createdAt:String(o.created_at??""),status:o.status==="settled"?"settled":"cost_pending",connectionId:a.connectionId,providerConfigKey:a.providerConfigKey,amountMc:a.charge.amountMc,credits:a.charge.credits,usage:a.usage,costBreakdown:je(a.usage,a.charge),metadata:a.safeMetadata})}catch{}}return i}function _e(e){return e.annotations?.readOnlyHint===!0?"read":e.annotations?.readOnlyHint===!1?"action":/^(get|list|search|query|read|download|fetch|find|lookup|inspect|describe|check)-/i.test(e.name)?"read":"action"}function Be(e){return new Map(Object.entries(e??{}).map(([t,n])=>[t,[...new Set(n.map(i=>i.trim()).filter(Boolean))].sort()]))}function Y(e){let t=Be(e.requiredPermissionsByTool),n=Be(e.requiredFeaturesByTool),i=new Set(e.grantedPermissions??[]),r=new Set(e.enabledFeatures??[]),o=new Set(e.adminBlockedTools??[]),a=new Map;for(let s of e.tools){let c=_e(s),d=t.get(s.name)??[],l=n.get(s.name)??[],u=d.filter(I=>!i.has(I)),p=l.filter(I=>!r.has(I)),_=e.connectionActive?o.has(s.name)?"admin_blocked":c==="action"&&!e.actionsEnabled?"actions_disabled":d.length>0&&e.permissionVerification==="unavailable"?"permission_verification_unavailable":u.length>0?"missing_permission":p.length>0?"missing_app_feature":null:"inactive_connection";a.set(s.name,{name:s.name,classification:c,requiredPermissions:d,requiredFeatures:l,available:_===null,blockedReason:_,missingPermissions:u,missingFeatures:p})}return a}function Ie(e,t){let n=e.get(t);if(!n)throw new Error("connected_tool_policy_missing");return n}var Dt="https://api.nango.dev/mcp",Ut=2e4,qt=24e4,Fe=100,Lt=20,Kt=360*60*1e3,$t=new Set(["stripe_revenue","salesforce","pipedrive"]),jt="2026-07-16.1",Bt="f037859ec80c2ea2fac6e4a67c1a59f3200dd22d3642c97789b9bb3236723d3e",w=class extends Error{status;code;retryable;retryAfterMs;constructor(t,n,i,r=n===429||n>=500,o=null){super(t),this.name="MainNangoTransportError",this.status=n,this.code=i,this.retryable=r,this.retryAfterMs=o}};function Q(e){return typeof e=="string"&&$t.has(e.normalize("NFKC").trim().toLowerCase())}function ze(e){if(Q(e))throw new w("This provider integration is not currently available.",409,"provider_unavailable",!1)}function Ft(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return""}}function Je(e){let t=e.match(/retry[_ -]?after[_ -]?ms[^0-9]{0,20}(\d{1,7})/i);if(t)return Math.min(Math.max(Number(t[1]),1e3),6e4);let n=e.match(/retry[_ -]?after[^0-9]{0,20}(\d{1,4})/i);return n?Math.min(Math.max(Number(n[1]),1)*1e3,6e4):null}function Xe(e){if(e instanceof w)return e;let t=Ft(e),n=e&&typeof e=="object"?e:null;return n?.code===-32001||n?.name==="RequestTimeout"||/Request timed out|RequestTimeout|Maximum total timeout exceeded/i.test(t)?new w("The connected service operation timed out before returning a result. Retry failed items or use a smaller batch.",503,"mcp_request_timeout",!0):/SERVICE_DISABLED|accessNotConfigured/i.test(t)?new w("The provider API required by this connection is disabled. Enable it in the provider project, wait for propagation, then retry.",409,"provider_api_disabled",!1):/PERMISSION_DENIED|insufficientPermissions|insufficient permission/i.test(t)?new w("The connected account does not have permission to run this provider operation.",403,"missing_provider_permission",!1):/RESOURCE_EXHAUSTED|rate.?limit|status["']?\s*:\s*429/i.test(t)?new w("The connected provider is temporarily rate limited.",429,"upstream_rate_limited",!0,Je(t)):/UNAUTHENTICATED|invalid_grant|status["']?\s*:\s*401/i.test(t)?new w("The service connection requires reconnection.",409,"connection_inactive",!1):new w("The service connection is temporarily unavailable.",503,"connection_transport_unavailable")}async function Ht(e,t,n){return e.callTool({name:t,arguments:n},{timeout:qt})}function g(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function m(e){return typeof e=="string"&&e.trim()?e.trim():null}function be(e,t){if(Array.isArray(e))return e;let n=g(e);if(Array.isArray(n?.[t]))return n[t];if(Array.isArray(n?.data))return n.data;let i=g(n?.data);return Array.isArray(i?.[t])?i[t]:[]}function Ve(){let e=process.env.NANGO_SECRET_KEY?.trim();if(!e)throw new w("Nango is not configured.",503,"nango_not_configured");return e}function We(){try{return new URL(process.env.NANGO_MCP_URL?.trim()||Dt)}catch{throw new w("Nango MCP URL is invalid.",503,"nango_invalid_url")}}async function P(e,t={}){let n=new URL(e,`${We().origin}/`);for(let[a,s]of Object.entries(t.query??{}))s!==void 0&&n.searchParams.set(a,String(s));let i;try{i=await fetch(n,{method:t.method??"GET",headers:{authorization:`Bearer ${Ve()}`,accept:"application/json",...t.body?{"content-type":"application/json"}:{},...t.headers},body:t.body?JSON.stringify(t.body):void 0,signal:AbortSignal.timeout(Ut)})}catch{throw new w("Nango is temporarily unavailable.",503,"connection_transport_unavailable")}let r=await i.text(),o={};try{o=r?JSON.parse(r):{}}catch{throw new w("Nango returned an invalid response.",502,"nango_invalid_response")}if(!i.ok){let a=i.status===400||i.status===403||i.status===404||i.status===409||i.status===429||i.status===503?i.status:502;throw new w(a===429?"The connected provider is temporarily rate limited.":"Nango request failed.",a,a===429?"upstream_rate_limited":a===404?"connection_not_found":"connection_transport_unavailable",a===429||a>=500,a===429?Je(`retry-after: ${i.headers.get("retry-after")??""}`):null)}return o}function $(e){let t=m(e);return t?t.normalize("NFKC").toLowerCase():null}function zt(e,t){let n=g(e),i=g(n?.tags),r=g(n?.end_user),o=$(t);if(!o)return!1;let a=[$(i?.end_user_email),$(r?.email)].filter(c=>!!c);if(a.some(c=>c!==o))return!1;let s=[$(i?.end_user_id),$(r?.id)].filter(c=>!!c&&c.includes("@"));return s.some(c=>c!==o)?!1:a.length>0?a.includes(o):s.includes(o)}function Jt(e){let t=g(e),n=m(t?.connection_id),i=m(t?.provider_config_key);if(!n||!i)return null;let o=(Array.isArray(t?.errors)?t.errors:[]).some(a=>m(g(a)?.type)==="auth");return{upstreamConnectionId:n,providerConfigKey:i,provider:m(t?.provider)??i,label:null,lifecycleStatus:o?"needs_reauth":"connected",reconnectRequired:o,createdAt:m(t?.created_at)??m(t?.created),updatedAt:m(t?.updated_at)}}var Xt=new Set(["facebook","github-getting-started","google-analytics","google-calendar","google-drive","google-mail","google-search-console","linkedin","meta-marketing-api","slack","twitter-v2","xero","youtube","zoom"]);function Vt(e){let t=m(e);return t||(typeof e=="number"&&Number.isFinite(e)?String(e):null)}function O(e){let t=m(e)?.toLowerCase()??null;return t&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)?t:null}function T(e){return e.id||e.email||e.name?e:null}async function k(e){return P(`/proxy${e.path}`,{query:e.query,headers:{"connection-id":e.upstreamConnectionId,"provider-config-key":e.providerConfigKey,...e.baseUrlOverride?{"base-url-override":e.baseUrlOverride}:{}}})}var Wt=[{method:"GET",pattern:/^\/gmail\/v1\/users\/me\/messages$/},{method:"GET",pattern:/^\/gmail\/v1\/users\/me\/messages\/[A-Za-z0-9_-]+$/},{method:"GET",pattern:/^\/gmail\/v1\/users\/me\/messages\/[A-Za-z0-9_-]+\/attachments\/[A-Za-z0-9_-]+$/},{method:"GET",pattern:/^\/gmail\/v1\/users\/me\/labels$/},{method:"POST",pattern:/^\/gmail\/v1\/users\/me\/messages\/batchModify$/},{method:"POST",pattern:/^\/gmail\/v1\/users\/me\/messages\/batchDelete$/},{method:"POST",pattern:/^\/gmail\/v1\/users\/me\/messages\/send$/},{method:"POST",pattern:/^\/gmail\/v1\/users\/me\/messages\/[A-Za-z0-9_-]+\/(?:trash|untrash)$/}],Yt=new Set(["q","maxResults","pageToken","format","metadataHeaders","fields"]);async function Ye(e){let t=await Z(e.identity,e.connectionId);if(t.providerConfigKey!=="google-mail")throw new w("Service connection not found.",404,"connection_not_found",!1);if(!Wt.some(c=>c.method===e.method&&c.pattern.test(e.path)))throw new w("The Gmail provider operation is not allowed.",403,"tool_not_allowed",!1);if(Object.keys(e.query??{}).some(c=>!Yt.has(c)))throw new w("The Gmail provider query is not allowed.",400,"invalid_request",!1);let n=e.method==="POST";if(n&&!t.actionsEnabled)throw new w("Actions are disabled for this service connection.",403,"actions_disabled",!1);await he({identity:e.identity,ratePolicyVersion:C});let i=e.requestId?.trim()||He(),r=`main-gmail-proxy:${D("sha256").update(e.identity.toLowerCase()).update("\0").update(t.id).update("\0").update(e.method).update("\0").update(e.path).update("\0").update(i).digest("hex")}`,o=performance.now(),a,s;try{a=await P(`/proxy${e.path}`,{method:e.method,query:e.query,body:e.body,headers:{"connection-id":t.upstreamConnectionId,"provider-config-key":"google-mail","base-url-override":"https://gmail.googleapis.com"}})}catch(c){s=c}if(await we({identity:e.identity,idempotencyKey:r,ratePolicyVersion:C,connectionId:t.id,providerConfigKey:t.providerConfigKey,functionRuns:0,proxyRequests:1,computeMilliseconds:Math.max(0,Math.round(performance.now()-o)),sourceSurface:"main_mcp",metadata:{operationKind:n?"action":"read",outcome:s?"error":"success",requestId:i.length<=200?i:D("sha256").update(i).digest("hex")}}),s)throw Xe(s);return a}async function Qt(e){let t=(n,i,r)=>k({...e,path:n,query:i,baseUrlOverride:r});try{if(e.providerConfigKey==="google-mail"){let n=g(await t("/gmail/v1/users/me/profile",void 0,"https://gmail.googleapis.com")),i=O(n?.emailAddress);return T({id:i,email:i,name:null})}if(e.providerConfigKey==="google-drive"){let n=g(await t("/drive/v3/about",{fields:"user(permissionId,displayName,emailAddress)"},"https://www.googleapis.com")),i=g(n?.user);return T({id:m(i?.permissionId),email:O(i?.emailAddress),name:m(i?.displayName)})}if(e.providerConfigKey==="google-calendar"){let n=g(await t("/calendar/v3/calendars/primary",void 0,"https://www.googleapis.com")),i=m(n?.id);return T({id:i,email:O(i),name:m(n?.summary)})}if(e.providerConfigKey==="youtube"){let n=g(await t("/youtube/v3/channels",{part:"snippet",mine:"true",maxResults:1},"https://www.googleapis.com")),i=Array.isArray(n?.items)?g(n.items[0]):null;return T({id:m(i?.id),email:null,name:m(g(i?.snippet)?.title)})}}catch{}try{let n=g(await t("/v1/userinfo",void 0,"https://openidconnect.googleapis.com"));return T({id:m(n?.sub),email:n?.email_verified===!1?null:O(n?.email),name:m(n?.name)})}catch{return null}}async function Zt(e){if(!Xt.has(e.providerConfigKey))return null;if(e.providerConfigKey.startsWith("google-")||e.providerConfigKey==="youtube")return Qt(e);try{if(e.providerConfigKey==="github-getting-started"){let t=g(await k({...e,path:"/user"}));return T({id:Vt(t?.id),email:O(t?.email),name:m(t?.name)??m(t?.login)})}if(e.providerConfigKey==="slack"){let t=g(await k({...e,path:"/api/auth.test"}));return T({id:m(t?.user_id),email:null,name:[m(t?.user),m(t?.team)].filter(Boolean).join(" \xB7 ")||null})}if(e.providerConfigKey==="zoom"){let t=g(await k({...e,path:"/v2/users/me"})),n=[m(t?.first_name),m(t?.last_name)].filter(Boolean).join(" ");return T({id:m(t?.id),email:O(t?.email),name:m(t?.display_name)??(n||null)})}if(e.providerConfigKey==="linkedin"){let t=g(await k({...e,path:"/v2/userinfo"}));return T({id:m(t?.sub),email:t?.email_verified===!1?null:O(t?.email),name:m(t?.name)})}if(e.providerConfigKey==="meta-marketing-api"||e.providerConfigKey==="facebook"){let t=g(await k({...e,path:"/me",query:{fields:"id,name,email"}}));return T({id:m(t?.id),email:O(t?.email),name:m(t?.name)})}if(e.providerConfigKey==="twitter-v2"){let t=g(await k({...e,path:"/2/users/me",query:{"user.fields":"id,name,username"}})),n=g(t?.data);return T({id:m(n?.id),email:null,name:m(n?.username)??m(n?.name)})}if(e.providerConfigKey==="xero"){let t=await k({...e,path:"/connections"}),n=Array.isArray(t)?g(t[0]):null;return T({id:m(n?.tenantId),email:null,name:m(n?.tenantName)})}}catch{return null}return null}async function Gn(e,t={}){let n=[];for(let s=0;s<Lt;s+=1){let c=await P("/connections",{query:{limit:Fe,page:s}}),d=be(c,"connections");if(n.push(...d),d.length<Fe)break}let i=n.filter(s=>zt(s,e)).map(Jt).filter(s=>s!==null),o=(await de(e,i)).filter(s=>!Q(s.providerConfigKey));if(t.resolveProviderIdentity===!1)return o;let a=new Map(i.map(s=>[`${s.providerConfigKey}\0${s.upstreamConnectionId}`,s]));return await Promise.all(o.map(async s=>{if(s.lifecycleStatus!=="connected"||!s.upstreamConnectionId)return;let c=a.get(`${s.providerConfigKey}\0${s.upstreamConnectionId}`);if(!c)return;let d=c.updatedAt??c.createdAt??s.lifecycleStatus,l=!!(s.providerAccountId||s.providerAccountEmail||s.providerAccountName),u=s.providerIdentityCheckedAt?Date.parse(`${s.providerIdentityCheckedAt.replace(" ","T")}Z`):Number.NaN,p=!l&&Number.isFinite(u)&&Date.now()-u<Kt;if(s.providerIdentitySourceUpdatedAt===d&&(l||p))return;let _=await Zt({upstreamConnectionId:s.upstreamConnectionId,providerConfigKey:s.providerConfigKey});await Ue({connectionId:s.id,providerAccountId:_?.id,providerAccountEmail:_?.email,providerAccountName:_?.name,sourceUpdatedAt:d})})),(await de(e,i)).filter(s=>!Q(s.providerConfigKey))}async function Dn(){let[e,t]=await Promise.all([P("/integrations"),P("/providers")]),n=new Map;for(let i of be(t,"providers")){let r=g(i),o=m(r?.name);r&&o&&n.set(o,r)}return be(e,"integrations").flatMap(i=>{let r=g(i),o=m(r?.unique_key)??m(r?.id),a=m(r?.provider);if(!o||!a||Q(o))return[];let s=n.get(a);return[{id:o,provider:a,displayName:m(r?.display_name)??m(s?.display_name)??o,authMode:m(s?.auth_mode),categories:Array.isArray(s?.categories)?s.categories:[],docsUrl:m(s?.docs),logoUrl:m(r?.logo),safeDefaultAllowedTools:[],actionTools:[],setupStatus:"ready"}]})}function Qe(e){let n={linkedin:"openid profile email w_member_social","github-getting-started":"repo workflow read:org read:user user:email","google-drive":"openid profile email https://www.googleapis.com/auth/drive","google-search-console":"openid profile email https://www.googleapis.com/auth/webmasters.readonly https://www.googleapis.com/auth/webmasters"}[e];return n?{[e]:{connection_config:{oauth_scopes_override:n}}}:void 0}function Ze(e){let t=g(e),n=g(t?.data)??t,i=m(n?.connect_link);if(!i)throw new w("Nango did not return a connect link.",502,"nango_missing_connect_link");return{connectLink:i,expiresAt:m(n?.expires_at)}}async function Un(e,t){ze(t);let n=Qe(t);return Ze(await P("/connect/sessions",{method:"POST",body:{tags:{end_user_id:e,end_user_email:e},allowed_integrations:[t],...n?{integrations_config_defaults:n}:{}}}))}async function qn(e,t){let n=await Z(e,t,!0),i=Qe(n.providerConfigKey);return Ze(await P("/connect/sessions/reconnect",{method:"POST",body:{connection_id:n.upstreamConnectionId,integration_id:n.providerConfigKey,tags:{end_user_id:e,end_user_email:e},...i?{integrations_config_defaults:i}:{}}}))}async function Ln(e,t){let n=await et(e,t);try{await P(`/connections/${encodeURIComponent(n.upstreamConnectionId)}`,{method:"DELETE",query:{provider_config_key:n.providerConfigKey}})}catch(i){if(!(i instanceof w)||i.status!==404)throw i}}async function et(e,t){let n=await le(e,t);if(!n||n.transport!=="nango"||!n.upstreamConnectionId)throw new w("Service connection not found.",404,"connection_not_found",!1);return n}async function Z(e,t,n=!1){let i=await et(e,t);if(ze(i.providerConfigKey),i.lifecycleStatus!=="connected"&&!(n&&i.lifecycleStatus==="needs_reauth"))throw new w("Service connection requires reconnection.",409,"connection_inactive",!1);return i}async function ve(e,t){let n=new Gt(We(),{requestInit:{headers:{Authorization:`Bearer ${Ve()}`,"connection-id":e.upstreamConnectionId,"provider-config-key":e.providerConfigKey}}}),i=new Mt({name:"mcp-scraper-integrations",version:"1.0.0"},{capabilities:{}});try{await i.connect(n);let r=await t(i);return await ue({connectionId:e.id,operationalStatus:"available",evidenceSource:"nango_mcp"}),r}catch(r){let o=Xe(r);throw await ue({connectionId:e.id,operationalStatus:o.code==="connection_transport_unavailable"?"unavailable":"degraded",failureCode:o.code,retryable:o.retryable,evidenceSource:"nango_mcp"}).catch(()=>{}),o}finally{await i.close().catch(()=>{})}}async function Kn(e,t){let n=await Z(e,t);(n.provider??n.providerConfigKey)==="google-search-console"&&await ve(n,async r=>{if(!(await r.listTools()).tools.some(a=>a.name==="list-sites"))throw new w("The Search Console health-check tool is unavailable.",404,"live_tool_missing",!1);await r.callTool({name:"list-sites",arguments:{}})})}async function tt(e,t){let n=await Z(e,t),r=(await ve(n,l=>l.listTools())).tools.flatMap(l=>{let u=g(l.inputSchema);return!l.name||!u?[]:[{name:l.name,...l.title?{title:l.title}:{},...l.description?{description:l.description}:{},inputSchema:u,...g(l.outputSchema)?{outputSchema:g(l.outputSchema)}:{},...g(l.annotations)?{annotations:g(l.annotations)}:{}}]}),o=Y({tools:r,connectionActive:n.lifecycleStatus==="connected",actionsEnabled:n.actionsEnabled}),a=[...o.values()].filter(l=>l.classification==="read").map(l=>l.name),s=[...o.values()].filter(l=>l.classification==="action").map(l=>l.name),c=D("sha256").update(JSON.stringify(r.map(l=>({name:l.name,inputSchema:l.inputSchema})))).digest("hex");return await De(n.id,a,s,c),{connection:await le(e,n.id)??{...n,readTools:a,actionTools:s,toolRevision:c},tools:r}}async function $n(e){let{connection:t,tools:n}=await tt(e.identity,e.connectionId),i=n.find(p=>p.name===e.tool);if(!i)throw new w("The requested provider tool is unavailable.",404,"live_tool_missing",!1);let r=Ie(Y({tools:n,connectionActive:t.lifecycleStatus==="connected",actionsEnabled:t.actionsEnabled}),i.name);if(r.classification!==e.classification)throw new w("The provider tool classification does not match this operation.",403,"tool_not_allowed",!1);if(!r.available&&r.blockedReason==="actions_disabled")throw new w("Actions are disabled for this service connection.",403,"actions_disabled",!1);if(!r.available)throw new w("The provider tool is not authorized for this connection.",403,"tool_not_allowed",!1);await he({identity:e.identity,ratePolicyVersion:C});let o=e.requestId?.trim()||He(),a=`main-nango:${D("sha256").update(e.identity.toLowerCase()).update("\0").update(t.id).update("\0").update(e.tool).update("\0").update(o).digest("hex")}`,s=new Date,c=performance.now(),d,l;try{d=await ve(t,p=>Ht(p,e.tool,e.input))}catch(p){l=p}let u=new Date;if(await we({identity:e.identity,idempotencyKey:a,ratePolicyVersion:C,connectionId:t.id,providerConfigKey:t.providerConfigKey,functionRuns:1,proxyRequests:0,computeMilliseconds:Math.max(0,Math.round(performance.now()-c)),sourceSurface:"main_mcp",metadata:{toolName:e.tool,operationKind:e.operationKind??e.classification,outcome:l?"error":"partial",requestId:o.length<=200?o:D("sha256").update(o).digest("hex"),startedAt:s.toISOString(),completedAt:u.toISOString()}}),l)throw l;return d}async function jn(e,t,n){let{connection:i,tools:r}=await tt(e,t),o=r.find(l=>l.name===n);if(!o)throw new w("The requested provider tool is unavailable.",404,"live_tool_missing",!1);let a=Ie(Y({tools:r,connectionActive:i.lifecycleStatus==="connected",actionsEnabled:i.actionsEnabled}),o.name),s=_e(o),c=a.available,d={name:o.name,...o.title?{title:o.title}:{},...o.description?{description:o.description}:{},inputSchema:o.inputSchema,...o.outputSchema?{outputSchema:o.outputSchema}:{},...o.annotations?{annotations:o.annotations}:{}};return{...d,classification:s,callable:c,blockedReason:a.blockedReason,requiredPermissions:a.requiredPermissions,missingPermissions:a.missingPermissions,requiredFeatures:a.requiredFeatures,missingFeatures:a.missingFeatures,transport:"nango",providerConfigKey:i.providerConfigKey,providerContractVersion:jt,providerContractHash:Bt,protocolVersion:null,schemaSource:"live_tools_list",schemaHash:D("sha256").update(JSON.stringify(d)).digest("hex"),fetchedAt:new Date().toISOString()}}import{createHash as en,randomUUID as ot}from"crypto";var tn=1440*60*1e3,nt=5e3,S=class extends Error{constructor(n,i,r=400){super(i);this.code=n;this.status=r;this.name="GmailSelectionError"}code;status},j=null,Se=null;function Ce(e){return e===null||typeof e!="object"?JSON.stringify(e):Array.isArray(e)?`[${e.map(Ce).join(",")}]`:`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Ce(n)}`).join(",")}}`}function U(e){return en("sha256").update(Ce(e)).digest("hex")}async function A(){let e=y();return j&&Se===e||(Se=e,j=(async()=>{await e.execute(`
20
- CREATE TABLE IF NOT EXISTS gmail_selections (
21
- selection_id TEXT PRIMARY KEY,
22
- owner_identity TEXT NOT NULL,
23
- connection_id TEXT NOT NULL,
24
- purpose TEXT NOT NULL,
25
- source_json TEXT NOT NULL,
26
- message_ids_json TEXT NOT NULL,
27
- message_count INTEGER NOT NULL,
28
- selection_sha256 TEXT NOT NULL,
29
- provider_snapshot_json TEXT,
30
- created_at TEXT NOT NULL,
31
- expires_at TEXT NOT NULL,
32
- UNIQUE(owner_identity, connection_id, purpose, selection_sha256)
33
- )
34
- `),await e.execute("CREATE INDEX IF NOT EXISTS gmail_selections_owner_expiry ON gmail_selections(owner_identity, expires_at)"),await e.execute(`
35
- CREATE TABLE IF NOT EXISTS gmail_action_executions (
36
- action_id TEXT PRIMARY KEY,
37
- owner_identity TEXT NOT NULL,
38
- idempotency_key TEXT NOT NULL,
39
- fingerprint TEXT NOT NULL,
40
- status TEXT NOT NULL,
41
- result_json TEXT,
42
- created_at TEXT NOT NULL,
43
- updated_at TEXT NOT NULL,
44
- UNIQUE(owner_identity, idempotency_key)
45
- )
46
- `),await e.execute("CREATE INDEX IF NOT EXISTS gmail_actions_owner_updated ON gmail_action_executions(owner_identity, updated_at)"),await e.execute(`CREATE TABLE IF NOT EXISTS gmail_action_chunks (
47
- action_id TEXT NOT NULL, chunk_key TEXT NOT NULL, status TEXT NOT NULL,
48
- result_json TEXT, updated_at TEXT NOT NULL,
49
- PRIMARY KEY(action_id, chunk_key)
50
- )`),await e.execute(`CREATE TABLE IF NOT EXISTS gmail_selection_exports (
51
- selection_id TEXT PRIMARY KEY, owner_identity TEXT NOT NULL, fingerprint TEXT NOT NULL,
52
- status TEXT NOT NULL, result_json TEXT, updated_at TEXT NOT NULL
53
- )`)})().catch(t=>{throw j=null,Se=null,t})),j}function it(e){let t=[...new Set(e.map(n=>n.trim()).filter(n=>/^[A-Za-z0-9_-]+$/.test(n)))];return t.sort(),t}function rt(e){return{selectionId:String(e.selection_id),ownerId:String(e.owner_identity),connectionId:String(e.connection_id),purpose:String(e.purpose),source:JSON.parse(String(e.source_json)),messageIds:JSON.parse(String(e.message_ids_json)),count:Number(e.message_count),selectionSha256:String(e.selection_sha256),createdAt:String(e.created_at),expiresAt:String(e.expires_at),providerSnapshot:typeof e.provider_snapshot_json=="string"?JSON.parse(e.provider_snapshot_json):null}}async function at(e){await A();let t=it(e.resolvedMessageIds);if(t.length===0)throw new S("selection_empty","No Gmail messages matched the selection.");if(t.length>nt)throw new S("selection_too_large",`Narrow the Gmail selection to at most ${nt} messages.`);let n=e.source.kind==="query"?{kind:"query",query:e.source.query.trim().replace(/\s+/g," ")}:{kind:"message_ids",messageIds:it(e.source.messageIds)},i=U({connectionId:e.connectionId,purpose:e.purpose,source:n,messageIds:t}),r=await y().execute({sql:"SELECT * FROM gmail_selections WHERE owner_identity = ? AND connection_id = ? AND purpose = ? AND selection_sha256 = ? AND expires_at > ? LIMIT 1",args:[e.ownerId,e.connectionId,e.purpose,i,(e.now??new Date).toISOString()]});if(r.rows[0])return rt(r.rows[0]);let o=e.now??new Date,a={selectionId:`gsel_${ot().replace(/-/g,"")}`,ownerId:e.ownerId,connectionId:e.connectionId,purpose:e.purpose,source:n,messageIds:t,count:t.length,selectionSha256:i,createdAt:o.toISOString(),expiresAt:new Date(o.getTime()+tn).toISOString(),providerSnapshot:e.providerSnapshot??null};return await y().execute({sql:"INSERT INTO gmail_selections (selection_id, owner_identity, connection_id, purpose, source_json, message_ids_json, message_count, selection_sha256, provider_snapshot_json, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",args:[a.selectionId,a.ownerId,a.connectionId,a.purpose,JSON.stringify(a.source),JSON.stringify(a.messageIds),a.count,a.selectionSha256,a.providerSnapshot?JSON.stringify(a.providerSnapshot):null,a.createdAt,a.expiresAt]}),a}async function ee(e){await A();let n=(await y().execute({sql:"SELECT * FROM gmail_selections WHERE selection_id = ? AND owner_identity = ? AND connection_id = ? AND expires_at > ? LIMIT 1",args:[e.selectionId,e.ownerId,e.connectionId,(e.now??new Date).toISOString()]})).rows[0];if(!n)throw new S("selection_not_found","Gmail selection not found.",404);return rt(n)}function te(e,t,n){if(t!==e.count||n!==e.selectionSha256)throw new S("selection_changed","The Gmail selection receipt does not match the immutable selection.",409)}function xe(e){return{actionId:String(e.action_id),ownerId:String(e.owner_identity),idempotencyKey:String(e.idempotency_key),fingerprint:String(e.fingerprint),status:String(e.status),result:typeof e.result_json=="string"?JSON.parse(e.result_json):null,createdAt:String(e.created_at),updatedAt:String(e.updated_at)}}async function ne(e){await A();let t=e.idempotencyKey.trim();if(t.length<8||t.length>200)throw new S("idempotency_key_invalid","Idempotency-Key must be 8-200 characters.");let n=await y().execute({sql:"SELECT * FROM gmail_action_executions WHERE owner_identity = ? AND idempotency_key = ? LIMIT 1",args:[e.ownerId,t]});if(n.rows[0]){let o=xe(n.rows[0]);if(o.fingerprint!==e.fingerprint)throw new S("idempotency_conflict","This Idempotency-Key is already bound to a different Gmail action.",409);if(o.status==="running"&&!o.result&&Date.now()-Date.parse(o.updatedAt)>6e4){let a=new Date().toISOString(),s=await y().execute({sql:"UPDATE gmail_action_executions SET updated_at = ? WHERE action_id = ? AND updated_at = ?",args:[a,o.actionId,o.updatedAt]});if(Number(s.rowsAffected??0)===1)return{execution:{...o,updatedAt:a},replay:!1}}return{execution:o,replay:!0}}let i=new Date().toISOString(),r={actionId:`gact_${ot().replace(/-/g,"")}`,ownerId:e.ownerId,idempotencyKey:t,fingerprint:e.fingerprint,status:"running",result:null,createdAt:i,updatedAt:i};try{await y().execute({sql:"INSERT INTO gmail_action_executions (action_id, owner_identity, idempotency_key, fingerprint, status, created_at, updated_at) VALUES (?, ?, ?, ?, 'running', ?, ?)",args:[r.actionId,r.ownerId,r.idempotencyKey,r.fingerprint,i,i]})}catch{let o=await y().execute({sql:"SELECT * FROM gmail_action_executions WHERE owner_identity = ? AND idempotency_key = ? LIMIT 1",args:[e.ownerId,t]});if(!o.rows[0])throw new S("action_claim_failed","The Gmail action could not be claimed.",409);let a=xe(o.rows[0]);if(a.fingerprint!==e.fingerprint)throw new S("idempotency_conflict","This Idempotency-Key is already bound to a different Gmail action.",409);return{execution:a,replay:!0}}return{execution:r,replay:!1}}async function ie(e){await A(),await y().execute({sql:"UPDATE gmail_action_executions SET updated_at = ? WHERE action_id = ? AND status = 'running'",args:[new Date().toISOString(),e]})}function nn(e){return{actionId:String(e.action_id),chunkKey:String(e.chunk_key),status:String(e.status),result:typeof e.result_json=="string"?JSON.parse(e.result_json):null,updatedAt:String(e.updated_at)}}async function B(e,t){await A();let n=new Date().toISOString();try{return await y().execute({sql:"INSERT INTO gmail_action_chunks (action_id, chunk_key, status, updated_at) VALUES (?, ?, 'running', ?)",args:[e,t,n]}),{receipt:{actionId:e,chunkKey:t,status:"running",result:null,updatedAt:n},claimed:!0}}catch{let i=await y().execute({sql:"SELECT * FROM gmail_action_chunks WHERE action_id = ? AND chunk_key = ? LIMIT 1",args:[e,t]});if(!i.rows[0])throw new S("action_chunk_claim_failed","The Gmail action chunk could not be claimed.",409);return{receipt:nn(i.rows[0]),claimed:!1}}}async function N(e,t,n,i){await A(),await y().execute({sql:"UPDATE gmail_action_chunks SET status = ?, result_json = ?, updated_at = ? WHERE action_id = ? AND chunk_key = ?",args:[n,JSON.stringify(i),new Date().toISOString(),e,t]})}async function st(e){await A();let t=await y().execute({sql:"SELECT * FROM gmail_selection_exports WHERE selection_id = ? AND owner_identity = ? LIMIT 1",args:[e.selectionId,e.ownerId]});if(t.rows[0]){let n=t.rows[0];if(String(n.fingerprint)!==e.fingerprint)throw new S("export_conflict","This Gmail selection export receipt conflicts with the stored export.",409);let i=typeof n.result_json=="string"?JSON.parse(n.result_json):null;if(i)return{replay:i,claimed:!1};if(Date.now()-Date.parse(String(n.updated_at))>5*6e4){let r=await y().execute({sql:"UPDATE gmail_selection_exports SET updated_at = ? WHERE selection_id = ? AND owner_identity = ? AND updated_at = ?",args:[new Date().toISOString(),e.selectionId,e.ownerId,String(n.updated_at)]});if(Number(r.rowsAffected??0)===1)return{replay:null,claimed:!0}}return{replay:null,claimed:!1}}try{return await y().execute({sql:"INSERT INTO gmail_selection_exports (selection_id, owner_identity, fingerprint, status, updated_at) VALUES (?, ?, ?, 'running', ?)",args:[e.selectionId,e.ownerId,e.fingerprint,new Date().toISOString()]}),{replay:null,claimed:!0}}catch{let n=await y().execute({sql:"SELECT * FROM gmail_selection_exports WHERE selection_id = ? AND owner_identity = ? LIMIT 1",args:[e.selectionId,e.ownerId]});if(!n.rows[0])throw new S("export_claim_failed","The Gmail export could not be claimed.",409);let i=n.rows[0];if(String(i.fingerprint)!==e.fingerprint)throw new S("export_conflict","This Gmail selection export receipt conflicts with the stored export.",409);return{replay:typeof i.result_json=="string"?JSON.parse(i.result_json):null,claimed:!1}}}async function ct(e,t,n){await A(),await y().execute({sql:"UPDATE gmail_selection_exports SET status = 'complete', result_json = ?, updated_at = ? WHERE selection_id = ? AND owner_identity = ?",args:[JSON.stringify(n),new Date().toISOString(),t,e]})}async function F(e,t,n){await A();let i=new Date().toISOString();await y().execute({sql:"UPDATE gmail_action_executions SET status = ?, result_json = ?, updated_at = ? WHERE action_id = ?",args:[t,JSON.stringify(n),i,e]});let r=await y().execute({sql:"SELECT * FROM gmail_action_executions WHERE action_id = ? LIMIT 1",args:[e]});if(!r.rows[0])throw new S("action_not_found","Gmail action not found.",404);return xe(r.rows[0])}var rn="2026-08-27.1",Qn="9c82b270bb70e7795814cac408a41786ec70d4d7a4bb0f4a11bcc1b7fd02088b",H=2e4,an=10080*60*1e3,f=class extends Error{constructor(n,i,r=400,o=r===429||r>=500,a=null){super(i);this.code=n;this.status=r;this.retryable=o;this.retryAfterMs=a;this.name="GmailServiceError"}code;status;retryable;retryAfterMs};function v(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function h(e){return typeof e=="string"&&e.length>0?e:null}function q(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function J(e){if(!/^[A-Za-z0-9_-]*={0,2}$/.test(e))throw new f("gmail_invalid_base64","Gmail returned invalid encoded content.",502);let t=e.replace(/-/g,"+").replace(/_/g,"/");return Buffer.from(t.padEnd(Math.ceil(t.length/4)*4,"="),"base64")}function sn(e){return/^[\x20-\x7e]*$/.test(e)?e:`=?UTF-8?B?${Buffer.from(e,"utf8").toString("base64")}?=`}function cn(e,t,n){let i=Buffer.from(n,"utf8").toString("base64").match(/.{1,76}/g)?.join(`\r
54
- `)??"";return[`To: ${e}`,`Subject: ${sn(t)}`,"MIME-Version: 1.0","Content-Type: text/plain; charset=UTF-8","Content-Transfer-Encoding: base64","",i].join(`\r
55
- `)}function ft(e){let t=e.toString("latin1").replace(/=\r?\n/g,""),n=[];for(let i=0;i<t.length;i++)t[i]==="="&&/^[0-9A-Fa-f]{2}$/.test(t.slice(i+1,i+3))?(n.push(Number.parseInt(t.slice(i+1,i+3),16)),i+=2):n.push(t.charCodeAt(i)&255);return Buffer.from(n)}function Ae(e){return e.replace(/=\?([^?]+)\?([bq])\?([^?]+)\?=/gi,(t,n,i,r)=>{try{let o=i.toLowerCase()==="b"?Buffer.from(r,"base64"):ft(Buffer.from(r.replace(/_/g," "),"latin1"));return/^(?:utf-8|us-ascii)$/i.test(n)?o.toString("utf8"):o.toString("latin1")}catch{return r}})}function dn(e){return Array.isArray(e)?e.flatMap(t=>{let n=v(t),i=h(n?.name),r=h(n?.value);return!i||r===null?[]:[{name:i,value:Ae(r.replace(/\r?\n[ \t]+/g," "))}]}):[]}function E(e,t){return e.find(n=>n.name.toLowerCase()===t.toLowerCase())?.value??null}function z(e){return e?(e.match(/(?:"(?:[^"\\]|\\.)*"|[^,])+/g)??[]).flatMap(n=>{let i=n.trim(),r=i.match(/^(.*?)\s*<([^<>\s]+@[^<>\s]+)>$/),o=(r?.[2]??i).replace(/^mailto:/i,"").trim().toLowerCase();if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o))return[];let a=r?.[1]?.trim().replace(/^"|"$/g,"")||null;return[{name:a?Ae(a):null,email:o}]}):[]}function ln(e,t){let n=J(e),i=E(t,"content-transfer-encoding")?.toLowerCase();if(i==="quoted-printable")return ft(n);if(i==="base64"){let r=n.toString("ascii").replace(/\s/g,"");return/^[A-Za-z0-9+/]*={0,2}$/.test(r)?Buffer.from(r,"base64"):n}return n}function un(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(/<!doctype\b[^>]*>/gi,"").replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<(?:iframe|object|embed|svg|math)\b[^>]*>[\s\S]*?<\/(?:iframe|object|embed|svg|math)>/gi,"").replace(/<\/?(?:script|style|iframe|object|embed|svg|math|form|input|button|textarea|select|option|meta|link|base|img|audio|video|source|track)\b[^>]*>/gi,"").replace(/\son\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi,"").replace(/\s(?:href|src|srcset|action|formaction|poster|background|xlink:href)\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi,"").replace(/<[^>]*>/g," ").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\s+/g," ").trim()}function gt(){return Te("sha256").update(Ge()).update("\0gmail-ref-v1").digest()}function yt(e){let t=Buffer.from(JSON.stringify(e)).toString("base64url"),n=pt("sha256",gt()).update(t).digest("base64url");return`gref1.${t}.${n}`}function dt(e,t,n){let[i,r,o]=e.split(".");if(i!=="gref1"||!r||!o)throw new f("reference_not_found","Gmail reference not found.",404,!1);let a=pt("sha256",gt()).update(r).digest(),s;try{s=Buffer.from(o,"base64url")}catch{throw new f("reference_not_found","Gmail reference not found.",404,!1)}if(a.length!==s.length||!on(a,s))throw new f("reference_not_found","Gmail reference not found.",404,!1);let c;try{c=JSON.parse(Buffer.from(r,"base64url").toString("utf8"))}catch{throw new f("reference_not_found","Gmail reference not found.",404,!1)}if(c.ownerId!==t||c.kind!==n||typeof c.expiresAt!="number"||c.expiresAt<=Date.now())throw new f("reference_not_found","Gmail reference not found.",404,!1);return c}function mn(e){return yt({kind:"attachment",...e,expiresAt:Date.now()+an})}function ht(e){let t=dn(e.part.headers),n=v(e.part.body),i=h(e.part.mimeType)?.toLowerCase()??"application/octet-stream",r=Ae(h(e.part.filename)??""),o=h(e.part.partId)??e.path,a=h(n?.data),s=h(n?.attachmentId),c=E(t,"content-id")?.replace(/^<|>$/g,"")??null,d=/^inline\b/i.test(E(t,"content-disposition")??"")||!!c,l=i.startsWith("text/"),u=null,p=!0;l&&a?u=ln(a,t).toString("utf8"):l&&s&&(p=!1);let _=!!r||!!s||d&&!!a&&!l,I=null,M=q(n?.size)??(a?J(a).byteLength:0);if(_){let L=M;I=mn({ownerId:e.ownerId,connectionId:e.connectionId,messageId:e.messageId,partId:o,attachmentId:s,filename:r||`gmail-${e.messageId}-${o}`,mimeType:i,size:L}),e.attachments.push({filename:r||`gmail-${e.messageId}-${o}`,declaredMime:i,size:L,inline:d,contentId:c,partId:o,attachmentRef:I})}let It=Array.isArray(e.part.parts)?e.part.parts.map((L,bt)=>ht({...e,part:v(L)??{},path:`${e.path}.${bt+1}`})):[];return{partId:o,mimeType:i,filename:r,headers:t,size:M,inline:d,contentId:c,contentComplete:p,text:u,attachmentRef:I,parts:It}}function Ee(e,t){return[...e.mimeType===t&&e.text!==null?[e.text]:[],...e.parts.flatMap(i=>Ee(i,t))]}function lt(e){let t=v(e.payload),n=h(t?.id),i=v(t?.payload);if(!n||!i)throw new f("gmail_invalid_message","Gmail returned an invalid message.",502);let r=[],o=ht({part:i,ownerId:e.ownerId,connectionId:e.connectionId,messageId:n,path:"0",attachments:r}),a=o.headers,s=Ee(o,"text/plain").join(`
56
- `).trim()||null,c=Ee(o,"text/html").join(`
57
- `).trim()||null;return{messageId:n,threadId:h(t?.threadId),messageIdHeader:E(a,"message-id"),internalDate:h(t?.internalDate)?new Date(Number(t.internalDate)).toISOString():null,headers:a,from:z(E(a,"from")),to:z(E(a,"to")),cc:z(E(a,"cc")),bcc:z(E(a,"bcc")),replyTo:z(E(a,"reply-to")),subject:E(a,"subject"),labels:Array.isArray(t?.labelIds)?t.labelIds.filter(d=>typeof d=="string"):[],snippet:h(t?.snippet),plainText:s,sanitizedHtml:c?un(c):null,contentComplete:wt(o),providerSizeEstimate:q(t?.sizeEstimate),mime:o,attachments:r,provenance:{provider:"gmail",connectionId:e.connectionId,fetchedAt:(e.fetchedAt??new Date).toISOString(),format:"full"}}}function wt(e){return e.contentComplete&&e.parts.every(wt)}var ut=class{providerCall;createArtifact;createJsonlArtifact;constructor(t={}){this.providerCall=t.providerCall??Ye,this.createArtifact=t.createArtifact??Me,this.createJsonlArtifact=t.createJsonlArtifact??Pe}async sendMessage(t){let n=t.to.trim().toLowerCase(),i=t.subject.trim();if(!/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(n)||/[\r\n]/.test(t.to))throw new f("invalid_request","A valid recipient email address is required.");if(!i||i.length>500||/[\r\n]/.test(i))throw new f("invalid_request","A subject of at most 500 characters without line breaks is required.");if(!t.body||t.body.length>5e4)throw new f("invalid_request","A plain-text body of at most 50,000 characters is required.");if(t.idempotencyKey.length<8||t.idempotencyKey.length>200)throw new f("idempotency_key_invalid","Idempotency key must contain 8-200 characters.");let r=U({connectionId:t.connectionId,to:n,subject:i,bodySha256:Te("sha256").update(t.body).digest("hex")}),o=await ne({ownerId:t.ownerId,idempotencyKey:t.idempotencyKey,fingerprint:r});if(o.replay&&o.execution.result)return{...o.execution.result,replay:!0};if(o.replay)return{actionId:o.execution.actionId,status:"outcome_unknown",replay:!0,retryable:!1};let a=await B(o.execution.actionId,"send:0");if(!a.claimed)return{...a.receipt.result??{},actionId:o.execution.actionId,status:a.receipt.status,replay:!0};try{let s=v(await this.providerCall({identity:t.providerIdentity??t.ownerId,connectionId:t.connectionId,method:"POST",path:"/gmail/v1/users/me/messages/send",body:{raw:Buffer.from(cn(n,i,t.body),"utf8").toString("base64url")},requestId:t.idempotencyKey})),c={actionId:o.execution.actionId,status:"complete",messageId:h(s?.id),threadId:h(s?.threadId),replay:!1};return await N(o.execution.actionId,"send:0","complete",c),await F(o.execution.actionId,"complete",c),c}catch(s){let c={actionId:o.execution.actionId,status:"outcome_unknown",code:oe(s),retryable:!1};throw await N(o.execution.actionId,"send:0","failed",c),await F(o.execution.actionId,"partial",c),s}}async searchMessages(t){let n=t.query.trim();if(!n||n.length>2e3)throw new f("invalid_request","A Gmail query of at most 2,000 characters is required.");let i=t.limit??25;if(!Number.isInteger(i)||i<1||i>500)throw new f("invalid_request","Gmail search limit must be an integer from 1 to 500.");let r=i,o;if(t.cursor){let d=dt(t.cursor,t.ownerId,"search_cursor");if(d.connectionId!==t.connectionId||d.query!==n)throw new f("cursor_not_found","Gmail cursor not found.",404,!1);o=h(d.pageToken)??void 0}let a=v(await this.providerCall({identity:t.providerIdentity??t.ownerId,connectionId:t.connectionId,method:"GET",path:"/gmail/v1/users/me/messages",query:{q:n,maxResults:r,pageToken:o}})),s=Array.isArray(a?.messages)?a.messages.flatMap(d=>{let l=v(d),u=h(l?.id);return u?[{messageId:u,threadId:h(l?.threadId)}]:[]}):[],c=h(a?.nextPageToken);return{messages:s,estimatedMatches:q(a?.resultSizeEstimate),complete:!c,truncated:!!c,nextCursor:c?yt({kind:"search_cursor",ownerId:t.ownerId,connectionId:t.connectionId,query:n,pageToken:c,expiresAt:Date.now()+1440*60*1e3}):null}}async getMessage(t){let n=await this.getCompleteMessage(t),i=!!n.canonicalArtifact,r=n.plainText&&Buffer.byteLength(n.plainText)>H?`${Buffer.from(n.plainText).subarray(0,H).toString("utf8")}\u2026`:n.plainText;return{...n,plainText:r,contentComplete:n.contentComplete&&!i}}async getCompleteMessage(t){if(!/^[A-Za-z0-9_-]+$/.test(t.messageId))throw new f("invalid_request","A valid Gmail message ID is required.");let n=encodeURIComponent(t.messageId),i=t.providerIdentity??t.ownerId,r=await this.providerCall({identity:i,connectionId:t.connectionId,method:"GET",path:`/gmail/v1/users/me/messages/${n}`,query:{format:"full"}}),o=lt({ownerId:t.ownerId,connectionId:t.connectionId,payload:r}),a=null;if(t.includeRawArtifact!==!1){let l=v(await this.providerCall({identity:i,connectionId:t.connectionId,method:"GET",path:`/gmail/v1/users/me/messages/${n}`,query:{format:"raw"}})),u=h(l?.raw);if(!u)throw new f("gmail_raw_unavailable","Gmail did not return the raw message.",502);a=await this.createArtifact({ownerId:t.ownerId,exportId:`gmail-raw-${t.messageId}`,filename:`${t.messageId}.eml`,content:J(u),contentType:"message/rfc822"})}let s=JSON.stringify(o),d=Buffer.byteLength(s)>H||!o.contentComplete?await this.createArtifact({ownerId:t.ownerId,exportId:`gmail-message-${t.messageId}`,filename:`${t.messageId}.json`,content:s,contentType:"application/json"}):null;return{...o,rawArtifact:a,canonicalArtifact:d}}async getAttachment(t){let n=dt(t.attachmentRef,t.ownerId,"attachment"),i=h(n.connectionId),r=h(n.messageId);if(!i||!r)throw new f("reference_not_found","Gmail reference not found.",404,!1);let o,a=h(n.attachmentId);if(a){let _=v(await this.providerCall({identity:t.providerIdentity??t.ownerId,connectionId:i,method:"GET",path:`/gmail/v1/users/me/messages/${encodeURIComponent(r)}/attachments/${encodeURIComponent(a)}`})),I=h(_?.data);if(!I)throw new f("gmail_attachment_unavailable","Gmail did not return attachment bytes.",502);o=J(I);let M=q(_?.size);if(M!==null&&M!==o.byteLength)throw new f("gmail_attachment_size_mismatch","Gmail attachment bytes did not match the declared size.",502)}else{let _=v(await this.providerCall({identity:t.providerIdentity??t.ownerId,connectionId:i,method:"GET",path:`/gmail/v1/users/me/messages/${encodeURIComponent(r)}`,query:{format:"full"}})),I=_t(v(_?.payload),h(n.partId)??"");if(!I)throw new f("reference_not_found","Gmail reference not found.",404,!1);o=J(I)}let s=h(n.mimeType)??"application/octet-stream",c=q(n.size);if(c!==null&&c>0&&c!==o.byteLength)throw new f("gmail_attachment_size_mismatch","Gmail attachment bytes did not match the reviewed MIME part size.",502);let d=gn(o,s),l=h(n.filename)??`gmail-${r}.bin`,u=await this.createArtifact({ownerId:t.ownerId,exportId:`gmail-attachment-${r}`,filename:l,content:o,contentType:d}),p=d.startsWith("text/")||d==="application/json"?o.subarray(0,H).toString("utf8"):null;return{filename:l,declaredMime:s,observedMime:d,bytes:o.byteLength,sha256:Te("sha256").update(o).digest("hex"),contentComplete:p!==null?o.byteLength<=H:!0,text:p,artifact:u}}async prepareSelection(t){let n,i=null;if(t.source.kind==="message_ids"){if(!t.source.messageIds.length||t.source.messageIds.some(r=>typeof r!="string"||!/^[A-Za-z0-9_-]+$/.test(r.trim())))throw new f("invalid_request","Every explicit Gmail message ID must be valid.");n=[...new Set(t.source.messageIds.map(r=>r.trim()))];for(let r of n)try{await this.providerCall({identity:t.providerIdentity??t.ownerId,connectionId:t.connectionId,method:"GET",path:`/gmail/v1/users/me/messages/${encodeURIComponent(r)}`,query:{format:"metadata"}})}catch{throw new f("selection_message_not_found","One or more explicit Gmail message IDs do not exist in this connection.",404,!1)}}else{n=[];let r,o=null;do{let a=v(await this.providerCall({identity:t.providerIdentity??t.ownerId,connectionId:t.connectionId,method:"GET",path:"/gmail/v1/users/me/messages",query:{q:t.source.query.trim(),maxResults:500,pageToken:r}}));o===null&&(o=q(a?.resultSizeEstimate));for(let s of Array.isArray(a?.messages)?a.messages:[]){let c=h(v(s)?.id);c&&n.push(c)}if(new Set(n).size>5e3)throw new f("selection_too_large","Narrow the Gmail selection to at most 5,000 messages.");r=h(a?.nextPageToken)??void 0}while(r);if(t.exactRange){let a=Date.parse(t.exactRange.from),s=Date.parse(t.exactRange.to);if(!Number.isFinite(a)||!Number.isFinite(s)||a>=s)throw new f("invalid_request","exactRange.from must be before exactRange.to.");let c=[];for(let d of n){let l=await this.providerCall({identity:t.providerIdentity??t.ownerId,connectionId:t.connectionId,method:"GET",path:`/gmail/v1/users/me/messages/${encodeURIComponent(d)}`,query:{format:"full"}}),u=lt({ownerId:t.ownerId,connectionId:t.connectionId,payload:l}),p=u.internalDate?Date.parse(u.internalDate):Number.NaN;Number.isFinite(p)&&p>=a&&p<s&&c.push(d)}n=c}i={estimatedMatches:o,pagesComplete:!0,...t.exactRange?{exactRange:t.exactRange}:{}}}return at({ownerId:t.ownerId,connectionId:t.connectionId,source:t.source,purpose:t.purpose,resolvedMessageIds:n,providerSnapshot:i})}async exportSelection(t){let n=await ee(t);if(n.purpose!=="export"&&n.purpose!=="scheduled_export")throw new f("selection_purpose_mismatch","This Gmail selection was not prepared for export.",409,!1);te(n,t.expectedCount,t.selectionSha256);let i=U({selectionId:n.selectionId,selectionSha256:n.selectionSha256,expectedCount:n.count}),r=await st({ownerId:t.ownerId,selectionId:n.selectionId,fingerprint:i});if(r.replay)return{...r.replay,replay:!0};if(!r.claimed)throw new f("export_in_progress","This Gmail selection export is already running; retry shortly with the same receipt.",409,!0);let o=[];for(let u of n.messageIds)o.push(await this.getCompleteMessage({ownerId:t.ownerId,providerIdentity:t.providerIdentity,connectionId:t.connectionId,messageId:u}));let a=`gexp_${n.selectionSha256.slice(0,32)}`,s={version:rn,selectionId:n.selectionId,selectionSha256:n.selectionSha256,count:o.length},c=[JSON.stringify({type:"manifest",...s}),...o.map(u=>JSON.stringify({type:"message",message:u}))].join(`
58
- `)+`
59
- `,d=await this.createJsonlArtifact({ownerId:t.ownerId,exportId:a,filename:`gmail-${n.selectionId}.jsonl`,content:c,stableCreatedAt:n.createdAt,stableKey:i.slice(0,32)}),l={exportId:a,selectionId:n.selectionId,selectionSha256:n.selectionSha256,count:o.length,status:"complete",artifact:d,sampleMessages:o.slice(0,5).map(fn)};return await ct(t.ownerId,n.selectionId,l),l}async bulkManageSelection(t){let n=await ee(t);if(n.purpose!=="mailbox_action")throw new f("selection_purpose_mismatch","This Gmail selection was not prepared for mailbox actions.",409,!1);te(n,t.expectedCount,t.selectionSha256);let i=U({selectionSha256:n.selectionSha256,operation:t.operation}),r=await ne({ownerId:t.ownerId,idempotencyKey:t.idempotencyKey,fingerprint:i});if(r.replay&&r.execution.result)return r.execution.result;if(r.replay)return{actionId:r.execution.actionId,selectionId:n.selectionId,status:"running",changedCount:0,failedCount:0,failedChunks:[],retryable:!0};let o=[],a=0,s=pn(t.operation);if(s.mode==="batch"){s.validateIds.length&&await this.validateLabels(t.providerIdentity??t.ownerId,t.connectionId,s.validateIds);let d=mt(n.messageIds,1e3);for(let l=0;l<d.length;l++){await ie(r.execution.actionId);let u=`batch:${l}`,p=await B(r.execution.actionId,u);if(!p.claimed){p.receipt.status==="complete"?a+=Number(p.receipt.result?.changedCount??d[l].length):o.push({chunk:l,code:p.receipt.status==="failed"?String(p.receipt.result?.code??"provider_error"):"outcome_unknown"});continue}try{await this.providerCall({identity:t.providerIdentity??t.ownerId,connectionId:t.connectionId,method:"POST",path:"/gmail/v1/users/me/messages/batchModify",body:{ids:d[l],addLabelIds:s.addLabelIds,removeLabelIds:s.removeLabelIds},requestId:`${t.idempotencyKey}:${l}`}),a+=d[l].length,await N(r.execution.actionId,u,"complete",{changedCount:d[l].length})}catch(_){let I=oe(_);o.push({chunk:l,code:I}),await N(r.execution.actionId,u,"failed",{code:I})}}}else for(let d=0;d<n.messageIds.length;d++){await ie(r.execution.actionId);let l=`single:${d}`,u=await B(r.execution.actionId,l);if(!u.claimed){u.receipt.status==="complete"?a+=1:o.length<20&&o.push({chunk:d,code:u.receipt.status==="failed"?String(u.receipt.result?.code??"provider_error"):"outcome_unknown"});continue}try{await this.providerCall({identity:t.providerIdentity??t.ownerId,connectionId:t.connectionId,method:"POST",path:`/gmail/v1/users/me/messages/${encodeURIComponent(n.messageIds[d])}/${s.path}`,body:{},requestId:`${t.idempotencyKey}:${d}`}),a+=1,await N(r.execution.actionId,l,"complete",{changedCount:1})}catch(p){let _=oe(p);o.length<20&&o.push({chunk:d,code:_}),await N(r.execution.actionId,l,"failed",{code:_})}}let c={actionId:r.execution.actionId,selectionId:n.selectionId,status:o.length?"partial":"complete",changedCount:a,failedCount:n.count-a,failedChunks:o.slice(0,20)};return await F(r.execution.actionId,o.length?"partial":"complete",c),c}async permanentlyDeleteSelection(t){if(t.confirmPermanentDelete!==!0)throw new f("permanent_delete_confirmation_required","Set confirmPermanentDelete to true after explicit user confirmation.");let n=await ee(t);if(te(n,t.expectedCount,t.selectionSha256),n.purpose!=="mailbox_action")throw new f("selection_purpose_mismatch","This Gmail selection was not prepared for mailbox actions.",409,!1);let i=U({selectionSha256:n.selectionSha256,operation:"permanent_delete"}),r=await ne({ownerId:t.ownerId,idempotencyKey:t.idempotencyKey,fingerprint:i});if(r.replay&&r.execution.result)return r.execution.result;if(r.replay)return{actionId:r.execution.actionId,selectionId:n.selectionId,status:"running",submittedCount:0,failedCount:0,failedChunks:[],retryable:!0,providerGuarantee:"The original permanent-delete attempt is still being finalized; no provider chunk was replayed."};let o=[],a=0,s=mt(n.messageIds,1e3);for(let d=0;d<s.length;d++){await ie(r.execution.actionId);let l=`delete:${d}`,u=await B(r.execution.actionId,l);if(!u.claimed){u.receipt.status==="complete"?a+=Number(u.receipt.result?.submittedCount??s[d].length):o.push({chunk:d,code:u.receipt.status==="failed"?String(u.receipt.result?.code??"provider_error"):"outcome_unknown"});continue}try{await this.providerCall({identity:t.providerIdentity??t.ownerId,connectionId:t.connectionId,method:"POST",path:"/gmail/v1/users/me/messages/batchDelete",body:{ids:s[d]},requestId:`${t.idempotencyKey}:${d}`}),a+=s[d].length,await N(r.execution.actionId,l,"complete",{submittedCount:s[d].length})}catch(p){let _=oe(p);o.push({chunk:d,code:_}),await N(r.execution.actionId,l,"failed",{code:_})}}let c={actionId:r.execution.actionId,selectionId:n.selectionId,status:o.length?"partial":"complete",submittedCount:a,failedCount:n.count-a,failedChunks:o.slice(0,20),providerGuarantee:"Gmail accepts batch deletion but does not report whether every supplied message previously existed."};return await F(r.execution.actionId,o.length?"partial":"complete",c),c}async validateLabels(t,n,i){let r=v(await this.providerCall({identity:t,connectionId:n,method:"GET",path:"/gmail/v1/users/me/labels"})),o=new Set((Array.isArray(r?.labels)?r.labels:[]).map(s=>h(v(s)?.id)).filter(s=>!!s));if(i.filter(s=>!o.has(s)).length)throw new f("gmail_label_not_found","One or more Gmail label IDs were not found.",404,!1)}};function pn(e){if(e.kind==="trash")return{mode:"single",path:"trash"};if(e.kind==="restore")return{mode:"single",path:"untrash"};if(e.kind==="labels"){let n=[...new Set(e.addLabelIds??[])],i=[...new Set(e.removeLabelIds??[])];if(!n.length&&!i.length)throw new f("invalid_request","At least one label must be added or removed.");if(n.some(r=>i.includes(r)))throw new f("invalid_request","The same label cannot be added and removed.");return{mode:"batch",addLabelIds:n,removeLabelIds:i,validateIds:[...n,...i]}}return{mode:"batch",...{mark_read:{addLabelIds:[],removeLabelIds:["UNREAD"]},mark_unread:{addLabelIds:["UNREAD"],removeLabelIds:[]},archive:{addLabelIds:[],removeLabelIds:["INBOX"]},move_to_inbox:{addLabelIds:["INBOX"],removeLabelIds:[]}}[e.kind],validateIds:[]}}function mt(e,t){let n=[];for(let i=0;i<e.length;i+=t)n.push(e.slice(i,i+t));return n}function oe(e){return e&&typeof e=="object"&&typeof e.code=="string"?String(e.code):"provider_error"}function fn(e){return{messageId:e.messageId,threadId:e.threadId,internalDate:e.internalDate,from:e.from,to:e.to,subject:e.subject,snippet:e.snippet,labels:e.labels,attachmentCount:e.attachments.length}}function _t(e,t){if(!e)return null;if(h(e.partId)===t)return h(v(e.body)?.data);for(let n of Array.isArray(e.parts)?e.parts:[]){let i=_t(v(n),t);if(i!==null)return i}return null}function gn(e,t){if(e.subarray(0,5).toString("ascii")==="%PDF-")return"application/pdf";if(e.subarray(0,4).equals(Buffer.from([80,75,3,4])))return"application/zip";if(e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])))return"image/png";if(e.subarray(0,3).equals(Buffer.from([255,216,255])))return"image/jpeg";if(t.startsWith("text/"))try{return new TextDecoder("utf-8",{fatal:!0}).decode(e),t}catch{return"application/octet-stream"}if(t==="application/json")try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e)),t}catch{return"application/octet-stream"}return"application/octet-stream"}export{_n as a,Tt as b,Et as c,x as d,he as e,we as f,Tn as g,w as h,Q as i,ze as j,Gn as k,Dn as l,Un as m,qn as n,Ln as o,Kn as p,tt as q,$n as r,jn as s,S as t,U as u,ee as v,te as w,rn as x,Qn as y,H as z,an as A,f as B,z as C,lt as D,ut as E};