corsair 0.1.107 → 0.1.108

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.
@@ -1,4 +1,4 @@
1
- import { B as BrowserDeliveryPayload } from './index-CdzrawUJ.js';
1
+ import { B as BrowserDeliveryPayload } from './index-F_9QUwf4.js';
2
2
 
3
3
  /**
4
4
  * Browser (client) delivery — hub redirects the user's browser to the app with `?d=<token>`.
@@ -0,0 +1,38 @@
1
+ import{a as $r,b as de,c as jr,d as C,e as F,f as Wr,g as L,h as H,i as I,j as kn,k as Kr,l as qr,m as kt,n as Zr,o as Gr}from"./chunk-WDF3YE27.js";import{a as Nr}from"./chunk-IGGCNGU2.js";import{ZodBoolean as cu,ZodDate as lu,ZodEnum as du,ZodNullable as pu,ZodNumber as gu,ZodObject as fu,ZodOptional as yu,ZodRecord as mu,ZodString as hu,ZodType as bu}from"zod";var Cn=["agentql","ahrefs","airtable","algolia","amplitude","asana","bitwarden","bluesky","box","cal","calendly","cloudflare","confluence","cursor","datadog","deepseek","digitalocean","discord","dodopayments","dropbox","exa","figma","firecrawl","fireflies","gemini","github","gitlab","gmail","googlebigquery","googlecalendar","googledocs","googledrive","googlemeet","googlesheets","grafana","hackernews","heygen","hubspot","insightoai","instagram","intercom","jira","linear","linkedin","mailchimp","monday","neon","notion","ollama","onedrive","onepassword","openai","openweathermap","oura","outlook","pagerduty","perplexityai","posthog","razorpay","reddit","resend","retailed","sentry","sharepoint","slack","spotify","strava","stripe","supabase","tally","tavily","teams","telegram","todoist","trello","twilio","twitter","twitterapiio","typeform","vapi","whatsapp","vercel","xquik","youtube","zendesk","zohomail","zoom"],Jr={agentql:"AgentQL",ahrefs:"Ahrefs",airtable:"Airtable",algolia:"Algolia",amplitude:"Amplitude",asana:"Asana",bitwarden:"Bitwarden",bluesky:"Bluesky",box:"Box",cal:"Cal",calendly:"Calendly",cloudflare:"Cloudflare",confluence:"Confluence",cursor:"Cursor",datadog:"Datadog",deepseek:"DeepSeek",digitalocean:"DigitalOcean",discord:"Discord",dodopayments:"Dodo Payments",dropbox:"Dropbox",exa:"Exa",figma:"Figma",firecrawl:"Firecrawl",fireflies:"Fireflies",gemini:"Gemini",github:"GitHub",gitlab:"GitLab",gmail:"Gmail",googlebigquery:"Google BigQuery",googlecalendar:"Google Calendar",googledocs:"Google Docs",googledrive:"Google Drive",googlemeet:"Google Meet",googlesheets:"Google Sheets",grafana:"Grafana",hackernews:"Hacker News",heygen:"HeyGen",hubspot:"HubSpot",insightoai:"Insighto.ai",instagram:"Instagram",intercom:"Intercom",jira:"Jira",linear:"Linear",linkedin:"LinkedIn",mailchimp:"Mailchimp",monday:"Monday",neon:"Neon",notion:"Notion",ollama:"Ollama",onedrive:"OneDrive",onepassword:"1Password",openai:"OpenAI",openweathermap:"OpenWeatherMap",oura:"Oura",outlook:"Outlook",pagerduty:"PagerDuty",perplexityai:"Perplexity AI",posthog:"PostHog",razorpay:"Razorpay",reddit:"Reddit",resend:"Resend",retailed:"Retailed",sentry:"Sentry",sharepoint:"SharePoint",slack:"Slack",spotify:"Spotify",strava:"Strava",stripe:"Stripe",supabase:"Supabase",tally:"Tally",tavily:"Tavily",teams:"Teams",telegram:"Telegram",todoist:"Todoist",trello:"Trello",twilio:"Twilio",twitter:"Twitter",twitterapiio:"Twitter API IO",typeform:"Typeform",vapi:"Vapi",whatsapp:"WhatsApp",vercel:"Vercel",xquik:"XQuik",youtube:"YouTube",zendesk:"Zendesk",zohomail:"Zoho Mail",zoom:"Zoom"};function pe(e){let n=Jr[e];return n||e.charAt(0).toUpperCase()+e.slice(1)}import{randomUUID as Zi}from"crypto";var Ni="corsair:client-bridge";function Ct(e){return new URL(e).origin}function De(e){let n=JSON.stringify({type:Ni,requestId:e.requestId,ok:e.ok,body:e.body??null,error:e.error??null}),t=JSON.stringify(Ct(e.hubOrigin));return`<!DOCTYPE html><html><head><meta charset="utf-8"></head><body><script>
2
+ (function () {
3
+ var message = ${n};
4
+ var targetOrigin = ${t};
5
+ if (window.parent && window.parent !== window) {
6
+ window.parent.postMessage(message, targetOrigin);
7
+ }
8
+ })();
9
+ </script></body></html>`}var $i=new Set(["localhost","127.0.0.1","[::1]","::1"]);function wt(e){try{let{hostname:n,protocol:t}=new URL(e);return t!=="http:"&&t!=="https:"?!1:$i.has(n)}catch{return!1}}function Qe(e){return e==="development"?"browser":"server"}function zr(e){return Qe(e)==="browser"}function Vr(e){return wt(e)?"Production delivery URL must be a public URL, not localhost":null}import{randomBytes as qi}from"crypto";var Yr=new Set(["oauth.callback","oauth.tokens","webhook","permission.approve","permission.deny","auth.credentials","integration.credentials","connect.create_link","connections.sync"]),ge=60*1e3,Pe=300*1e3;import{createHmac as ji,randomBytes as Wi,timingSafeEqual as Ki}from"crypto";function oe(){return Wi(16).toString("base64url")}function Xe(e,n){let t=n.trim();if(!t)throw new Error("Signing secret is required");return ji("sha256",t).update(e).digest("base64url")}function X(e,n){let t=n.trim();if(!t)return null;let r=e.split(".");if(r.length!==2)return null;let[o,i]=r;if(!o||!i)return null;let s=Xe(o,t);try{if(!Ki(Buffer.from(i,"utf8"),Buffer.from(s,"utf8")))return null}catch{return null}let a;try{a=JSON.parse(Buffer.from(o,"base64url").toString("utf8"))}catch{return null}return a.exp*1e3<Date.now()?null:a}function wn(e,n,t){let r=Math.floor(Date.now()/1e3),o={...e,iat:r,exp:t},i=Buffer.from(JSON.stringify(o)).toString("base64url"),s=Xe(i,n);return`${i}.${s}`}function en(e,n,t){let r=Math.floor(Date.now()/1e3);return wn(e,n,r+Math.floor(t/1e3))}function Ae(e){return decodeURIComponent(e)}function vt(e){return encodeURIComponent(e).replace(/\./g,"%2E")}function Qr(e){let n=e.trim();return n.length>0?n:null}function Oe(e,n){let t=new URL(e);return t.searchParams.set("d",n),t.toString()}function Me(e,n){if(!Qr(n))throw new Error("Signing secret is required for browser delivery tokens");let t=Math.floor(Date.now()/1e3),r={...e,jti:e.jti??qi(16).toString("base64url"),iat:t,exp:t+Math.floor(ge/1e3)},o=Buffer.from(JSON.stringify(r)).toString("base64url"),i=Xe(o,n);return`${o}.${i}`}function fe(e,n){return Qr(n)?X(e,n):null}function Gi(e){let n=Ct(e.hubOrigin),t={connectJti:e.requestId,projectId:e.projectId,hubSuccessUrl:e.hubOrigin,deliveryMode:e.deliveryMode,hubOrigin:n,requestId:e.requestId};switch(e.deliveryMode){case"connections.sync":return{...t,plugin:"connections.sync",tenantId:"*"};case"connect.create_link":return{...t,plugin:"connect.create_link",tenantId:e.tenantId,connectLinkPlugins:e.plugins}}}function Tt(e){let n=Me(Gi(e),e.signingSecret);return Oe(e.deliveryUrl,n)}function Xr(e){if(Qe(e.environmentSlug)==="server")return{transport:"server"};if(!e.hubOrigin)throw new Error(`hubOrigin is required for development ${e.deliveryMode} delivery`);let t=Zi(),r={...e,hubOrigin:e.hubOrigin,requestId:t};return{transport:"browser",requestId:t,deliveryUrl:Tt(r)}}var nn="https://auth.corsair.dev";var ie=class extends Error{constructor(){super("Hub is not configured. Pass hub: { projectApiKey, signingSecret } to createCorsair()."),this.name="HubNotConfiguredError"}};function vn(e){let n=(e.apiUrl?.trim()||nn).replace(/\/$/,""),t=e.projectApiKey.trim(),r=e.signingSecret.trim();if(!t||!r)throw new Error("Hub config requires non-empty projectApiKey and signingSecret");return{apiUrl:n,projectApiKey:t,signingSecret:r,oauthCallbackUrl:e.oauthCallbackUrl?.trim().replace(/\/$/,"")}}function Ji(e){return e.apiUrl.trim().length>0&&e.projectApiKey.trim().length>0&&e.signingSecret.trim().length>0}function M(e){let n=C(e).hub;if(!n||!Ji(n))throw new ie;return n}function eo(e){return e.replace(/\/$/,"")}function Tn(e){return e.oauthCallbackUrl?eo(e.oauthCallbackUrl.trim()):`${eo(e.apiUrl)}/oauth/callback`}function He(e){if(e.startsWith("ck_dev_"))return"development";if(e.startsWith("ck_prod_"))return"production";throw new Error("Hub API key must start with ck_dev_ (development) or ck_prod_ (production)")}function A(e){return typeof e=="string"&&e.length>0}function zi(e){return e==="ready"||e==="partial"||e==="not_started"||e==="missing_integration"}function Vi(e){return e==="oauth_2"||e==="api_key"||e==="bot_token"||e==="managed"}function Pn(e){if(!e||typeof e!="object")throw new Error("Hub API returned an empty connect session");let n=e;if(!A(n.connectUrl)||!A(n.token)||!A(n.projectId))throw new Error("Hub API returned an incomplete connect session (expected connectUrl, token, and projectId)");let t={connectUrl:n.connectUrl,token:n.token,projectId:n.projectId,environmentId:A(n.environmentId)?n.environmentId:n.projectId};return A(n.expiresAt)&&(t.expiresAt=n.expiresAt),t}function An(e){if(!Array.isArray(e))throw new Error("Hub API returned an invalid connections response (expected array)");let n=[];for(let t of e){if(!t||typeof t!="object")continue;let r=t;if(!A(r.tenantId)||!A(r.plugin)||!zi(r.status)||!Vi(r.authType)||typeof r.connected!="boolean"||typeof r.verified!="boolean")continue;let o=Array.isArray(r.missingFields)?r.missingFields.filter(i=>typeof i=="string"):[];n.push({tenantId:r.tenantId,plugin:r.plugin,status:r.status,authType:r.authType,connected:r.connected,verified:r.verified,missingFields:o,reportedAt:A(r.reportedAt)?r.reportedAt:new Date().toISOString()})}return n}function xn(e){if(!e||typeof e!="object")throw new Error("Hub API returned an empty permission session");let n=e;if(!A(n.approvalUrl)||!A(n.token)||!A(n.projectId)||!A(n.expiresAt))throw new Error("Hub API returned an incomplete permission session (expected approvalUrl, token, projectId, and expiresAt)");return{approvalUrl:n.approvalUrl,token:n.token,projectId:n.projectId,expiresAt:n.expiresAt}}function In(e){if(!e||typeof e!="object")throw new Error("Hub token refresh returned an empty response");let n=e;if(A(n.access_token))return{access_token:n.access_token,refresh_token:A(n.refresh_token)?n.refresh_token:void 0,expires_in:(()=>{if(typeof n.expires_in=="number")return n.expires_in;if(typeof n.expires_in=="string"&&n.expires_in.trim().length>0){let t=Number(n.expires_in);return Number.isFinite(t)?t:void 0}})(),scope:A(n.scope)?n.scope:void 0};throw new Error(A(n.error)?A(n.error_description)?n.error_description:n.error:"Hub token refresh returned no access_token")}function Yi(e){return Array.isArray(e)?e.filter(n=>typeof n=="string"):[]}function Qi(e){if(!Array.isArray(e))return[];let n=[];for(let t of e){if(!t||typeof t!="object")continue;let r=t;A(r.name)&&n.push({name:r.name,level:r.level==="integration"||r.level==="account"?r.level:"account",required:r.required===!0,configured:r.configured===!0})}return n}function Xi(e,n,t,r){return e==="ready"||e==="partial"||e==="not_started"||e==="missing_integration"?e:n?"ready":t.some(i=>i.level==="integration"&&i.required&&!i.configured)?"missing_integration":t.some(i=>i.level==="account"&&i.required&&i.configured)?"partial":(r.length>0,"not_started")}function no(e){if(!e||typeof e!="object")throw new Error("Connect status response was empty");let n=e;if(!A(n.tenantId)||!Array.isArray(n.plugins))throw new Error("Connect status response was incomplete (expected tenantId and plugins)");let t=[];for(let r of n.plugins){if(!r||typeof r!="object")continue;let o=r;if(!A(o.plugin)||typeof o.connected!="boolean")continue;let i=o.authKind==="oauth"||o.authKind==="api_key"||o.authKind==="bot_token"?o.authKind:"api_key",s=Qi(o.fields),a=Yi(o.missingRequiredFields),u=Xi(o.status,o.connected,s,a);t.push({plugin:o.plugin,providerName:A(o.providerName)?o.providerName:o.plugin,authKind:i,status:u,connected:o.connected,fields:s,missingRequiredFields:a})}return{tenantId:n.tenantId,plugins:t}}function Sn(e){if(!e||typeof e!="object")return null;let n=e;return n.error??n.message??null}var es="3000",ns="/api/corsair";function ts(e){return e.replace(/\/$/,"")}function ye(e){let n=e?.deliveryUrl?.trim()||process.env.CORSAIR_DELIVERY_URL?.trim();if(n){let r=/^https?:\/\//i.test(n)?n:`https://${n}`;return ts(r)}return`http://localhost:${process.env.PORT?.trim()||es}${ns}`}function to(e){return e.replace(/\/$/,"")}function Pt(e){if(!e.projectApiKey.startsWith("ck_dev_"))return null;try{return ye()}catch{return null}}function ro(e){let n=Pt(e);return n?{"x-corsair-delivery-url":n}:{}}async function oo(e){let n=e.headers.get("content-type")??"",t=await e.text();if(!t)return null;if(!n.includes("application/json")&&t.trimStart().startsWith("<"))throw new Error(`Hub API returned HTML instead of JSON (HTTP ${e.status}). Check HUB_API_URL and deploy the latest hub API.`);try{return JSON.parse(t)}catch{throw new Error(`Hub API returned invalid JSON (HTTP ${e.status})`)}}function io(e,n,t){if(n===404&&t)return t;let r=Sn(e);return r||`Hub API returned HTTP ${n}`}async function N(e){let n=to(e.hub.apiUrl),t=await fetch(`${n}${e.path}`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.hub.projectApiKey}`,...ro(e.hub)},body:JSON.stringify(e.body)}),r=await oo(t);if(!t.ok)throw new Error(io(r,t.status,e.notFoundMessage));return e.parseResponse(r)}async function Rn(e){let n=to(e.hub.apiUrl),t=await fetch(`${n}${e.path}`,{method:"GET",headers:{authorization:`Bearer ${e.hub.projectApiKey}`,...ro(e.hub)}}),r=await oo(t);if(!t.ok)throw new Error(io(r,t.status,e.notFoundMessage));return e.parseResponse(r)}import{createCipheriv as so,createDecipheriv as ao,randomBytes as En,scrypt as rs}from"crypto";import{promisify as os}from"util";var uo=os(rs),_n="aes-256-gcm",co=12,Dn=16,is=16,tn=32;function se(){return En(tn).toString("base64")}async function ae(e,n){let t=En(is),r=await uo(n,t,tn),o=En(co),i=so(_n,r,o,{authTagLength:Dn}),s=Buffer.concat([i.update(e,"utf8"),i.final()]),a=i.getAuthTag();return[t.toString("base64"),o.toString("base64"),a.toString("base64"),s.toString("base64")].join(":")}async function q(e,n){let[t,r,o,i]=e.split(":");if(!t||!r||!o||!i)throw new Error("Invalid encrypted DEK format");let s=Buffer.from(t,"base64"),a=Buffer.from(r,"base64"),u=Buffer.from(o,"base64"),l=Buffer.from(i,"base64"),c=await uo(n,s,tn),p=ao(_n,c,a,{authTagLength:Dn});return p.setAuthTag(u),Buffer.concat([p.update(l),p.final()]).toString("utf8")}function At(e,n){let t=Buffer.from(n,"base64"),r=En(co),o=so(_n,t,r,{authTagLength:Dn}),i=Buffer.concat([o.update(e,"utf8"),o.final()]),s=o.getAuthTag();return[r.toString("base64"),s.toString("base64"),i.toString("base64")].join(":")}function rn(e,n){let[t,r,o]=e.split(":");if(!t||!r||!o)throw new Error("Invalid encrypted data format");let i=Buffer.from(n,"base64"),s=Buffer.from(t,"base64"),a=Buffer.from(r,"base64"),u=Buffer.from(o,"base64"),l=ao(_n,i,s,{authTagLength:Dn});return l.setAuthTag(a),Buffer.concat([l.update(u),l.final()]).toString("utf8")}function me(e,n){let t={};for(let[r,o]of Object.entries(e))t[r]=At(o,n);return t}function ue(e,n){let t={};for(let[r,o]of Object.entries(e))t[r]=rn(o,n);return t}function on(e,n,t){let r=ue(e,n);return me(r,t)}function lo(e,n,t){let r={};for(let o of t)r[`get_${o}`]=async()=>(await e())[o]??null,r[`set_${o}`]=async i=>{let s=[null,void 0,""].includes(i)?null:i;await n({[o]:s})};return r}var xt=e=>{if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return e};function D(e){let{authType:n,integrationName:t,kek:r,database:o,extraIntegrationFields:i=[]}=e,s=[...H[n].integration,...i],a=null,u={kek:r,integrationName:t,getIntegration:async()=>{if(a)return a;let m=await o.db.selectFrom("corsair_integrations").selectAll().where("name","=",t).executeTakeFirst();if(!m)throw new Error(`Integration "${t}" not found. Make sure to create the integration first.`);return a={id:m.id,config:xt(m.config),dek:m.dek??null},a},updateIntegration:async m=>{let h=await u.getIntegration();await o.db.updateTable("corsair_integrations").set({...m.config!==void 0?{config:m.config}:{},...m.dek!==void 0?{dek:m.dek}:{},updated_at:new Date}).where("id","=",h.id).execute(),a=null}},l=null,c=async()=>{if(l)return l;let m=await u.getIntegration();if(!m.dek)throw new Error(`No DEK found for integration "${t}". Initialize the integration first.`);return l=await q(m.dek,r),l},p=async()=>{let m=await u.getIntegration(),h=await c(),k=m.config;return!k||Object.keys(k).length===0?{}:ue(k,h)},g=Promise.resolve(),d=m=>{let h=g.then(()=>y(m));return g=h.catch(()=>{}),h},y=async m=>{let h=await c(),k;try{k=await p()}catch(x){console.error(`[corsair] Failed to decrypt config for integration "${t}", starting fresh:`,x),k={}}let w={...k};for(let[x,E]of Object.entries(m))E===null?delete w[x]:w[x]=E;let R=me(w,h);await u.updateIntegration({config:R})};return{get_dek:c,issue_new_dek:async()=>{let m=await u.getIntegration(),h=se(),k={};if(m.dek){let R=await q(m.dek,r),x=m.config;x&&Object.keys(x).length>0&&(k=on(x,R,h))}let w=await ae(h,r);return await u.updateIntegration({config:k,dek:w}),l=h,h},...lo(p,d,s)}}function _(e){let{authType:n,integrationName:t,tenantId:r,kek:o,database:i,extraAccountFields:s=[],ensureProvisioned:a}=e,u=[...H[n].account,...s],l=null,c=null,p=async()=>{if(c)return c;let b=!1;for(;;){let v=await i.db.selectFrom("corsair_integrations").selectAll().where("name","=",t).executeTakeFirst();if(!v){if(!b&&a){b=!0,await a();continue}throw new Error(`Integration "${t}" not found. Make sure to create the integration first.`)}return c={id:v.id,config:xt(v.config),dek:v.dek??null},c}},g={kek:o,integrationName:t,tenantId:r,getIntegration:p,getAccount:async()=>{if(l)return l;let b=!1;for(;;){let v=await p(),T=await i.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",r).where("integration_id","=",v.id).executeTakeFirst();if(!T){if(!b&&a){b=!0,await a();continue}throw new Error(`Account not found for tenant "${r}" and integration "${t}". Make sure to create the account first.`)}return l={id:T.id,config:xt(T.config),dek:T.dek??null},l}},updateAccount:async b=>{let v=await g.getAccount();await i.db.updateTable("corsair_accounts").set({...b.config!==void 0?{config:b.config}:{},...b.dek!==void 0?{dek:b.dek}:{},updated_at:new Date}).where("id","=",v.id).execute(),l=null}},d=null,y=null,f=async()=>{if(d)return d;let b=await g.getAccount();if(!b.dek)throw new Error(`No DEK found for account (tenant: "${r}", integration: "${t}"). Initialize the account first.`);return d=await q(b.dek,o),d},m=async()=>{if(y)return y;let b=await g.getIntegration();if(!b.dek)throw new Error(`No DEK found for integration "${t}". Initialize the integration first.`);return y=await q(b.dek,o),y},h=async()=>{let b=await g.getAccount(),v=await f(),T=b.config;return!T||Object.keys(T).length===0?{}:ue(T,v)},k=async()=>{let b=await g.getIntegration(),v=await m(),T=b.config;return!T||Object.keys(T).length===0?{}:ue(T,v)},w=Promise.resolve(),R=b=>{let v=w.then(()=>x(b));return w=v.catch(()=>{}),v},x=async b=>{let v=await f(),T;try{T=await h()}catch(P){console.error(`[corsair] Failed to decrypt config for account (tenant: "${r}", integration: "${t}"), starting fresh:`,P),T={}}let j={...T};for(let[P,V]of Object.entries(b))V===null?delete j[P]:j[P]=V;let te=me(j,v);await g.updateAccount({config:te})},E={get_dek:f,issue_new_dek:async()=>{let b=await g.getAccount(),v=se(),T={};if(b.dek){let te=await q(b.dek,o),P=b.config;P&&Object.keys(P).length>0&&(T=on(P,te,v))}let j=await ae(v,o);return await g.updateAccount({config:T,dek:j}),d=v,v},...lo(h,R,u)};return n==="oauth_2"&&(E.get_integration_credentials=async()=>{let b=await k();return{...b,client_id:b.client_id||null,client_secret:b.client_secret||null,redirect_url:b.redirect_url??null}}),E}async function po(e,n,t){let r=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!r)throw new Error(`Integration "${n}" not found.`);let o=se(),i=await ae(o,t);return await e.db.updateTable("corsair_integrations").set({dek:i,updated_at:new Date}).where("id","=",r.id).execute(),o}async function go(e,n,t,r){let o=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!o)throw new Error(`Integration "${n}" not found.`);let i=await e.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",t).where("integration_id","=",o.id).executeTakeFirst();if(!i)throw new Error(`Account not found for tenant "${t}" and integration "${n}".`);let s=se(),a=await ae(s,r);return await e.db.updateTable("corsair_accounts").set({dek:a,updated_at:new Date}).where("id","=",i.id).execute(),s}var ss=new Set(["webhook_signature","expires_at","scope","redirect_url"]);function he(e){return ss.has(e)}function as(e,n){return he(n)?!1:e==="oauth_2"?n==="client_id"||n==="client_secret":!0}function us(e){return!he(e)}function cs(e){switch(e){case"oauth_2":case"managed":return["access_token","refresh_token"];case"api_key":return["api_key"];case"bot_token":return["bot_token"]}}function ls(e,n){return cs(e).every(r=>n.find(i=>i.level==="account"&&i.name===r)?.configured??!1)}async function fo(e,n){if(!e)return!1;let t=L(e,`get_${n}`);if(!t)return!1;try{let r=await t();return typeof r=="string"&&r.length>0}catch{return!1}}function ds(e,n){let r=e.authConfig?.[n]?.integration??[];return[...H[n].integration,...r]}function ps(e,n){let r=e.authConfig?.[n]?.account??[];return[...H[n].account,...r]}function gs(e,n,t){let r=t.filter(a=>a.required&&!a.configured).map(a=>a.name),o=t.filter(a=>a.level==="integration"&&a.required&&!a.configured).map(a=>a.name),i=t.filter(a=>a.level==="account"&&a.required&&a.configured),s;return o.length>0?s="missing_integration":r.length===0?s="ready":i.length>0?s="partial":s="not_started",{plugin:e,authType:n,status:s,connected:ls(n,t),fields:t,missingRequiredFields:r}}async function xe(e,n,t){let r=I(n);if(!r||!e.database||!e.kek)return null;let o=t.trim()||"default",i=n.authConfig,s=i?.[r]?.integration??[],a=i?.[r]?.account??[],u=D({authType:r,integrationName:n.id,kek:e.kek,database:e.database,extraIntegrationFields:s}),l=_({authType:r,integrationName:n.id,tenantId:o,kek:e.kek,database:e.database,extraAccountFields:a}),c=ds(n,r),p=ps(n,r),g=[];for(let d of c)g.push({name:d,level:"integration",required:as(r,d),configured:await fo(u,d)});for(let d of p)g.push({name:d,level:"account",required:us(d),configured:await fo(l,d)});return gs(n.id,r,g)}async function sn(e,n,t={}){let r=n.trim()||"default",o=t.pluginIds?.length?new Set(t.pluginIds):null,i=[];for(let s of e.plugins){if(o&&!o.has(s.id))continue;let a=await xe(e,s,r);a&&i.push(a)}return i}function On(e){return e.connected?"connected":e.status==="missing_integration"?"missing_credentials":"not_connected"}var yo=Symbol.for("corsair:internal"),mo=new WeakMap,ho=new WeakMap;function fs(e,n){let t=n.map(r=>r.id).sort().join("\0");return`${e}\0${t}`}function ys(e){if(e.database){let t=mo.get(e.database);return t||(t=new Map,mo.set(e.database,t)),t}let n=ho.get(e);return n||(n=new Map,ho.set(e,n)),n}function ms(e){return e.multiTenancy?{withTenant:()=>({}),[yo]:e}:{[yo]:e}}async function Fe(e,n){if(!e.database)return;let t=n.trim()||"default",r=ys(e),o=fs(t,e.plugins),i=r.get(o);if(i){await i;return}let s=(async()=>{let{setupCorsair:a}=await import("./setup-U5CPTDCM.js");await a(ms(e),{tenantId:e.multiTenancy?t:void 0,silent:!0})})().finally(()=>{r.delete(o)});r.set(o,s),await s}import*as an from"crypto";function be(e,n){return Buffer.from(JSON.stringify({plugin:e,tenantId:n,iat:Date.now()})).toString("base64url")}function It(e,{maxAgeMs:n}={}){try{let t=e.includes(".")?e.split(".")[0]:e,r=JSON.parse(Buffer.from(t,"base64url").toString("utf-8"));if(r!==null&&typeof r=="object"&&"plugin"in r&&"tenantId"in r&&typeof r.plugin=="string"&&typeof r.tenantId=="string"){let o=r;return n!==void 0&&typeof o.iat=="number"&&Date.now()-o.iat>n?null:o}return null}catch{return null}}function Be(e,n){let t=an.createHmac("sha256",n).update(e).digest("base64url");return`${e}.${t}`}var St=600*1e3;function Mn(e,n){let t=e.lastIndexOf(".");if(t===-1)return null;let r=e.slice(0,t),o=e.slice(t+1),i=an.createHmac("sha256",n).update(r).digest("base64url"),s=Buffer.from(o,"base64url"),a=Buffer.from(i,"base64url");return s.length!==a.length||!an.timingSafeEqual(s,a)?null:It(r,{maxAgeMs:St})}function bo(e){return{tenantId:e.tenantId,plugin:e.plugin,authType:e.authType??"oauth_2",status:"ready",connected:!0,verified:!0,webhookLink:e.link}}function ko(e){return{tenantId:e.tenantId,plugin:e.plugin,authType:e.authType,status:e.status,connected:e.connected,verified:e.verified,missingFields:e.missingFields,webhookLink:e.webhookLink,webhookSecret:e.webhookSecret}}async function Ue(e,n){await N({hub:e,path:"/connections/report",body:bo(n),parseResponse:()=>({ok:!0})}).catch(()=>{})}function hs(e,n){try{let t=M(e);N({hub:t,path:"/connections/report",body:n,parseResponse:()=>({ok:!0})}).catch(()=>{})}catch(t){if(t instanceof ie)return}}async function bs(e){if(!e.hub||!e.database||!e.kek)return;let n={database:e.database,kek:e.kek,plugins:e.plugins};if(!I(e.plugin))return;let r=e.tenantId?.trim()||"default",o=await xe(n,e.plugin,r);o&&wo(e.hub,ko({tenantId:r,plugin:e.plugin.id,authType:o.authType,status:o.status,connected:o.connected,verified:e.verified??o.connected,missingFields:o.missingRequiredFields}))}function Co(e,n){hs(e,n)}function wo(e,n){N({hub:e,path:"/connections/report",body:n,parseResponse:()=>({ok:!0})}).catch(()=>{})}function un(e){bs(e).catch(()=>{})}async function Rt(e,n){let t=C(e);if(!I(n.plugin))return;let o=await xe(t,n.plugin,n.tenantId);o&&Co(e,ko({tenantId:n.tenantId.trim()||"default",plugin:n.plugin.id,authType:o.authType,status:o.status,connected:o.connected,verified:n.verified??o.connected,missingFields:o.missingRequiredFields,webhookLink:n.webhookLink,webhookSecret:n.webhookSecret}))}async function Hn(e,n,t){for(let r of e){if(r.id!==n)continue;let o=r.oauthWebhookTenantLinkResolver;return o?o(t):null}return null}var vo=e=>{if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return e};async function ks(e){let n=await e.database.db.selectFrom("corsair_integrations").selectAll().where("name","=",e.pluginId).executeTakeFirst();if(!n)throw new Error(`Integration '${e.pluginId}' not found. Run setupCorsair before registering webhook tenant links.`);let t=await e.database.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",e.tenantId).where("integration_id","=",n.id).executeTakeFirst();if(!t)throw new Error(`Account not found for tenant '${e.tenantId}' and integration '${e.pluginId}'.`);return{integrationId:n.id,accountId:t.id}}async function Cs(e){let n=await e.database.db.selectFrom("corsair_accounts").selectAll().where("id","=",e.accountId).executeTakeFirst();if(!n?.dek)throw new Error(`Account '${e.accountId}' has no DEK.`);let t=await q(n.dek,e.kek),r=vo(n.config),o={};Object.keys(r).length>0&&(o=ue(r,t)),o[e.link.linkType]=e.link.externalId;let i=me(o,t);await e.database.db.updateTable("corsair_accounts").set({config:i,updated_at:new Date}).where("id","=",n.id).execute()}async function Le(e){let{database:n,kek:t,pluginId:r,tenantId:o,link:i,authType:s,extraAccountFields:a=[]}=e,{accountId:u}=await ks({database:n,pluginId:r,tenantId:o}),l=!1;if(s){let c=_({authType:s,integrationName:r,tenantId:o,kek:t,database:n,extraAccountFields:a}),p=`set_${i.linkType}`,g=c[p];typeof g=="function"&&(await g(i.externalId),l=!0)}l||await Cs({database:n,kek:t,accountId:u,link:i})}async function Et(e){let{database:n,kek:t,pluginId:r,linkType:o,externalId:i}=e,s=await n.db.selectFrom("corsair_accounts as accounts").innerJoin("corsair_integrations as integrations","integrations.id","accounts.integration_id").selectAll("accounts").where("integrations.name","=",r).execute();for(let a of s)if(a.dek)try{let u=await q(a.dek,t),c=vo(a.config)[o];if(!c)continue;if(rn(c,u)===i)return a}catch{continue}return null}async function Fn(e){return(await Et(e))?.tenant_id??null}async function To(e){return Fn({database:e.database,kek:e.kek,pluginId:e.pluginId,linkType:e.match.linkType,externalId:e.match.externalId})}import*as Po from"querystring";function Ie(e){let{oauthConfig:n,clientId:t,redirectUri:r,state:o}=e,i={...n.authParams,client_id:t,redirect_uri:r,response_type:"code",scope:n.scopes.join(" "),state:o};return`${n.authUrl}?${Po.stringify(i)}`}async function Ao(e,n){try{return await Rn({hub:e,path:`/webhooks/endpoint?plugin=${encodeURIComponent(n)}`,parseResponse:t=>t?.url??null})}catch{return null}}async function Bn(e,n,t,r){if(!n.subscribe)return;let o=M(e),i=await Ao(o,n.id);if(!i)return;let s=await n.subscribe({keys:r},{webhookUrl:i});s&&await Rt(e,{plugin:n,tenantId:t,verified:!0,webhookLink:s.webhookLink,webhookSecret:s.webhookSecret})}var B=class extends Error{code;constructor(n,t){super(t),this.name="OAuthCallbackError",this.code=n}};function xo(e){let n=e.oauthConfig;if(!n)throw new B("plugin_has_no_oauth_config",`Plugin '${e.id}' has no oauthConfig`);return n}async function ws(e,n,t,r){let o=Gr(e),i=await o.integrations.findByName(n);if(!i)throw new Error(`Integration '${n}' not found. Run setupCorsair first.`);if(await o.accounts.findOne({tenant_id:t,integration_id:i.id}))return;let a=se(),u=await ae(a,r);await o.accounts.create({tenant_id:t,integration_id:i.id,config:{},dek:u})}async function _t(e,n,t){let{tenantId:r,redirectUri:o,hubConnect:i=!1}=t,s=C(e,()=>new B("invalid_corsair_instance","Invalid corsair instance"));if(!s.database)throw new Error("No database configured on corsair instance");let a=F(s,n,g=>new B("plugin_not_found",g)),u=xo(a),c=await D({authType:"oauth_2",integrationName:n,kek:s.kek,database:s.database}).get_client_id();if(!c)throw new Error(`client_id not configured for '${n}'`);if(i){let g=new URL(Ie({oauthConfig:u,clientId:c,redirectUri:o,state:""}));return g.searchParams.delete("state"),{url:g.toString(),state:""}}let p=Be(be(n,r),s.kek);return{url:Ie({oauthConfig:u,clientId:c,redirectUri:o,state:p}),state:p}}async function cn(e,n){let{code:t,state:r,redirectUri:o}=n,i=C(e,()=>new B("invalid_corsair_instance","Invalid corsair instance")),s,a;if(n.trusted){if(!n.plugin||!n.tenantId)throw new B("invalid_state","trusted callback requires plugin and tenantId");s=n.plugin,a=n.tenantId}else{let f=Mn(r,i.kek);if(!f)throw new B("invalid_state","Invalid or tampered state parameter");s=f.plugin,a=f.tenantId}if(!i.database)throw new B("no_database","No database configured on corsair instance");let u=F(i,s,f=>new B("plugin_not_found",f)),l=xo(u),c=D({authType:"oauth_2",integrationName:s,kek:i.kek,database:i.database}),p=await c.get_client_id(),g=await c.get_client_secret();if(!p||!g)throw new B("credentials_not_configured",`Credentials not configured for '${s}'`);await ws(i.database,s,a,i.kek);let d=await Un(t,p,g,l,o);if(!d.access_token)throw new B("no_access_token",`No access_token returned from ${l.providerName}`);let y=_({authType:"oauth_2",integrationName:s,tenantId:a,kek:i.kek,database:i.database,extraAccountFields:[...u.authConfig?.oauth_2?.account??[]]});await y.set_access_token(d.access_token),d.refresh_token&&await y.set_refresh_token(d.refresh_token),d.expires_in&&await y.set_expires_at(String(Math.floor(Date.now()/1e3)+d.expires_in));try{let f=await Hn(i.plugins,s,d);if(f){try{let m=u.authConfig?.oauth_2?.account??[];await Le({database:i.database,kek:i.kek,pluginId:s,tenantId:a,link:f,authType:"oauth_2",extraAccountFields:m})}catch(m){console.warn(`[corsair:oauth] Failed to persist webhook tenant link for '${s}' tenant '${a}':`,m)}i.hub&&Ue(i.hub,{plugin:s,tenantId:a,link:f,authType:"oauth_2"})}}catch(f){console.warn(`[corsair:oauth] Failed to resolve webhook tenant link for '${s}' tenant '${a}':`,f)}if(u.subscribe)try{await Bn(e,u,a,y)}catch(f){console.warn(`[corsair:oauth] BYO subscribe failed for '${s}' tenant '${a}':`,f)}return{plugin:s,tenantId:a}}async function vs(e){let{corsair:n,internal:t,rows:r}=e,o=e.subscribeAndReport??Bn,i=[],s=[];if(!t.database)return{renewed:i,failed:s};for(let a of r){let u=t.plugins.find(c=>c.id===a.integrationName);if(!u?.subscribe)continue;let l=`${u.id}/${a.tenantId}`;try{let c=_({authType:"oauth_2",integrationName:u.id,tenantId:a.tenantId,kek:t.kek,database:t.database,extraAccountFields:[...u.authConfig?.oauth_2?.account??[]]}),p=u.keyBuilder;if(p){let g=Object.create(c,{get_expires_at:{value:async()=>"0"}});await p({authType:"oauth_2",keys:g},"endpoint")}await o(n,u,a.tenantId,c),i.push(l)}catch(c){console.warn(`[corsair:renewal] re-subscribe failed for '${l}':`,c),s.push(l)}}return{renewed:i,failed:s}}async function Io(e){let n=C(e);if(!n.database)return{renewed:[],failed:[]};let t=await n.database.db.selectFrom("corsair_accounts as a").innerJoin("corsair_integrations as i","i.id","a.integration_id").select(["a.tenant_id as tenantId","i.name as integrationName"]).where("a.dek","is not",null).execute();return vs({corsair:e,internal:n,rows:t.filter(r=>!!r.tenantId)})}function Ts(e,n={}){let t=!1,r=()=>{t||(t=!0,Io(e).catch(i=>console.warn("[corsair:renewal] renewal pass failed:",i)).finally(()=>{t=!1}))};r();let o=setInterval(r,(n.intervalMinutes??45)*6e4);return o.unref?.(),()=>clearInterval(o)}async function So(e){if(!C(e).database)throw new Error("A database must be configured to provision Corsair integrations");await Ln(e,{silent:!0})}async function Ne(e,n){let t=C(e);if(!t.database)throw new Error("A database must be configured to provision Corsair for connect");await Fe(t,n)}var Ps=Symbol.for("corsair:internal"),As=new Set(["access_token","refresh_token","expires_at","scope"]);function xs(e){return e==="oauth_2"||e==="managed"?"oauth":e==="bot_token"?"bot_token":"api_key"}function Is(e,n){return e==="oauth_2"||e==="managed"?n.filter(t=>!he(t)&&!As.has(t)):n.filter(t=>!he(t))}function Ro(e){return{plugins:e.plugins,database:e.database,kek:e.kek,multiTenancy:e.multiTenancy??!1}}function Ss(e){return{plugins:e.plugins,database:e.database,kek:e.kek,multiTenancy:e.multiTenancy??!1}}function Rs(e){return{[Ps]:Ro(e)}}async function Nn(e,n,t={}){let r=Tn(e.hub),o=[],i=t.pluginIds?new Set(t.pluginIds):null,s=Ro(e),a=Rs(e);for(let u of e.plugins){if(i&&!i.has(u.id))continue;let l=I(u);if(!l)continue;let c=xs(l),p=t.providerNameOverrides?.[u.id]??pe(u.id),g=await xe(s,u,n),d=kn(u,l),y=Is(l,d),f={plugin:u.id,providerName:p,authKind:c,alreadyConfigured:g?.connected??!1};if(y.length>0&&(f.credentialFields=y),c==="oauth"){let h=t.oauthModeOverrides?.[u.id]??(l==="managed"?"managed":"byo");if(f.oauthMode=h,!t.skipOAuthUrlGeneration&&h!=="managed")try{let k=await _t(a,u.id,{tenantId:n,redirectUri:r,hubConnect:!0});f.oauthUrl=k.url}catch(k){f.setupError=k instanceof Error?k.message:`Could not prepare OAuth for ${u.id}`}}o.push(f)}return o}async function dl(e,n,t={}){let r=C(e),o=r.hub;if(!o)throw new Error("Hub is not configured");return Nn({plugins:r.plugins,database:r.database,kek:r.kek,hub:o},n,t)}async function Eo(e,n){if(!e.database)throw new Error("A database must be configured to provision Corsair for connect");await Fe(e.internalConfig??Ss(e),n)}async function _o(e,n){await Ne(e,n)}async function Do(e,n){let t=He(e.projectApiKey),r={tenantId:n.tenantId,plugins:n.plugins};return t==="development"&&(r.deliveryUrl=ye({deliveryUrl:n.deliveryUrl})),N({hub:e,path:"/connect/sessions",notFoundMessage:"Hub REST API not found at /connect/sessions. Check HUB_API_URL and ensure the Hub API is deployed.",body:r,parseResponse:Pn})}async function Dt(e,n){let t={plugins:n.plugins,database:n.database,kek:n.kek,hub:e,multiTenancy:n.multiTenancy};await Eo(t,n.tenantId);let r=await Nn(t,n.tenantId,{pluginIds:[n.plugin.id]});if(r.length===0)throw new Error(`Plugin '${n.plugin.id}' is not configured on this Corsair instance`);return Do(e,{tenantId:n.tenantId,plugins:r,deliveryUrl:n.deliveryUrl})}async function $n(e,n){let t=C(e),r=M(e),o={plugins:t.plugins,database:t.database,kek:t.kek,hub:r,multiTenancy:t.multiTenancy,internalConfig:t};await _o(e,n.tenantId);let i=n.plugin?[n.plugin]:void 0,s=n.plugin&&n.oauthMode?{[n.plugin]:n.oauthMode}:void 0,a=n.plugin&&n.providerName?{[n.plugin]:n.providerName}:void 0,u=await Nn(o,n.tenantId,{pluginIds:i,oauthModeOverrides:s,providerNameOverrides:a});if(u.length===0)throw new Error(n.plugin?`Plugin '${n.plugin}' is not configured on this Corsair instance`:"No plugins are configured on this Corsair instance");return Do(r,{tenantId:n.tenantId,plugins:u,deliveryUrl:n.deliveryUrl})}function Oo(e){return e==="oauth_2"||e==="managed"?"oauth":e==="bot_token"?"bot_token":"api_key"}function Es(e,n){return n&&!n.has(e.id)?!1:I(e)!==null}async function Mo(e,n,t={}){let r=C(e),o=n.trim()||"default",i=t.pluginIds?.length?new Set(t.pluginIds):null,s=await sn(r,o,{pluginIds:t.pluginIds}),a=new Map(s.map(l=>[l.plugin,l])),u=r.plugins.filter(l=>Es(l,i)).map(l=>{let c=I(l),p=a.get(l.id);return p?{plugin:l.id,providerName:pe(l.id),authKind:Oo(c),status:p.status,connected:p.connected,fields:p.fields.map(g=>({name:g.name,level:g.level,required:g.required,configured:g.configured})),missingRequiredFields:p.missingRequiredFields}:{plugin:l.id,providerName:pe(l.id),authKind:Oo(c),status:"not_started",connected:!1,fields:[],missingRequiredFields:[]}});return{tenantId:o,plugins:u}}async function Ho(e,n){let t=M(e);return Rn({hub:t,path:`/projects/${encodeURIComponent(n.projectId)}/connections`,notFoundMessage:"Hub REST API not found at /projects/:id/connections. Check HUB_API_URL and ensure the Hub API is deployed.",parseResponse:An})}function $e(e){return!!(e?.baseUrl?.trim()&&e?.redirectUri?.trim())}var Z=class extends Error{code;constructor(n,t){super(t),this.name="ConnectError",this.code=n}};function _s(e){let n=e.oauthConfig;if(!n)throw new Z("plugin_has_no_oauth_config",`Plugin '${e.id}' has no oauthConfig`);return n}async function Ot(e,n){let t=C(e,()=>new Z("invalid_corsair_instance","Invalid corsair instance"));if(!t.database)throw new Z("no_database","No database configured on corsair instance");let r=t.manual?.redirectUri;if(!r)throw new Z("no_redirect_uri","No redirectUri configured. Set manual.redirectUri in createCorsair().");let o=Mn(n,t.kek);if(!o)throw new Z("invalid_state","Invalid or tampered state parameter");let{plugin:i,tenantId:s}=o,a=F(t,i,g=>new Z("plugin_not_found",g)),u=_s(a),c=await D({authType:"oauth_2",integrationName:i,kek:t.kek,database:t.database}).get_client_id();if(!c)throw new Z("client_id_not_configured",`client_id not configured for '${i}'`);let p=Ie({oauthConfig:u,clientId:c,redirectUri:r,state:n});return{plugin:i,tenantId:s,providerName:u.providerName,oauthUrl:p,state:n}}import{AsyncLocalStorage as Os}from"async_hooks";import{randomBytes as Ms}from"crypto";import{v4 as Hs}from"uuid";async function jn(e,n){let t=He(e.projectApiKey),r={permissionId:n.permissionId,permissionToken:n.permissionToken,plugin:n.plugin,endpoint:n.endpoint,args:n.args,tenantId:n.tenantId,expiresAt:n.expiresAt};return t==="development"&&(r.deliveryUrl=ye({deliveryUrl:n.deliveryUrl})),N({hub:e,path:"/permission/sessions",notFoundMessage:"Hub REST API not found at /permission/sessions. Check HUB_API_URL and ensure the Hub API is deployed.",body:r,parseResponse:xn})}function Wn(e){return`Approval required. Visit ${e} to approve or deny, then tell the agent to retry this action.`}var Mt="Permission approval required. Set manual.approvalBaseUrl (or use hub for hosted approval) so an approval URL can be generated. Optionally set manual.onApprovalRequired to customize the agent message.";function Ft(e){return e?e.approvalBaseUrl!==void 0||e.onApprovalRequired!==void 0:!1}function Fo(e,n){return`${e.replace(/\/+$/,"")}/${n}`}function Ht(e){return Wn(e)}async function Bt(e,n){if(Ft(e.manual)){let r=e.manual?.approvalBaseUrl?.trim();return r?Fo(r,n.token):null}let t=e.hub;if(!t)return null;try{return(await jn(t,{permissionId:n.id,permissionToken:n.token,plugin:n.plugin,endpoint:n.endpoint,args:Ds(n.args),tenantId:n.tenant_id,expiresAt:n.expires_at})).approvalUrl}catch{return null}}function Ds(e){try{return JSON.parse(e)}catch{return e}}async function Kn(e,n){if(!(n.status==="pending"||n.status==="approved"))return{...n,approvalUrl:null};let r=await Bt(e,n);return{...n,approvalUrl:r}}async function Ut(e){let{permissionsOptions:n,manual:t,hub:r,permissionId:o,permissionToken:i,plugin:s,endpoint:a,args:u,tenantId:l,expiresAt:c,operationPath:p}=e;if(n?.formatAsyncMessage)return n.formatAsyncMessage({token:i,id:o,plugin:s,endpoint:a,args:u});let d=await Bt({manual:t,hub:r},{id:o,token:i,plugin:s,endpoint:a,args:JSON.stringify(u),tenant_id:l,expires_at:c});return Ft(t)?d?t?.onApprovalRequired?t.onApprovalRequired({approvalUrl:d}):Ht(d):Mt:r?d?Ht(d):`Action '${p}' requires user approval before it can run. Could not create approval link. Check hub configuration and server logs.`:Mt}var je=class extends Error{constructor(n){super(n),Object.setPrototypeOf(this,new.target.prototype),this.name="PermissionRequiredError"}};var Uo=new Os,qn=class extends Error{endpointPath;riskLevel;constructor(n,t){super(`Action '${n}' is a '${t}' operation and is forbidden in readonly mode. Only read operations are permitted \u2014 rewrite the script to avoid write/destructive actions.`),this.name="ReadonlyForbiddenError",this.endpointPath=n,this.riskLevel=t}};function Fs(e){return Uo.run(!0,e)}function Lo(){return Uo.getStore()===!0}function Lt(e,n){if(Lo()&&n!=="read")throw new qn(e,n)}var Bs={open:{read:"allow",write:"allow",destructive:"allow"},cautious:{read:"allow",write:"allow",destructive:"require_approval"},strict:{read:"allow",write:"require_approval",destructive:"deny"},readonly:{read:"allow",write:"deny",destructive:"deny"}};function Us(e,n,t){return t!==void 0?t:Bs[n][e]}function Nt(e){let n=/(\d+)(d|h|m|s)/g,t=0,r;for(;(r=n.exec(e))!==null;){let o=parseInt(r[1],10);switch(r[2]){case"d":t+=o*864e5;break;case"h":t+=o*36e5;break;case"m":t+=o*6e4;break;case"s":t+=o*1e3;break}}return t>0?t:600*1e3}function No(e){return{async find_by_permission_id(n){if(e)return e.db.selectFrom("corsair_permissions").selectAll().where("id","=",n).executeTakeFirst()},async find_by_token(n){if(e)return e.db.selectFrom("corsair_permissions").selectAll().where("token","=",n).executeTakeFirst()},async set_executing(n){e&&await e.db.updateTable("corsair_permissions").set({status:"executing",updated_at:new Date}).where("id","=",n).execute()},async set_completed(n){e&&await e.db.updateTable("corsair_permissions").set({status:"completed",updated_at:new Date}).where("id","=",n).execute()}}}async function Bo(e,n,t){let r=Date.now()+t;for(;Date.now()<r;){let o=await e.db.selectFrom("corsair_permissions").select(["id","status"]).where("id","=",n).executeTakeFirst();if(!o)return{result:"blocked",reason:"pending"};if(o.status==="approved")return{result:"allow",onComplete:async()=>{await e.db.updateTable("corsair_permissions").set({status:"completed",updated_at:new Date}).where("id","=",n).execute()}};if(o.status==="denied")return{result:"blocked",reason:"denied"};if(o.status==="expired"||o.status==="failed")return{result:"blocked",reason:"timeout"};await new Promise(i=>setTimeout(i,500))}return{result:"blocked",reason:"timeout"}}async function $o(e){let n=Us(e.riskLevel,e.mode,e.override);if(n==="allow")return{result:"allow"};let t=e.meta?.irreversible?" (irreversible)":"",r=e.meta?.description?`${e.meta.description}${t}`:`${e.pluginId}.${e.endpointPath}${t}`;if(n==="deny"||!e.db)return console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 denied by permission mode '${e.mode}'.`,`
10
+ Action: ${r}`,`
11
+ To allow this, update the permission mode or add an override in your corsair config.`),{result:"blocked",reason:"policy"};let o=JSON.stringify(e.args),i=new Date().toISOString(),s=e.tenantId??"default",a=await e.db.db.selectFrom("corsair_permissions").selectAll().where("plugin","=",e.pluginId).where("endpoint","=",e.endpointPath).where("args","=",o).where("tenant_id","=",s).where("expires_at",">",i).where("status","in",["pending","approved","executing"]).orderBy("created_at","desc").limit(1).executeTakeFirst();if(a){if(a.status==="approved"){let y=e.db,f=a.id;return{result:"allow",onComplete:async()=>{await y.db.updateTable("corsair_permissions").set({status:"completed",updated_at:new Date}).where("id","=",f).execute()}}}return a.status==="executing"?{result:"allow"}:(console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 approval already pending.`,`
12
+ Action: ${r}`,`
13
+ Permission ID: ${a.id}`,`
14
+ Use the token to approve or deny this request.`),(typeof e.approvalMode=="function"?e.approvalMode():e.approvalMode)==="synchronous"?Bo(e.db,a.id,e.timeoutMs??600*1e3):{result:"blocked",reason:"pending",id:a.id,token:a.token,expiresAt:a.expires_at})}let u=Hs(),l=Ms(32).toString("hex"),c=e.timeoutMs??600*1e3,p=new Date(Date.now()+c).toISOString();return await e.db.db.insertInto("corsair_permissions").values({id:u,created_at:new Date,updated_at:new Date,token:l,plugin:e.pluginId,endpoint:e.endpointPath,args:o,tenant_id:s,status:"pending",expires_at:p}).execute(),console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 approval required.`,`
15
+ Action: ${r}`,`
16
+ Permission ID: ${u}`,`
17
+ Permission token: ${l}`,`
18
+ Expires at: ${p}`,`
19
+ Use the token to approve or deny this request.`),(typeof e.approvalMode=="function"?e.approvalMode():e.approvalMode)==="synchronous"?Bo(e.db,u,c):{result:"blocked",reason:"pending",id:u,token:l,expiresAt:p}}var S=class extends Error{status;code;extra;constructor(n,t,r,o={}){super(r??t),this.name="ManagementApiError",this.status=n,this.code=t,this.extra=o}};function O(e,n){return new Response(JSON.stringify(n),{status:e,headers:{"content-type":"application/json"}})}function jo(e){let n={error:e.code,message:e.message,...e.extra};return O(e.status,n)}function ke(e){return new S(404,"not_found",e)}function ce(e,n={}){return new S(400,"bad_request",e,n)}function Wo(e,n){return F(e,n,t=>ke(t))}async function Ko(e,n){let t=e.options?.authType;if(!t||!n.database||!n.kek)return{configured:!1,missingFields:[]};let r=D({authType:t,integrationName:e.id,kek:n.kek,database:n.database}),o=H[t].integration,i=r,s;try{s=await Promise.all(o.map(l=>i[`get_${l}`]()))}catch{s=o.map(()=>null)}let a=o.filter((l,c)=>s[c]==null),u;return t==="oauth_2"?u=!a.includes("client_id")&&!a.includes("client_secret"):u=a.length===0,{configured:u,missingFields:a}}async function qo(e,n){let t=e.options?.authType??null,r=e.oauthConfig,{configured:o,missingFields:i}=await Ko(e,n);return{id:e.id,authType:t,configured:o,missingFields:i,oauth:r?{providerName:r.providerName,scopes:r.scopes,requiresRegisteredRedirect:!!r.requiresRegisteredRedirect}:null}}function Zn(){return{ok:!0}}async function We(e){return Promise.all(e.plugins.map(n=>qo(n,e)))}async function Gn(e,n){let t=Wo(e,n);return qo(t,e)}async function Ls(e,n){return e.database?(await e.database.db.selectFrom("corsair_accounts as a").innerJoin("corsair_integrations as i","i.id","a.integration_id").select(["a.id as accountId","a.dek as dek","i.name as integrationName"]).where("a.tenant_id","=",n).execute()).map(r=>({integrationName:r.integrationName,hasCredentials:!!r.dek})):[]}async function Zo(e,n){let t=await Ls(e,n),r=t.filter(o=>o.hasCredentials).map(o=>o.integrationName);return{id:n,accounts:t,connectedPlugins:r}}async function Ke(e){let n=new Map;if(n.set("default",{id:"default",accounts:[],connectedPlugins:[]}),e.database){let t=await e.database.db.selectFrom("corsair_accounts as a").innerJoin("corsair_integrations as i","i.id","a.integration_id").select(["a.tenant_id","a.dek as dek","i.name as integrationName"]).execute();for(let r of t){let o=r.tenant_id;if(!o)continue;let i=n.get(o);i||(i={id:o,accounts:[],connectedPlugins:[]},n.set(o,i));let s=!!r.dek;i.accounts.push({integrationName:r.integrationName,hasCredentials:s}),s&&i.connectedPlugins.push(r.integrationName)}}return[...n.values()]}async function Jn(e,n){if(!n)throw ce("Tenant id must be a non-empty string");return Zo(e,n)}async function zn(e,n){let t=n?.id?.trim();if(!t)throw ce("Tenant id is required",{missingFields:["id"]});return Zo(e,t)}async function Vn(e,n){let t=n?.trim()||"default",r={},o=await sn(e,t);for(let i of o)r[i.plugin]=On(i);for(let i of e.plugins)i.id in r||(!i.options?.authType||!e.database||!e.kek?r[i.id]="missing_credentials":r[i.id]="not_connected");return r}async function $t(e,n){if(!e.database)throw ke(`Permission '${n}' not found`);let t=await e.database.db.selectFrom("corsair_permissions").selectAll().where("id","=",n).executeTakeFirst();if(!t)throw ke(`Permission '${n}' not found`);return Kn(e,t)}function Ns(e){if(!e.oauthConfig)throw ce(`Plugin '${e.id}' has no oauthConfig`)}function $s(e){if(!e.manual)throw new S(500,"connect_not_configured","createCorsair was not given manual config. Set { manual: { baseUrl, redirectUri } } to enable manual connect routes.");return e.manual}function jt(e){let n=$s(e);if(!n.baseUrl?.trim()||!n.redirectUri?.trim())throw new S(500,"connect_not_configured","Manual connect requires manual.baseUrl and manual.redirectUri. Use hub for hosted connect, or set both URLs for manual OAuth.");return n}function js(e){let n=!!e.hub,t=$e(e.manual);if(!n&&!t)throw new S(500,"connect_not_configured","createCorsair was not given connect config. Set hub: { ... } for Hub mode, or manual: { baseUrl, redirectUri } for manual connect.")}function Go(e){if(!e.database||!e.kek)throw new S(500,"database_not_configured","A database and kek are required to issue connect links.")}async function Ws(e,n){let t=n?.plugin?.trim();if(!t)throw ce("Plugin id is required",{missingFields:["plugin"]});let r=n.tenantId?.trim()||"default",o=Wo(e,t);Ns(o);let i=jt(e);Go(e);let s=await Ko(o,e);if(!s.configured)throw new S(400,"missing_credentials",`Plugin '${t}' is missing OAuth client credentials`,{missingFields:s.missingFields});let a=Be(be(t,r),e.kek),u;try{u=new URL(i.baseUrl)}catch{throw new S(500,"connect_misconfigured","manual.baseUrl is not a valid URL. Set a full URL including protocol (e.g. https://app.example.com/connect).")}return u.searchParams.set("state",a),{connectUrl:u.toString(),expiresAt:new Date(Date.now()+St).toISOString()}}async function Ks(e,n,t){Go(n);let o={tenantId:t.tenantId?.trim()||"default",oauthMode:t.oauthMode},i=t.plugin?.trim();i&&(o.plugin=i);let s=t.providerName?.trim();s&&(o.providerName=s);let a=await $n(e,o);return{connectUrl:a.connectUrl,expiresAt:a.expiresAt}}async function Yn(e,n,t){return js(n),n.hub?Ks(e,n,t):Ws(n,t)}async function Qn(e,n,t){if(n.hub&&!$e(n.manual))throw new S(400,"hub_mode","resolve is not used with hub config. Redirect users to connectUrl from createLink.");let r=t?.trim();if(!r)throw ce("state is required",{missingFields:["state"]});jt(n);try{return await Ot(e,r)}catch(o){if(o instanceof Z)switch(o.code){case"invalid_state":throw ce("Invalid or expired state");case"client_id_not_configured":throw new S(400,"missing_credentials","OAuth client_id is not configured for this plugin",{missingFields:["client_id"]});case"no_redirect_uri":break}throw new S(500,"resolve_failed","Could not resolve connect link. Check server logs for details.")}}async function Xn(e,n,t){if(n.hub&&!$e(n.manual))throw new S(400,"hub_mode","oauthCallback is not used with hub config. Hub delivers tokens to your deliveryUrl.");let r=t?.code?.trim(),o=t?.state?.trim(),i=[];if(r||i.push("code"),o||i.push("state"),i.length)throw ce("Missing required fields",{missingFields:i});let s=jt(n),{processOAuthCallback:a}=await import("./oauth.js");try{return await a(e,{code:r,state:o,redirectUri:s.redirectUri})}catch(u){if(u instanceof Error&&u.name==="OAuthCallbackError")switch(u.code){case"invalid_state":throw ce("Invalid or expired state");case"credentials_not_configured":throw new S(400,"missing_credentials","OAuth client credentials are not configured for this plugin",{missingFields:["client_id","client_secret"]})}throw new S(502,"oauth_callback_failed","OAuth callback did not complete. Check server logs for details.")}}async function Wt(e,n){if(!e.database)throw ke("Permission not found");let t=await e.database.db.selectFrom("corsair_permissions").selectAll().where("token","=",n).executeTakeFirst();if(!t)throw ke("Permission not found");return Kn(e,t)}async function Jo(e,n){return"id"in n?$t(e,n.id):Wt(e,n.token)}import{createCipheriv as Ys,createDecipheriv as dd,randomBytes as Qo,scryptSync as Qs}from"crypto";import{createHmac as Kt,randomUUID as qs,timingSafeEqual as Vo}from"crypto";function Yo(e){if(e)return e.startsWith("sha256=")?e.slice(7):e}function et(e){let n=JSON.stringify({type:e.type,payload:e.payload}),t=Math.floor(Date.now()/1e3).toString(),r=Kt("sha256",e.signingSecret.trim()).update(n).digest("hex");return{body:n,headers:{"content-type":"application/json","x-corsair-signature":`sha256=${r}`,"x-corsair-timestamp":t,"x-corsair-project":e.projectId,"x-corsair-nonce":qs()}}}function qt(e){let n=e.signingSecret.trim();if(!n)return!1;let t=Yo(e.signatureHeader);if(!t)return!1;let r=Number(e.timestampHeader);if(!Number.isFinite(r)||Math.abs(Date.now()-r*1e3)>Pe)return!1;let i=Kt("sha256",n).update(e.body).digest("hex");try{return Vo(Buffer.from(i,"utf8"),Buffer.from(t,"utf8"))}catch{return!1}}function qe(e){let n=e.signingSecret.trim();if(!n)return{ok:!1,error:"Tunnel signing secret is required"};let t=Yo(e.signatureHeader);if(!t)return{ok:!1,error:"Invalid tunnel signature"};let r=Number(e.timestampHeader);if(!Number.isFinite(r))return{ok:!1,error:"Invalid or missing tunnel timestamp"};if(Math.abs(Date.now()-r*1e3)>Pe)return{ok:!1,error:"Tunnel request timestamp is outside the allowed window"};let i=Kt("sha256",n).update(e.body).digest("hex");try{if(!Vo(Buffer.from(i,"utf8"),Buffer.from(t,"utf8")))return{ok:!1,error:"Invalid tunnel signature"}}catch{return{ok:!1,error:"Invalid tunnel signature"}}return{ok:!0}}function Ze(e){if(!e)return{};try{return JSON.parse(e)}catch{return{}}}function nt(e){return e.httpOk&&(e.status===204||e.body.status==="ok"||e.body.ok===!0)}function tt(e){let n=e.sync?.encrypted;return typeof n!="string"||!n.trim()?null:{encrypted:n.trim()}}function ln(e){let n=e.connectUrl?.trim();return n?{connectUrl:n,expiresAt:e.expiresAt}:null}function Zt(e){return ln(Ze(e))}async function Gt(e){let n=await it({deliveryUrl:e.deliveryUrl,projectId:e.projectId,signingSecret:e.signingSecret,type:"connect.create_link",payload:{tenantId:e.tenantId,plugins:e.plugins}}),t=Ze(n.body),r=nt({httpOk:n.ok,status:n.status,body:t}),o=ln(t);if(!r||!o)throw new Error(ot({deliveryUrl:e.deliveryUrl,status:n.status,body:n.body,ack:t}));return o}function rt(e){return tt(Ze(e))}function Zs(e){let n=e;for(;n;){if(n instanceof Error){let t=n.code;if(typeof t=="string")return t;n=n.cause;continue}if(typeof n=="object"&&n!==null&&"code"in n){let t=n.code;if(typeof t=="string")return t}break}}function zo(e,n=200){let t=e.trim();return t.length<=n?t:`${t.slice(0,n)}\u2026`}var Gs="Verify hub.signingSecret in your app matches the signing secret shown in Hub project settings.",Js="Check the delivery URL configured for this environment.";function zs(e){return`${e.ack.error?`${e.ack.error} (HTTP ${e.status} from ${e.deliveryUrl})`:`App rejected the signed delivery (HTTP ${e.status} from ${e.deliveryUrl})`}. ${Gs}`}function Vs(e){return`${e.ack.error?`${e.ack.error} (HTTP 404 from ${e.deliveryUrl})`:`Delivery endpoint not found at ${e.deliveryUrl} (HTTP 404)`}. ${Js}`}function dn(e,n){let t=Zs(n),r=n instanceof Error?n.message:"Delivery request failed",o;switch(t){case"ECONNREFUSED":o="connection refused \u2014 nothing accepted a TCP connection on that host and port";break;case"ENOTFOUND":o="host not found \u2014 DNS could not resolve the hostname";break;case"ETIMEDOUT":case"UND_ERR_CONNECT_TIMEOUT":o="connection timed out before the app responded";break;case"ECONNRESET":o="connection reset while talking to the app";break;case"CERT_HAS_EXPIRED":case"UNABLE_TO_VERIFY_LEAF_SIGNATURE":case"DEPTH_ZERO_SELF_SIGNED_CERT":o=`TLS certificate error (${t})`;break;default:o=r==="fetch failed"&&t?`${r} (${t})`:r}return[`Could not reach ${e}`,o].join(". ")}function ot(e){if(e.status===0)return e.ack.error?e.ack.error:e.body.startsWith("Could not reach")?e.body:dn(e.deliveryUrl,new Error(e.body||"Delivery request failed"));if(e.status===401||e.status===403)return zs(e);if(e.status===404)return Vs(e);if(e.ack.error)return`${e.ack.error} (HTTP ${e.status} from ${e.deliveryUrl})`;if(e.status>=500){let t=e.body.trim();return t?`App failed while processing the delivery (HTTP ${e.status} from ${e.deliveryUrl}): ${zo(t)}`:`App failed while processing the delivery (HTTP ${e.status} from ${e.deliveryUrl})`}let n=e.body.trim();return n?`${zo(n)} (HTTP ${e.status} from ${e.deliveryUrl})`:`Delivery failed with HTTP ${e.status} from ${e.deliveryUrl}`}async function it(e){let{body:n,headers:t}=et(e);try{let r=await fetch(e.deliveryUrl,{method:"POST",headers:t,body:n}),o=await r.text();return{ok:r.ok,status:r.status,body:o}}catch(r){return{ok:!1,status:0,body:dn(e.deliveryUrl,r)}}}var Xs="aes-256-gcm",ea=12,na=16,ta=16,ra=32;function oa(e,n){return Qs(e.trim(),n,ra)}function Jt(e,n){let t=n.trim();if(!t)throw new Error("Signing secret is required to encrypt sync manifest");let r=Qo(ta),o=oa(t,r),i=Qo(ea),s=Ys(Xs,o,i,{authTagLength:na}),a=JSON.stringify(e),u=Buffer.concat([s.update(a,"utf8"),s.final()]),l=s.getAuthTag();return[r.toString("base64"),i.toString("base64"),l.toString("base64"),u.toString("base64")].join(":")}var ia=["invalid corsair instance","a database must be configured to sync connections from the app","a database must be configured on the corsair instance","signing secret is required to encrypt sync manifest"];function zt(e){if(e instanceof $r)return!1;if(!(e instanceof Error))return!0;let n=e.message.toLowerCase();return!ia.some(t=>n.includes(t))}function sa(e){if(!e)return[];let n=I(e);return n?(e.authConfig?.[n]?.integration??[]).filter(r=>!he(r)):[]}async function pn(e,n){let t=C(e);if(!t.database)throw new Error("A database must be configured to sync connections from the app");await Ln(e,{silent:!0});let[r,o]=await Promise.all([Ke(t),We(t)]),i={tenants:r.map(s=>({id:s.id})),plugins:o.map(s=>{let a=sa(t.plugins.find(u=>u.id===s.id));return{id:s.id,authType:s.authType,configured:s.configured,missingFields:s.missingFields,...a.length>0?{integrationCredentialFields:a}:{}}}),syncedAt:new Date().toISOString()};return Jt(i,n)}async function st(e,n){let t=n.tenantId.trim();if(!t)throw new Error("tenantId is required");let r=n.plugins.map(s=>s.trim()).filter(Boolean);if(r.length===0)throw new Error("At least one plugin is required");let o=C(e);if(!o.hub)throw new Error("Hub is not configured on this Corsair instance");if(!o.database)throw new Error("Database not configured");let i=await aa(o.hub,{plugins:o.plugins,database:o.database,kek:o.kek,multiTenancy:o.multiTenancy},{tenantId:t,pluginIds:r});return{connectUrl:i.connectUrl,expiresAt:i.expiresAt}}async function aa(e,n,t){let{buildConnectPluginManifestFromContext:r,ensureConnectAccountRowsFromContext:o}=await import("./setup-introspect-YSOQWBTI.js"),{postHubConnectSession:i}=await import("./connect-JSSSZTJ4.js"),s={plugins:n.plugins,database:n.database,kek:n.kek,hub:e,multiTenancy:n.multiTenancy};await o(s,t.tenantId);let a=await r(s,t.tenantId,{pluginIds:t.pluginIds});if(a.length===0)throw new Error("No connectable plugins found for this tenant");let u=a.find(l=>l.setupError);if(u)throw new Error(u.setupError??`Could not prepare connect link for ${u.plugin}`);return i(e,{tenantId:t.tenantId,plugins:a})}var ee=class extends Error{code;constructor(n,t){super(t),this.name="AuthCredentialsDeliveryError",this.code=n}};async function at(e,n){let t=C(e,()=>new ee("invalid_corsair_instance","Invalid corsair instance"));if(!t.database)throw new ee("no_database","Database not configured");let r=F(t,n.plugin,c=>new ee("plugin_not_found",c)),o=I(r);if(!o)throw new ee("invalid_credentials",`Plugin '${r.id}' has no authType configured`);if(o==="oauth_2"||o==="managed")throw new ee("invalid_credentials","OAuth plugins must be connected via sign-in, not credentials delivery");await Ne(e,n.tenantId);let i=new Set(kn(r,o)),a=r.authConfig?.[o]?.account??[],u=_({authType:o,integrationName:n.plugin,tenantId:n.tenantId,kek:t.kek,database:t.database,extraAccountFields:a}),l=0;for(let[c,p]of Object.entries(n.credentials)){if(!p.trim())continue;if(!i.has(c))throw new ee("invalid_credentials",`Unknown credential field '${c}' for plugin '${n.plugin}'`);let g=L(u,`set_${c}`);if(!g)throw new ee("invalid_credentials",`Cannot set credential field '${c}' for plugin '${n.plugin}'`);await g(p.trim()),l+=1}if(l===0)throw new ee("invalid_credentials","Provide at least one credential field to save");return{plugin:n.plugin,tenantId:n.tenantId}}var ne=class extends Error{code;constructor(n,t){super(t),this.name="IntegrationCredentialsDeliveryError",this.code=n}};async function Vt(e,n){let t=C(e,()=>new ne("invalid_corsair_instance","Invalid corsair instance"));if(!t.database)throw new ne("no_database","Database not configured");let r=F(t,n.plugin,c=>new ne("plugin_not_found",c)),o=I(r);if(!o)throw new ne("invalid_credentials",`Plugin '${r.id}' has no authType configured`);await So(e);let i=new Set(Kr(r,o)),a=r.authConfig?.[o]?.integration??[],u=D({authType:o,integrationName:n.plugin,kek:t.kek,database:t.database,extraIntegrationFields:a}),l=0;for(let[c,p]of Object.entries(n.credentials)){if(!p.trim())continue;if(!i.has(c))throw new ne("invalid_credentials",`Unknown integration credential field '${c}' for plugin '${n.plugin}'`);let g=L(u,`set_${c}`);if(!g)throw new ne("invalid_credentials",`Cannot set integration field '${c}' for plugin '${n.plugin}'`);await g(p.trim()),l+=1}if(l===0)throw new ne("invalid_credentials","Provide at least one integration credential field to save");return{plugin:n.plugin}}var ut=new Map;function ua(e){for(let[n,t]of ut)t<=e&&ut.delete(n)}function ct(e,n){let t=e.trim();if(!t)return{ok:!1,error:"Delivery replay key is required"};let r=Date.now();return ua(r),ut.has(t)?{ok:!1,error:"Delivery request already consumed"}:(ut.set(t,r+n),{ok:!0})}var Ce=class extends Error{code;constructor(n,t){super(t),this.name="ManagedOAuthDeliveryError",this.code=n}};async function Ge(e,n){let{plugin:t,tenantId:r,accessToken:o,refreshToken:i,expiresIn:s,scope:a}=n;if(!o.trim())throw new Ce("no_access_token","Managed OAuth delivery missing access_token");let u=C(e,()=>new Ce("invalid_corsair_instance","Invalid corsair instance"));if(!u.database)throw new Ce("no_database","No database configured on corsair instance");let l=F(u,t,p=>new Ce("plugin_not_found",p));await Ne(e,r);let c=_({authType:"managed",integrationName:t,tenantId:r,kek:u.kek,database:u.database});await c.set_access_token(o),i&&await c.set_refresh_token(i),s&&await c.set_expires_at(String(Math.floor(Date.now()/1e3)+s)),a&&await c.set_scope(a);try{let p=await Hn(u.plugins,t,{access_token:o,refresh_token:i,scope:a});if(p){try{let g=l.authConfig?.managed?.account??[];await Le({database:u.database,kek:u.kek,pluginId:t,tenantId:r,link:p,authType:"managed",extraAccountFields:g})}catch(g){console.warn(`[corsair:managed-oauth] Failed to persist webhook tenant link for '${t}' tenant '${r}':`,g)}u.hub&&Ue(u.hub,{plugin:t,tenantId:r,link:p,authType:"managed"})}}catch(p){console.warn(`[corsair:managed-oauth] Failed to resolve webhook tenant link for '${t}' tenant '${r}':`,p)}return{plugin:t,tenantId:r}}function ca(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function Xo(e,n,t=[]){for(let[r,o]of Object.entries(e))if(ca(o)){if(o.match(n))return{webhook:o,path:[...t,r]}}else if(o&&typeof o=="object"){let i=Xo(o,n,[...t,r]);if(i)return i}return null}function la(e){let n={};for(let[t,r]of Object.entries(e))n[t.toLowerCase()]=Array.isArray(r)?r[0]:r;return n}function da(e){let n=e["x-goog-resource-uri"],t=e["x-goog-channel-id"];if(!n||!t)return null;let r={resourceId:e["x-goog-resource-id"]||"",resourceState:e["x-goog-resource-state"]||"",resourceUri:n,channelId:t,channelExpiration:e["x-goog-channel-expiration"]||""};return n.includes("/drive/")&&(r.kind="drive#change"),{message:{data:Buffer.from(JSON.stringify(r)).toString("base64"),messageId:e["x-goog-message-number"]||""}}}async function ei(e,n,t,r,o){let i=la(n),s=typeof t=="string"?JSON.parse(t):t;(!s||typeof s=="object"&&Object.keys(s).length===0)&&i["x-goog-resource-uri"]&&(s=da(i)||s);let u={headers:i,body:s,...r?{query:r}:{}},l=r?.tenantId||"default",c=e.withTenant?e.withTenant(l):e,p=o?.plugin,g=p?[p]:Cn;for(let d of g){let y=c[d];if(!y||!y.webhooks||!p&&y.pluginWebhookMatcher&&!y.pluginWebhookMatcher(u))continue;let f=Xo(y.webhooks,u);if(!f)continue;let m=f.path.join("."),h={payload:s,headers:i,rawBody:typeof t=="string"?t:JSON.stringify(t),...r?{query:r}:{}};try{let k=await f.webhook.handler(h),w=!!Object.keys(k.returnToSender||{})?.length;return{plugin:d,action:m,body:s,response:w?{...k?.returnToSender,success:!0}:{success:!0},...k.responseHeaders&&{responseHeaders:k.responseHeaders}}}catch(k){return console.error(`Error executing webhook handler for ${d}.${m}:`,k),{plugin:d,action:m,body:s,response:{success:!1,error:k instanceof Error?k.message:"Unknown error"}}}}return{plugin:null,action:null,body:null}}function Se(e){return e.deliveryMode==="auth.credentials"}function gn(e){return e.deliveryMode==="connections.sync"}function lt(e){return e.deliveryMode==="connect.create_link"}function fn(e){return e.deliveryMode==="permission.approve"||e.deliveryMode==="permission.deny"}function yn(e){return e.deliveryMode==="oauth.tokens"}function dt(e){return e.deliveryMode==="oauth.callback"||e.deliveryMode===void 0&&!Se(e)&&!gn(e)&&!lt(e)&&!fn(e)&&!yn(e)}async function pa(e,n){try{return{status:"ok",webhookResponse:{status:200,body:{status:"ok",sync:{encrypted:await pn(e,n)}}}}}catch(t){return{status:"failed",retryable:zt(t),error:t instanceof Error?t.message:"Connections sync delivery failed"}}}async function ga(e,n){try{let t=await st(e,n);return{status:"ok",webhookResponse:{status:200,body:{status:"ok",connectUrl:t.connectUrl,expiresAt:t.expiresAt}}}}catch(t){return{status:"failed",retryable:!1,error:t instanceof Error?t.message:"Connect link delivery failed"}}}function Yt(e,n){if(e instanceof Headers)return e.get(n)??void 0;let t=e[n]??e[n.toLowerCase()];return Array.isArray(t)?t[0]:typeof t=="string"?t:void 0}async function fa(e,n,t){let r=typeof t.tenantId=="string"?t.tenantId:typeof t.query?.tenantId=="string"?t.query.tenantId:void 0;return r||(!n.database||!t.plugin||!t.linkType||!t.externalId?void 0:await Fn({database:n.database,kek:n.kek,pluginId:t.plugin,linkType:t.linkType,externalId:t.externalId})??void 0)}async function ya(e,n,t){let r=await fa(e,n,t),o={...t.query??{},...r?{tenantId:r}:{}},i=await ei(e,t.headers,t.body,o,t.plugin?{plugin:t.plugin}:void 0);if(!i.plugin)return{status:"failed",retryable:!1,error:"No matching webhook handler found"};if(i.response&&i.response.success===!1)return{status:"failed",retryable:!1,error:typeof i.response.error=="string"?i.response.error:"Webhook handler failed"};let s=i.response?.returnToSender,a=s&&typeof s=="object"&&typeof s.validationToken=="string"&&Object.keys(s).length===1?s.validationToken:s||(i.response?.data??i.response);return{status:"ok",webhookResponse:{status:i.response?.statusCode??200,body:a,headers:i.responseHeaders}}}async function ma(e,n){return await cn(e,{code:n.code,state:n.state,redirectUri:n.redirectUri,...n.plugin&&n.tenantId?{trusted:!0,plugin:n.plugin,tenantId:n.tenantId}:{}}),{status:"ok"}}async function ha(e,n){return await Ge(e,{plugin:n.plugin,tenantId:n.tenantId,accessToken:n.accessToken,refreshToken:n.refreshToken,expiresIn:n.expiresIn,scope:n.scope}),{status:"ok"}}async function Xt(e,n,t){let r=await Qt(e,{token:n},t);if(r.status!=="ok")throw new Error(r.error??"Permission decision failed")}async function Qt(e,n,t){let r=C(e),o=n.token?.trim();if(!o)return{status:"failed",retryable:!1,error:"Permission token is required"};if(!r.database)return{status:"failed",retryable:!1,error:"Database not configured"};let i=new Date().toISOString(),s=await r.database.db.selectFrom("corsair_permissions").selectAll().where("token","=",o).executeTakeFirst();return s?s.status!=="pending"?{status:"ok"}:s.expires_at<i?(await r.database.db.updateTable("corsair_permissions").set({status:"expired",updated_at:new Date}).where("id","=",s.id).execute(),{status:"failed",retryable:!1,error:"Permission has expired"}):(await r.database.db.updateTable("corsair_permissions").set({status:t,updated_at:new Date}).where("id","=",s.id).execute(),{status:"ok"}):{status:"failed",retryable:!1,error:"Permission not found"}}async function ba(e,n){try{return await at(e,n),{status:"ok"}}catch(t){return{status:"failed",retryable:!1,error:t instanceof Error?t.message:"Credential delivery failed"}}}async function ka(e,n){try{return await Vt(e,n),{status:"ok"}}catch(t){return{status:"failed",retryable:!1,error:t instanceof Error?t.message:"Integration credential delivery failed"}}}async function er(e,n,t={}){let r=C(e),o=Yt(n.headers,"x-corsair-signature"),i=Yt(n.headers,"x-corsair-timestamp"),s=Yt(n.headers,"x-corsair-nonce");if(t.signingSecret?.trim()){let u=qe({body:n.body,signatureHeader:o,timestampHeader:i,signingSecret:t.signingSecret});if(!u.ok)return{status:"failed",retryable:!1,error:u.error};if(!s?.trim())return{status:"failed",retryable:!1,error:"Missing tunnel nonce"};let l=ct(`nonce:${s.trim()}`,Pe);if(!l.ok)return{status:"failed",retryable:!1,error:l.error}}else if(!t.allowUnsignedTunnel)return{status:"failed",retryable:!1,error:"Tunnel signing secret is required"};let a;try{a=JSON.parse(n.body)}catch{return{status:"failed",retryable:!1,error:"Invalid tunnel envelope JSON"}}if(a.type==="connect.status")return{status:"failed",retryable:!1,error:"connect.status is deprecated; use connections.sync signed delivery instead"};switch(a.type){case"webhook":return ya(e,r,a.payload);case"oauth.callback":return ma(e,a.payload);case"oauth.tokens":return ha(e,a.payload);case"permission.approve":return Qt(e,a.payload,"approved");case"permission.deny":return Qt(e,a.payload,"denied");case"auth.credentials":return ba(e,a.payload);case"integration.credentials":return ka(e,a.payload);case"connect.create_link":return ga(e,a.payload);case"connections.sync":{let u=t.signingSecret?.trim();return u?pa(e,u):{status:"failed",retryable:!1,error:"Tunnel signing secret is required for connections.sync"}}default:return Ca(String(a.type))}}function Ca(e){return Yr.has(e)?{status:"failed",retryable:!1,error:`Unsupported tunnel type: ${e}`}:{status:"failed",retryable:!1,error:`Unsupported tunnel type: ${e}`}}var nr=new Map;function ni(e){let n;try{n=M(e)}catch{return}let t=Pt(n);t&&nr.get(n.projectApiKey)!==t&&(nr.set(n.projectApiKey,t),N({hub:n,path:"/apps/announce",body:{deliveryUrl:t},parseResponse:()=>({ok:!0})}).catch(()=>{nr.delete(n.projectApiKey)}))}var wa=[".corsair.dev"];function va(e){return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}function Ta(e){try{let{hostname:n,protocol:t}=new URL(e);return t!=="http:"&&t!=="https:"?!1:va(n)?!0:wa.some(r=>n===r.slice(1)||n.endsWith(r))}catch{return!1}}function ti(e){return!e||!Ta(e)?null:{"Access-Control-Allow-Origin":e,"Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"content-type, x-corsair-signature, x-corsair-timestamp, x-corsair-project, x-corsair-nonce, access-control-request-private-network","Access-Control-Allow-Private-Network":"true","Access-Control-Max-Age":"0",Vary:"Origin"}}function ri(e,n){if(!n)return e;let t=new Headers(e.headers);for(let[r,o]of Object.entries(n))t.set(r,o);return new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}function tr(e,n){let t=new URL(e);return n.error?(t.searchParams.set("error",n.error),t.toString()):n.connectedPlugin?(t.searchParams.set("connected",n.connectedPlugin),t.toString()):(n.status!==void 0&&t.searchParams.set("status",Buffer.from(JSON.stringify(n.status)).toString("base64url")),t.toString())}async function rr(e,n){let t=M(e),o=new URL(n).searchParams.get("d");if(!o)return{type:"json",status:200,body:{status:"ok",message:"Corsair tunnel endpoint is active",timestamp:new Date().toISOString()}};let i=fe(o,t.signingSecret);if(!i)return{type:"json",status:400,body:{error:"Invalid or expired delivery token"}};let s=ct(`browser:${i.jti}`,ge);if(!s.ok)return{type:"json",status:400,body:{error:s.error}};try{if(gn(i)){if(!i.hubOrigin||!i.requestId)return{type:"json",status:400,body:{error:"Connections sync delivery requires hubOrigin and requestId for client bridge"}};let a=await pn(e,t.signingSecret);return{type:"text",status:200,headers:{"Content-Type":"text/html; charset=utf-8"},body:De({hubOrigin:i.hubOrigin,requestId:i.requestId,ok:!0,body:{status:"ok",sync:{encrypted:a}}})}}if(lt(i)){if(!i.hubOrigin||!i.requestId)return{type:"json",status:400,body:{error:"Connect link delivery requires hubOrigin and requestId for client bridge"}};let a=i.connectLinkPlugins?.filter(Boolean)??[];if(a.length===0)return{type:"json",status:400,body:{error:"Connect link delivery requires at least one plugin in connectLinkPlugins"}};let u=await st(e,{tenantId:i.tenantId,plugins:a});return{type:"text",status:200,headers:{"Content-Type":"text/html; charset=utf-8"},body:De({hubOrigin:i.hubOrigin,requestId:i.requestId,ok:!0,body:{status:"ok",connectUrl:u.connectUrl,expiresAt:u.expiresAt}})}}if(Se(i))return i.hubSuccessUrl?i.credentials?(await at(e,{plugin:i.plugin,tenantId:i.tenantId,credentials:i.credentials}),{type:"redirect",url:tr(i.hubSuccessUrl,{connectedPlugin:i.plugin})}):{type:"redirect",url:tr(i.hubSuccessUrl,{error:"Credential delivery missing credentials"})}:{type:"json",status:400,body:{error:"Credential delivery missing hubSuccessUrl"}};if(fn(i)){if(!i.permissionToken)return{type:"json",status:400,body:{error:"Permission delivery missing permission token"}};await Xt(e,i.permissionToken,i.deliveryMode==="permission.approve"?"approved":"denied")}else if(yn(i)){if(!i.accessToken)return{type:"json",status:400,body:{error:"Managed OAuth delivery missing access_token"}};await Ge(e,{plugin:i.plugin,tenantId:i.tenantId,accessToken:i.accessToken,refreshToken:i.refreshToken,expiresIn:i.expiresIn,scope:i.scope})}else{if(!dt(i)||!i.code||!i.state||!i.redirectUri)return{type:"json",status:400,body:{error:"Invalid BYO OAuth delivery token"}};await cn(e,{code:i.code,state:i.state,redirectUri:i.redirectUri,trusted:!0,plugin:i.plugin,tenantId:i.tenantId})}}catch(a){let u=a instanceof Error?a.message:"Hub delivery failed";return gn(i)&&i.hubOrigin&&i.requestId?{type:"text",status:400,headers:{"Content-Type":"text/html; charset=utf-8"},body:De({hubOrigin:i.hubOrigin,requestId:i.requestId,ok:!1,error:u})}:lt(i)&&i.hubOrigin&&i.requestId?{type:"text",status:400,headers:{"Content-Type":"text/html; charset=utf-8"},body:De({hubOrigin:i.hubOrigin,requestId:i.requestId,ok:!1,error:u})}:Se(i)&&i.hubSuccessUrl?{type:"redirect",url:tr(i.hubSuccessUrl,{error:u})}:Se(i)&&i.hubOrigin&&i.requestId?{type:"text",status:400,headers:{"Content-Type":"text/html; charset=utf-8"},body:De({hubOrigin:i.hubOrigin,requestId:i.requestId,ok:!1,error:u})}:{type:"json",status:400,body:{error:u}}}return{type:"redirect",url:i.hubSuccessUrl}}async function or(e,n){let t=M(e),r=await er(e,n,{signingSecret:t.signingSecret});if(r.status!=="ok")return{type:"json",status:r.retryable===!1?400:502,body:{error:r.error??"Tunnel processing failed"}};let o=r.webhookResponse;if(!o)return{type:"json",status:200,body:{status:"ok"}};let i=o.status??200,s=o.headers;return o.body&&typeof o.body=="object"&&!(o.body instanceof ArrayBuffer)?{type:"json",status:i,body:o.body,headers:s}:{type:"text",status:i,body:typeof o.body=="string"?o.body:o.body?JSON.stringify(o.body):null,headers:s}}function ir(e){if(e.type==="redirect")return Response.redirect(e.url,302);let n=new Headers;for(let[t,r]of Object.entries(e.headers??{}))typeof r=="string"&&n.set(t,r);return e.type==="json"?Response.json(e.body,{status:e.status,headers:n}):new Response(e.body,{status:e.status,headers:n})}async function sr(e,n){return n.method==="GET"?rr(e,n.url):or(e,{headers:n.headers,body:n.body??""})}async function ar(e,n){try{let t=await sr(e,n);return ir(t)}catch(t){if(t instanceof ie)return Response.json({error:t.message},{status:503});throw t}}async function Re(e,n){ni(e);let t=n.method.toUpperCase(),r=ti(n.headers.get("origin"));if(t==="OPTIONS")return r?new Response(null,{status:204,headers:r}):Response.json({error:"Method not allowed"},{status:405});if(t!=="GET"&&t!=="POST")return Response.json({error:"Method not allowed"},{status:405});let o=await ar(e,{method:t,url:n.url,headers:n.headers,body:t==="POST"?await n.text():void 0});return ri(o,r)}var $=class extends Error{pluginId;authType;constructor(n,t,r){super(r??`[auth-missing:${n}:${t}]`),Object.setPrototypeOf(this,new.target.prototype),this.name="AuthMissingError",this.pluginId=n,this.authType=t}};var oi=300;async function ur(e,n){let{keys:t,hub:r,plugin:o,tenantId:i}=e,s=n?.forceRefresh??!1,[a,u,l]=await Promise.all([t.get_access_token(),t.get_expires_at(),t.get_refresh_token()]);if(!a&&!l)throw new $(o,"managed");let c=Math.floor(Date.now()/1e3);if(!s&&a&&u&&Number(u)>c+oi)return{accessToken:a,expiresAt:Number(u),refreshed:!1};if(!l&&a&&!s){let d=u?Number(u):null;if(d===null||d>c+oi)return{accessToken:a,expiresAt:d??c+3600,refreshed:!1}}let p=await Aa(r,o,i),g=p.expires_in?c+p.expires_in:u?Number(u):c+3600;return await t.set_access_token(p.access_token),await t.set_expires_at(String(g)),p.refresh_token&&await t.set_refresh_token(p.refresh_token),p.scope&&await t.set_scope(p.scope),{accessToken:p.access_token,expiresAt:g,refreshed:!0}}function Pa(e){return e.includes("Managed OAuth connection not found")||e.includes("Managed OAuth connection has no tokens")}async function Aa(e,n,t){try{return await N({hub:e,path:"/oauth/refresh",body:{plugin:n,tenantId:t},parseResponse:In})}catch(r){let o=r instanceof Error?r.message:"";throw Pa(o)?new $(n,"managed"):r}}async function ii(e,n){e._refreshAuth=async()=>(await ur(n,{forceRefresh:!0})).accessToken}function si(e){return{delivery:n=>Re(e,n),deliveryOptions:n=>Re(e,n)}}var ai=1200*1e3;function cr(){return oe()}function lr(){return ai}function dr(e,n){return en(e,n,ai)}function pr(e,n){return X(e,n)}function gr(e){return Ae(e)}var ui=600*1e3;function fr(){return oe()}function yr(){return ui}function mr(e,n){return en(e,n,ui)}function hr(e,n){return X(e,n)}function br(e){return vt(e)}function kr(e){return Ae(e)}function Cr(){return oe()}function wr(e,n,t){return wn(e,n,Math.floor(t.getTime()/1e3))}function vr(e,n){return X(e,n)}function Tr(e){return Ae(e)}function pt(e,n){let t=[];e||t.push("database"),n||t.push("kek");let r={};return new Proxy(r,{get(o,i){let s=t.length>1;throw new Error(`corsair.keys.${String(i)}: Cannot access keys because ${t.join(" and ")} ${s?"are":"is"} not configured. Provide both 'database' and 'kek' in createCorsair() to enable key management.
20
+
21
+ To generate a KEK, run: openssl rand -base64 ${tn}`)}})}async function xa(e){let n=!1;for(;;){let t=await e.database.db.selectFrom("corsair_integrations").selectAll().where("name","=",e.integrationName).executeTakeFirst();if(!t){if(!n&&e.ensureProvisioned){n=!0,await e.ensureProvisioned();continue}throw new Error(`Integration "${e.integrationName}" not found. Make sure to create the integration first.`)}let r=await e.database.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",e.tenantId).where("integration_id","=",t.id).executeTakeFirst();if(!r){if(!n&&e.ensureProvisioned){n=!0,await e.ensureProvisioned();continue}throw new Error(`Account not found for tenant "${e.tenantId}" and integration "${e.integrationName}". Make sure to create the account first.`)}return{integrationId:t.id,accountId:r.id,integration:{id:t.id,config:t.config,dek:t.dek??null},account:{id:r.id,config:r.config,dek:r.dek??null}}}}async function ci(e){let{integrationId:n,accountId:t}=await xa(e);return{integrationId:n,accountId:t}}function Pr(e,n){return`[auth-missing:${e}] Authentication required. Direct the user to connect their account: ${n}`}async function Ia(e,n){let t=e.hub;if(!t||!n.database||!n.kek)return null;try{return(await Dt(t,{tenantId:n.tenantId,plugin:n.plugin,database:n.database,kek:n.kek,plugins:n.plugins,multiTenancy:n.multiTenancy})).connectUrl}catch{return null}}async function Sa(e){let n=e.hub;if(n&&e.database&&e.kek)try{let r=await Dt(n,{tenantId:e.tenantId,plugin:e.plugin,database:e.database,kek:e.kek,plugins:e.plugins,multiTenancy:e.multiTenancy});return e.manual?.onAuthMissing?e.manual.onAuthMissing({plugin:e.pluginId,connectUrl:r.connectUrl,state:r.token}):Pr(e.pluginId,r.connectUrl)}catch{return`[auth-missing:${e.pluginId}:${e.authType}] Authentication required. Could not create connect link. Check hub configuration and server logs.`}let t=await Ia({manual:e.manual,hub:e.hub},{plugin:e.plugin,tenantId:e.tenantId,database:e.database,kek:e.kek,plugins:e.plugins,multiTenancy:e.multiTenancy});return t?Pr(e.pluginId,t):`[auth-missing:${e.pluginId}:${e.authType}]`}function Ra(e,n,t){let r=Be(be(e,n.tenantId??t??"default"),n.kek),o=new URL(n.baseUrl);o.searchParams.set("state",r);let i=o.toString();return n.onAuthMissing?n.onAuthMissing({plugin:e,connectUrl:i,state:r}):Pr(e,i)}async function Ea(e){let n=e.tenantId??"default",t=e.error.pluginId;return e.manual&&$e(e.manual)&&e.manual.oauthConfig&&e.manual.kek&&e.error.authType==="oauth_2"?Ra(t,{...e.manual,baseUrl:e.manual.baseUrl,kek:e.manual.kek},e.tenantId):e.hub&&e.plugin&&e.kek&&e.database&&e.plugins?Sa({manual:e.manual,hub:e.hub,plugin:e.plugin,pluginId:t,tenantId:n,authType:e.error.authType,database:e.database,kek:e.kek,plugins:e.plugins,multiTenancy:e.multiTenancy}):e.error.message}async function li(e){let n=await Ea(e);throw new $(e.error.pluginId,e.error.authType,n)}var _a=async(e,n)=>(console.error(`[corsair:${n.pluginId}:${n.operation}]`,{error:e.message,input:n.input}),{maxRetries:0});async function di(e,n,t,r,o){let i={pluginId:n,operation:t,input:r,originalError:e},s=Object.keys(o).find(l=>o[l]?.match(e,i));return await(o[s||"DEFAULT"]?.handler||_a)(e,i)}function Da(e){return typeof e=="function"}function Ar({endpoints:e,hooks:n,ctx:t,tree:r,pluginId:o,errorHandlers:i,currentPath:s=[],keyBuilder:a,permissionsConfig:u,endpointMeta:l,database:c,permissionsOptions:p,tenantId:g,manualConfig:d,hubConfig:y,plugin:f,kek:m,allPlugins:h,multiTenancy:k}){for(let[w,R]of Object.entries(e)){let x=n?.[w];if(Da(R)){let E=x,b=[...s,w].join("."),v=async(T={})=>{let j=l?.[b];Lt(b,j?.riskLevel??"write");let te;if(u){let W=j,{result:bn,reason:Y,onComplete:Ye,token:re,id:Te,expiresAt:K}=await $o({pluginId:o,endpointPath:b,args:T,mode:u.mode,override:u.overrides?.[b],riskLevel:W?.riskLevel??"write",meta:W,db:c,timeoutMs:p?Nt(p.timeout):void 0,tenantId:g,approvalMode:p?.mode});if(bn==="blocked"){let Q;throw Y==="denied"?Q=`Action '${b}' was denied by the user. Await further instructions before proceeding.`:Y==="policy"?Q=`Action '${b}' is blocked by the permission policy. Update the corsair config to allow it.`:Y==="timeout"?Q=`Action '${b}' timed out waiting for approval.`:re&&Te?Q=await Ut({permissionsOptions:p,manual:d,hub:y,permissionId:Te,permissionToken:re,plugin:o,endpoint:b,args:T,tenantId:g??"default",expiresAt:K??new Date(Date.now()+(p?Nt(p.timeout):600*1e3)).toISOString(),operationPath:b}):Q=`Action '${b}' requires user approval before it can run.`,new je(Q)}te=Ye}let P=async(W,bn,Y)=>{try{return await R(bn,Y)}catch(Ye){if(Ye instanceof Error){let re=await di(Ye,o,b,typeof Y=="object"&&Y!==null?Y:{args:Y},i);if(W<(re.maxRetries||0)){let Te=W+1;console.log(`Retrying (${Te} / ${re.maxRetries})...`);let K;if(re.headersRetryAfterMs)K=re.headersRetryAfterMs;else switch(re.retryStrategy){case"exponential_backoff":K=Math.pow(2,Te-1)*1e3;break;case"exponential_backoff_jitter":let Q=Math.pow(2,Te-1)*1e3,Li=(Math.random()-.5)*1e3;K=Math.max(0,Q+Li);break;case"linear_1s":K=1e3;break;case"linear_2s":K=2e3;break;case"linear_3s":K=3e3;break;case"linear_4s":K=4e3;break;default:K=1e3;break}await new Promise(Q=>setTimeout(Q,K)),await P(Te,bn,Y),console.log(`[corsair:${o}:${b}] Retry strategy:`,re)}}throw Ye}},V;try{V=a?await a(t,"endpoint"):void 0}catch(W){throw W instanceof $&&(f&&y&&un({hub:y,database:c,kek:m,plugins:h??[],plugin:f,tenantId:g,verified:!1}),await li({error:W,manual:d,hub:y,plugin:f,tenantId:g,database:c,kek:m,plugins:h,multiTenancy:k})),W}if(!E?.before&&!E?.after){let W=await P(0,{...t,key:V},T);return await te?.(),f&&y&&un({hub:y,database:c,kek:m,plugins:h??[],plugin:f,tenantId:g,verified:!0}),W}let Ve={...t,key:V},ve=E.before?await E.before(Ve,T):{ctx:Ve,args:T,continue:!0,passToAfter:void 0};if(ve.continue===!1)return;let Lr=await P(0,ve.ctx,ve.args);return await E.after?.(ve.ctx,Lr,ve.passToAfter),await te?.(),f&&y&&un({hub:y,database:c,kek:m,plugins:h??[],plugin:f,tenantId:g,verified:!0}),Lr};r[w]=v}else if(R&&typeof R=="object"){let E={};Ar({endpoints:R,hooks:x,ctx:t,tree:E,pluginId:o,errorHandlers:i,currentPath:[...s,w],keyBuilder:a,permissionsConfig:u,endpointMeta:l,database:c,permissionsOptions:p,tenantId:g,manualConfig:d,hubConfig:y,plugin:f,kek:m,allPlugins:h,multiTenancy:k}),r[w]=E}}}function Oa(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function xr({webhooks:e,hooks:n,ctx:t,webhooksTree:r,keyBuilder:o}){for(let[i,s]of Object.entries(e)){let a=n?.[i];if(Oa(s)){let u=a,l=async c=>{let p=(d,y)=>s.handler(d,y),g=o?await o(t,"webhook"):void 0;return!u?.before&&!u?.after?p({...t,key:g},c):(async()=>{let d={...t,key:g},y=u.before?await u.before(d,c):{ctx:d,args:c,continue:!0,passToAfter:void 0};if(y.continue===!1)return;let f=await p(y.ctx,y.args);return f?.success===!0&&await u.after?.(y.ctx,f,y.passToAfter),f})()};r[i]={match:s.match,handler:l}}else if(s&&typeof s=="object"){let u={};xr({webhooks:s,hooks:a,ctx:t,webhooksTree:u,keyBuilder:o}),r[i]=u}}}function Ma(e,n,t,r){let o=null;return async()=>{if(o)return o;if(!e)throw new Error("Database not configured");let{accountId:i}=await ci({database:e,integrationName:n,tenantId:t,ensureProvisioned:r});return o=i,o}}function Ha(e,n,t,r,o){return e?kt(e.db,n,t,r,o):{findByEntityId:async()=>null,existsByEntityId:async()=>!1,findIdByEntityId:async()=>null,findById:async()=>null,findManyByEntityIds:async()=>[],list:async()=>[],search:async()=>[],upsertByEntityId:async()=>{throw new Error("Database not configured")},deleteById:async()=>!1,deleteByEntityId:async()=>!1,count:async()=>0}}function Ir(e,n){let{database:t,tenantId:r,kek:o,rootErrorHandlers:i,permissionsOptions:s,manualConfig:a,hubConfig:u,internalConfig:l}=n,c=l&&t?()=>Fe(l,r??"default"):void 0,p={},g={};for(let d of e)p[d.id]={},g[d.id]={};for(let d of e){let y=d.schema,f=r??"default",m=Ma(t,d.id,f,c);if(y?.entities){let P={};for(let[V,Ve]of Object.entries(y.entities)){let ve=t?kt(t.db,m,V,y.version,Ve):Ha(void 0,m,V,y.version,Ve);P[V]=ve}g[d.id].db=P,p[d.id].db=P}let h=d.options,k=d.authConfig,w;if(t&&o&&h?.authType){let P=k?.[h.authType]?.account??[];w=_({authType:h.authType,integrationName:d.id,tenantId:f,kek:o,database:t,extraAccountFields:P,ensureProvisioned:c}),p[d.id].keys=w}let R={database:t,db:g[d.id]?.db??{},$getAccountId:m,...d.options?{options:d.options}:{},...w?{keys:w,authType:h?.authType}:{},tenantId:f,...u?{hub:u}:{}},x=d.endpoints??{},E=d.hooks,b={...i,...d.errorHandlers},v={},T=d.options?.permissions;Ar({endpoints:x,hooks:E,ctx:R,tree:v,pluginId:d.id,errorHandlers:b,currentPath:[],keyBuilder:d.keyBuilder,permissionsConfig:T,endpointMeta:d.endpointMeta,database:t,permissionsOptions:s,tenantId:r,manualConfig:a?{...a,oauthConfig:d.oauthConfig,kek:o,tenantId:f}:void 0,hubConfig:u,plugin:d,kek:o,allPlugins:e,multiTenancy:l?.multiTenancy}),Object.keys(v).length>0&&(p[d.id].api=v),R.endpoints=v;let j=d.webhooks??{},te=d.webhookHooks;if(Object.keys(j).length>0){let P={};xr({webhooks:j,hooks:te,ctx:R,webhooksTree:P,keyBuilder:d.keyBuilder}),p[d.id].webhooks=P,d.pluginWebhookMatcher&&(p[d.id].pluginWebhookMatcher=d.pluginWebhookMatcher),d.pluginTenantWebhookMatcher&&(p[d.id].pluginTenantWebhookMatcher=d.pluginTenantWebhookMatcher)}}return p}function pi(e,n,t){let r={};for(let o of e){let i=o.options,s=o.authConfig;if(i?.authType){let a=s?.[i.authType]?.integration??[],u=D({authType:i.authType,integrationName:o.id,kek:t,database:n,extraIntegrationFields:a});r[o.id]=u}}return r}var Fa="createCorsair({ approval: ... }) is deprecated. Rename to permissions: { timeout, onTimeout, mode }.";function gi(e){let{permissions:n,approval:t}=e;if(n&&t)throw new Error("createCorsair was given both permissions and approval config. Use permissions only \u2014 approval is deprecated.");return t?(console.warn(`[corsair] ${Fa}`),t):n}var fi=[{method:"GET",pattern:"/ok",handler:async()=>O(200,Zn())},{method:"GET",pattern:"/tenants",handler:async({internal:e})=>O(200,await Ke(e))},{method:"POST",pattern:"/tenants",handler:async({internal:e,body:n})=>O(201,await zn(e,n))},{method:"GET",pattern:"/tenants/:id",handler:async({internal:e,params:n})=>O(200,await Jn(e,n.id))},{method:"GET",pattern:"/plugins",handler:async({internal:e})=>O(200,await We(e))},{method:"GET",pattern:"/plugins/:id",handler:async({internal:e,params:n})=>O(200,await Gn(e,n.id))},{method:"GET",pattern:"/connection-status",handler:async({internal:e,query:n})=>O(200,await Vn(e,n.tenantId))},{method:"GET",pattern:"/permissions/:id",handler:async({internal:e,params:n})=>O(200,await $t(e,n.id))},{method:"POST",pattern:"/permissions/lookup-by-token",handler:async({internal:e,body:n})=>{let t=n?.token?.trim();return t?O(200,await Wt(e,t)):O(400,{error:"bad_request",message:"token is required",missingFields:["token"]})}},{method:"POST",pattern:"/connect/links",handler:async({corsair:e,internal:n,body:t})=>O(200,await Yn(e,n,t))},{method:"GET",pattern:"/connect/resolve",handler:async({corsair:e,internal:n,query:t})=>O(200,await Qn(e,n,t.state??""))},{method:"POST",pattern:"/connect/oauth/callback",handler:async({corsair:e,internal:n,body:t})=>O(200,await Xn(e,n,t))}];(()=>{let e=new Set;for(let n of fi){let t=`${n.method} ${n.pattern}`;if(e.has(t))throw new Error(`Duplicate management route registered: ${t}`);e.add(t)}})();function Ba(e,n){let t=e.split("/").filter(Boolean),r=n.split("/").filter(Boolean);if(t.length!==r.length)return null;let o={};for(let i=0;i<t.length;i++){let s=t[i],a=r[i];if(s.startsWith(":"))o[s.slice(1)]=decodeURIComponent(a);else if(s!==a)return null}return o}function Ua(e,n){if(!n)return e;let t=n.endsWith("/")?n.slice(0,-1):n;return e===t?"/":e.startsWith(`${t}/`)?e.slice(t.length):e}async function La(e){if(!(e.method==="GET"||e.method==="HEAD"||!(e.headers.get("content-type")??"").includes("application/json")))try{let t=await e.text();return t?JSON.parse(t):void 0}catch{throw new S(400,"invalid_json","Request body is not valid JSON")}}var Na="/api/corsair";function Ee(e,n={}){let t=n.basePath??Na,r=C(e,()=>new Error("managementHandler: invalid corsair instance (missing internal config)"));return async o=>{try{let i=new URL(o.url),s=Ua(i.pathname,t),a=o.method.toUpperCase();if(a==="OPTIONS"||s==="/"||s==="")return await Re(e,o);if(a!=="GET"&&a!=="POST")return O(405,{error:"method_not_allowed",message:`Method ${a} not allowed`});let u=Object.fromEntries(i.searchParams);for(let l of fi){if(l.method!==a)continue;let c=Ba(l.pattern,s);if(!c)continue;let p=await La(o);return await l.handler({corsair:e,internal:r,req:o,params:c,query:u,body:p})}throw ke(`No route for ${a} ${s}`)}catch(i){if(n.onError){let a=await n.onError(i,o);if(a)return a}if(i instanceof S)return jo(i);let s=i instanceof Error?i.message:"Internal server error";return O(500,{error:"internal_error",message:s})}}}function $a(e){let n=e.get?.("host")??"localhost",t=e.protocol??"http",r=e.originalUrl??e.url,o=`${t}://${n}${r}`,i=new Headers;for(let[u,l]of Object.entries(e.headers))if(l!=null)if(Array.isArray(l))for(let c of l)i.append(u,c);else i.set(u,l);let s=e.method!=="GET"&&e.method!=="HEAD",a={method:e.method,headers:i};return s&&e.body!==void 0&&(a.body=typeof e.body=="string"?e.body:JSON.stringify(e.body),i.has("content-type")||i.set("content-type","application/json")),new Request(o,a)}async function ja(e,n){e.status(n.status),n.headers.forEach((r,o)=>e.setHeader(o,r));let t=Buffer.from(await n.arrayBuffer());e.send(t)}function yi(e,n){let t=Ee(e,n);return async(r,o,i)=>{try{let s=await t($a(r));await ja(o,s)}catch(s){i(s)}}}function mi(e,n){let t=Ee(e,n);return r=>t(r.req.raw)}function hi(e,n){let t=Ee(e,n);return{GET:t,POST:t,OPTIONS:t}}function bi(e){let n={[mn]:e};return{ok:Zn,tenants:{list:()=>Ke(e),create:t=>zn(e,t),get:t=>Jn(e,t)},plugins:{list:()=>We(e),get:t=>Gn(e,t)},connectionStatus:{get:t=>Vn(e,t?.tenantId)},permissions:{get:t=>Jo(e,t)},connect:{createLink:t=>Yn(n,e,t),resolve:t=>Qn(n,e,t),oauthCallback:t=>Xn(n,e,t)}}}async function ki(e,n,t,r,o="pending"){if(!e)return null;try{let i=qr(),s=new Date;return await e.db.insertInto("corsair_events").values({id:i,created_at:s,updated_at:s,account_id:n,event_type:t,payload:r,status:o}).execute(),i}catch(i){return console.warn("Failed to log event:",i),null}}async function Wa(e,n,t,r="pending"){try{let o=await e.$getAccountId();return ki(e.database,o,n,t,r)}catch(o){return console.warn("Failed to log event:",o),null}}import*as wi from"https";import*as gt from"querystring";var Ka=["expires_in","refresh_token_expires_in"];function Ci(e){let n={...e};for(let t of Ka){let r=e[t];if(typeof r=="string"){let o=Number(r);n[t]=Number.isFinite(o)?o:void 0}}return n}function qa(e){try{return Ci(JSON.parse(e))}catch{}if(!e.includes("="))return null;let n=gt.parse(e);return!n.access_token&&!n.error?null:Ci({...n})}function Un(e,n,t,r,o){let i=new URL(r.tokenUrl),s=r.tokenAuthMethod==="basic";return new Promise((a,u)=>{let l={code:e.trim(),redirect_uri:o,grant_type:"authorization_code"};s||(l.client_id=n,l.client_secret=t);let c=gt.stringify(l),p={"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json","Content-Length":Buffer.byteLength(c).toString()};s&&(p.Authorization=`Basic ${Buffer.from(`${n}:${t}`).toString("base64")}`);let g=wi.request({hostname:i.hostname,...i.port?{port:Number(i.port)}:{},path:i.pathname+i.search,method:"POST",headers:p},d=>{let y="";d.on("data",f=>{y+=f}),d.on("end",()=>{if(d.statusCode!==200){u(new Error(`Token exchange failed (${d.statusCode}): ${y}`));return}let f=qa(y);f?a(f):u(new Error(`Token endpoint returned non-JSON response: ${y}`))})});g.on("error",d=>u(new Error(`Request failed: ${d.message}`))),g.write(c),g.end()})}var vi=" ";function J(e){let n=e;return n._def??n.def??{}}function z(e){let n=e.typeName;if(n)return n;let t=e.type;if(t)return`Zod${t.split("_").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join("")}`}function G(e){return e.innerType??e.schema??e.out??e.in}function Pi(e,n){switch(n){case"ZodPipe":return e.in??e.innerType;case"ZodEffects":return e.schema??e.innerType;case"ZodTransform":return e.schema??e.innerType??e.in;default:return G(e)}}function Ai(e){let n=e.type;return e.element??(typeof n=="string"?void 0:n)}function yt(e,n){let t=n.shape??e.shape;return typeof t=="function"?t():t}function Je(e){return Array.isArray(e.options)?e.options:Array.isArray(e.values)?e.values:e.entries!==null&&typeof e.entries=="object"&&!Array.isArray(e.entries)?Object.values(e.entries):[]}function xi(e,n){return e.description??n.description}function Za(e){let n=e;for(;n;){let t=J(n),r=xi(n,t);if(r)return r;let o=z(t);if(Dr(o)||o==="ZodPipe"||o==="ZodEffects"||o==="ZodTransform"){n=Pi(t,o);continue}break}}function Dr(e){return e==="ZodOptional"||e==="ZodNullable"||e==="ZodDefault"||e==="ZodCatch"}function U(e){let n=J(e),t=z(n);switch(t){case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodDate":return"Date";case"ZodNull":return"null";case"ZodUnknown":case"ZodAny":return"any";case"ZodLiteral":return String(n.value??Je(n)[0]??"unknown");case"ZodEnum":return Je(n).map(r=>String(r)).join(" | ");case"ZodOptional":{let r=G(n);return r?U(r):"unknown"}case"ZodNullable":{let r=G(n);return`${r?U(r):"unknown"} | null`}case"ZodDefault":case"ZodCatch":{let r=G(n);return r?U(r):"unknown"}case"ZodArray":{let r=Ai(n);if(!r)return"unknown[]";let o=J(r),i=z(o)==="ZodUnion",s=U(r);return`${i?`(${s})`:s}[]`}case"ZodRecord":return"{}";case"ZodObject":{let r=yt(e,n),o=Object.entries(r);return o.length===0?"{}":`{ ${o.map(([s,a])=>{let u=z(J(a));return`${u==="ZodOptional"||u==="ZodNullable"?s+"?":s}: ${U(a)}`}).join(", ")} }`}case"ZodUnion":return Je(n).map(r=>U(r)).join(" | ");case"ZodIntersection":return`${U(n.left)} & ${U(n.right)}`;case"ZodPipe":case"ZodTransform":case"ZodEffects":{let r=Pi(n,t);return r?U(r):"unknown"}default:return(t??"unknown").replace("Zod","").toLowerCase()}}function le(e){let n=J(e),t=z(n),r=xi(e,n);switch(t){case"ZodString":return{kind:"string",optional:!1,description:r};case"ZodNumber":return{kind:"number",optional:!1,description:r};case"ZodBoolean":return{kind:"boolean",optional:!1,description:r};case"ZodLiteral":{let o=n.value??Je(n)[0],i=typeof o=="string"||typeof o=="number"||typeof o=="boolean"?o:String(o??"");return{kind:"literal",optional:!1,description:r,value:i}}case"ZodEnum":{let o=Je(n).map(i=>String(i));return{kind:"string",optional:!1,description:r,enum:o}}case"ZodOptional":{let o=G(n),i=o?le(o):{kind:"unknown",optional:!1};return{...i,optional:!0,description:r??i.description}}case"ZodNullable":{let o=G(n),i=o?le(o):{kind:"unknown",optional:!1};return{...i,optional:!0,description:r??i.description}}case"ZodDefault":case"ZodCatch":{let o=G(n);return o?{...le(o),description:r}:{kind:"unknown",optional:!1,description:r}}case"ZodArray":{let o=Ai(n);return{kind:"array",optional:!1,description:r,items:o?le(o):{kind:"unknown",optional:!1}}}case"ZodObject":{let o=yt(e,n),i={};for(let[s,a]of Object.entries(o))i[s]=le(a);return{kind:"object",optional:!1,description:r,fields:i}}case"ZodRecord":return{kind:"unknown",optional:!1,description:r};case"ZodUnion":{let o=Je(n);for(let i of o){let s=J(i);if(z(s)==="ZodObject")return{...le(i),description:r}}return{kind:"unknown",optional:!1,description:r}}case"ZodIntersection":case"ZodPipe":case"ZodTransform":case"ZodEffects":{let o=G(n);return o?{...le(o),description:r}:{kind:"unknown",optional:!1,description:r}}default:return{kind:"unknown",optional:!1,description:r}}}function Sf(e,n){let t=n.toLowerCase(),r=t.indexOf(".");if(r===-1)return null;let o=t.slice(0,r),i=t.slice(r+1),s=e.find(c=>c.id===o);if(!s)return null;let a=i;a.startsWith("api.")&&(a=a.slice(4));let u=we(s.endpointMeta,a),l=we(s.endpointSchemas,a);return!u&&!l?null:{input:l?.input?le(l.input):null,output:l?.output?le(l.output):null,description:u?.description}}var Or=["equals","contains","startsWith","endsWith","in"],Ga=["equals","gt","gte","lt","lte","in"],Ja=["equals"],za=["equals","before","after","between"];function Ii(e){let n=J(e);switch(z(n)){case"ZodOptional":case"ZodNullable":case"ZodDefault":case"ZodCatch":{let r=G(n);return r?Ii(r):null}case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodDate":return"date";default:return null}}function Mr(e){let n=J(e),t=z(n);if(Dr(t)){let i=G(n);return i?Mr(i):{}}if(t!=="ZodObject")return{};let r=yt(e,n),o={};for(let[i,s]of Object.entries(r)){let a=Ii(s);a==="string"?o[i]={type:"string",operators:Or}:a==="number"?o[i]={type:"number",operators:Ga}:a==="boolean"?o[i]={type:"boolean",operators:Ja}:a==="date"&&(o[i]={type:"date",operators:za})}return o}function Si(e,n){for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return[t,r]}function Rr(e,n,t){for(let[r,o]of Object.entries(e)){let i=[...n,r];typeof o=="function"?t.push(i.join(".")):o!==null&&typeof o=="object"&&Rr(o,i,t)}}function Er(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function _r(e,n,t){for(let[r,o]of Object.entries(e)){let i=[...n,r];Er(o)?t.push(i.join(".")):o!==null&&typeof o=="object"&&_r(o,i,t)}}function Hr(e,n){if(n.length===0)return null;let[t,...r]=n,o=Object.entries(e).find(([a])=>a.toLowerCase()===t);if(!o)return null;let[i,s]=o;if(r.length===0)return Er(s)?[i]:null;if(s!==null&&typeof s=="object"&&!Er(s)){let a=Hr(s,r);if(a!==null)return[i,...a]}return null}function Ri(e,n){let t=[];t.push(`${e}({`),t.push(" webhookHooks: {");for(let i=0;i<n.length;i++){let s=" ".repeat(i+2);t.push(`${s}${n[i]}: {`)}let r=" ".repeat(n.length+2),o=r+" ";t.push(`${r}before(ctx, args) {`),t.push(`${o}return { ctx, args };`),t.push(`${r}},`),t.push(`${r}after(ctx, response) {`),t.push(`${r}},`);for(let i=n.length-1;i>=0;i--){let s=" ".repeat(i+2);t.push(`${s}},`)}return t.push(" },"),t.push("})"),t.join(`
22
+ `)}var Va=new Set(Cn);function _e(e,n){let t=n?.type??"api",r=n?.plugin;if(r!==void 0){let i=e.find(a=>a.id===r);if(!i)return Va.has(r)?`This plugin (${r}) is not configured. Please add it to the Corsair instance to see its associated methods.`:_e(e);if(t==="webhooks"){if(!i.webhooks)return[];let a=[];return _r(i.webhooks,[],a),a.map(u=>`${i.id}.webhooks.${u}`)}if(t==="db"){let a=i.schema?.entities;return a?Object.keys(a).map(u=>`${i.id}.db.${u}.search`):[]}if(!i.endpoints)return[];let s=[];return Rr(i.endpoints,[],s),s.map(a=>`${i.id}.api.${a}`)}let o={};if(t==="webhooks")for(let i of e){if(!i.webhooks)continue;let s=[];_r(i.webhooks,[],s),o[i.id]=s.map(a=>`${i.id}.webhooks.${a}`)}else if(t==="db")for(let i of e){let s=i.schema?.entities;s&&(o[i.id]=Object.keys(s).map(a=>`${i.id}.db.${a}.search`))}else for(let i of e){if(!i.endpoints)continue;let s=[];Rr(i.endpoints,[],s),o[i.id]=s.map(a=>`${i.id}.api.${a}`)}return o}function we(e,n){if(e){for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n)return r}}function Ya(e,n){let t=e.toLowerCase(),r=n.toLowerCase();if(!t.startsWith(`${r}.`)){let i=t.slice(n.length+1),s=i.startsWith(".")?i.slice(1):i;return s.startsWith("api.")&&(s=s.slice(4)),{shortPath:s,lookupKey:s}}let o=e.slice(n.length+1);return o.toLowerCase().startsWith("api.")&&(o=o.slice(4)),{shortPath:o,lookupKey:o.toLowerCase()}}function Sr(e,n){return typeof e=="string"?e:Array.isArray(e)?`${n}:
23
+ ${e.join(", ")}`:`${n}:
24
+ `+Object.entries(e).map(([t,r])=>` ${t}: ${r.join(", ")}`).join(`
25
+ `)}function Rf(e,n){let t=n.toLowerCase(),r=t.indexOf(".");if(r!==-1){let o=t.slice(0,r),i=t.slice(r+1),s=e.find(a=>a.id===o);if(s){if(i.startsWith("db.")){let c=i.slice(3),p=c.lastIndexOf(".");if(p!==-1){let g=c.slice(0,p),d=c.slice(p+1),y=s.schema?.entities;if(d==="search"&&y){let f=Si(y,g);if(f){let[m,h]=f,k=Mr(h),w=[`Search ${o} ${m} stored in the local database.`,"Pass limit and offset as numbers for pagination.","","filters {",` entity_id: string [${Or.join(", ")}]`];for(let[R,x]of Object.entries(k))w.push(` ${R}?: ${x.type} [${x.operators.join(", ")}]`);return w.push("}"),w.join(`
26
+ `)}}}return Sr(_e(e,{type:"db"}),"Path not found. Available db operations")}if(i.startsWith("webhooks.")){let c=i.slice(9);if(s.webhooks){let p=Hr(s.webhooks,c.split("."));if(p!==null){let g=p.join("."),d=we(s.webhookSchemas,g.toLowerCase()),y=d?.response?U(d.response):null,f=[];return d?.description&&f.push(d.description),d?.payload&&f.push(`payload ${ft(ze(d.payload))}`),y&&f.push(`response: ${y}`),f.push(`usage:
27
+ ${Ri(o,p)}`),f.join(`
28
+
29
+ `)}}return Sr(_e(e,{type:"webhooks"}),"Path not found. Available webhooks")}let a=i;a.startsWith("api.")&&(a=a.slice(4));let u=we(s.endpointMeta,a),l=we(s.endpointSchemas,a);if(u||l){let c=[],p=[u?.riskLevel?`[${u.riskLevel}]`:"",u?.irreversible?"[irreversible]":""].filter(Boolean).join(" "),g=[u?.description,p].filter(Boolean).join(" ");return g&&c.push(g),l?.input&&c.push(`input ${ft(ze(l.input))}`),l?.output&&c.push(`output ${ft(ze(l.output))}`),c.join(`
30
+
31
+ `)}}}return Sr(_e(e),"Path not found. Available operations")}function Ti(e){let n=e;for(;;){let t=J(n),r=z(t);if(Dr(r)){let o=G(t);if(!o)return n;n=o;continue}return n}}function ze(e){if(e===void 0)return{kind:"inline",type:"unknown"};let n=Ti(e),t=J(n);if(z(t)==="ZodObject"){let o=yt(n,t),i=[];for(let[s,a]of Object.entries(o)){let u=J(a),l=z(u),c=l==="ZodOptional"||l==="ZodNullable",p=Ti(a),g=Za(a);i.push({key:s,optional:c,type:U(p),...g!==void 0?{description:g}:{}})}return{kind:"object",fields:i}}return{kind:"inline",type:U(n)}}function ft(e,n=0){if(e===void 0)return"{}";if(e.kind==="inline")return e.type;if(e.kind==="object"){if(e.fields.length===0)return"{}";let t=vi.repeat(n+1),r=vi.repeat(n);return`{
32
+ ${e.fields.map(i=>{let s=i.optional?`${i.key}?`:i.key,a=i.description?` // ${i.description}`:"";return`${t}${s}: ${i.type}${a}`}).join(`
33
+ `)}
34
+ ${r}}`}return"unknown"}function Qa(e,n){let t=_e(e,{plugin:n,type:"api"});if(typeof t=="string")return{ok:!1,error:t};if(!Array.isArray(t))return{ok:!1,error:"list_operations did not return a path array \u2014 pass a configured plugin id."};let r=e.find(c=>c.id===n);if(!r)return{ok:!1,error:`Plugin "${n}" is not configured on this instance.`};let o=[];for(let c of t){let{shortPath:p,lookupKey:g}=Ya(c,n),d=we(r.endpointMeta,g),y=we(r.endpointSchemas,g);!d&&!y||o.push({path:c,shortPath:p,description:d?.description,riskLevel:d?.riskLevel,irreversible:d?.irreversible,input:ze(y?.input),output:ze(y?.output)})}o.sort((c,p)=>c.path.localeCompare(p.path));let i=[],s=_e(e,{plugin:n,type:"webhooks"});if(Array.isArray(s)&&r.webhooks)for(let c of s){let g=c.toLowerCase().slice(n.length+1),d=g.startsWith(".")?g.slice(1):g;if(!d.startsWith("webhooks."))continue;let y=d.slice(9),f=Hr(r.webhooks,y.split("."));if(f===null)continue;let m=f.join("."),h=we(r.webhookSchemas,m.toLowerCase()),k=h?.response?U(h.response):void 0;i.push({path:c,description:h?.description,payload:ze(h?.payload),responseType:k,usageExample:Ri(n,f)})}i.sort((c,p)=>c.path.localeCompare(p.path));let a=[],u=_e(e,{plugin:n,type:"db"}),l=r.schema?.entities;if(Array.isArray(u)&&l)for(let c of u){let g=c.toLowerCase().slice(n.length+1),d=g.startsWith(".")?g.slice(1):g;if(!d.startsWith("db."))continue;let y=d.slice(3),f=y.lastIndexOf(".");if(f===-1)continue;let m=y.slice(0,f);if(y.slice(f+1)!=="search")continue;let k=Si(l,m);if(!k)continue;let[w,R]=k,x=Mr(R),E=Object.entries(x).map(([b,v])=>({field:b,type:v.type,operators:v.operators}));a.push({path:c,entityName:w,filters:[{field:"entity_id",type:"string",operators:Or},...E]})}return a.sort((c,p)=>c.path.localeCompare(p.path)),{ok:!0,data:{pluginId:n,api:o,webhooks:i,db:a}}}import{randomUUID as Ei}from"crypto";async function Xa(e,n){let t=await e.keys.get_access_token();if(!t)return null;let r=Ei(),o=Ei(),i=await fetch(n.watchUrl,{method:"POST",signal:AbortSignal.timeout(2e4),headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:JSON.stringify({id:r,type:"web_hook",address:n.webhookUrl,token:o,...n.body})});if(!i.ok)throw new Error(`Google channel watch failed (${i.status}): ${await i.text()}`);return{webhookLink:{linkType:"channel_id",externalId:r},webhookSecret:o}}import{randomUUID as eu}from"crypto";var mt="https://graph.microsoft.com/v1.0",Fr=2e4,nu=60;async function tu(e,n){let t=await e.keys.get_access_token();if(!t)return null;let r={authorization:`Bearer ${t}`};try{let u=await fetch(`${mt}/subscriptions`,{headers:r,signal:AbortSignal.timeout(Fr)});if(u.ok){let{value:l}=await u.json(),c=(l??[]).filter(p=>p.notificationUrl===n.webhookUrl);await Promise.all(c.map(p=>fetch(`${mt}/subscriptions/${p.id}`,{method:"DELETE",headers:r,signal:AbortSignal.timeout(Fr)}).catch(()=>{})))}}catch{}let o=eu(),i=new Date(Date.now()+nu*6e4).toISOString(),s=await fetch(`${mt}/subscriptions`,{method:"POST",headers:{...r,"content-type":"application/json"},signal:AbortSignal.timeout(Fr),body:JSON.stringify({changeType:n.changeType,notificationUrl:n.webhookUrl,resource:n.resource,expirationDateTime:i,clientState:o})});if(!s.ok)throw new Error(`MS Graph subscribe failed (${s.status}): ${await s.text()}`);let a=await s.json();return a.id?(await e.keys.set_webhook_signature(o),{webhookLink:{linkType:"subscription_id",externalId:a.id},webhookSecret:o}):null}function _i(e,n){for(let[t,r]of Object.entries(e))if(r?.pluginWebhookMatcher&&r.pluginWebhookMatcher(n))return t;return null}function ru(e,n){let t=_i(e,n);if(!t)return null;let r=e[t];if(!r?.pluginTenantWebhookMatcher)return null;let o=r.pluginTenantWebhookMatcher(n);return o?{plugin:t,tenantMatch:o}:null}function ou(e){let n={};for(let t of e)!t.pluginWebhookMatcher&&!t.pluginTenantWebhookMatcher||(n[t.id]={pluginWebhookMatcher:t.pluginWebhookMatcher,pluginTenantWebhookMatcher:t.pluginTenantWebhookMatcher});return n}function Di(e,n){let t=n.toLowerCase(),r=e[t]??e[n];return Array.isArray(r)?r[0]:typeof r=="string"?r:void 0}function Oi(e){if(typeof e=="string"){let n=e.trim();return n.length>0?n:void 0}if(typeof e=="number"&&Number.isFinite(e))return String(e)}function hn(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function iu(e){return hn(e.body)}function Mi(e,n){let t=e.query;if(!t)return;let r=t[n]??t[n.toLowerCase()];return ht(Array.isArray(r)?r:[r])}function Hi(e){let n=e.headers??{},t=[n.validationtoken,n.validationToken,n["validation-token"],n["ms-validation-token"]];for(let u of t){let l=ht(Array.isArray(u)?u:[u]);if(l)return decodeURIComponent(l)}let r=Mi({query:e.query},"validationToken");if(r)return r;let o=["x-forwarded-uri","x-original-uri","x-rewrite-url","x-envoy-original-path","referer"];for(let u of o){let l=n[u],c=Array.isArray(l)?l[0]:l;if(!(!c||typeof c!="string"))try{let g=(c.startsWith("http")?new URL(c):new URL(`https://example.invalid${c.startsWith("/")?c:`/${c}`}`)).searchParams.get("validationToken");if(g?.trim())return g.trim()}catch{continue}}let i=e.payload!==void 0?e.payload:e.body!==void 0?e.body:void 0,s=hn(typeof i=="string"?(()=>{try{return JSON.parse(i)}catch{return i}})():i);return ht([s?.validationToken])??null}function su(e){if(Hi(e))return!0;let n=hn(e.body??e.payload);return Di(e.headers??{},"content-type")?.includes("text/plain")?!n||Object.keys(n).length===0:!1}function ht(e){for(let n of e){let t=Oi(n);if(t)return t}}function au(e){let t=hn(e.message)?.data;if(typeof t!="string")return null;try{return JSON.parse(Buffer.from(t,"base64").toString("utf8"))}catch{return null}}var mn=Symbol.for("corsair:internal");function Fi(e){let n=e.database?Nr(e.database):void 0,t=n&&e.kek?pi(e.plugins,n,e.kek):pt(!!n,!!e.kek),r=gi(e),o={plugins:e.plugins,database:n,kek:e.kek,multiTenancy:!!e.multiTenancy,permissions:r,manual:e.manual,hub:e.hub?vn(e.hub):void 0},i=No(n),s=bi(o);if(e.multiTenancy)return Object.assign({withTenant:u=>{if(!u)throw new Error("corsair.withTenant(tenantId): tenantId must be a non-empty string");let l=Ir(e.plugins,{database:n,tenantId:u,kek:e.kek,rootErrorHandlers:e.errorHandlers,permissionsOptions:r,manualConfig:e.manual,hubConfig:o.hub,internalConfig:o});return Object.assign(l,{[mn]:o})},keys:t,permissions:i,manage:s},{[mn]:o});let a=Ir(e.plugins,{database:n,tenantId:void 0,kek:e.kek,rootErrorHandlers:e.errorHandlers,permissionsOptions:r,manualConfig:e.manual,hubConfig:o.hub,internalConfig:o});return Object.assign({},a,{keys:t,permissions:i,manage:s,[mn]:o})}var uu={slack:{channels:{list:{}},users:{list:{}}},linear:{projects:{list:{}},issues:{list:{}},users:{list:{}}},github:{issues:{list:{}},repositories:{list:{}}},discord:{guilds:{list:{}},channels:{list:{}}},hubspot:{contacts:{getMany:{}},companies:{getMany:{}},deals:{getMany:{}}},gmail:{messages:{list:{}},labels:{list:{}},drafts:{list:{}},threads:{list:{}}},googlecalendar:{events:{getMany:{}}},googlemeet:{conferenceRecords:{list:{}}},googledrive:{files:{list:{}},folders:{list:{}},sharedDrives:{list:{}}},notion:{databases:{getManyDatabases:{}},databasePages:{getManyDatabasePages:{}},users:{getManyUsers:{}}},airtable:{bases:{getMany:{}}},todoist:{projects:{getMany:{}},tasks:{getMany:{}}},cal:{bookings:{list:{}}},zohomail:{folders:{list:{}},messages:{list:{}}}},Br=uu;async function Ln(e,n){let t=[],r=n?.silent??!1,o=d=>{t.push(d),r||console.log(d)},i=d=>{t.push(d),r||console.warn(d)},s=n?.caller??"script",a=jr(e);if(!a)throw new Error("setupCorsair: invalid corsair instance");if(!a.database)throw new Error("setupCorsair: a database must be configured on the corsair instance");let u=Cu(e,a.plugins,n),l={...a,database:a.database},c=l.database.db;await Tu(c,i);let p=await Pu(c,l,u.tenantId,u.provisionAccounts,o);n?.credentials&&Object.keys(n.credentials).length>0&&await Iu(e,u,n.credentials,l,o,i);let g=await Ru(p,u,o,s);if(n?.backfill){o("[corsair:setup] Starting backfill...");let d=Fi({plugins:a.plugins,database:c,kek:a.kek,multiTenancy:!0}).withTenant(u.tenantId);await Eu(d,a.plugins,g,o,i),o("[corsair:setup] Backfill complete.")}return t.join(`
35
+ `)}function Ur(e,n,t){let r=t==="integration"?e.authConfig?.[n]?.integration??[]:e.authConfig?.[n]?.account??[];return new Set([...H[n][t],...r])}function ku(e,n){if(!e)return!1;for(let[t,r]of Object.entries(e)){let o=n.find(a=>a.id===t);if(!o)continue;let i=I(o);if(!i)continue;let s=Ur(o,i,"account");for(let a of Object.keys(r))if(s.has(a))return!0}return!1}function Cu(e,n,t){let r=Wr(e),o=t?.tenantId?.trim(),i=o!==void 0&&o.length>0;if(r&&t?.backfill&&!i)throw new Error("setupCorsair: tenantId is required for backfill on a multi-tenant instance");if(r&&ku(t?.credentials,n)&&!i)throw new Error("setupCorsair: tenantId is required when setting account-level credentials on a multi-tenant instance");if(i&&!o)throw new Error("setupCorsair: tenantId must be a non-empty string");return{multiTenant:r,tenantIdProvided:i,tenantId:i?o:"default",provisionAccounts:!r||i}}function Ui(e,n){return de(e)?n===0?!0:Object.values(e).every(t=>Ui(t,n-1)):!1}function wu(e){return Ui(e,4)}var vu={...Zr};function bt(e){if(e instanceof fu){let n={};for(let[t,r]of Object.entries(e.shape))n[t]=r instanceof bu?bt(r):"unknown";return n}return e instanceof pu?`${bt(e.unwrap())} | null`:e instanceof yu?`${bt(e.unwrap())} | undefined`:e instanceof du?e.options.join(" | "):e instanceof hu?"string":e instanceof gu?"number":e instanceof cu?"boolean":e instanceof lu?"date":e instanceof mu?"jsonb":"unknown"}async function Tu(e,n){let t=await e.introspection.getTables(),r=new Set(t.map(o=>o.name));for(let[o,i]of Object.entries(vu))r.has(o)||n(`[corsair:setup] Table "${o}" does not exist. Run your database migrations before calling setupCorsair.
36
+ Schema: ${JSON.stringify(bt(i),null,2)}`)}async function Pu(e,n,t,r,o){let i=new Date,s=new Map;for(let a of n.plugins){let u=a.id,l=I(a),c=await e.selectFrom("corsair_integrations").selectAll().where("name","=",u).executeTakeFirst();if(!c){let f=crypto.randomUUID();await e.insertInto("corsair_integrations").values({id:f,name:u,config:{},created_at:i,updated_at:i}).execute(),c=await e.selectFrom("corsair_integrations").selectAll().where("id","=",f).executeTakeFirst(),o(`[corsair:setup] Created integration: ${u}`)}let p=l?a.authConfig?.[l]?.integration??[]:[],g=l?a.authConfig?.[l]?.account??[]:[],d=l&&c?D({authType:l,integrationName:u,kek:n.kek,database:n.database,extraIntegrationFields:p}):void 0;if(c&&!c.dek&&d&&(await d.issue_new_dek(),o(`[corsair:setup] Issued integration DEK: ${u}`)),!c||!l||!d)continue;let y;if(r){let f=await e.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",t).where("integration_id","=",c.id).executeTakeFirst();if(!f){let m=crypto.randomUUID();await e.insertInto("corsair_accounts").values({id:m,tenant_id:t,integration_id:c.id,config:{},created_at:i,updated_at:i}).execute(),f=await e.selectFrom("corsair_accounts").selectAll().where("id","=",m).executeTakeFirst(),o(`[corsair:setup] Created account: ${u}`)}y=f&&_({authType:l,integrationName:u,tenantId:t,kek:n.kek,database:n.database,extraAccountFields:g}),f&&y&&!f.dek&&(await y.issue_new_dek(),o(`[corsair:setup] Issued account DEK: ${u}`))}s.set(u,{pluginId:u,authType:l,integration:d,account:y,integrationFields:[...H[l].integration,...p],accountFields:r?[...H[l].account,...g]:[]})}return s}function Au(e){if(!de(e))return;let n=e.keys;return de(n)?n:void 0}function xu(e,n){return"withTenant"in e&&typeof e.withTenant=="function"?e.withTenant(n):e}async function Iu(e,n,t,r,o,i){let s=Au(e),a=n.provisionAccounts?xu(e,n.tenantId):void 0;for(let[u,l]of Object.entries(t)){let c=r.plugins.find(h=>h.id===u);if(!c){i(`[corsair:setup] Unknown plugin '${u}' \u2014 skipping credentials.`);continue}let p=I(c);if(!p){i(`[corsair:setup] Plugin '${u}' has no auth type \u2014 skipping credentials.`);continue}let g=Ur(c,p,"integration"),d=Ur(c,p,"account"),y=s?.[u],f=a?.[u],m=de(f)?f.keys:void 0;for(let[h,k]of Object.entries(l))if(k){if(g.has(h)){if(n.multiTenant&&n.tenantIdProvided)throw new Error(`[corsair:setup] '${u}.${h}' is an integration-level credential shared across all tenants. You passed tenantId="${n.tenantId}", which only scopes account-level credentials. Run setup without --tenant if you intend to change this credential globally.`);let w=L(y,`set_${h}`);if(!w){i(`[corsair:setup] Cannot set integration field '${h}' for '${u}'.`);continue}await w(k),o(`[corsair:setup] Set ${u} integration.${h}`);continue}if(d.has(h)){if(n.multiTenant&&!n.tenantIdProvided)throw new Error(`setupCorsair: tenantId is required to set account-level credential '${u}.${h}' on a multi-tenant instance`);let w=L(m,`set_${h}`);if(!w){i(`[corsair:setup] Cannot set account field '${h}' for '${u}'.`);continue}await w(k),o(`[corsair:setup] Set ${u} account.${h} (tenant=${n.tenantId})`);continue}i(`[corsair:setup] Unknown credential field '${h}' for plugin '${u}'.`)}}}var Bi=new Set(["webhook_signature","expires_at","scope","redirect_url"]);async function Su(e,n,t,r,o,i,s,a,u){let l=[],c=[];for(let g of o){if(Bi.has(g))continue;let d=L(t,`get_${g}`);if(!d)continue;let y=null;try{let f=await d();y=typeof f=="string"?f:null}catch{}y||l.push(g)}if(r&&i.length>0)for(let g of i){if(Bi.has(g))continue;let d=L(r,`get_${g}`);if(!d)continue;let y=null;try{let f=await d();y=typeof f=="string"?f:null}catch{}y||c.push(g)}let p=l.length===0&&c.length===0;if(p)a(`[corsair:setup] '${e}' (${n}) is configured \u2713`);else if(n==="managed")a(`[corsair:setup] '${e}' (managed) is not connected yet. Use Connect in your app \u2014 Corsair Hub delivers OAuth tokens after authorization.`);else{let g=[...l,...c];if(u==="cli"){let d=g.map(y=>`${y}=VALUE`).join(" ");a(`[corsair:setup] '${e}' (${n}) needs credentials. Run:
37
+ corsair setup --${e} ${d}`)}else{let d=[`[corsair:setup] '${e}' (${n}) needs credentials. Call:`];for(let y of l)d.push(` await corsair.keys.${e}.set_${y}(value)`);for(let y of c){let f=s.provisionAccounts?s.tenantId==="default"?`corsair.${e}`:`corsair.withTenant(${JSON.stringify(s.tenantId)}).${e}`:`corsair.withTenant(<tenant>).${e}`;d.push(` await ${f}.keys.set_${y}(value)`)}a(d.join(`
38
+ `))}}return p}async function Ru(e,n,t,r){let o=new Set;for(let i of e.values())await Su(i.pluginId,i.authType,i.integration,i.account,i.integrationFields,i.accountFields,n,t,r)&&o.add(i.pluginId);return o}async function Eu(e,n,t,r,o){if(!wu(Br)){o("[corsair:setup] Backfill config is invalid - skipping backfill.");return}let i=Br,s=new Set(n.map(a=>a.id));for(let[a,u]of Object.entries(i)){if(!s.has(a))continue;if(!t.has(a)){r(`[corsair:setup] Skipping backfill for '${a}' \u2014 auth not configured.`);continue}let l=de(e)?e[a]:void 0,c=de(l)?l.api:void 0;if(c)for(let[p,g]of Object.entries(u))for(let[d,y]of Object.entries(g)){r(`[corsair:setup] Backfilling ${a} \u203A ${p}.${d}...`);try{let f=de(c)?c[p]:void 0;await L(f,d)?.(y)}catch(f){o(`[corsair:setup] ${a} \u203A ${p}.${d} failed: `+(f instanceof Error?f.message:String(f)))}}}}export{Jr as a,pe as b,wt as c,Qe as d,zr as e,Vr as f,ge as g,Pe as h,oe as i,Oe as j,Me as k,fe as l,Tt as m,Xr as n,nn as o,ie as p,vn as q,M as r,Tn as s,He as t,Pn as u,An as v,xn as w,In as x,no as y,Sn as z,ye as A,se as B,ae as C,q as D,At as E,rn as F,me as G,ue as H,on as I,D as J,_ as K,po as L,go as M,Ln as N,Iu as O,be as P,It as Q,Ue as R,Le as S,Et as T,Fn as U,To as V,Ie as W,B as X,_t as Y,cn as Z,Io as _,Ts as $,Nn as aa,dl as ba,Eo as ca,_o as da,Do as ea,Dt as fa,$n as ga,Mo as ha,Ho as ia,Ot as ja,jn as ka,Wn as la,je as ma,qn as na,Fs as oa,Lo as pa,Lt as qa,et as ra,qt as sa,qe as ta,Ze as ua,nt as va,tt as wa,ln as xa,Zt as ya,Gt as za,rt as Aa,dn as Ba,ot as Ca,it as Da,Ce as Ea,Ge as Fa,ei as Ga,Se as Ha,fn as Ia,yn as Ja,dt as Ka,Xt as La,er as Ma,rr as Na,or as Oa,ir as Pa,sr as Qa,ar as Ra,Re as Sa,$ as Ta,ur as Ua,ii as Va,si as Wa,cr as Xa,lr as Ya,dr as Za,pr as _a,gr as $a,fr as ab,yr as bb,mr as cb,hr as db,br as eb,kr as fb,Cr as gb,wr as hb,vr as ib,Tr as jb,Ee as kb,yi as lb,mi as mb,hi as nb,ki as ob,Wa as pb,Un as qb,Sf as rb,_e as sb,Rf as tb,ft as ub,Qa as vb,Xa as wb,mt as xb,tu as yb,_i as zb,ru as Ab,ou as Bb,Di as Cb,Oi as Db,hn as Eb,iu as Fb,Mi as Gb,Hi as Hb,su as Ib,ht as Jb,au as Kb,mn as Lb,Fi as Mb};
@@ -0,0 +1 @@
1
+ import{b as D,c as P,d as B,e as R}from"./chunk-IGGCNGU2.js";var L=Symbol.for("corsair:internal"),x=class extends Error{constructor(t="Invalid corsair instance"){super(t),this.name="InvalidCorsairInstanceError"}};function _(e){return typeof e=="object"&&e!==null}function S(e){if(!_(e)||!Array.isArray(e.plugins)||typeof e.kek!="string"||typeof e.multiTenancy!="boolean")return!1;if(e.database===void 0)return!0;if(!_(e.database))return!1;let t=e.database.db;return typeof t=="object"&&t!==null&&typeof t.selectFrom=="function"}function O(e){if(!e||typeof e!="object")return;let r=Object.getOwnPropertyDescriptor(e,L)?.value;return S(r)?r:void 0}function J(e,t){let r=O(e);if(!r)throw t?.()??new x;return r}function v(e,t){return e.plugins.find(r=>r.id===t)}function H(e,t,r){let n=v(e,t);if(!n)throw r(`Plugin '${t}' not found`);return n}function G(e){return"withTenant"in e&&typeof e.withTenant=="function"}function X(e,t){if(!e||typeof e!="object")return;let r=e[t];return typeof r=="function"?(...n)=>Reflect.apply(r,e,n):void 0}var F={oauth_2:{integration:["client_id","client_secret","redirect_url"],account:["access_token","refresh_token","expires_at","scope","webhook_signature"]},api_key:{integration:[],account:["api_key","webhook_signature"]},bot_token:{integration:[],account:["bot_token","webhook_signature"]},managed:{integration:[],account:["access_token","refresh_token","expires_at","scope","webhook_signature"]}};function N(e){return e==="oauth_2"||e==="api_key"||e==="bot_token"||e==="managed"}function Y(e){let t=e.options?.authType;return N(t)?t:void 0}function q(e,t){let r=e.authConfig,n=F[t].account,i=r?.[t]?.account??[];return[...n,...i]}function xe(e,t){let r=e.authConfig,n=F[t].integration,i=r?.[t]?.integration??[];return[...n,...i]}import{v7 as V}from"uuid";function T(){return V()}import{z as C}from"zod";import{sql as w}from"kysely";function k(e){return e.replace(/'/g,"''")}function W(e){let t=k(e);return w`data->>'${w.raw(t)}'`}function j(e){let t=k(e);return w`(data->>'${w.raw(t)}')::numeric`}function K(e){let t=k(e);return w`(data->>'${w.raw(t)}')::boolean`}function U(e){let t=k(e);return w`(data->>'${w.raw(t)}')::timestamptz`}function ee(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}function Z(e){let t=e;for(;t;){if(t instanceof C.ZodOptional||t instanceof C.ZodNullable){t=t._def.innerType;continue}if(t instanceof C.ZodDefault){t=t._def.innerType;continue}break}return t}function te(e){let t=Z(e);if(t instanceof C.ZodString)return"string";if(t instanceof C.ZodNumber)return"number";if(t instanceof C.ZodBoolean)return"boolean";if(t instanceof C.ZodDate)return"date"}function ne(e){let t=Z(e);if(!(t instanceof C.ZodObject))return{};let r=t.shape,n={};for(let[i,a]of Object.entries(r)){let u=te(a);u&&(n[i]=u)}return n}function re(e,t,r){if(typeof r=="string")return e.where(t,"=",r);if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let n=r;"equals"in n&&typeof n.equals=="string"&&(e=e.where(t,"=",n.equals)),"contains"in n&&typeof n.contains=="string"&&(e=e.where(t,"like",`%${n.contains}%`)),"startsWith"in n&&typeof n.startsWith=="string"&&(e=e.where(t,"like",`${n.startsWith}%`)),"endsWith"in n&&typeof n.endsWith=="string"&&(e=e.where(t,"like",`%${n.endsWith}`)),"in"in n&&Array.isArray(n.in)&&(e=e.where(t,"in",n.in))}return e}function ie(e,t,r){if(typeof r=="number")return e.where(t,"=",r);if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let n=r;typeof n.equals=="number"&&(e=e.where(t,"=",n.equals)),typeof n.gt=="number"&&(e=e.where(t,">",n.gt)),typeof n.gte=="number"&&(e=e.where(t,">=",n.gte)),typeof n.lt=="number"&&(e=e.where(t,"<",n.lt)),typeof n.lte=="number"&&(e=e.where(t,"<=",n.lte)),Array.isArray(n.in)&&(e=e.where(t,"in",n.in))}return e}function oe(e,t,r){if(typeof r=="boolean")return e.where(t,"=",r);if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let n=r;typeof n.equals=="boolean"&&(e=e.where(t,"=",n.equals))}return e}function se(e,t,r){if(r instanceof Date)return e.where(t,"=",r);if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let n=r;if(n.equals instanceof Date&&(e=e.where(t,"=",n.equals)),n.before instanceof Date&&(e=e.where(t,"<",n.before)),n.after instanceof Date&&(e=e.where(t,">",n.after)),Array.isArray(n.between)&&n.between.length===2){let[i,a]=n.between;i instanceof Date&&(e=e.where(t,">=",i)),a instanceof Date&&(e=e.where(t,"<=",a))}}return e}function ae(e,t,r,n){return r==="number"?ie(e,j(t),n):r==="boolean"?oe(e,K(t),n):r==="date"?se(e,U(t),n):re(e,W(t),n)}function ue(e,t,r){if(typeof r=="object"&&r!==null&&!Array.isArray(r)){let n=r;return"equals"in n&&(e=e.where(t,"=",n.equals)),"contains"in n&&typeof n.contains=="string"&&(e=e.where(t,"like",`%${n.contains}%`)),"startsWith"in n&&typeof n.startsWith=="string"&&(e=e.where(t,"like",`${n.startsWith}%`)),"endsWith"in n&&typeof n.endsWith=="string"&&(e=e.where(t,"like",`%${n.endsWith}`)),"in"in n&&Array.isArray(n.in)&&(e=e.where(t,"in",n.in)),e}return e.where(t,"=",r)}function ce(e){return typeof e=="number"?e:typeof e=="bigint"?Number(e):Number.parseInt(String(e??0),10)}function h(e,t,r){return e.selectFrom("corsair_entities").selectAll().where("account_id","=",t).where("entity_type","=",r)}function $(e,t,r,n,i){let a=ne(i);function u(o){let l=ee(o.data);return{...o,data:i.parse(l)}}return{findByEntityId:async o=>{let l=await t(),c=await h(e,l,r).where("entity_id","=",o).executeTakeFirst();return c?u(c):null},existsByEntityId:async o=>{let l=await t();return await h(e,l,r).select("id").where("entity_id","=",o).executeTakeFirst()!==void 0},findIdByEntityId:async o=>{let l=await t();return(await h(e,l,r).select("id").where("entity_id","=",o).executeTakeFirst())?.id??null},findById:async o=>{let l=await t(),c=await h(e,l,r).where("id","=",o).executeTakeFirst();return c?u(c):null},findManyByEntityIds:async o=>{if(o.length===0)return[];let l=await t();return(await h(e,l,r).where("entity_id","in",o).execute()).map(u)},list:async o=>{let l=await t(),c=h(e,l,r);return typeof o?.limit=="number"&&(c=c.limit(o.limit)),typeof o?.offset=="number"&&(c=c.offset(o.offset)),(await c.execute()).map(u)},search:async o=>{let l=await t(),c=h(e,l,r),d=new Set(["data","limit","offset"]);for(let[y,f]of Object.entries(o))d.has(y)||f===void 0||(c=ue(c,y,f));if(o.data&&typeof o.data=="object")for(let[y,f]of Object.entries(o.data)){if(f===void 0)continue;let g=a[y]??"string";c=ae(c,y,g,f)}return typeof o.limit=="number"&&(c=c.limit(o.limit)),typeof o.offset=="number"&&(c=c.offset(o.offset)),(await c.execute()).map(u)},upsertByEntityId:async(o,l)=>{let c=await t(),d=i.parse(l),s=new Date,y=await h(e,c,r).select("id").where("entity_id","=",o).executeTakeFirst();if(y?.id){await e.updateTable("corsair_entities").set({version:n,data:d,updated_at:s}).where("id","=",y.id).execute();let I=await e.selectFrom("corsair_entities").selectAll().where("id","=",y.id).executeTakeFirst();return u(I)}let f=T();await e.insertInto("corsair_entities").values({id:f,created_at:s,updated_at:s,account_id:c,entity_id:o,entity_type:r,version:n,data:d}).execute();let g=await e.selectFrom("corsair_entities").selectAll().where("id","=",f).executeTakeFirst();return u(g)},deleteById:async o=>{let l=await t(),c=await e.deleteFrom("corsair_entities").where("account_id","=",l).where("entity_type","=",r).where("id","=",o).executeTakeFirst();return Number(c.numDeletedRows)>0},deleteByEntityId:async o=>{let l=await t(),c=await e.deleteFrom("corsair_entities").where("account_id","=",l).where("entity_type","=",r).where("entity_id","=",o).executeTakeFirst();return Number(c.numDeletedRows)>0},count:async()=>{let o=await t(),l=await e.selectFrom("corsair_entities").select(c=>c.fn.countAll().as("count")).where("account_id","=",o).where("entity_type","=",r).executeTakeFirst();return ce(l?.count)}}}var de={corsair_integrations:D,corsair_accounts:P,corsair_entities:B,corsair_events:R};function le(e){return de[e]}function M(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}function p(e){if(!e)throw new Error("Corsair database is not configured. Pass `database` to createCorsair(...) to enable ORM.")}function b(e){if(!e)return[];let t=[];for(let r in e){let n=r,i=e[n];if(i!==void 0)if(typeof i=="object"&&i!==null&&!Array.isArray(i)&&!(i instanceof Date)){let a=i;"in"in a&&Array.isArray(a.in)?t.push({field:n,operator:"in",value:a.in}):"like"in a&&typeof a.like=="string"&&t.push({field:n,operator:"like",value:a.like})}else t.push({field:n,value:i})}return t}function m(e,t){if(!t?.length)return e;let r=e;for(let n of t){let i=n.operator??"=";r=r.where(n.field,i,n.value)}return r}function ye(e){return typeof e=="number"?e:typeof e=="bigint"?Number(e):Number.parseInt(String(e??0),10)}function A(e,t){let r=le(t),n=()=>(p(e),e),i=()=>n().db.selectFrom(t),a=()=>n().db.insertInto(t),u=()=>n().db.updateTable(t),o=()=>n().db.deleteFrom(t);function l(d){let s={};for(let[y,f]of Object.entries(d))s[y]=M(f);return r.parse(s)}function c(d){let s={};for(let[y,f]of Object.entries(d))s[y]=M(f);return r.parse(s)}return{findById:async d=>{p(e);let s=i().selectAll();s=m(s,[{field:"id",value:d}]);let y=await s.executeTakeFirst();return y?l(y):null},findOne:async d=>{p(e);let s=i().selectAll();s=m(s,b(d));let y=await s.executeTakeFirst();return y?l(y):null},findMany:async d=>{p(e);let s=i().selectAll();return s=m(s,b(d?.where)),typeof d?.limit=="number"&&(s=s.limit(d.limit)),typeof d?.offset=="number"&&(s=s.offset(d.offset)),(await s.execute()).map(f=>l(f))},create:async d=>{p(e);let s=new Date,y={id:d.id??T(),created_at:s,updated_at:s,...d},f=await a().values(y).returningAll().executeTakeFirst();return f?l(f):c(y)},update:async(d,s)=>{p(e);let y={...s,updated_at:new Date},f=u().set(y).returningAll();f=m(f,[{field:"id",value:d}]);let g=await f.executeTakeFirst();return g?l(g):null},updateMany:async(d,s)=>{p(e);let y={...s,updated_at:new Date},f=i().select("id");f=m(f,b(d));let g=await f.execute();for(let I of g){let E=u().set(y);E=m(E,[{field:"id",value:I.id}]),await E.execute()}return g.length},delete:async d=>{p(e);let s=o();s=m(s,[{field:"id",value:d}]);let y=await s.executeTakeFirst();return Number(y?.numDeletedRows??0)>0},deleteMany:async d=>{p(e);let s=o();s=m(s,b(d));let y=await s.executeTakeFirst();return Number(y?.numDeletedRows??0)},count:async d=>{p(e);let s=i().select(f=>f.fn.countAll().as("count"));s=m(s,b(d));let y=await s.executeTakeFirst();return ye(y?.count)}}}function fe(e){let t=A(e,"corsair_integrations");return{...t,findByName:r=>t.findOne({name:r}),upsertByName:async(r,n)=>{let i=await t.findOne({name:r});return i?await t.update(i.id,n):t.create({...n,name:r})}}}function pe(e){let t=A(e,"corsair_accounts");return{...t,findByTenantAndIntegration:async(r,n)=>{p(e);let i=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();return i?t.findOne({tenant_id:r,integration_id:i.id}):null},listByTenant:(r,n)=>t.findMany({where:{tenant_id:r},limit:n?.limit,offset:n?.offset}),upsertByTenantAndIntegration:async(r,n,i)=>{let a=await t.findOne({tenant_id:r,integration_id:n});return a?await t.update(a.id,i):t.create({...i,tenant_id:r,integration_id:n})}}}function ge(e){let t=A(e,"corsair_entities");return{...t,findByEntityId:({accountId:r,entityType:n,entityId:i})=>t.findOne({account_id:r,entity_type:n,entity_id:i}),findManyByEntityIds:async({accountId:r,entityType:n,entityIds:i})=>i.length===0?[]:(p(e),await e.db.selectFrom("corsair_entities").selectAll().where("account_id","=",r).where("entity_type","=",n).where("entity_id","in",i).execute()),listByScope:({accountId:r,entityType:n,limit:i,offset:a})=>t.findMany({where:{account_id:r,entity_type:n},limit:i,offset:a}),searchByEntityId:async({accountId:r,entityType:n,query:i,limit:a,offset:u})=>{p(e);let o=e.db.selectFrom("corsair_entities").selectAll().where("account_id","=",r).where("entity_type","=",n).where("entity_id","like",`%${i}%`);return typeof a=="number"&&(o=o.limit(a)),typeof u=="number"&&(o=o.offset(u)),await o.execute()},upsertByEntityId:async({accountId:r,entityType:n,entityId:i,version:a,data:u})=>{let o=await t.findOne({account_id:r,entity_type:n,entity_id:i});return o?await t.update(o.id,{version:a,data:u}):t.create({account_id:r,entity_type:n,entity_id:i,version:a,data:u})},deleteByEntityId:async({accountId:r,entityType:n,entityId:i})=>{p(e);let a=await e.db.deleteFrom("corsair_entities").where("account_id","=",r).where("entity_type","=",n).where("entity_id","=",i).executeTakeFirst();return Number(a.numDeletedRows)>0}}}function me(e){let t=A(e,"corsair_events");return{...t,listByAccount:(r,n)=>t.findMany({where:{account_id:r},limit:n?.limit,offset:n?.offset}),listByStatus:(r,n)=>{let i={status:r};return n?.accountId&&(i.account_id=n.accountId),t.findMany({where:i,limit:n?.limit,offset:n?.offset})},listPending:r=>{let n={status:"pending"};return r?.accountId&&(n.account_id=r.accountId),t.findMany({where:n,limit:r?.limit??100})},updateStatus:(r,n)=>t.update(r,{status:n})}}function Q(e){return{integrations:fe(e),accounts:pe(e),entities:ge(e),events:me(e)}}function we(e,t,r,n,i){let a=null;async function u(){if(a!==null)return a;p(e);let o=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",t.integrationName).executeTakeFirst();if(!o)throw new Error(`Integration "${t.integrationName}" not found. Make sure to create the integration first.`);let l=await e.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",t.tenantId).where("integration_id","=",o.id).executeTakeFirst();if(!l)throw new Error(`Account not found for tenant "${t.tenantId}" and integration "${t.integrationName}". Make sure to create the account first.`);return a=l.id,a}return p(e),$(e.db,u,r,n,i)}function z(e){let{database:t,integrationName:r,schema:n,tenantId:i}=e,a=Q(t),u={tenantId:i,integrationName:r},o=null;async function l(){if(o!==null)return o;p(t);let d=await t.db.selectFrom("corsair_integrations").selectAll().where("name","=",r).executeTakeFirst();if(!d)throw new Error(`Integration "${r}" not found. Make sure to create the integration first.`);let s=await t.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",i).where("integration_id","=",d.id).executeTakeFirst();if(!s)throw new Error(`Account not found for tenant "${i}" and integration "${r}". Make sure to create the account first.`);return o=s.id,o}let c={};for(let[d,s]of Object.entries(n.entities))c[d]=we(t,u,d,n.version,s);return{...c,$orm:a,$integrationName:r,$tenantId:i,$getAccountId:l}}function Ze(e,t){let r=Q(e);return{$tenantId:t,$orm:r,listAccounts:n=>r.accounts.listByTenant(t,n),findAccountByIntegration:n=>r.accounts.findByTenantAndIntegration(t,n),listEntities:async n=>{p(e);let i=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",t).execute();if(i.length===0)return[];let a=i.map(o=>o.id),u=e.db.selectFrom("corsair_entities").selectAll().where("account_id","in",a);return n?.entityType&&(u=u.where("entity_type","=",n.entityType)),typeof n?.limit=="number"&&(u=u.limit(n.limit)),typeof n?.offset=="number"&&(u=u.offset(n.offset)),await u.execute()},listEvents:async n=>{p(e);let i=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",t).execute();if(i.length===0)return[];let a=i.map(o=>o.id),u=e.db.selectFrom("corsair_events").selectAll().where("account_id","in",a);return n?.status&&(u=u.where("status","=",n.status)),typeof n?.limit=="number"&&(u=u.limit(n.limit)),typeof n?.offset=="number"&&(u=u.offset(n.offset)),await u.execute()},forIntegration:n=>z({database:e,integrationName:n.integrationName,schema:n.schema,tenantId:t})}}function $e(e,t){return{forTenant:r=>z({database:e,integrationName:t.integrationName,schema:t.schema,tenantId:r})}}export{x as a,_ as b,O as c,J as d,H as e,G as f,X as g,F as h,Y as i,q as j,xe as k,T as l,$ as m,de as n,Q as o,z as p,Ze as q,$e as r};
@@ -1,6 +1,6 @@
1
- import { T as Tenant, C as CreateTenantInput, P as PluginInfo, a as ConnectionStatus, b as PermissionRecord, c as ConnectLink, d as CreateConnectLinkInput, O as OAuthCallbackResult, e as OAuthCallbackInput } from '../../types-1nBbBn-U.js';
2
- export { f as PermissionLookupInput } from '../../types-1nBbBn-U.js';
3
- import { C as CorsairClientOptions, a as CorsairManagementClient } from '../../types-DvDEtIUw.js';
1
+ import { T as Tenant, C as CreateTenantInput, P as PluginInfo, a as ConnectionStatus, b as PermissionRecord, c as ConnectLink, d as CreateConnectLinkInput, O as OAuthCallbackResult, e as OAuthCallbackInput } from '../../types-Bsv_KdHs.js';
2
+ export { f as PermissionLookupInput } from '../../types-Bsv_KdHs.js';
3
+ import { C as CorsairClientOptions, a as CorsairManagementClient } from '../../types-MvrzaDrs.js';
4
4
  import '../../index-eydqYIn0.js';
5
5
  import 'zod';
6
6
 
@@ -0,0 +1 @@
1
+ import{ea as a,fa as b,ga as c}from"./chunk-F5GBHMO2.js";import"./chunk-WDF3YE27.js";import"./chunk-IGGCNGU2.js";import"./chunk-QAIKSQAD.js";export{c as createHubConnectSession,b as createHubConnectSessionForPlugin,a as postHubConnectSession};
package/dist/core.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- export { C as CORSAIR_INTERNAL, a as CorsairInternalConfig, c as createCorsair } from './index-D7aqzKjb.js';
1
+ export { C as CORSAIR_INTERNAL, a as CorsairInternalConfig, c as createCorsair } from './index-BzMy2KpY.js';
2
2
  import { CorsairDatabase } from './db.js';
3
- import { A as AccountKeyManagerFor, I as IntegrationKeyManagerFor, f as CorsairPluginSubscribeResult } from './index-DwegPGYj.js';
4
- export { g as AccountFieldNames, k as BASE_AUTH_FIELDS, B as BaseAuthFieldConfig, h as BaseKeyManager, M as BeforeHookResult, n as BindEndpoints, a8 as BindWebhooks, a6 as Bivariant, o as BoundEndpointFn, p as BoundEndpointTree, a9 as BoundWebhook, aa as BoundWebhookTree, m as CorsairClient, q as CorsairContext, r as CorsairEndpoint, t as CorsairErrorHandler, c as CorsairIntegration, N as CorsairKeyBuilder, Q as CorsairKeyBuilderBase, ab as CorsairOAuthWebhookTenantLinkResolver, z as CorsairPermissionsNamespace, C as CorsairPlugin, S as CorsairPluginContext, U as CorsairPluginSubscribe, e as CorsairSingleTenantClient, d as CorsairTenantWrapper, ac as CorsairWebhook, ad as CorsairWebhookHandler, ae as CorsairWebhookMatcher, af as CorsairWebhookTenantMatcher, V as EndpointHooks, X as EndpointMetaEntry, E as EndpointPathsOf, Y as EndpointRiskLevel, s as EndpointTree, D as EnforcePermissionOptions, F as EnforcePermissionResult, u as ErrorContext, v as ErrorHandler, w as ErrorHandlerAndMatchFunction, x as ErrorMatcher, i as IntegrationFieldNames, Z as KeyBuilderContext, j as OAuth2IntegrationCredentials, O as OAuthConfig, _ as PermissionMode, $ as PermissionPolicy, P as PluginAuthConfig, a0 as PluginEndpointMeta, a1 as PluginPermissionsConfig, ag as RawWebhookRequest, K as ReadonlyForbiddenError, a2 as RequiredPluginEndpointMeta, a3 as RequiredPluginEndpointSchemas, a4 as RequiredPluginWebhookSchemas, R as RetryStrategies, y as RetryStrategy, T as TokenResponse, a7 as UnionToIntersection, a5 as WebhookHooks, ah as WebhookPathsOf, ai as WebhookRequest, aj as WebhookResponse, W as WebhookTenantMatch, ak as WebhookTree, G as assertReadonlyAllowed, l as exchangeCodeForTokens, J as isReadonlyScopeActive, L as runReadonly } from './index-DwegPGYj.js';
5
- export { A as AuthMissingError, D as DocSchemaFieldRow, a as DocSchemaShape, b as DocsApiEndpoint, c as DocsDbEntity, d as DocsDbFilterField, e as DocsWebhook, E as EndpointSchemaResult, I as IntrospectPluginForDocsResult, L as ListOperationsOptions, P as PluginDocsIntrospection, j as PluginWebhookMatchers, R as ResolveConnectLinkResult, W as WebhookPluginTenantMatch, k as asRecord, g as collectPluginWebhookMatchers, l as decodePubSubData, n as extractMicrosoftGraphValidationToken, o as firstString, f as formatDocSchemaShape, p as getHeader, i as introspectPluginForDocs, q as isMicrosoftGraphValidationHandshake, m as matchWebhookPlugin, h as matchWebhookPluginAndTenant, s as readBodyRecord, t as readQueryParam, r as resolveConnectLink, u as toExternalId } from './tenant-match-utils-f49OxmPU.js';
6
- import { A as AuthTypes } from './types-1nBbBn-U.js';
7
- export { g as AllProviders, B as BaseProviders, h as PickAuth, j as ProviderDisplayNames, i as formatProviderDisplayName } from './types-1nBbBn-U.js';
3
+ import { A as AccountKeyManagerFor, I as IntegrationKeyManagerFor, f as CorsairPluginSubscribeResult } from './index-CCwyDzOb.js';
4
+ export { g as AccountFieldNames, k as BASE_AUTH_FIELDS, B as BaseAuthFieldConfig, h as BaseKeyManager, M as BeforeHookResult, n as BindEndpoints, a8 as BindWebhooks, a6 as Bivariant, o as BoundEndpointFn, p as BoundEndpointTree, a9 as BoundWebhook, aa as BoundWebhookTree, m as CorsairClient, q as CorsairContext, r as CorsairEndpoint, t as CorsairErrorHandler, c as CorsairIntegration, N as CorsairKeyBuilder, Q as CorsairKeyBuilderBase, ab as CorsairOAuthWebhookTenantLinkResolver, z as CorsairPermissionsNamespace, C as CorsairPlugin, S as CorsairPluginContext, U as CorsairPluginSubscribe, e as CorsairSingleTenantClient, d as CorsairTenantWrapper, ac as CorsairWebhook, ad as CorsairWebhookHandler, ae as CorsairWebhookMatcher, af as CorsairWebhookTenantMatcher, V as EndpointHooks, X as EndpointMetaEntry, E as EndpointPathsOf, Y as EndpointRiskLevel, s as EndpointTree, D as EnforcePermissionOptions, F as EnforcePermissionResult, u as ErrorContext, v as ErrorHandler, w as ErrorHandlerAndMatchFunction, x as ErrorMatcher, i as IntegrationFieldNames, Z as KeyBuilderContext, j as OAuth2IntegrationCredentials, O as OAuthConfig, _ as PermissionMode, $ as PermissionPolicy, P as PluginAuthConfig, a0 as PluginEndpointMeta, a1 as PluginPermissionsConfig, ag as RawWebhookRequest, K as ReadonlyForbiddenError, a2 as RequiredPluginEndpointMeta, a3 as RequiredPluginEndpointSchemas, a4 as RequiredPluginWebhookSchemas, R as RetryStrategies, y as RetryStrategy, T as TokenResponse, a7 as UnionToIntersection, a5 as WebhookHooks, ah as WebhookPathsOf, ai as WebhookRequest, aj as WebhookResponse, W as WebhookTenantMatch, ak as WebhookTree, G as assertReadonlyAllowed, l as exchangeCodeForTokens, J as isReadonlyScopeActive, L as runReadonly } from './index-CCwyDzOb.js';
5
+ export { A as AuthMissingError, D as DocSchemaFieldRow, a as DocSchemaShape, b as DocsApiEndpoint, c as DocsDbEntity, d as DocsDbFilterField, e as DocsWebhook, E as EndpointSchemaResult, I as IntrospectPluginForDocsResult, L as ListOperationsOptions, g as PermissionRequiredError, P as PluginDocsIntrospection, k as PluginWebhookMatchers, R as ResolveConnectLinkResult, W as WebhookPluginTenantMatch, l as asRecord, h as collectPluginWebhookMatchers, n as decodePubSubData, o as extractMicrosoftGraphValidationToken, p as firstString, f as formatDocSchemaShape, q as getHeader, i as introspectPluginForDocs, s as isMicrosoftGraphValidationHandshake, m as matchWebhookPlugin, j as matchWebhookPluginAndTenant, t as readBodyRecord, u as readQueryParam, r as resolveConnectLink, v as toExternalId } from './tenant-match-utils-DhiFkgcG.js';
6
+ import { A as AuthTypes } from './types-Bsv_KdHs.js';
7
+ export { g as AllProviders, B as BaseProviders, h as PickAuth, j as ProviderDisplayNames, i as formatProviderDisplayName } from './types-Bsv_KdHs.js';
8
8
  import 'kysely';
9
9
  import './index-eydqYIn0.js';
10
10
  import 'zod';
package/dist/core.js CHANGED
@@ -1 +1 @@
1
- import{Ab as F,B as d,Bb as G,C as e,Cb as H,D as f,Db as I,E as g,Eb as J,F as h,Fb as K,G as i,Gb as L,H as j,Hb as M,I as k,Ib as N,J as l,Jb as O,K as m,Kb as P,L as n,Lb as Q,M as o,Sa as u,a,b,ja as p,ma as q,na as r,nb as v,oa as s,ob as w,pa as t,pb as x,tb as y,ub as z,vb as A,wb as B,xb as C,yb as D,zb as E}from"./chunk-6WGGD3SS.js";import{h as c}from"./chunk-BPFUYXOD.js";import"./chunk-IGGCNGU2.js";import"./chunk-QAIKSQAD.js";export{u as AuthMissingError,c as BASE_AUTH_FIELDS,P as CORSAIR_INTERNAL,B as MS_GRAPH_API_BASE,a as ProviderDisplayNames,q as ReadonlyForbiddenError,I as asRecord,t as assertReadonlyAllowed,F as collectPluginWebhookMatchers,m as createAccountKeyManager,Q as createCorsair,l as createIntegrationKeyManager,O as decodePubSubData,j as decryptConfig,f as decryptDEK,h as decryptWithDEK,i as encryptConfig,e as encryptDEK,g as encryptWithDEK,x as exchangeCodeForTokens,L as extractMicrosoftGraphValidationToken,N as firstString,y as formatDocSchemaShape,b as formatProviderDisplayName,d as generateDEK,G as getHeader,A as googleChannelSubscribe,o as initializeAccountDEK,n as initializeIntegrationDEK,z as introspectPluginForDocs,M as isMicrosoftGraphValidationHandshake,s as isReadonlyScopeActive,v as logEvent,w as logEventFromContext,D as matchWebhookPlugin,E as matchWebhookPluginAndTenant,C as msGraphSubscribe,k as reEncryptConfig,J as readBodyRecord,K as readQueryParam,p as resolveConnectLink,r as runReadonly,H as toExternalId};
1
+ import{Ab as F,B as d,Bb as G,C as e,Cb as H,D as f,Db as I,E as g,Eb as J,F as h,Fb as K,G as i,Gb as L,H as j,Hb as M,I as k,Ib as N,J as l,Jb as O,K as m,Kb as P,L as n,Lb as Q,M as o,Mb as R,Ta as v,a,b,ja as p,ma as q,na as r,oa as s,ob as w,pa as t,pb as x,qa as u,qb as y,ub as z,vb as A,wb as B,xb as C,yb as D,zb as E}from"./chunk-F5GBHMO2.js";import{h as c}from"./chunk-WDF3YE27.js";import"./chunk-IGGCNGU2.js";import"./chunk-QAIKSQAD.js";export{v as AuthMissingError,c as BASE_AUTH_FIELDS,Q as CORSAIR_INTERNAL,C as MS_GRAPH_API_BASE,q as PermissionRequiredError,a as ProviderDisplayNames,r as ReadonlyForbiddenError,J as asRecord,u as assertReadonlyAllowed,G as collectPluginWebhookMatchers,m as createAccountKeyManager,R as createCorsair,l as createIntegrationKeyManager,P as decodePubSubData,j as decryptConfig,f as decryptDEK,h as decryptWithDEK,i as encryptConfig,e as encryptDEK,g as encryptWithDEK,y as exchangeCodeForTokens,M as extractMicrosoftGraphValidationToken,O as firstString,z as formatDocSchemaShape,b as formatProviderDisplayName,d as generateDEK,H as getHeader,B as googleChannelSubscribe,o as initializeAccountDEK,n as initializeIntegrationDEK,A as introspectPluginForDocs,N as isMicrosoftGraphValidationHandshake,t as isReadonlyScopeActive,w as logEvent,x as logEventFromContext,E as matchWebhookPlugin,F as matchWebhookPluginAndTenant,D as msGraphSubscribe,k as reEncryptConfig,K as readBodyRecord,L as readQueryParam,p as resolveConnectLink,s as runReadonly,I as toExternalId};
package/dist/hub.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { A as AuthTypes } from './types-1nBbBn-U.js';
2
- export { i as formatProviderDisplayName } from './types-1nBbBn-U.js';
3
- import { am as HubOAuthMode, an as HubConnectSessionResult, ao as HubPermissionSessionResult, H as HubConfig, ap as HubConfigInput, aq as HubConnectSessionInput, ar as HubListProjectConnectionsInput, A as AccountKeyManagerFor, as as HubPermissionSessionInput } from './index-DwegPGYj.js';
4
- export { at as DEFAULT_HUB_API_URL, au as HubEnvironmentSlug } from './index-DwegPGYj.js';
5
- import { g as TunnelType, c as ProcessCorsairRequest, h as WebhookTenantLink } from './index-CdzrawUJ.js';
6
- export { i as BROWSER_DELIVERY_TTL_MS, j as BrowserDeliveryMode, B as BrowserDeliveryPayload, S as SIGNED_TUNNEL_REPLAY_WINDOW_MS, f as TunnelEnvelope } from './index-CdzrawUJ.js';
7
- export { b as buildBrowserDeliveryRedirectUrl, s as signBrowserDeliveryToken, v as verifyBrowserDeliveryToken } from './browser-delivery-ARqe7lph.js';
1
+ import { A as AuthTypes } from './types-Bsv_KdHs.js';
2
+ export { i as formatProviderDisplayName } from './types-Bsv_KdHs.js';
3
+ import { am as HubOAuthMode, an as HubConnectSessionResult, ao as HubPermissionSessionResult, H as HubConfig, ap as HubConfigInput, aq as HubConnectSessionInput, ar as HubListProjectConnectionsInput, A as AccountKeyManagerFor, as as HubPermissionSessionInput } from './index-CCwyDzOb.js';
4
+ export { at as DEFAULT_HUB_API_URL, au as HubEnvironmentSlug } from './index-CCwyDzOb.js';
5
+ import { g as TunnelType, c as ProcessCorsairRequest, h as WebhookTenantLink } from './index-F_9QUwf4.js';
6
+ export { i as BROWSER_DELIVERY_TTL_MS, j as BrowserDeliveryMode, B as BrowserDeliveryPayload, S as SIGNED_TUNNEL_REPLAY_WINDOW_MS, f as TunnelEnvelope } from './index-F_9QUwf4.js';
7
+ export { b as buildBrowserDeliveryRedirectUrl, s as signBrowserDeliveryToken, v as verifyBrowserDeliveryToken } from './browser-delivery-ClbNhluI.js';
8
8
  import './index-eydqYIn0.js';
9
9
  import 'zod';
10
10
  import './db.js';
package/dist/hub.js CHANGED
@@ -1 +1 @@
1
- import{$a as ha,A as z,Aa as Q,Ba as R,Ca as S,Da as T,Ea as U,Ma as V,Na as W,Oa as X,P as A,Pa as Y,Qa as Z,Ra as _,Ta as $,Ua as aa,Va as ba,Wa as ca,Xa as da,Ya as ea,Za as fa,_a as ga,ab as ia,b as a,bb as ja,c as b,cb as ka,d as c,db as la,e as d,eb as ma,f as e,fb as na,g as f,ga as B,gb as oa,h as g,ha as C,hb as pa,i as h,ia as D,ib as qa,j as i,k as j,ka as E,l as k,la as F,m as l,n as m,o as n,p as o,q as p,qa as G,r as q,ra as H,s as r,sa as I,t as s,ta as J,u as t,ua as K,v as u,va as L,w as v,wa as M,x as w,xa as N,y as x,ya as O,z as y,za as P}from"./chunk-6WGGD3SS.js";import"./chunk-BPFUYXOD.js";import"./chunk-IGGCNGU2.js";import"./chunk-QAIKSQAD.js";export{f as BROWSER_DELIVERY_TTL_MS,n as DEFAULT_HUB_API_URL,o as HubNotConfiguredError,T as ManagedOAuthDeliveryError,g as SIGNED_TUNNEL_REPLAY_WINDOW_MS,aa as attachManagedRefreshAuth,i as buildBrowserDeliveryRedirectUrl,l as buildClientBridgeBrowserDeliveryUrl,ca as createConnectSessionJti,ha as createConnectTokenJti,B as createHubConnectSession,E as createHubPermissionSession,ba as createHubRouteHandlers,na as createPermissionSessionJti,h as createSignedTokenJti,ga as decodeConnectSessionTokenFromPath,ma as decodeConnectTokenFromPath,qa as decodePermissionTokenFromPath,O as deliverConnectCreateLink,S as deliverSignedEnvelope,Q as describeDeliveryNetworkError,la as encodeConnectTokenForPath,M as extractConnectLinkFromDeliveryAck,L as extractSyncFromDeliveryAck,F as formatHubApprovalMessage,a as formatProviderDisplayName,R as formatServerDeliveryError,da as getConnectSessionExpiryMs,C as getConnectStatusForTenant,ia as getConnectTokenExpiryMs,q as getHubConfig,$ as getManagedAccessToken,V as handleHubDeliveryGet,W as handleHubDeliveryPost,Y as handleHubDeliveryRequest,X as hubDeliveryToResponse,s as inferHubEnvironmentSlug,b as isLoopbackUrl,K as isServerDeliveryAckSuccessful,D as listHubProjectConnections,p as normalizeHubConfig,N as parseConnectLinkFromDeliveryBody,t as parseConnectSessionResponse,x as parseConnectStatusResponse,y as parseHubApiErrorBody,w as parseOAuthRefreshResponse,v as parsePermissionSessionResponse,u as parseProjectConnectionsResponse,J as parseServerDeliveryAckBody,P as parseSyncFromDeliveryBody,m as prepareClientBridgeDeliveryTransport,U as processManagedOAuthDelivery,A as registerHubWebhookTenantLink,c as resolveDeliveryTransport,z as resolveHubDeliveryUrl,r as resolveHubOAuthCallbackUrl,Z as respondToHubDelivery,_ as respondToHubDeliveryFromRequest,j as signBrowserDeliveryToken,ea as signConnectSessionToken,ja as signConnectToken,G as signDeliveryEnvelope,oa as signPermissionToken,d as usesBrowserDelivery,e as validateProductionDeliveryUrl,k as verifyBrowserDeliveryToken,fa as verifyConnectSessionToken,ka as verifyConnectToken,H as verifyDeliveryEnvelope,pa as verifyPermissionToken,I as verifySignedTunnelDelivery};
1
+ import{$a as ga,A as z,Aa as P,Ba as Q,Ca as R,Da as S,Ea as T,Fa as U,Na as V,Oa as W,Pa as X,Qa as Y,R as A,Ra as Z,Sa as _,Ua as $,Va as aa,Wa as ba,Xa as ca,Ya as da,Za as ea,_a as fa,ab as ha,b as a,bb as ia,c as b,cb as ja,d as c,db as ka,e as d,eb as la,f as e,fb as ma,g as f,ga as B,gb as na,h as g,ha as C,hb as oa,i as h,ia as D,ib as pa,j as i,jb as qa,k as j,ka as E,l as k,la as F,m as l,n as m,o as n,p as o,q as p,r as q,ra as G,s as r,sa as H,t as s,ta as I,u as t,ua as J,v as u,va as K,w as v,wa as L,x as w,xa as M,y as x,ya as N,z as y,za as O}from"./chunk-F5GBHMO2.js";import"./chunk-WDF3YE27.js";import"./chunk-IGGCNGU2.js";import"./chunk-QAIKSQAD.js";export{f as BROWSER_DELIVERY_TTL_MS,n as DEFAULT_HUB_API_URL,o as HubNotConfiguredError,T as ManagedOAuthDeliveryError,g as SIGNED_TUNNEL_REPLAY_WINDOW_MS,aa as attachManagedRefreshAuth,i as buildBrowserDeliveryRedirectUrl,l as buildClientBridgeBrowserDeliveryUrl,ca as createConnectSessionJti,ha as createConnectTokenJti,B as createHubConnectSession,E as createHubPermissionSession,ba as createHubRouteHandlers,na as createPermissionSessionJti,h as createSignedTokenJti,ga as decodeConnectSessionTokenFromPath,ma as decodeConnectTokenFromPath,qa as decodePermissionTokenFromPath,O as deliverConnectCreateLink,S as deliverSignedEnvelope,Q as describeDeliveryNetworkError,la as encodeConnectTokenForPath,M as extractConnectLinkFromDeliveryAck,L as extractSyncFromDeliveryAck,F as formatHubApprovalMessage,a as formatProviderDisplayName,R as formatServerDeliveryError,da as getConnectSessionExpiryMs,C as getConnectStatusForTenant,ia as getConnectTokenExpiryMs,q as getHubConfig,$ as getManagedAccessToken,V as handleHubDeliveryGet,W as handleHubDeliveryPost,Y as handleHubDeliveryRequest,X as hubDeliveryToResponse,s as inferHubEnvironmentSlug,b as isLoopbackUrl,K as isServerDeliveryAckSuccessful,D as listHubProjectConnections,p as normalizeHubConfig,N as parseConnectLinkFromDeliveryBody,t as parseConnectSessionResponse,x as parseConnectStatusResponse,y as parseHubApiErrorBody,w as parseOAuthRefreshResponse,v as parsePermissionSessionResponse,u as parseProjectConnectionsResponse,J as parseServerDeliveryAckBody,P as parseSyncFromDeliveryBody,m as prepareClientBridgeDeliveryTransport,U as processManagedOAuthDelivery,A as registerHubWebhookTenantLink,c as resolveDeliveryTransport,z as resolveHubDeliveryUrl,r as resolveHubOAuthCallbackUrl,Z as respondToHubDelivery,_ as respondToHubDeliveryFromRequest,j as signBrowserDeliveryToken,ea as signConnectSessionToken,ja as signConnectToken,G as signDeliveryEnvelope,oa as signPermissionToken,d as usesBrowserDelivery,e as validateProductionDeliveryUrl,k as verifyBrowserDeliveryToken,fa as verifyConnectSessionToken,ka as verifyConnectToken,H as verifyDeliveryEnvelope,pa as verifyPermissionToken,I as verifySignedTunnelDelivery};
@@ -1,5 +1,5 @@
1
1
  import { CorsairDatabase } from './db.js';
2
- import { C as CorsairPlugin, a as CorsairPermissionsOptions, b as CorsairManualConfig, H as HubConfig, c as CorsairIntegration, d as CorsairTenantWrapper, e as CorsairSingleTenantClient } from './index-DwegPGYj.js';
2
+ import { C as CorsairPlugin, a as CorsairPermissionsOptions, b as CorsairManualConfig, H as HubConfig, c as CorsairIntegration, d as CorsairTenantWrapper, e as CorsairSingleTenantClient } from './index-CCwyDzOb.js';
3
3
 
4
4
  declare const CORSAIR_INTERNAL: unique symbol;
5
5
  type CorsairInternalConfig = {
@@ -1,7 +1,7 @@
1
1
  import { ZodTypeAny } from 'zod';
2
2
  import { CorsairDatabase, CorsairDatabaseInput } from './db.js';
3
3
  import { CorsairPluginSchema, PluginEntityClients } from './orm.js';
4
- import { A as AuthTypes, l as AllErrors, M as ManagementOk, T as Tenant, C as CreateTenantInput, P as PluginInfo, a as ConnectionStatus, f as PermissionLookupInput, b as PermissionRecord, d as CreateConnectLinkInput, c as ConnectLink, R as ResolvedConnectLink, e as OAuthCallbackInput, O as OAuthCallbackResult, g as AllProviders } from './types-1nBbBn-U.js';
4
+ import { A as AuthTypes, l as AllErrors, M as ManagementOk, T as Tenant, C as CreateTenantInput, P as PluginInfo, a as ConnectionStatus, f as PermissionLookupInput, b as PermissionRecord, d as CreateConnectLinkInput, c as ConnectLink, R as ResolvedConnectLink, e as OAuthCallbackInput, O as OAuthCallbackResult, g as AllProviders } from './types-Bsv_KdHs.js';
5
5
  import { C as CorsairPermission } from './index-eydqYIn0.js';
6
6
 
7
7
  type HubEnvironmentSlug = 'development' | 'production';
@@ -1,5 +1,5 @@
1
- import { A as AuthTypes } from './types-1nBbBn-U.js';
2
- import { W as WebhookTenantMatch } from './index-DwegPGYj.js';
1
+ import { A as AuthTypes } from './types-Bsv_KdHs.js';
2
+ import { W as WebhookTenantMatch } from './index-CCwyDzOb.js';
3
3
  import { a as CorsairAccount } from './index-eydqYIn0.js';
4
4
  import { CorsairDatabase } from './db.js';
5
5
 
package/dist/index.d.ts CHANGED
@@ -1,14 +1,14 @@
1
- import { C as CorsairClientOptions, a as CorsairManagementClient } from './types-DvDEtIUw.js';
2
- export { b as CorsairClientError } from './types-DvDEtIUw.js';
3
- export { c as createCorsair } from './index-D7aqzKjb.js';
4
- import { e as CorsairSingleTenantClient, C as CorsairPlugin, d as CorsairTenantWrapper, m as CorsairClient, z as CorsairPermissionsNamespace, aa as BoundWebhookTree, ag as RawWebhookRequest, af as CorsairWebhookTenantMatcher, aj as WebhookResponse } from './index-DwegPGYj.js';
5
- export { al as CorsairManageNamespace, b as CorsairManualConfig, a as CorsairPermissionsOptions, K as ReadonlyForbiddenError, L as runReadonly } from './index-DwegPGYj.js';
6
- import { F as FormFieldSchema, L as ListOperationsOptions } from './tenant-match-utils-f49OxmPU.js';
7
- export { A as AuthMissingError, j as PluginWebhookMatchers, R as ResolveConnectLinkResult, W as WebhookPluginTenantMatch, k as asRecord, g as collectPluginWebhookMatchers, l as decodePubSubData, o as firstString, f as formatDocSchemaShape, p as getHeader, m as matchWebhookPlugin, h as matchWebhookPluginAndTenant, s as readBodyRecord, r as resolveConnectLink, u as toExternalId } from './tenant-match-utils-f49OxmPU.js';
1
+ import { C as CorsairClientOptions, a as CorsairManagementClient } from './types-MvrzaDrs.js';
2
+ export { b as CorsairClientError } from './types-MvrzaDrs.js';
3
+ export { c as createCorsair } from './index-BzMy2KpY.js';
4
+ import { e as CorsairSingleTenantClient, C as CorsairPlugin, d as CorsairTenantWrapper, m as CorsairClient, z as CorsairPermissionsNamespace, aa as BoundWebhookTree, ag as RawWebhookRequest, af as CorsairWebhookTenantMatcher, aj as WebhookResponse } from './index-CCwyDzOb.js';
5
+ export { al as CorsairManageNamespace, b as CorsairManualConfig, a as CorsairPermissionsOptions, K as ReadonlyForbiddenError, L as runReadonly } from './index-CCwyDzOb.js';
6
+ import { F as FormFieldSchema, L as ListOperationsOptions } from './tenant-match-utils-DhiFkgcG.js';
7
+ export { A as AuthMissingError, g as PermissionRequiredError, k as PluginWebhookMatchers, R as ResolveConnectLinkResult, W as WebhookPluginTenantMatch, l as asRecord, h as collectPluginWebhookMatchers, n as decodePubSubData, p as firstString, f as formatDocSchemaShape, q as getHeader, m as matchWebhookPlugin, j as matchWebhookPluginAndTenant, t as readBodyRecord, r as resolveConnectLink, v as toExternalId } from './tenant-match-utils-DhiFkgcG.js';
8
8
  export { SetupCorsairOptions, setupCorsair } from './setup.js';
9
- export { O as OAuthCallbackTunnelPayload, P as ProcessCorsairOptions, c as ProcessCorsairRequest, R as ResolveAccountFromWebhookLinkInput, T as TunnelAck, f as TunnelEnvelope, g as TunnelType, h as WebhookTenantLink, W as WebhookTunnelPayload, p as processCorsair, r as resolveAccountFromWebhookLink, d as resolveTenantFromWebhookLink, e as resolveTenantIdFromWebhookLink, s as setWebhookTenantLink } from './index-CdzrawUJ.js';
10
- import { B as BaseProviders } from './types-1nBbBn-U.js';
11
- export { c as ConnectLink, a as ConnectionStatus, d as CreateConnectLinkInput, C as CreateTenantInput, M as ManagementOk, e as OAuthCallbackInput, O as OAuthCallbackResult, f as PermissionLookupInput, b as PermissionRecord, k as PluginConnectionState, P as PluginInfo, R as ResolvedConnectLink, T as Tenant } from './types-1nBbBn-U.js';
9
+ export { O as OAuthCallbackTunnelPayload, P as ProcessCorsairOptions, c as ProcessCorsairRequest, R as ResolveAccountFromWebhookLinkInput, T as TunnelAck, f as TunnelEnvelope, g as TunnelType, h as WebhookTenantLink, W as WebhookTunnelPayload, p as processCorsair, r as resolveAccountFromWebhookLink, d as resolveTenantFromWebhookLink, e as resolveTenantIdFromWebhookLink, s as setWebhookTenantLink } from './index-F_9QUwf4.js';
10
+ import { B as BaseProviders } from './types-Bsv_KdHs.js';
11
+ export { c as ConnectLink, a as ConnectionStatus, d as CreateConnectLinkInput, C as CreateTenantInput, M as ManagementOk, e as OAuthCallbackInput, O as OAuthCallbackResult, f as PermissionLookupInput, b as PermissionRecord, k as PluginConnectionState, P as PluginInfo, R as ResolvedConnectLink, T as Tenant } from './types-Bsv_KdHs.js';
12
12
  import './db.js';
13
13
  import 'kysely';
14
14
  import './index-eydqYIn0.js';
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import{a as B,b as J}from"./chunk-XLNT2UI2.js";import{Ab as E,Bb as _,Cb as $,Db as M,Eb as D,Fa as I,Ib as H,Jb as N,Kb as g,La as O,Lb as j,Q as y,R as h,S as k,Sa as R,T as x,_ as P,ja as b,jb as T,kb as A,lb as L,ma as S,mb as F,na as w,qb as l,rb as c,sb as d,tb as m,yb as W,zb as v}from"./chunk-6WGGD3SS.js";import"./chunk-BPFUYXOD.js";import"./chunk-IGGCNGU2.js";import"./chunk-QAIKSQAD.js";function s(n){let t=n[g];if(!t)throw new Error("listOperations / getSchema: invalid corsair instance. Pass the value returned by createCorsair() or corsair.withTenant().");return t.plugins}function q(n,t){let r=c(s(n),t);return typeof r=="string"?r:Array.isArray(r)?r.join(`
1
+ import{a as B,b as J}from"./chunk-XLNT2UI2.js";import{Ab as v,Bb as _,Cb as $,Db as M,Eb as D,Fb as H,Ga as R,Jb as N,Kb as j,Lb as g,Ma as O,Mb as q,N as y,S as h,T as k,Ta as T,U as x,V as P,ja as b,kb as A,lb as L,ma as S,mb as F,na as w,nb as W,oa as I,rb as l,sb as c,tb as d,ub as m,zb as E}from"./chunk-F5GBHMO2.js";import"./chunk-WDF3YE27.js";import"./chunk-IGGCNGU2.js";import"./chunk-QAIKSQAD.js";function s(n){let t=n[g];if(!t)throw new Error("listOperations / getSchema: invalid corsair instance. Pass the value returned by createCorsair() or corsair.withTenant().");return t.plugins}function Y(n,t){let r=c(s(n),t);return typeof r=="string"?r:Array.isArray(r)?r.join(`
2
2
  `):Object.values(r).flat().join(`
3
- `)}function Y(n,t){return d(s(n),t)}function z(n,t){return l(s(n),t)}var G=Symbol.for("corsair:internal");function K(n,t){let r=n;for(let e of t){if(!r||typeof r!="object")return null;r=r[e]}return typeof r=="function"?r:null}function C(n){return n[G]?.database}async function Q(n,t){let r=new Date().toISOString(),e=await n.permissions.find_by_token(t);if(!e)return console.error("executePermission: no permission found for token."),{error:"executePermission: no permission found for token."};if(e.status!=="approved")return console.error(`executePermission: permission '${e.id}' is '${e.status}', expected 'approved'.`),{endpoint:e.endpoint,plugin:e.plugin,result:null,error:`executePermission: permission '${e.id}' is '${e.status}', expected 'approved'.`};if(e.expires_at<r){let o=C(n);return o&&await o.db.updateTable("corsair_permissions").set({status:"expired",updated_at:new Date}).where("id","=",e.id).execute(),console.error(`executePermission: permission '${e.id}' has expired.`),{error:`executePermission: permission '${e.id}' has expired.`,endpoint:e.endpoint,plugin:e.plugin,result:null}}let f=e.tenant_id??"default",a=(n.withTenant?n.withTenant(f):n)[e.plugin];if(!a?.api)return console.error(`executePermission: plugin '${e.plugin}' not found or has no API on this corsair instance.`),{error:`executePermission: plugin '${e.plugin}' not found or has no API on this corsair instance.`,plugin:e.plugin,endpoint:e.endpoint,result:null};let p=K(a.api,e.endpoint.split("."));if(!p)return console.error(`executePermission: endpoint '${e.endpoint}' not found in plugin '${e.plugin}'.`),{endpoint:e.endpoint,plugin:e.plugin,result:null,error:`executePermission: endpoint '${e.endpoint}' not found in plugin '${e.plugin}'.`};await n.permissions.set_executing(e.id);try{let o=typeof e.args=="string"?JSON.parse(e.args):e.args,i=await p(o);return await n.permissions.set_completed(e.id),{plugin:e.plugin,endpoint:e.endpoint,result:i}}catch(o){let i=o instanceof Error?o.message:String(o),u=C(n);return u&&await u.db.updateTable("corsair_permissions").set({status:"failed",error:i,updated_at:new Date}).where("id","=",e.id).execute(),{plugin:e.plugin,endpoint:e.endpoint,result:null,error:i}}}export{R as AuthMissingError,B as CorsairClientError,S as ReadonlyForbiddenError,M as asRecord,E as collectPluginWebhookMatchers,j as createCorsair,J as createCorsairClient,N as decodePubSubData,Q as executePermission,H as firstString,m as formatDocSchemaShape,_ as getHeader,Y as getSchema,z as getStructuredSchema,q as listOperations,T as managementHandler,W as matchWebhookPlugin,v as matchWebhookPluginAndTenant,O as processCorsair,I as processWebhook,D as readBodyRecord,h as resolveAccountFromWebhookLink,b as resolveConnectLink,x as resolveTenantFromWebhookLink,k as resolveTenantIdFromWebhookLink,w as runReadonly,y as setWebhookTenantLink,P as setupCorsair,A as toExpressHandler,$ as toExternalId,L as toHonoHandler,F as toNextJsHandler};
3
+ `)}function z(n,t){return d(s(n),t)}function G(n,t){return l(s(n),t)}var K=Symbol.for("corsair:internal");function Q(n,t){let r=n;for(let e of t){if(!r||typeof r!="object")return null;r=r[e]}return typeof r=="function"?r:null}function C(n){return n[K]?.database}async function U(n,t){let r=new Date().toISOString(),e=await n.permissions.find_by_token(t);if(!e)return console.error("executePermission: no permission found for token."),{error:"executePermission: no permission found for token."};if(e.status!=="approved")return console.error(`executePermission: permission '${e.id}' is '${e.status}', expected 'approved'.`),{endpoint:e.endpoint,plugin:e.plugin,result:null,error:`executePermission: permission '${e.id}' is '${e.status}', expected 'approved'.`};if(e.expires_at<r){let o=C(n);return o&&await o.db.updateTable("corsair_permissions").set({status:"expired",updated_at:new Date}).where("id","=",e.id).execute(),console.error(`executePermission: permission '${e.id}' has expired.`),{error:`executePermission: permission '${e.id}' has expired.`,endpoint:e.endpoint,plugin:e.plugin,result:null}}let f=e.tenant_id??"default",a=(n.withTenant?n.withTenant(f):n)[e.plugin];if(!a?.api)return console.error(`executePermission: plugin '${e.plugin}' not found or has no API on this corsair instance.`),{error:`executePermission: plugin '${e.plugin}' not found or has no API on this corsair instance.`,plugin:e.plugin,endpoint:e.endpoint,result:null};let p=Q(a.api,e.endpoint.split("."));if(!p)return console.error(`executePermission: endpoint '${e.endpoint}' not found in plugin '${e.plugin}'.`),{endpoint:e.endpoint,plugin:e.plugin,result:null,error:`executePermission: endpoint '${e.endpoint}' not found in plugin '${e.plugin}'.`};await n.permissions.set_executing(e.id);try{let o=typeof e.args=="string"?JSON.parse(e.args):e.args,i=await p(o);return await n.permissions.set_completed(e.id),{plugin:e.plugin,endpoint:e.endpoint,result:i}}catch(o){let i=o instanceof Error?o.message:String(o),u=C(n);return u&&await u.db.updateTable("corsair_permissions").set({status:"failed",error:i,updated_at:new Date}).where("id","=",e.id).execute(),{plugin:e.plugin,endpoint:e.endpoint,result:null,error:i}}}export{T as AuthMissingError,B as CorsairClientError,S as PermissionRequiredError,w as ReadonlyForbiddenError,D as asRecord,_ as collectPluginWebhookMatchers,q as createCorsair,J as createCorsairClient,j as decodePubSubData,U as executePermission,N as firstString,m as formatDocSchemaShape,$ as getHeader,z as getSchema,G as getStructuredSchema,Y as listOperations,A as managementHandler,E as matchWebhookPlugin,v as matchWebhookPluginAndTenant,O as processCorsair,R as processWebhook,H as readBodyRecord,k as resolveAccountFromWebhookLink,b as resolveConnectLink,P as resolveTenantFromWebhookLink,x as resolveTenantIdFromWebhookLink,I as runReadonly,h as setWebhookTenantLink,y as setupCorsair,L as toExpressHandler,M as toExternalId,F as toHonoHandler,W as toNextJsHandler};