corsair 0.2.4 → 0.2.5

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.
@@ -0,0 +1 @@
1
+ import{d as ce,e as ue,f as de,g as le}from"./chunk-XPXWKPFZ.js";var Ze=Symbol.for("corsair:internal"),K=class extends Error{constructor(t="Invalid corsair instance"){super(t),this.name="InvalidCorsairInstanceError"}};function z(e){return typeof e=="object"&&e!==null}function ye(e){if(!z(e)||!Array.isArray(e.plugins)||typeof e.kek!="string"||typeof e.multiTenancy!="boolean")return!1;if(e.database===void 0)return!0;if(!z(e.database))return!1;let t=e.database.db;return typeof t=="object"&&t!==null&&typeof t.selectFrom=="function"}function fe(e){if(!e||typeof e!="object")return;let n=Object.getOwnPropertyDescriptor(e,Ze)?.value;return ye(n)?n:void 0}function Je(e,t){let n=fe(e);if(!n)throw t?.()??new K;return n}function ge(e,t){return e.plugins.find(n=>n.id===t)}function Qe(e,t,n){let r=ge(e,t);if(!r)throw n(`Plugin '${t}' not found`);return r}function ze(e){return"withTenant"in e&&typeof e.withTenant=="function"}function He(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="function"?(...r)=>Reflect.apply(n,e,r):void 0}var H={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"]},managed_pricing:{integration:[],account:[]}};function pe(e){return e==="oauth_2"||e==="api_key"||e==="bot_token"||e==="managed"||e==="managed_pricing"}function Ge(e){let t=e.options?.authType;return pe(t)?t:void 0}function Ot(e){return e==="managed_pricing"}function qe(e,t){let n=e.authConfig,r=H[t].account,i=n?.[t]?.account??[];return[...r,...i]}function vt(e,t){let n=e.authConfig,r=H[t].integration,i=n?.[t]?.integration??[];return[...r,...i]}import{createCipheriv as me,createDecipheriv as we,randomBytes as O,scrypt as Ye}from"crypto";import{promisify as Xe}from"util";var be=Xe(Ye),v="aes-256-gcm",he=12,$=16,Ve=16,G=32;function q(){return O(G).toString("base64")}async function Y(e,t){let n=O(Ve),r=await be(t,n,G),i=O(he),o=me(v,r,i,{authTagLength:$}),a=Buffer.concat([o.update(e,"utf8"),o.final()]),l=o.getAuthTag();return[n.toString("base64"),i.toString("base64"),l.toString("base64"),a.toString("base64")].join(":")}async function F(e,t){let[n,r,i,o]=e.split(":");if(!n||!r||!i||!o)throw new Error("Invalid encrypted DEK format");let a=Buffer.from(n,"base64"),l=Buffer.from(r,"base64"),p=Buffer.from(i,"base64"),b=Buffer.from(o,"base64"),u=await be(t,a,G),s=we(v,u,l,{authTagLength:$});return s.setAuthTag(p),Buffer.concat([s.update(b),s.final()]).toString("utf8")}function X(e,t){let n=Buffer.from(t,"base64"),r=O(he),i=me(v,n,r,{authTagLength:$}),o=Buffer.concat([i.update(e,"utf8"),i.final()]),a=i.getAuthTag();return[r.toString("base64"),a.toString("base64"),o.toString("base64")].join(":")}function V(e,t){let[n,r,i]=e.split(":");if(!n||!r||!i)throw new Error("Invalid encrypted data format");let o=Buffer.from(t,"base64"),a=Buffer.from(n,"base64"),l=Buffer.from(r,"base64"),p=Buffer.from(i,"base64"),b=we(v,o,a,{authTagLength:$});return b.setAuthTag(l),Buffer.concat([b.update(p),b.final()]).toString("utf8")}function ee(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=X(i,t);return n}function j(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=V(i,t);return n}function Lt(e,t,n){let r=j(e,t);return ee(r,n)}import{v7 as et}from"uuid";function P(){return et()}function M(e,t){return e.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",t.tenantId).where("integration_id","=",t.integrationId).orderBy("created_at","asc").orderBy("id","asc")}async function B(e,t){return M(e,t).executeTakeFirst()}async function tt(e){let t=!1;for(;;){let n=await e.database.db.selectFrom("corsair_integrations").selectAll().where("name","=",e.integrationName).executeTakeFirst();if(!n){if(!t&&e.ensureProvisioned){t=!0,await e.ensureProvisioned();continue}throw new Error(`Integration "${e.integrationName}" not found. Make sure to create the integration first.`)}let r={tenantId:e.tenantId,integrationId:n.id},i=e.account?await ot({db:e.database.db,kek:e.account.kek,...r,ref:e.account.ref}):await B(e.database.db,r);if(!i){if(!t&&e.ensureProvisioned){t=!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:n.id,accountId:i.id,integration:{id:n.id,config:n.config,dek:n.dek??null},account:{id:i.id,config:i.config,dek:i.dek??null}}}}async function rn(e){let{integrationId:t,accountId:n}=await tt(e);return{integrationId:t,accountId:n}}var S=class extends Error{code;accounts;constructor(t,n,r=[]){super(n),this.name="AccountSelectionError",this.code=t,this.accounts=r}};function re(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return e??{}}var ne=e=>({id:e.id,config:e.config,dek:e.dek??null});async function L(e,t){let n=re(e.config);if(!e.dek||!n?.account_ref)return{};try{let r=j(n,await F(e.dek,t));return{ref:r.account_ref,label:r.account_label}}catch{return{}}}async function on(e,t,n){if(e.id===t)return!0;let{ref:r,label:i}=await L(e,n);return r===t||i?.toLowerCase()===t.toLowerCase()}async function an(e,t,n){let r=n?await e.selectFrom("corsair_accounts").select(["config","dek"]).where("id","=",t).executeTakeFirst():void 0;return{id:t,...r&&n?await L(r,n):{}}}function nt(e){let t=new Set(e),n=1;for(;t.has(`Account ${n}`);)n++;return`Account ${n}`}var ke=(e,t)=>Promise.all(e.map(async n=>({...ne(n),...await L(n,t)})));async function Te(e){return ke(await M(e.db,e).execute(),e.kek)}var rt=e=>e.label??e.ref??e.id,W=({id:e,ref:t,label:n})=>({id:e,ref:t,label:n});async function sn(e){let t=await e.db.selectFrom("corsair_integrations").select("id").where("name","=",e.integrationName).executeTakeFirst();if(!t)return[];let n=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",e.tenantId).where("integration_id","=",t.id).execute();return n.length<2?n:(await Te({db:e.db,kek:e.kek,integrationId:t.id,tenantId:e.tenantId})).map(i=>({id:i.id,label:i.label??i.ref}))}async function cn(e){let t=await e.db.selectFrom("corsair_integrations").select("id").where("name","=",e.integrationName).executeTakeFirst();return t?(await Te({db:e.db,kek:e.kek,integrationId:t.id,tenantId:e.tenantId})).map(W):[]}async function it(e,t){return(await e.selectFrom("corsair_integrations").select("name").where("id","=",t).executeTakeFirst())?.name??t}async function ot(e){let t=await M(e.db,e).execute();if(t.length===0)return;if(!e.ref&&t.length===1)return ne(t[0]);let n=e.ref?t.find(u=>u.id===e.ref):void 0;if(n)return ne(n);let r=await ke(t,e.kek),i=e.ref?.toLowerCase(),o=e.ref?r.find(u=>u.ref===e.ref):void 0;if(o)return o;let a=e.ref?r.filter(u=>u.label?.toLowerCase()===i):[];if(a.length===1)return a[0];let l=await it(e.db,e.integrationId);if(a.length>1)throw new S("account_required",`Label "${e.ref}" matches ${a.length} accounts for "${l}" (tenant "${e.tenantId}"): ${a.map(u=>u.ref??u.id).join(", ")}. Name one by its id.`,a.map(W));let p=r.map(rt).join(", "),b=r.map(W);throw e.ref?new S("account_not_found",`No account "${e.ref}" for "${l}" (tenant "${e.tenantId}"). Accounts: ${p}.`,b):new S("account_required",`Plugin "${l}" has ${r.length} accounts for tenant "${e.tenantId}": ${p}. Name one with withTenant(tenantId, { accounts: { ${l}: "<account>" } }).`,b)}var at=5;async function un(e){let{database:t,kek:n,tenantId:r}=e;return t.db.transaction().execute(async i=>{let o=i.selectFrom("corsair_integrations").select(["id"]).where("name","=",e.integrationName);t.isPg===!0&&(o=o.forUpdate());let a=await o.executeTakeFirst();if(!a)throw new Error(`Integration '${e.integrationName}' not found. Run setupCorsair first.`);let l=await M(i,{tenantId:r,integrationId:a.id}).execute();if(!e.identity)return l[0]?{accountId:l[0].id,created:!1}:Ce(i,a.id,r,n);let p=await Promise.all(l.map(async w=>({row:w,...await L(w,n)}))),b=e.identity.label===void 0&&e.nameNew?{...e.identity,label:nt(p.map(w=>w.label))}:e.identity;if(e.rowId){let w=p.find(c=>c.row.id===e.rowId);if(!w)throw new S("account_not_found",`Account "${e.rowId}" is no longer connected for "${e.integrationName}" (tenant "${r}").`);return w.ref?{accountId:w.row.id,created:!1}:(await te(i,w.row,b,n),{accountId:w.row.id,created:!1})}let u=p.filter(w=>!w.ref),s=e.hubAccounts?.[0];u.length===1&&Object.keys(re(u[0].row.config)).length>0&&s&&s.id!==b.id&&!p.some(w=>w.ref===s.id)&&(await te(i,u[0].row,s,n),u[0].ref=s.id,u[0].label=s.label);let y=p.find(w=>w.ref===b.id),m=y??p.find(w=>!w.ref)??(e.allowMany?void 0:p[0]);if(m){if(!y||b.label&&m.label!==b.label){let w=!y&&m.ref!==void 0;await te(i,m.row,b,n,w)}return{accountId:m.row.id,created:!1}}if(l.length>=at)throw new S("account_limit",`Account limit reached: tenant "${r}" already has ${l.length} accounts for "${e.integrationName}".`,p.map(({row:w,ref:c,label:d})=>W({id:w.id,ref:c,label:d})));return Ce(i,a.id,r,n,b)})}async function Ae(e,t,n){let{account_label:r,...i}=t;return ee({...i,account_ref:n.id,...n.label?{account_label:n.label}:{}},e)}async function te(e,t,n,r,i=!1){let o=t.dek?await F(t.dek,r):q(),a=re(t.config),l=i?{}:t.dek?j(a,o):a;await e.updateTable("corsair_accounts").set({config:await Ae(o,l,n),dek:t.dek??await Y(o,r),updated_at:new Date}).where("id","=",t.id).execute()}async function Ce(e,t,n,r,i){let o=q(),a=new Date,l=P();return await e.insertInto("corsair_accounts").values({id:l,created_at:a,updated_at:a,tenant_id:n,integration_id:t,config:i?await Ae(o,{},i):{},dek:await Y(o,r)}).execute(),{accountId:l,created:!0}}import{SqliteAdapter as st,sql as Ke}from"kysely";import{z as A}from"zod";var ie="_corsair_enc";function Ie(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t[ie]=="string"&&Object.keys(t).length===1}function oe(e,t){return{[ie]:X(JSON.stringify(e),t)}}function ae(e,t){let n=Ee(e);return Ie(n)?JSON.parse(V(n[ie],t)):n}async function fn(e,t,n){let r=await e.selectFrom("corsair_accounts").select("dek").where("id","=",t).executeTakeFirst();if(!r?.dek)throw new Error(`No DEK found for account "${t}". Initialize the account first.`);return F(r.dek,n)}async function gn(e,t,n,r){let i=await e.selectFrom("corsair_entities").select(["id","data"]).where("account_id","=",t).execute();for(let a of i){let l=xe(a.data,n,r);l&&await e.updateTable("corsair_entities").set({data:l,updated_at:new Date}).where("id","=",a.id).execute()}let o=await e.selectFrom("corsair_events").select(["id","payload"]).where("account_id","=",t).execute();for(let a of o){let l=xe(a.payload,n,r);l&&await e.updateTable("corsair_events").set({payload:l,updated_at:new Date}).where("id","=",a.id).execute()}}function xe(e,t,n){let r=Ee(e);if(Ie(r))return oe(ae(r,t),n)}function Ee(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}import{sql as D}from"kysely";function U(e){return e.replace(/'/g,"''")}function _e(e){let t=U(e);return D`data->>'${D.raw(t)}'`}function De(e){let t=U(e);return D`(data->>'${D.raw(t)}')::numeric`}function Fe(e){let t=U(e);return D`(data->>'${D.raw(t)}')::boolean`}function Pe(e){let t=U(e);return D`(data->>'${D.raw(t)}')::timestamptz`}import{sql as Z}from"kysely";function Se(e){return e.replace(/'/g,"''").replace(/\\/g,"\\\\")}function Re(e){let t=Se(e);return Z`CAST(json_extract(data, '$.${Z.raw(t)}') AS REAL)`}function Be(e){let t=Se(e);return Z`json_extract(data, '$.${Z.raw(t)}')`}var ct={number:e=>De(e),booleanEquals:(e,t)=>Ke`${Fe(e)} = ${t}`,timestamp:e=>Pe(e)},ut={number:e=>Re(e),booleanEquals:(e,t)=>Ke`json_extract(data, ${`$.${e}`}) = ${t?1:0}`,timestamp:e=>Be(e)};function dt(e){return e.getExecutor().adapter instanceof st?ut:ct}function lt(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}function Oe(e){let t=e;for(;t;){if(t instanceof A.ZodOptional||t instanceof A.ZodNullable){t=t._def.innerType;continue}if(t instanceof A.ZodDefault){t=t._def.innerType;continue}break}return t}function Ne(e){if(typeof e=="string")return"string";if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean"}function se(e){let[t]=e;return t&&e.every(n=>n===t)?t:void 0}function ve(e){let t=Oe(e);if(t instanceof A.ZodString)return"string";if(t instanceof A.ZodNumber)return"number";if(t instanceof A.ZodBoolean)return"boolean";if(t instanceof A.ZodDate)return"date";if(t instanceof A.ZodEnum)return se(t.options.map(Ne));if(t instanceof A.ZodLiteral)return se([...t.values].map(Ne));if(t instanceof A.ZodUnion)return se(t.options.filter(n=>!(n instanceof A.ZodNull)).map(n=>ve(n)))}function yt(e){let t=Oe(e);if(!(t instanceof A.ZodObject))return{};let n=t.shape,r={};for(let[i,o]of Object.entries(n)){let a=ve(o);a&&(r[i]=a)}return r}function ft(e,t,n){if(typeof n=="string")return e.where(t,"=",n);if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;"equals"in r&&typeof r.equals=="string"&&(e=e.where(t,"=",r.equals)),"contains"in r&&typeof r.contains=="string"&&(e=e.where(t,"like",`%${r.contains}%`)),"startsWith"in r&&typeof r.startsWith=="string"&&(e=e.where(t,"like",`${r.startsWith}%`)),"endsWith"in r&&typeof r.endsWith=="string"&&(e=e.where(t,"like",`%${r.endsWith}`)),"in"in r&&Array.isArray(r.in)&&(e=e.where(t,"in",r.in))}return e}function gt(e,t,n){if(typeof n=="number")return e.where(t,"=",n);if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;typeof r.equals=="number"&&(e=e.where(t,"=",r.equals)),typeof r.gt=="number"&&(e=e.where(t,">",r.gt)),typeof r.gte=="number"&&(e=e.where(t,">=",r.gte)),typeof r.lt=="number"&&(e=e.where(t,"<",r.lt)),typeof r.lte=="number"&&(e=e.where(t,"<=",r.lte)),Array.isArray(r.in)&&(e=e.where(t,"in",r.in))}return e}function pt(e,t,n){if(typeof n=="boolean")return e.where(t(n));if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;typeof r.equals=="boolean"&&(e=e.where(t(r.equals)))}return e}function mt(e,t,n){if(n instanceof Date)return e.where(t,"=",n);if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;if(r.equals instanceof Date&&(e=e.where(t,"=",r.equals)),r.before instanceof Date&&(e=e.where(t,"<",r.before)),r.after instanceof Date&&(e=e.where(t,">",r.after)),Array.isArray(r.between)&&r.between.length===2){let[i,o]=r.between;i instanceof Date&&(e=e.where(t,">=",i)),o instanceof Date&&(e=e.where(t,"<=",o))}}return e}function wt(e,t,n,r,i){return r==="number"?gt(e,t.number(n),i):r==="boolean"?pt(e,o=>t.booleanEquals(n,o),i):r==="date"?mt(e,t.timestamp(n),i):ft(e,_e(n),i)}function bt(e,t,n){if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;return"equals"in r&&(e=e.where(t,"=",r.equals)),"contains"in r&&typeof r.contains=="string"&&(e=e.where(t,"like",`%${r.contains}%`)),"startsWith"in r&&typeof r.startsWith=="string"&&(e=e.where(t,"like",`${r.startsWith}%`)),"endsWith"in r&&typeof r.endsWith=="string"&&(e=e.where(t,"like",`%${r.endsWith}`)),"in"in r&&Array.isArray(r.in)&&(e=e.where(t,"in",r.in)),e}return e.where(t,"=",n)}function ht(e){return typeof e=="number"?e:typeof e=="bigint"?Number(e):Number.parseInt(String(e??0),10)}function $e(e,t){return Array.isArray(t)?e("account_id","in",t):e("account_id","=",t)}function R(e,t,n){let r=e.selectFrom("corsair_entities").selectAll().where(i=>$e(i,t)).where("entity_type","=",n);return Array.isArray(t)?r.orderBy("created_at").orderBy("id"):r}function je(e,t,n,r,i,o,a){let l=yt(i),p=new Map,b=async c=>{if(!o?.kek)throw new Error("encryptDataAtRest requires kek");let d=await e.selectFrom("corsair_accounts").select("dek").where("id","=",c).executeTakeFirst();if(!d?.dek)throw new Error(`No DEK found for account "${c}". Initialize the account first.`);let f=p.get(c);if(f&&f.wrapped===d.dek)return f.dek;let g=await F(d.dek,o.kek);return p.set(c,{wrapped:d.dek,dek:g}),g};async function u(c,d){let f=lt(c.data);return o&&(f=ae(f,d??await b(c.account_id))),{...c,data:i.parse(f)}}async function s(){let c=a?await a():[];return c.length<2?{ids:await t()}:{ids:c.map(d=>d.id),labels:new Map(c.map(d=>[d.id,d.label??d.id]))}}async function y(c){let{ids:d,labels:f}=await s(),C=await R(e,d,n).where("entity_id","=",c).execute();return Array.isArray(d)?(C.sort((I,x)=>d.indexOf(I.account_id)-d.indexOf(x.account_id)),{row:C[0],labels:f}):{row:C[0],labels:f}}async function m(c,d){let f=new Map;return o&&await Promise.all([...new Set(c.map(g=>g.account_id))].map(async g=>f.set(g,await b(g)))),Promise.all(c.map(async g=>{let C=await u(g,f.get(g.account_id)),I=d?.get(g.account_id);return I?{...C,account:I}:C}))}async function w(c,d){return o?oe(d,await b(c)):d}return{findByEntityId:async c=>{let{row:d,labels:f}=await y(c);return d?(await m([d],f))[0]:null},existsByEntityId:async c=>{let{ids:d}=await s();return await R(e,d,n).select("id").where("entity_id","=",c).executeTakeFirst()!==void 0},findIdByEntityId:async c=>{let{row:d}=await y(c);return d?.id??null},findById:async c=>{let{ids:d,labels:f}=await s(),g=await R(e,d,n).where("id","=",c).executeTakeFirst();return g?(await m([g],f))[0]:null},findManyByEntityIds:async c=>{if(c.length===0)return[];let{ids:d,labels:f}=await s(),g=await R(e,d,n).where("entity_id","in",c).execute();return m(g,f)},list:async c=>{let{ids:d,labels:f}=await s(),g=R(e,d,n);typeof c?.limit=="number"&&(g=g.limit(c.limit)),typeof c?.offset=="number"&&(g=g.offset(c.offset));let C=await g.execute();return m(C,f)},search:async c=>{if(o&&c.data&&typeof c.data=="object"&&Object.keys(c.data).length>0)throw new Error("Entity JSON field search cannot run while encryptDataAtRest is enabled. The stored document is ciphertext.");let{ids:d,labels:f}=await s(),g=R(e,d,n),C=new Set(["data","limit","offset"]);for(let[x,_]of Object.entries(c))C.has(x)||_===void 0||(g=bt(g,x,_));if(c.data&&typeof c.data=="object")for(let[x,_]of Object.entries(c.data)){if(_===void 0)continue;let Q=l[x]??"string";g=wt(g,dt(e),x,Q,_)}typeof c.limit=="number"&&(g=g.limit(c.limit)),typeof c.offset=="number"&&(g=g.offset(c.offset));let I=await g.execute();return m(I,f)},upsertByEntityId:async(c,d)=>{let f=await t(),g=i.parse(d),C=await w(f,g),I=new Date,x=await R(e,f,n).select("id").where("entity_id","=",c).executeTakeFirst();if(x?.id){await e.updateTable("corsair_entities").set({version:r,data:C,updated_at:I}).where("id","=",x.id).execute();let Ue=await e.selectFrom("corsair_entities").selectAll().where("id","=",x.id).executeTakeFirst();return u(Ue)}let _=P();await e.insertInto("corsair_entities").values({id:_,created_at:I,updated_at:I,account_id:f,entity_id:c,entity_type:n,version:r,data:C}).execute();let Q=await e.selectFrom("corsair_entities").selectAll().where("id","=",_).executeTakeFirst();return u(Q)},deleteById:async c=>{let d=await t(),f=await e.deleteFrom("corsair_entities").where("account_id","=",d).where("entity_type","=",n).where("id","=",c).executeTakeFirst();return Number(f.numDeletedRows)>0},deleteByEntityId:async c=>{let d=await t(),f=await e.deleteFrom("corsair_entities").where("account_id","=",d).where("entity_type","=",n).where("entity_id","=",c).executeTakeFirst();return Number(f.numDeletedRows)>0},count:async()=>{let{ids:c}=await s(),d=await e.selectFrom("corsair_entities").select(f=>f.fn.countAll().as("count")).where(f=>$e(f,c)).where("entity_type","=",n).executeTakeFirst();return ht(d?.count)}}}var Ct={corsair_integrations:ce,corsair_accounts:ue,corsair_entities:de,corsair_events:le};function kt(e){return Ct[e]}function We(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}function h(e){if(!e)throw new Error("Corsair database is not configured. Pass `database` to createCorsair(...) to enable ORM.")}function N(e){if(!e)return[];let t=[];for(let n in e){let r=n,i=e[r];if(i!==void 0)if(typeof i=="object"&&i!==null&&!Array.isArray(i)&&!(i instanceof Date)){let o=i;"in"in o&&Array.isArray(o.in)?t.push({field:r,operator:"in",value:o.in}):"like"in o&&typeof o.like=="string"&&t.push({field:r,operator:"like",value:o.like})}else t.push({field:r,value:i})}return t}function E(e,t){if(!t?.length)return e;let n=e;for(let r of t){let i=r.operator??"=";n=n.where(r.field,i,r.value)}return n}function Tt(e){return typeof e=="number"?e:typeof e=="bigint"?Number(e):Number.parseInt(String(e??0),10)}function J(e,t){let n=kt(t),r=()=>(h(e),e),i=()=>r().db.selectFrom(t),o=()=>r().db.insertInto(t),a=()=>r().db.updateTable(t),l=()=>r().db.deleteFrom(t);function p(u){let s={};for(let[y,m]of Object.entries(u))s[y]=We(m);return n.parse(s)}function b(u){let s={};for(let[y,m]of Object.entries(u))s[y]=We(m);return n.parse(s)}return{findById:async u=>{h(e);let s=i().selectAll();s=E(s,[{field:"id",value:u}]);let y=await s.executeTakeFirst();return y?p(y):null},findOne:async u=>{h(e);let s=i().selectAll();s=E(s,N(u));let y=await s.executeTakeFirst();return y?p(y):null},findMany:async u=>{h(e);let s=i().selectAll();return s=E(s,N(u?.where)),typeof u?.limit=="number"&&(s=s.limit(u.limit)),typeof u?.offset=="number"&&(s=s.offset(u.offset)),(await s.execute()).map(m=>p(m))},create:async u=>{h(e);let s=new Date,y={id:u.id??P(),created_at:s,updated_at:s,...u},m=await o().values(y).returningAll().executeTakeFirst();return m?p(m):b(y)},update:async(u,s)=>{h(e);let y={...s,updated_at:new Date},m=a().set(y).returningAll();m=E(m,[{field:"id",value:u}]);let w=await m.executeTakeFirst();return w?p(w):null},updateMany:async(u,s)=>{h(e);let y={...s,updated_at:new Date},m=i().select("id");m=E(m,N(u));let w=await m.execute();for(let c of w){let d=a().set(y);d=E(d,[{field:"id",value:c.id}]),await d.execute()}return w.length},delete:async u=>{h(e);let s=l();s=E(s,[{field:"id",value:u}]);let y=await s.executeTakeFirst();return Number(y?.numDeletedRows??0)>0},deleteMany:async u=>{h(e);let s=l();s=E(s,N(u));let y=await s.executeTakeFirst();return Number(y?.numDeletedRows??0)},count:async u=>{h(e);let s=i().select(m=>m.fn.countAll().as("count"));s=E(s,N(u));let y=await s.executeTakeFirst();return Tt(y?.count)}}}function At(e){let t=J(e,"corsair_integrations");return{...t,findByName:n=>t.findOne({name:n}),upsertByName:async(n,r)=>{let i=await t.findOne({name:n});return i?await t.update(i.id,r):t.create({...r,name:n})}}}function xt(e){let t=J(e,"corsair_accounts");return{...t,findByTenantAndIntegration:async(n,r)=>{h(e);let i=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",r).executeTakeFirst();if(!i)return null;let o=await B(e.db,{tenantId:n,integrationId:i.id});return o?t.findOne({id:o.id,tenant_id:n,integration_id:i.id}):null},listByTenant:(n,r)=>t.findMany({where:{tenant_id:n},limit:r?.limit,offset:r?.offset}),upsertByTenantAndIntegration:async(n,r,i)=>{h(e);let o=await B(e.db,{tenantId:n,integrationId:r});return o?await t.update(o.id,i):t.create({...i,tenant_id:n,integration_id:r})}}}function It(e){let t=J(e,"corsair_entities");return{...t,findByEntityId:({accountId:n,entityType:r,entityId:i})=>t.findOne({account_id:n,entity_type:r,entity_id:i}),findManyByEntityIds:async({accountId:n,entityType:r,entityIds:i})=>i.length===0?[]:(h(e),await e.db.selectFrom("corsair_entities").selectAll().where("account_id","=",n).where("entity_type","=",r).where("entity_id","in",i).execute()),listByScope:({accountId:n,entityType:r,limit:i,offset:o})=>t.findMany({where:{account_id:n,entity_type:r},limit:i,offset:o}),searchByEntityId:async({accountId:n,entityType:r,query:i,limit:o,offset:a})=>{h(e);let l=e.db.selectFrom("corsair_entities").selectAll().where("account_id","=",n).where("entity_type","=",r).where("entity_id","like",`%${i}%`);return typeof o=="number"&&(l=l.limit(o)),typeof a=="number"&&(l=l.offset(a)),await l.execute()},upsertByEntityId:async({accountId:n,entityType:r,entityId:i,version:o,data:a})=>{let l=await t.findOne({account_id:n,entity_type:r,entity_id:i});return l?await t.update(l.id,{version:o,data:a}):t.create({account_id:n,entity_type:r,entity_id:i,version:o,data:a})},deleteByEntityId:async({accountId:n,entityType:r,entityId:i})=>{h(e);let o=await e.db.deleteFrom("corsair_entities").where("account_id","=",n).where("entity_type","=",r).where("entity_id","=",i).executeTakeFirst();return Number(o.numDeletedRows)>0}}}function Et(e){let t=J(e,"corsair_events");return{...t,listByAccount:(n,r)=>t.findMany({where:{account_id:n},limit:r?.limit,offset:r?.offset}),listByStatus:(n,r)=>{let i={status:n};return r?.accountId&&(i.account_id=r.accountId),t.findMany({where:i,limit:r?.limit,offset:r?.offset})},listPending:n=>{let r={status:"pending"};return n?.accountId&&(r.account_id=n.accountId),t.findMany({where:r,limit:n?.limit??100})},updateStatus:(n,r)=>t.update(n,{status:r})}}function Me(e){return{integrations:At(e),accounts:xt(e),entities:It(e),events:Et(e)}}function _t(e){if(e.encryptDataAtRest===!0)return{encryptDataAtRest:!0,kek:e.kek??""}}function Dt(e,t,n,r,i,o){let a=null;async function l(){if(a!==null)return a;h(e);let p=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",t.integrationName).executeTakeFirst();if(!p)throw new Error(`Integration "${t.integrationName}" not found. Make sure to create the integration first.`);let b=await B(e.db,{tenantId:t.tenantId,integrationId:p.id});if(!b)throw new Error(`Account not found for tenant "${t.tenantId}" and integration "${t.integrationName}". Make sure to create the account first.`);return a=b.id,a}return h(e),je(e.db,l,n,r,i,o)}function Le(e){let{database:t,integrationName:n,schema:r,tenantId:i}=e,o=_t(e),a=Me(t),l={tenantId:i,integrationName:n},p=null;async function b(){if(p!==null)return p;h(t);let s=await t.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!s)throw new Error(`Integration "${n}" not found. Make sure to create the integration first.`);let y=await B(t.db,{tenantId:i,integrationId:s.id});if(!y)throw new Error(`Account not found for tenant "${i}" and integration "${n}". Make sure to create the account first.`);return p=y.id,p}let u={};for(let[s,y]of Object.entries(r.entities))u[s]=Dt(t,l,s,r.version,y,o);return{...u,$orm:a,$integrationName:n,$tenantId:i,$getAccountId:b}}function On(e,t){let n=Me(e);return{$tenantId:t,$orm:n,listAccounts:r=>n.accounts.listByTenant(t,r),findAccountByIntegration:r=>n.accounts.findByTenantAndIntegration(t,r),listEntities:async r=>{h(e);let i=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",t).execute();if(i.length===0)return[];let o=i.map(l=>l.id),a=e.db.selectFrom("corsair_entities").selectAll().where("account_id","in",o);return r?.entityType&&(a=a.where("entity_type","=",r.entityType)),typeof r?.limit=="number"&&(a=a.limit(r.limit)),typeof r?.offset=="number"&&(a=a.offset(r.offset)),await a.execute()},listEvents:async r=>{h(e);let i=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",t).execute();if(i.length===0)return[];let o=i.map(l=>l.id),a=e.db.selectFrom("corsair_events").selectAll().where("account_id","in",o);return r?.status&&(a=a.where("status","=",r.status)),typeof r?.limit=="number"&&(a=a.limit(r.limit)),typeof r?.offset=="number"&&(a=a.offset(r.offset)),await a.execute()},forIntegration:r=>Le({database:e,integrationName:r.integrationName,schema:r.schema,tenantId:t,encryptDataAtRest:r.encryptDataAtRest,kek:r.kek})}}function vn(e,t){return{forTenant:n=>Le({database:e,integrationName:t.integrationName,schema:t.schema,tenantId:n,encryptDataAtRest:t.encryptDataAtRest,kek:t.kek})}}export{K as a,z as b,fe as c,Je as d,Qe as e,ze as f,He as g,H as h,Ge as i,Ot as j,qe as k,vt as l,G as m,q as n,Y as o,F as p,X as q,V as r,ee as s,j as t,Lt as u,Ie as v,oe as w,ae as x,fn as y,gn as z,P as A,B,rn as C,S as D,L as E,on as F,an as G,sn as H,cn as I,ot as J,at as K,un as L,je as M,Ct as N,Me as O,Le as P,On as Q,vn as R};
@@ -0,0 +1 @@
1
+ import{$ as b,_ as a,aa as c}from"./chunk-53L3BPC5.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-QUO2PWXT.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{c as createHubConnectSession,b as createHubConnectSessionForPlugin,a as postHubConnectSession};
package/dist/core.js CHANGED
@@ -1 +1 @@
1
- import{$b as P,Ab as E,Bb as F,Cb as G,D as n,Db as H,E as o,Eb as I,F as p,G as q,Sb as J,Tb as K,Ub as L,Vb as M,Wb as N,_b as O,a,ac as Q,b,ba as r,bb as B,bc as R,c,ca as s,cc as S,dc as T,ec as U,fa as t,fc as V,ga as u,gc as W,ha as v,hc as X,ia as w,ic as Y,ja as x,jc as Z,ka as y,kc as _,la as z,lc as $,ma as A,mc as aa,nc as ba,oc as ca,pc as da,qc as ea,rc as fa,sc as ga,yb as C,zb as D}from"./chunk-KSYLMKIZ.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import{D as m,h as d,n as e,o as f,p as g,q as h,r as i,s as j,t as k,u as l}from"./chunk-KOJBIKQZ.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{m as AccountSelectionError,B as AuthMissingError,d as BASE_AUTH_FIELDS,da as CORSAIR_INTERNAL,H as CloudApiError,C as CorsairKekMissingError,D as DB_METHOD_RISK,R as MS_GRAPH_API_BASE,A as ManagementApiError,M as OAuthRefreshError,s as PermissionRequiredError,a as ProviderDisplayNames,t as ReadonlyForbiddenError,c as ReconnectRequiredError,v as activeMode,Y as asRecord,z as assertModeAllows,y as assertReadonlyAllowed,G as callPluginDb,V as collectPluginWebhookMatchers,I as corsairCloud,o as createAccountKeyManager,ea as createCorsair,n as createIntegrationKeyManager,F as decodeDbArgs,ca as decodePubSubData,k as decryptConfig,g as decryptDEK,i as decryptWithDEK,E as encodeDbArgs,j as encryptConfig,f as encryptDEK,h as encryptWithDEK,L as exchangeCodeForTokens,$ as extractMicrosoftGraphValidationToken,ba as firstString,O as formatDocSchemaShape,b as formatProviderDisplayName,e as generateDEK,W as getHeader,N as getOAuthAccessToken,Q as googleChannelSubscribe,q as initializeAccountDEK,p as initializeIntegrationDEK,P as introspectPluginForDocs,aa as isMicrosoftGraphValidationHandshake,x as isReadonlyScopeActive,J as logEvent,K as logEventFromContext,T as matchWebhookPlugin,U as matchWebhookPluginAndTenant,S as msGraphSubscribe,l as reEncryptConfig,Z as readBodyRecord,_ as readQueryParam,r as resolveConnectLink,w as runReadonly,u as runWithMode,fa as shouldStartTunnel,ga as superviseTunnel,X as toExternalId};
1
+ import{$b as P,Ab as E,Bb as F,Cb as G,D as n,Db as H,E as o,Eb as I,F as p,G as q,Sb as J,Tb as K,Ub as L,Vb as M,Wb as N,_b as O,a,ac as Q,b,ba as r,bb as B,bc as R,c,ca as s,cc as S,dc as T,ec as U,fa as t,fc as V,ga as u,gc as W,ha as v,hc as X,ia as w,ic as Y,ja as x,jc as Z,ka as y,kc as _,la as z,lc as $,ma as A,mc as aa,nc as ba,oc as ca,pc as da,qc as ea,rc as fa,sc as ga,yb as C,zb as D}from"./chunk-53L3BPC5.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import{D as m,h as d,n as e,o as f,p as g,q as h,r as i,s as j,t as k,u as l}from"./chunk-QUO2PWXT.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{m as AccountSelectionError,B as AuthMissingError,d as BASE_AUTH_FIELDS,da as CORSAIR_INTERNAL,H as CloudApiError,C as CorsairKekMissingError,D as DB_METHOD_RISK,R as MS_GRAPH_API_BASE,A as ManagementApiError,M as OAuthRefreshError,s as PermissionRequiredError,a as ProviderDisplayNames,t as ReadonlyForbiddenError,c as ReconnectRequiredError,v as activeMode,Y as asRecord,z as assertModeAllows,y as assertReadonlyAllowed,G as callPluginDb,V as collectPluginWebhookMatchers,I as corsairCloud,o as createAccountKeyManager,ea as createCorsair,n as createIntegrationKeyManager,F as decodeDbArgs,ca as decodePubSubData,k as decryptConfig,g as decryptDEK,i as decryptWithDEK,E as encodeDbArgs,j as encryptConfig,f as encryptDEK,h as encryptWithDEK,L as exchangeCodeForTokens,$ as extractMicrosoftGraphValidationToken,ba as firstString,O as formatDocSchemaShape,b as formatProviderDisplayName,e as generateDEK,W as getHeader,N as getOAuthAccessToken,Q as googleChannelSubscribe,q as initializeAccountDEK,p as initializeIntegrationDEK,P as introspectPluginForDocs,aa as isMicrosoftGraphValidationHandshake,x as isReadonlyScopeActive,J as logEvent,K as logEventFromContext,T as matchWebhookPlugin,U as matchWebhookPluginAndTenant,S as msGraphSubscribe,l as reEncryptConfig,Z as readBodyRecord,_ as readQueryParam,r as resolveConnectLink,w as runReadonly,u as runWithMode,fa as shouldStartTunnel,ga as superviseTunnel,X as toExternalId};
package/dist/hub.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { b2 as HubOAuthMode, A as AuthTypes, b3 as HubConnectSessionResult, b4 as HubPermissionSessionResult, H as HubConfig, b5 as HubConfigInput, b6 as HubConnectSessionInput, b7 as HubListProjectConnectionsInput, f as AccountKeyManagerFor, k as AccountSelectionError, b8 as HubPermissionSessionInput } from './index-BvzynBUQ.js';
2
2
  export { b9 as DEFAULT_HUB_API_URL, ba as HubEnvironmentSlug, aK as formatProviderDisplayName } from './index-BvzynBUQ.js';
3
- import { R as RunResultPayload, P as ProbeResultPayload, h as TunnelType, c as ProcessCorsairRequest, m as WebhookTenantLink } from './index-VWD0zUpN.js';
4
- export { n as BROWSER_DELIVERY_TTL_MS, o as BrowserDeliveryMode, B as BrowserDeliveryPayload, S as SIGNED_TUNNEL_REPLAY_WINDOW_MS, g as TunnelEnvelope } from './index-VWD0zUpN.js';
5
- export { b as buildBrowserDeliveryRedirectUrl, s as signBrowserDeliveryToken, v as verifyBrowserDeliveryToken } from './browser-delivery-7xPxS7xK.js';
3
+ import { R as RunResultPayload, P as ProbeResultPayload, h as TunnelType, c as ProcessCorsairRequest, m as WebhookTenantLink } from './index-CD6RERuj.js';
4
+ export { n as BROWSER_DELIVERY_TTL_MS, o as BrowserDeliveryMode, B as BrowserDeliveryPayload, S as SIGNED_TUNNEL_REPLAY_WINDOW_MS, g as TunnelEnvelope } from './index-CD6RERuj.js';
5
+ export { b as buildBrowserDeliveryRedirectUrl, s as signBrowserDeliveryToken, v as verifyBrowserDeliveryToken } from './browser-delivery-a6T68C6o.js';
6
6
  import 'zod';
7
7
  import './db.js';
8
8
  import 'kysely';
@@ -451,6 +451,10 @@ type ProcessManagedOAuthDeliveryOptions = {
451
451
  id: string;
452
452
  label?: string;
453
453
  };
454
+ accounts?: {
455
+ id: string;
456
+ label?: string;
457
+ }[];
454
458
  };
455
459
  type ProcessManagedOAuthDeliveryResult = {
456
460
  plugin: string;
package/dist/hub.js CHANGED
@@ -1 +1 @@
1
- import{$a as ca,A as z,Aa as T,B as A,Ba as U,C as B,Ca as V,Da as W,L as C,Qa as X,Ra as Y,Sa as Z,Xa as _,Ya as $,Za as aa,_a as ba,aa as D,ab as da,b as a,cb as ea,d as b,da as E,db as fa,e as c,ea as F,eb as ga,f as d,fb as ha,g as e,gb as ia,h as f,hb as ja,i as g,ib as ka,j as i,jb as la,k as j,kb as ma,l as k,lb as na,m as l,mb as oa,n as m,na as G,nb as pa,o as n,oa as H,ob as qa,p as o,pa as I,pb as ra,q as p,qa as J,qb as sa,r as q,ra as K,rb as ta,s as r,sa as L,sb as ua,t as s,ta as M,tb as va,u as t,ua as N,ub as wa,v as u,va as O,vb as xa,w as v,wa as P,wb as ya,x as w,xa as Q,xb as za,y as x,ya as R,z as y,za as S}from"./chunk-KSYLMKIZ.js";import{a as h,b as Aa,c as Ba,d as Ca,e as Da,f as Ea}from"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-KOJBIKQZ.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{m as BROWSER_DELIVERY_TTL_MS,Ba as CORSAIR_TUNNEL_PATH,Aa as CORSAIR_TUNNEL_ZONE,u as DEFAULT_HUB_API_URL,Ca as FRPC_VERSION,w as HubCredentialsMissingError,v as HubNotConfiguredError,V as ManagedOAuthDeliveryError,n as SIGNED_TUNNEL_REPLAY_WINDOW_MS,fa as attachManagedRefreshAuth,p as buildBrowserDeliveryRedirectUrl,s as buildClientBridgeBrowserDeliveryUrl,la as createConnectSessionJti,qa as createConnectTokenJti,D as createHubConnectSession,E as createHubPermissionSession,ka as createHubRouteHandlers,ia as createManagedPricingCredentialCache,wa as createPermissionSessionJti,o as createSignedTokenJti,pa as decodeConnectSessionTokenFromPath,va as decodeConnectTokenFromPath,za as decodePermissionTokenFromPath,Q as deliverConnectCreateLink,U as deliverSignedEnvelope,S as describeDeliveryNetworkError,ua as encodeConnectTokenForPath,O as extractConnectLinkFromDeliveryAck,H as extractProbeFromDeliveryAck,G as extractRunFromDeliveryAck,N as extractSyncFromDeliveryAck,F as formatHubApprovalMessage,a as formatProviderDisplayName,T as formatServerDeliveryError,Da as frpcPlatformKey,ma as getConnectSessionExpiryMs,X as getConnectStatusForTenant,ra as getConnectTokenExpiryMs,z as getHubConfig,ea as getManagedAccessToken,ha as getManagedPricingApiKey,_ as handleHubDeliveryGet,$ as handleHubDeliveryPost,ba as handleHubDeliveryRequest,aa as hubDeliveryToResponse,B as inferHubEnvironmentSlug,i as isLoopbackUrl,M as isServerDeliveryAckSuccessful,Y as listHubProjectConnections,x as normalizeHubConfig,P as parseConnectLinkFromDeliveryBody,b as parseConnectSessionResponse,f as parseConnectStatusResponse,g as parseHubApiErrorBody,Z as parseManagedPricingCredentialsResponse,e as parseOAuthRefreshResponse,d as parsePermissionSessionResponse,c as parseProjectConnectionsResponse,L as parseServerDeliveryAckBody,R as parseSyncFromDeliveryBody,t as prepareClientBridgeDeliveryTransport,W as processManagedOAuthDelivery,C as registerHubWebhookTenantLink,ga as requireHubForManagedPricing,j as resolveDeliveryTransport,Ea as resolveFrpcBinary,y as resolveHubConfigInput,h as resolveHubDeliveryUrl,A as resolveHubOAuthCallbackUrl,ja as resolveManagedPricingApiKey,ca as respondToHubDelivery,da as respondToHubDeliveryFromRequest,q as signBrowserDeliveryToken,na as signConnectSessionToken,sa as signConnectToken,I as signDeliveryEnvelope,xa as signPermissionToken,k as usesBrowserDelivery,l as validateProductionDeliveryUrl,r as verifyBrowserDeliveryToken,oa as verifyConnectSessionToken,ta as verifyConnectToken,J as verifyDeliveryEnvelope,ya as verifyPermissionToken,K as verifySignedTunnelDelivery};
1
+ import{$a as ca,A as z,Aa as T,B as A,Ba as U,C as B,Ca as V,Da as W,L as C,Qa as X,Ra as Y,Sa as Z,Xa as _,Ya as $,Za as aa,_a as ba,aa as D,ab as da,b as a,cb as ea,d as b,da as E,db as fa,e as c,ea as F,eb as ga,f as d,fb as ha,g as e,gb as ia,h as f,hb as ja,i as g,ib as ka,j as i,jb as la,k as j,kb as ma,l as k,lb as na,m as l,mb as oa,n as m,na as G,nb as pa,o as n,oa as H,ob as qa,p as o,pa as I,pb as ra,q as p,qa as J,qb as sa,r as q,ra as K,rb as ta,s as r,sa as L,sb as ua,t as s,ta as M,tb as va,u as t,ua as N,ub as wa,v as u,va as O,vb as xa,w as v,wa as P,wb as ya,x as w,xa as Q,xb as za,y as x,ya as R,z as y,za as S}from"./chunk-53L3BPC5.js";import{a as h,b as Aa,c as Ba,d as Ca,e as Da,f as Ea}from"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-QUO2PWXT.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{m as BROWSER_DELIVERY_TTL_MS,Ba as CORSAIR_TUNNEL_PATH,Aa as CORSAIR_TUNNEL_ZONE,u as DEFAULT_HUB_API_URL,Ca as FRPC_VERSION,w as HubCredentialsMissingError,v as HubNotConfiguredError,V as ManagedOAuthDeliveryError,n as SIGNED_TUNNEL_REPLAY_WINDOW_MS,fa as attachManagedRefreshAuth,p as buildBrowserDeliveryRedirectUrl,s as buildClientBridgeBrowserDeliveryUrl,la as createConnectSessionJti,qa as createConnectTokenJti,D as createHubConnectSession,E as createHubPermissionSession,ka as createHubRouteHandlers,ia as createManagedPricingCredentialCache,wa as createPermissionSessionJti,o as createSignedTokenJti,pa as decodeConnectSessionTokenFromPath,va as decodeConnectTokenFromPath,za as decodePermissionTokenFromPath,Q as deliverConnectCreateLink,U as deliverSignedEnvelope,S as describeDeliveryNetworkError,ua as encodeConnectTokenForPath,O as extractConnectLinkFromDeliveryAck,H as extractProbeFromDeliveryAck,G as extractRunFromDeliveryAck,N as extractSyncFromDeliveryAck,F as formatHubApprovalMessage,a as formatProviderDisplayName,T as formatServerDeliveryError,Da as frpcPlatformKey,ma as getConnectSessionExpiryMs,X as getConnectStatusForTenant,ra as getConnectTokenExpiryMs,z as getHubConfig,ea as getManagedAccessToken,ha as getManagedPricingApiKey,_ as handleHubDeliveryGet,$ as handleHubDeliveryPost,ba as handleHubDeliveryRequest,aa as hubDeliveryToResponse,B as inferHubEnvironmentSlug,i as isLoopbackUrl,M as isServerDeliveryAckSuccessful,Y as listHubProjectConnections,x as normalizeHubConfig,P as parseConnectLinkFromDeliveryBody,b as parseConnectSessionResponse,f as parseConnectStatusResponse,g as parseHubApiErrorBody,Z as parseManagedPricingCredentialsResponse,e as parseOAuthRefreshResponse,d as parsePermissionSessionResponse,c as parseProjectConnectionsResponse,L as parseServerDeliveryAckBody,R as parseSyncFromDeliveryBody,t as prepareClientBridgeDeliveryTransport,W as processManagedOAuthDelivery,C as registerHubWebhookTenantLink,ga as requireHubForManagedPricing,j as resolveDeliveryTransport,Ea as resolveFrpcBinary,y as resolveHubConfigInput,h as resolveHubDeliveryUrl,A as resolveHubOAuthCallbackUrl,ja as resolveManagedPricingApiKey,ca as respondToHubDelivery,da as respondToHubDeliveryFromRequest,q as signBrowserDeliveryToken,na as signConnectSessionToken,sa as signConnectToken,I as signDeliveryEnvelope,xa as signPermissionToken,k as usesBrowserDelivery,l as validateProductionDeliveryUrl,r as verifyBrowserDeliveryToken,oa as verifyConnectSessionToken,ta as verifyConnectToken,J as verifyDeliveryEnvelope,ya as verifyPermissionToken,K as verifySignedTunnelDelivery};
@@ -145,6 +145,11 @@ type BrowserDeliveryPayload = {
145
145
  id: string;
146
146
  label?: string;
147
147
  };
148
+ /** Every account the hub holds for the plugin and tenant, oldest first (`deliveryMode: oauth.tokens`). */
149
+ accounts?: {
150
+ id: string;
151
+ label?: string;
152
+ }[];
148
153
  /** SDK permission token to approve or deny (`deliveryMode: permission.*`). */
149
154
  permissionToken?: string;
150
155
  /** Hub page origin for iframe postMessage replies (legacy client bridge). */
@@ -260,6 +265,10 @@ type OAuthTokensTunnelPayload = {
260
265
  id: string;
261
266
  label?: string;
262
267
  };
268
+ accounts?: {
269
+ id: string;
270
+ label?: string;
271
+ }[];
263
272
  };
264
273
  type ProcessCorsairRequest = {
265
274
  headers: Headers | Record<string, string | string[] | undefined>;
package/dist/index.d.ts CHANGED
@@ -5,7 +5,7 @@ import { aD as FormFieldSchema, Z as ListOperationsOptions } from './tenant-matc
5
5
  export { A as AuthMissingError, a as AuthType, C as CloudAccess, b as CloudApiError, c as CloudCatalogIntegration, d as CloudConnectSession, e as CloudConnection, f as CloudDeleted, g as CloudDelivery, h as CloudEmbeddedList, i as CloudInstance, j as CloudInstanceApply, k as CloudInstancePlane, l as CloudInstanceRemoval, m as CloudIntegration, n as CloudIntegrationOperations, o as CloudKey, p as CloudKeyRotation, q as CloudLink, r as CloudLinkLine, s as CloudList, t as CloudMcpToken, u as CloudOauthApp, v as CloudOperation, w as CloudProject, x as CloudProjectPlane, y as CloudSigningSecret, z as CloudSigningSecretRotation, B as CloudTenant, D as CloudWebhook, E as CorsairCloudConfig, F as CorsairCloudInstance, G as CorsairCloudInstanceHandle, H as CorsairCloudManage, I as CorsairCloudRegistry, J as CorsairKekMissingError, K as CreateConnectSessionInput, L as CreateInstanceInput, N as CreateWebhookInput, O as CredentialSource, X as LinkLine, Y as LinkPolicy, _ as ListQuery, $ as ManagementApiError, a0 as MintLinkInput, a1 as MintTokenInput, a2 as Permission, a3 as PermissionDecision, aE as PermissionMode, a4 as PermissionRequiredError, a6 as PluginWebhookMatchers, a7 as ProjectStatus, a8 as PutIntegrationInput, a9 as PutOauthAppInput, aa as ReconnectRequiredError, ab as RequestOptions, ac as ResolveConnectLinkResult, ad as RotateWebhookSecretInput, ae as SetAccessInput, af as UpdateInstanceInput, ag as UpdateLinkInput, ah as UpdateTenantInput, ai as V1Transport, aj as WebhookPluginTenantMatch, ak as asRecord, al as buildInstancePlane, am as buildProjectPlane, an as collectPluginWebhookMatchers, ao as corsairCloud, ap as decodePubSubData, ar as firstString, as as formatDocSchemaShape, at as getHeader, aw as mapV1Error, ax as matchWebhookPlugin, ay as matchWebhookPluginAndTenant, az as readBodyRecord, aB as resolveConnectLink, aC as toExternalId } from './tenant-match-utils-CRw_jLKW.js';
6
6
  export { c as createCorsair } from './index-COCwkKIX.js';
7
7
  export { SetupCorsairOptions, setupCorsair } from './setup.js';
8
- export { O as OAuthCallbackTunnelPayload, b as ProcessCorsairOptions, c as ProcessCorsairRequest, l as ResolveAccountFromWebhookLinkInput, T as TunnelAck, g as TunnelEnvelope, h as TunnelType, m as WebhookTenantLink, W as WebhookTunnelPayload, p as processCorsair, r as resolveAccountFromWebhookLink, j as resolveTenantFromWebhookLink, k as resolveTenantIdFromWebhookLink, s as setWebhookTenantLink } from './index-VWD0zUpN.js';
8
+ export { O as OAuthCallbackTunnelPayload, b as ProcessCorsairOptions, c as ProcessCorsairRequest, l as ResolveAccountFromWebhookLinkInput, T as TunnelAck, g as TunnelEnvelope, h as TunnelType, m as WebhookTenantLink, W as WebhookTunnelPayload, p as processCorsair, r as resolveAccountFromWebhookLink, j as resolveTenantFromWebhookLink, k as resolveTenantIdFromWebhookLink, s as setWebhookTenantLink } from './index-CD6RERuj.js';
9
9
  import './db.js';
10
10
  import 'kysely';
11
11
  import 'pg';
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{Db as J,Ea as q,Eb as Y,Fb as K,Gb as G,H as O,Hb as X,Ib as Q,Jb as V,Kb as nn,Lb as en,M as A,Ma as N,Mb as tn,N as L,Nb as rn,O as E,Ob as on,P as v,Pb as sn,Qb as an,Rb as un,Ta as j,Ua as B,Va as D,Wa as U,Xb as w,Yb as P,Zb as T,_b as x,ba as F,bb as Z,c as S,ca as M,dc as cn,ec as pn,fa as $,fc as ln,ga as _,gc as dn,hc as mn,ia as H,ic as gn,jc as Cn,ma as W,nc as fn,oc as yn,pc as I,qc as kn,yb as z}from"./chunk-KSYLMKIZ.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-KOJBIKQZ.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";import{z as p}from"zod";function C(e){let t=e[I];if(!t)throw new Error("listOperations / getSchema: invalid corsair instance. Pass the value returned by createCorsair() or corsair.withTenant().");return t.plugins}function y(e,t){let o=P(C(e),t);return typeof o=="string"?o:Array.isArray(o)?o.join(`
1
+ import{Db as J,Ea as q,Eb as Y,Fb as K,Gb as G,H as O,Hb as X,Ib as Q,Jb as V,Kb as nn,Lb as en,M as A,Ma as N,Mb as tn,N as L,Nb as rn,O as E,Ob as on,P as v,Pb as sn,Qb as an,Rb as un,Ta as j,Ua as B,Va as D,Wa as U,Xb as w,Yb as P,Zb as T,_b as x,ba as F,bb as Z,c as S,ca as M,dc as cn,ec as pn,fa as $,fc as ln,ga as _,gc as dn,hc as mn,ia as H,ic as gn,jc as Cn,ma as W,nc as fn,oc as yn,pc as I,qc as kn,yb as z}from"./chunk-53L3BPC5.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-QUO2PWXT.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";import{z as p}from"zod";function C(e){let t=e[I];if(!t)throw new Error("listOperations / getSchema: invalid corsair instance. Pass the value returned by createCorsair() or corsair.withTenant().");return t.plugins}function y(e,t){let o=P(C(e),t);return typeof o=="string"?o:Array.isArray(o)?o.join(`
2
2
  `):Object.values(o).flat().join(`
3
3
  `)}function hn(e,t){return T(C(e),t)}function k(e,t){return w(C(e),t)}function h(e,t){let o=C(e),n=t.toLowerCase(),i=n.indexOf(".");if(i===-1)return null;let u=n.slice(0,i),r=n.slice(i+1),s=o.find(c=>c.id===u);if(!s?.endpointSchemas)return null;let a=r;a.startsWith("api.")&&(a=a.slice(4));for(let[c,l]of Object.entries(s.endpointSchemas))if(c.toLowerCase()===a)return l.input??null;return null}function f(e){let t=wn(e);return e.description&&(t=t.describe(e.description)),e.optional&&(t=t.optional()),t}function wn(e){switch(e.kind){case"string":return e.enum&&e.enum.length>0?p.enum(e.enum):p.string();case"number":return p.number();case"boolean":return p.boolean();case"literal":return p.literal(e.value);case"object":{let t={};for(let[o,n]of Object.entries(e.fields))t[o]=f(n);return p.object(t)}case"array":return p.array(f(e.items));case"unknown":return p.unknown()}}function Pn(e,t){let o=t?.tenantId?In(e,t.tenantId):e;return(t?.operations??Tn(y(o,{plugin:t?.plugin,type:"api"}))).map(i=>{let u=k(o,i),s=h(o,i)??(u?.input?f(u.input):p.object({}));return{name:xn(i),operation:i,description:u?.description??i,schema:s,execute:a=>Rn(o,i,a??{})}})}function Tn(e){return e.split(`
4
4
  `).map(t=>t.trim()).filter(Boolean)}function xn(e){return e.replace(/[^a-zA-Z0-9_-]/g,"_")}function In(e,t){let o=e.withTenant;return typeof o=="function"?o.call(e,t):e}async function Rn(e,t,o){let n=t.split("."),i=n.pop();if(!i)throw new Error(`Invalid operation path: ${t}`);let u=e;for(let s of n)if(u=u?.[s],u==null)throw new Error(`Unknown operation path: ${t}`);let r=u[i];if(typeof r!="function")throw new Error(`Operation is not callable: ${t}`);return r.call(u,o)}var d=class extends Error{status;code;extra;constructor(t,o,n,i={}){super(n),this.name="CorsairClientError",this.status=t,this.code=o,this.extra=i}};function bn(e){return e.endsWith("/")?e.slice(0,-1):e}async function R(e){let t={};try{t=await e.json()}catch{}let o=typeof t.error=="string"?t.error:"request_failed",n=typeof t.message=="string"?t.message:`Request failed (${e.status})`,{error:i,message:u,...r}=t;return new d(e.status,o,n,r)}function Sn(e){let t=bn(e.baseURL),o=e.fetch??((...r)=>globalThis.fetch(...r));async function n(r,s){let a=s&&Object.keys(s).length?`?${new URLSearchParams(s).toString()}`:"",c=await o(`${t}${r}${a}`,{method:"GET"});if(!c.ok)throw await R(c);return await c.json()}async function i(r,s){let a=await o(`${t}${r}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(s)});if(!a.ok)throw await R(a);return await a.json()}let u=encodeURIComponent;return{ok:()=>n("/ok"),tenants:{list:()=>n("/tenants"),create:r=>i("/tenants",r),get:r=>n(`/tenants/${u(r)}`)},plugins:{list:()=>n("/plugins"),get:r=>n(`/plugins/${u(r)}`)},connectionStatus:{get:r=>{let s={};return r?.tenantId&&(s.tenantId=r.tenantId),n("/connection-status",s)}},permissions:{get:r=>"id"in r?n(`/permissions/${u(r.id)}`):i("/permissions/lookup-by-token",{token:r.token})},connect:{createLink:r=>i("/connect/links",r),resolve:r=>n("/connect/resolve",{state:r}),oauthCallback:r=>i("/connect/oauth/callback",r)},connectRequest:{get:r=>{let s={};return r?.tenantId&&(s.tenantId=r.tenantId),n("/connect/request",s)},clear:r=>i("/connect/request/clear",r??{})},call(r,s,a,c){return i(`/${u(a)}/${u(r)}/call/${u(s)}`,{args:c}).then(l=>l.data)}}}var On=Symbol.for("corsair:internal");function An(e,t){let o=e;for(let n of t){if(!o||typeof o!="object")return null;o=o[n]}return typeof o=="function"?o:null}function b(e){return e[On]?.database}async function Ln(e,t){let o=new Date().toISOString(),n=await e.permissions.find_by_token(t);if(!n)return console.error("executePermission: no permission found for token."),{error:"executePermission: no permission found for token."};if(n.status!=="approved")return console.error(`executePermission: permission '${n.id}' is '${n.status}', expected 'approved'.`),{endpoint:n.endpoint,plugin:n.plugin,result:null,error:`executePermission: permission '${n.id}' is '${n.status}', expected 'approved'.`};if(n.expires_at<o){let a=b(e);return a&&await a.db.updateTable("corsair_permissions").set({status:"expired",updated_at:new Date}).where("id","=",n.id).execute(),console.error(`executePermission: permission '${n.id}' has expired.`),{error:`executePermission: permission '${n.id}' has expired.`,endpoint:n.endpoint,plugin:n.plugin,result:null}}let i=n.tenant_id??"default",r=(e.withTenant?e.withTenant(i):e)[n.plugin];if(!r?.api)return console.error(`executePermission: plugin '${n.plugin}' not found or has no API on this corsair instance.`),{error:`executePermission: plugin '${n.plugin}' not found or has no API on this corsair instance.`,plugin:n.plugin,endpoint:n.endpoint,result:null};let s=An(r.api,n.endpoint.split("."));if(!s)return console.error(`executePermission: endpoint '${n.endpoint}' not found in plugin '${n.plugin}'.`),{endpoint:n.endpoint,plugin:n.plugin,result:null,error:`executePermission: endpoint '${n.endpoint}' not found in plugin '${n.plugin}'.`};await e.permissions.set_executing(n.id);try{let a=typeof n.args=="string"?JSON.parse(n.args):n.args,c=await s(a);return await e.permissions.set_completed(n.id),{plugin:n.plugin,endpoint:n.endpoint,result:c}}catch(a){let c=a instanceof Error?a.message:String(a),l=b(e);return l&&await l.db.updateTable("corsair_permissions").set({status:"failed",error:c,updated_at:new Date}).where("id","=",n.id).execute(),{plugin:n.plugin,endpoint:n.endpoint,result:null,error:c}}}export{Z as AuthMissingError,J as CloudApiError,d as CorsairClientError,z as CorsairKekMissingError,B as DEFAULT_BODY_STALL_TIMEOUT_MS,j as DEFAULT_MAX_BODY_BYTES,W as ManagementApiError,M as PermissionRequiredError,$ as ReadonlyForbiddenError,S as ReconnectRequiredError,gn as asRecord,Pn as buildCorsairTools,ln as collectPluginWebhookMatchers,Y as corsairCloud,kn as createCorsair,Sn as createCorsairClient,yn as decodePubSubData,Ln as executePermission,fn as firstString,f as formFieldToZod,x as formatDocSchemaShape,dn as getHeader,h as getInputSchema,hn as getSchema,k as getStructuredSchema,y as listOperations,K as managementHandler,cn as matchWebhookPlugin,pn as matchWebhookPluginAndTenant,N as processCorsair,q as processWebhook,Cn as readBodyRecord,X as registerCorsairRawBodyParser,L as resolveAccountFromWebhookLink,U as resolveBodyStallTimeoutMs,F as resolveConnectLink,D as resolveMaxBodyBytes,v as resolveTenantFromWebhookLink,E as resolveTenantIdFromWebhookLink,H as runReadonly,_ as runWithMode,A as setWebhookTenantLink,O as setupCorsair,on as toAstroHandler,G as toExpressHandler,mn as toExternalId,Q as toFastifyHandler,V as toHonoHandler,nn as toNextJsHandler,en as toNodeHandler,an as toNuxtHandler,rn as toRemixHandler,tn as toSvelteKitHandler,sn as toTanStackHandler,un as toWebHandler};
@@ -1 +1 @@
1
- import{Na as a,Oa as b,Pa as c}from"./chunk-KSYLMKIZ.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-KOJBIKQZ.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{a as deriveAck,b as pollOnce,c as startConnectLoop};
1
+ import{Na as a,Oa as b,Pa as c}from"./chunk-53L3BPC5.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-QUO2PWXT.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{a as deriveAck,b as pollOnce,c as startConnectLoop};
package/dist/oauth.js CHANGED
@@ -1 +1 @@
1
- import{J as a,K as b,Q as c,R as d,S as e,T as f,U as g,V as h}from"./chunk-KSYLMKIZ.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-KOJBIKQZ.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{d as OAuthCallbackError,c as buildOAuthAuthorizeUrl,b as decodeOAuthState,a as encodeOAuthState,e as generateOAuthUrl,f as processOAuthCallback,g as renewSubscriptions,h as startSubscriptionRenewal};
1
+ import{J as a,K as b,Q as c,R as d,S as e,T as f,U as g,V as h}from"./chunk-53L3BPC5.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-QUO2PWXT.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{d as OAuthCallbackError,c as buildOAuthAuthorizeUrl,b as decodeOAuthState,a as encodeOAuthState,e as generateOAuthUrl,f as processOAuthCallback,g as renewSubscriptions,h as startSubscriptionRenewal};
package/dist/orm.js CHANGED
@@ -1 +1 @@
1
- import"./chunk-B6OSDOR5.js";import{O as o,P as e,Q as n,R as s}from"./chunk-KOJBIKQZ.js";import{d as r,e as t,f as i,g as a}from"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{t as CorsairAccountsSchema,i as CorsairEntitiesSchema,a as CorsairEventsSchema,r as CorsairIntegrationsSchema,o as createCorsairOrm,e as createPluginOrm,s as createPluginOrmFactory,n as createTenantScopedOrm};
1
+ import"./chunk-B6OSDOR5.js";import{O as o,P as e,Q as n,R as s}from"./chunk-QUO2PWXT.js";import{d as r,e as t,f as i,g as a}from"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{t as CorsairAccountsSchema,i as CorsairEntitiesSchema,a as CorsairEventsSchema,r as CorsairIntegrationsSchema,o as createCorsairOrm,e as createPluginOrm,s as createPluginOrmFactory,n as createTenantScopedOrm};
@@ -1 +1 @@
1
- import{H as a,I as b}from"./chunk-KSYLMKIZ.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-KOJBIKQZ.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{b as applySetupCredentials,a as setupCorsair};
1
+ import{H as a,I as b}from"./chunk-53L3BPC5.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-QUO2PWXT.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{b as applySetupCredentials,a as setupCorsair};
@@ -1 +1 @@
1
- import{W as a,X as b,Y as c,Z as d}from"./chunk-KSYLMKIZ.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-KOJBIKQZ.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{b as buildConnectPluginManifest,a as buildConnectPluginManifestFromContext,d as ensureConnectAccountRows,c as ensureConnectAccountRowsFromContext};
1
+ import{W as a,X as b,Y as c,Z as d}from"./chunk-53L3BPC5.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-QUO2PWXT.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{b as buildConnectPluginManifest,a as buildConnectPluginManifestFromContext,d as ensureConnectAccountRows,c as ensureConnectAccountRowsFromContext};
package/dist/setup.js CHANGED
@@ -1 +1 @@
1
- import{H as a,I as b}from"./chunk-KSYLMKIZ.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-KOJBIKQZ.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{b as applySetupCredentials,a as setupCorsair};
1
+ import{H as a,I as b}from"./chunk-53L3BPC5.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-QUO2PWXT.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{b as applySetupCredentials,a as setupCorsair};
package/dist/tunnel.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { B as BrowserDeliveryPayload, R as RunResultPayload, P as ProbeResultPayload } from './index-VWD0zUpN.js';
2
- export { O as OAuthCallbackTunnelPayload, a as OAuthTokensTunnelPayload, b as ProcessCorsairOptions, c as ProcessCorsairRequest, d as RunStepResult, e as RunTriggerType, f as RunTunnelPayload, T as TunnelAck, g as TunnelEnvelope, h as TunnelType, W as WebhookTunnelPayload, i as applyPermissionDecision, p as processCorsair, r as resolveAccountFromWebhookLink, j as resolveTenantFromWebhookLink, k as resolveTenantIdFromWebhookLink, s as setWebhookTenantLink } from './index-VWD0zUpN.js';
3
- export { v as verifyBrowserDeliveryToken } from './browser-delivery-7xPxS7xK.js';
1
+ import { B as BrowserDeliveryPayload, R as RunResultPayload, P as ProbeResultPayload } from './index-CD6RERuj.js';
2
+ export { O as OAuthCallbackTunnelPayload, a as OAuthTokensTunnelPayload, b as ProcessCorsairOptions, c as ProcessCorsairRequest, d as RunStepResult, e as RunTriggerType, f as RunTunnelPayload, T as TunnelAck, g as TunnelEnvelope, h as TunnelType, W as WebhookTunnelPayload, i as applyPermissionDecision, p as processCorsair, r as resolveAccountFromWebhookLink, j as resolveTenantFromWebhookLink, k as resolveTenantIdFromWebhookLink, s as setWebhookTenantLink } from './index-CD6RERuj.js';
3
+ export { v as verifyBrowserDeliveryToken } from './browser-delivery-a6T68C6o.js';
4
4
  import './index-BvzynBUQ.js';
5
5
  import 'zod';
6
6
  import './db.js';
package/dist/tunnel.js CHANGED
@@ -1 +1 @@
1
- import{Fa as f,Ga as g,Ha as h,Ia as i,Ja as j,Ka as k,La as l,M as b,Ma as m,N as c,O as d,P as e,s as a}from"./chunk-KSYLMKIZ.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-KOJBIKQZ.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{l as applyPermissionDecision,f as executeWorkflowRun,h as isAuthCredentialsBrowserDelivery,k as isByoOAuthBrowserDelivery,j as isManagedBrowserDelivery,i as isPermissionBrowserDelivery,m as processCorsair,c as resolveAccountFromWebhookLink,e as resolveTenantFromWebhookLink,d as resolveTenantIdFromWebhookLink,g as runReadonlyProbe,b as setWebhookTenantLink,a as verifyBrowserDeliveryToken};
1
+ import{Fa as f,Ga as g,Ha as h,Ia as i,Ja as j,Ka as k,La as l,M as b,Ma as m,N as c,O as d,P as e,s as a}from"./chunk-53L3BPC5.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-QUO2PWXT.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{l as applyPermissionDecision,f as executeWorkflowRun,h as isAuthCredentialsBrowserDelivery,k as isByoOAuthBrowserDelivery,j as isManagedBrowserDelivery,i as isPermissionBrowserDelivery,m as processCorsair,c as resolveAccountFromWebhookLink,e as resolveTenantFromWebhookLink,d as resolveTenantIdFromWebhookLink,g as runReadonlyProbe,b as setWebhookTenantLink,a as verifyBrowserDeliveryToken};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "corsair",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
4
4
  "description": "Open-source integration layer for AI agents and apps. Managed OAuth, webhooks, and one API for 350+ integrations, with credentials that stay in your own database.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -88,12 +88,12 @@
88
88
  "zod": "^4.1.13"
89
89
  },
90
90
  "optionalDependencies": {
91
+ "@corsair-dev/frpc-linux-x64": "0.1.117",
91
92
  "@corsair-dev/frpc-linux-arm64": "0.1.117",
92
- "@corsair-dev/frpc-darwin-arm64": "0.1.117",
93
93
  "@corsair-dev/frpc-darwin-x64": "0.1.117",
94
94
  "@corsair-dev/frpc-win32-arm64": "0.1.117",
95
95
  "@corsair-dev/frpc-win32-x64": "0.1.117",
96
- "@corsair-dev/frpc-linux-x64": "0.1.117"
96
+ "@corsair-dev/frpc-darwin-arm64": "0.1.117"
97
97
  },
98
98
  "devDependencies": {
99
99
  "@testing-library/react": "^16.3.2",
@@ -1 +0,0 @@
1
- import{d as ae,e as se,f as ce,g as ue}from"./chunk-XPXWKPFZ.js";var Ze=Symbol.for("corsair:internal"),K=class extends Error{constructor(t="Invalid corsair instance"){super(t),this.name="InvalidCorsairInstanceError"}};function z(e){return typeof e=="object"&&e!==null}function de(e){if(!z(e)||!Array.isArray(e.plugins)||typeof e.kek!="string"||typeof e.multiTenancy!="boolean")return!1;if(e.database===void 0)return!0;if(!z(e.database))return!1;let t=e.database.db;return typeof t=="object"&&t!==null&&typeof t.selectFrom=="function"}function le(e){if(!e||typeof e!="object")return;let n=Object.getOwnPropertyDescriptor(e,Ze)?.value;return de(n)?n:void 0}function Je(e,t){let n=le(e);if(!n)throw t?.()??new K;return n}function ye(e,t){return e.plugins.find(n=>n.id===t)}function Qe(e,t,n){let r=ye(e,t);if(!r)throw n(`Plugin '${t}' not found`);return r}function ze(e){return"withTenant"in e&&typeof e.withTenant=="function"}function He(e,t){if(!e||typeof e!="object")return;let n=e[t];return typeof n=="function"?(...r)=>Reflect.apply(n,e,r):void 0}var H={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"]},managed_pricing:{integration:[],account:[]}};function fe(e){return e==="oauth_2"||e==="api_key"||e==="bot_token"||e==="managed"||e==="managed_pricing"}function Ge(e){let t=e.options?.authType;return fe(t)?t:void 0}function Ot(e){return e==="managed_pricing"}function qe(e,t){let n=e.authConfig,r=H[t].account,i=n?.[t]?.account??[];return[...r,...i]}function vt(e,t){let n=e.authConfig,r=H[t].integration,i=n?.[t]?.integration??[];return[...r,...i]}import{createCipheriv as ge,createDecipheriv as pe,randomBytes as O,scrypt as Ye}from"crypto";import{promisify as Xe}from"util";var me=Xe(Ye),v="aes-256-gcm",we=12,$=16,Ve=16,G=32;function q(){return O(G).toString("base64")}async function Y(e,t){let n=O(Ve),r=await me(t,n,G),i=O(we),o=ge(v,r,i,{authTagLength:$}),a=Buffer.concat([o.update(e,"utf8"),o.final()]),d=o.getAuthTag();return[n.toString("base64"),i.toString("base64"),d.toString("base64"),a.toString("base64")].join(":")}async function F(e,t){let[n,r,i,o]=e.split(":");if(!n||!r||!i||!o)throw new Error("Invalid encrypted DEK format");let a=Buffer.from(n,"base64"),d=Buffer.from(r,"base64"),p=Buffer.from(i,"base64"),w=Buffer.from(o,"base64"),l=await me(t,a,G),s=pe(v,l,d,{authTagLength:$});return s.setAuthTag(p),Buffer.concat([s.update(w),s.final()]).toString("utf8")}function X(e,t){let n=Buffer.from(t,"base64"),r=O(we),i=ge(v,n,r,{authTagLength:$}),o=Buffer.concat([i.update(e,"utf8"),i.final()]),a=i.getAuthTag();return[r.toString("base64"),a.toString("base64"),o.toString("base64")].join(":")}function V(e,t){let[n,r,i]=e.split(":");if(!n||!r||!i)throw new Error("Invalid encrypted data format");let o=Buffer.from(t,"base64"),a=Buffer.from(n,"base64"),d=Buffer.from(r,"base64"),p=Buffer.from(i,"base64"),w=pe(v,o,a,{authTagLength:$});return w.setAuthTag(d),Buffer.concat([w.update(p),w.final()]).toString("utf8")}function ee(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=X(i,t);return n}function j(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]=V(i,t);return n}function Lt(e,t,n){let r=j(e,t);return ee(r,n)}import{v7 as et}from"uuid";function P(){return et()}function M(e,t){return e.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",t.tenantId).where("integration_id","=",t.integrationId).orderBy("created_at","asc").orderBy("id","asc")}async function B(e,t){return M(e,t).executeTakeFirst()}async function tt(e){let t=!1;for(;;){let n=await e.database.db.selectFrom("corsair_integrations").selectAll().where("name","=",e.integrationName).executeTakeFirst();if(!n){if(!t&&e.ensureProvisioned){t=!0,await e.ensureProvisioned();continue}throw new Error(`Integration "${e.integrationName}" not found. Make sure to create the integration first.`)}let r={tenantId:e.tenantId,integrationId:n.id},i=e.account?await ot({db:e.database.db,kek:e.account.kek,...r,ref:e.account.ref}):await B(e.database.db,r);if(!i){if(!t&&e.ensureProvisioned){t=!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:n.id,accountId:i.id,integration:{id:n.id,config:n.config,dek:n.dek??null},account:{id:i.id,config:i.config,dek:i.dek??null}}}}async function rn(e){let{integrationId:t,accountId:n}=await tt(e);return{integrationId:t,accountId:n}}var S=class extends Error{code;accounts;constructor(t,n,r=[]){super(n),this.name="AccountSelectionError",this.code=t,this.accounts=r}};function Ce(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return e??{}}var te=e=>({id:e.id,config:e.config,dek:e.dek??null});async function L(e,t){let n=Ce(e.config);if(!e.dek||!n?.account_ref)return{};try{let r=j(n,await F(e.dek,t));return{ref:r.account_ref,label:r.account_label}}catch{return{}}}async function on(e,t,n){if(e.id===t)return!0;let{ref:r,label:i}=await L(e,n);return r===t||i?.toLowerCase()===t.toLowerCase()}async function an(e,t,n){let r=n?await e.selectFrom("corsair_accounts").select(["config","dek"]).where("id","=",t).executeTakeFirst():void 0;return{id:t,...r&&n?await L(r,n):{}}}function nt(e){let t=new Set(e),n=1;for(;t.has(`Account ${n}`);)n++;return`Account ${n}`}var ke=(e,t)=>Promise.all(e.map(async n=>({...te(n),...await L(n,t)})));async function Te(e){return ke(await M(e.db,e).execute(),e.kek)}var rt=e=>e.label??e.ref??e.id,W=({id:e,ref:t,label:n})=>({id:e,ref:t,label:n});async function sn(e){let t=await e.db.selectFrom("corsair_integrations").select("id").where("name","=",e.integrationName).executeTakeFirst();if(!t)return[];let n=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",e.tenantId).where("integration_id","=",t.id).execute();return n.length<2?n:(await Te({db:e.db,kek:e.kek,integrationId:t.id,tenantId:e.tenantId})).map(i=>({id:i.id,label:i.label??i.ref}))}async function cn(e){let t=await e.db.selectFrom("corsair_integrations").select("id").where("name","=",e.integrationName).executeTakeFirst();return t?(await Te({db:e.db,kek:e.kek,integrationId:t.id,tenantId:e.tenantId})).map(W):[]}async function it(e,t){return(await e.selectFrom("corsair_integrations").select("name").where("id","=",t).executeTakeFirst())?.name??t}async function ot(e){let t=await M(e.db,e).execute();if(t.length===0)return;if(!e.ref&&t.length===1)return te(t[0]);let n=e.ref?t.find(l=>l.id===e.ref):void 0;if(n)return te(n);let r=await ke(t,e.kek),i=e.ref?.toLowerCase(),o=e.ref?r.find(l=>l.ref===e.ref):void 0;if(o)return o;let a=e.ref?r.filter(l=>l.label?.toLowerCase()===i):[];if(a.length===1)return a[0];let d=await it(e.db,e.integrationId);if(a.length>1)throw new S("account_required",`Label "${e.ref}" matches ${a.length} accounts for "${d}" (tenant "${e.tenantId}"): ${a.map(l=>l.ref??l.id).join(", ")}. Name one by its id.`,a.map(W));let p=r.map(rt).join(", "),w=r.map(W);throw e.ref?new S("account_not_found",`No account "${e.ref}" for "${d}" (tenant "${e.tenantId}"). Accounts: ${p}.`,w):new S("account_required",`Plugin "${d}" has ${r.length} accounts for tenant "${e.tenantId}": ${p}. Name one with withTenant(tenantId, { accounts: { ${d}: "<account>" } }).`,w)}var at=5;async function un(e){let{database:t,kek:n,tenantId:r}=e;return t.db.transaction().execute(async i=>{let o=i.selectFrom("corsair_integrations").select(["id"]).where("name","=",e.integrationName);t.isPg===!0&&(o=o.forUpdate());let a=await o.executeTakeFirst();if(!a)throw new Error(`Integration '${e.integrationName}' not found. Run setupCorsair first.`);let d=await M(i,{tenantId:r,integrationId:a.id}).execute();if(!e.identity)return d[0]?{accountId:d[0].id,created:!1}:he(i,a.id,r,n);let p=await Promise.all(d.map(async u=>({row:u,...await L(u,n)}))),w=e.identity.label===void 0&&e.nameNew?{...e.identity,label:nt(p.map(u=>u.label))}:e.identity;if(e.rowId){let u=p.find(m=>m.row.id===e.rowId);if(!u)throw new S("account_not_found",`Account "${e.rowId}" is no longer connected for "${e.integrationName}" (tenant "${r}").`);return u.ref?{accountId:u.row.id,created:!1}:(await be(i,u.row,w,n),{accountId:u.row.id,created:!1})}let l=p.find(u=>u.ref===w.id),s=l??p.find(u=>!u.ref)??(e.allowMany?void 0:p[0]);if(s){if(!l||w.label&&s.label!==w.label){let u=!l&&s.ref!==void 0;await be(i,s.row,w,n,u)}return{accountId:s.row.id,created:!1}}if(d.length>=at)throw new S("account_limit",`Account limit reached: tenant "${r}" already has ${d.length} accounts for "${e.integrationName}".`,p.map(({row:u,ref:m,label:I})=>W({id:u.id,ref:m,label:I})));return he(i,a.id,r,n,w)})}async function Ae(e,t,n){let{account_label:r,...i}=t;return ee({...i,account_ref:n.id,...n.label?{account_label:n.label}:{}},e)}async function be(e,t,n,r,i=!1){let o=t.dek?await F(t.dek,r):q(),a=Ce(t.config),d=i?{}:t.dek?j(a,o):a;await e.updateTable("corsair_accounts").set({config:await Ae(o,d,n),dek:t.dek??await Y(o,r),updated_at:new Date}).where("id","=",t.id).execute()}async function he(e,t,n,r,i){let o=q(),a=new Date,d=P();return await e.insertInto("corsair_accounts").values({id:d,created_at:a,updated_at:a,tenant_id:n,integration_id:t,config:i?await Ae(o,{},i):{},dek:await Y(o,r)}).execute(),{accountId:d,created:!0}}import{SqliteAdapter as st,sql as Ke}from"kysely";import{z as T}from"zod";var ne="_corsair_enc";function Ie(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t[ne]=="string"&&Object.keys(t).length===1}function re(e,t){return{[ne]:X(JSON.stringify(e),t)}}function ie(e,t){let n=Ee(e);return Ie(n)?JSON.parse(V(n[ne],t)):n}async function fn(e,t,n){let r=await e.selectFrom("corsair_accounts").select("dek").where("id","=",t).executeTakeFirst();if(!r?.dek)throw new Error(`No DEK found for account "${t}". Initialize the account first.`);return F(r.dek,n)}async function gn(e,t,n,r){let i=await e.selectFrom("corsair_entities").select(["id","data"]).where("account_id","=",t).execute();for(let a of i){let d=xe(a.data,n,r);d&&await e.updateTable("corsair_entities").set({data:d,updated_at:new Date}).where("id","=",a.id).execute()}let o=await e.selectFrom("corsair_events").select(["id","payload"]).where("account_id","=",t).execute();for(let a of o){let d=xe(a.payload,n,r);d&&await e.updateTable("corsair_events").set({payload:d,updated_at:new Date}).where("id","=",a.id).execute()}}function xe(e,t,n){let r=Ee(e);if(Ie(r))return re(ie(r,t),n)}function Ee(e){if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}}import{sql as D}from"kysely";function U(e){return e.replace(/'/g,"''")}function _e(e){let t=U(e);return D`data->>'${D.raw(t)}'`}function De(e){let t=U(e);return D`(data->>'${D.raw(t)}')::numeric`}function Fe(e){let t=U(e);return D`(data->>'${D.raw(t)}')::boolean`}function Pe(e){let t=U(e);return D`(data->>'${D.raw(t)}')::timestamptz`}import{sql as Z}from"kysely";function Se(e){return e.replace(/'/g,"''").replace(/\\/g,"\\\\")}function Re(e){let t=Se(e);return Z`CAST(json_extract(data, '$.${Z.raw(t)}') AS REAL)`}function Be(e){let t=Se(e);return Z`json_extract(data, '$.${Z.raw(t)}')`}var ct={number:e=>De(e),booleanEquals:(e,t)=>Ke`${Fe(e)} = ${t}`,timestamp:e=>Pe(e)},ut={number:e=>Re(e),booleanEquals:(e,t)=>Ke`json_extract(data, ${`$.${e}`}) = ${t?1:0}`,timestamp:e=>Be(e)};function dt(e){return e.getExecutor().adapter instanceof st?ut:ct}function lt(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}function Oe(e){let t=e;for(;t;){if(t instanceof T.ZodOptional||t instanceof T.ZodNullable){t=t._def.innerType;continue}if(t instanceof T.ZodDefault){t=t._def.innerType;continue}break}return t}function Ne(e){if(typeof e=="string")return"string";if(typeof e=="number")return"number";if(typeof e=="boolean")return"boolean"}function oe(e){let[t]=e;return t&&e.every(n=>n===t)?t:void 0}function ve(e){let t=Oe(e);if(t instanceof T.ZodString)return"string";if(t instanceof T.ZodNumber)return"number";if(t instanceof T.ZodBoolean)return"boolean";if(t instanceof T.ZodDate)return"date";if(t instanceof T.ZodEnum)return oe(t.options.map(Ne));if(t instanceof T.ZodLiteral)return oe([...t.values].map(Ne));if(t instanceof T.ZodUnion)return oe(t.options.filter(n=>!(n instanceof T.ZodNull)).map(n=>ve(n)))}function yt(e){let t=Oe(e);if(!(t instanceof T.ZodObject))return{};let n=t.shape,r={};for(let[i,o]of Object.entries(n)){let a=ve(o);a&&(r[i]=a)}return r}function ft(e,t,n){if(typeof n=="string")return e.where(t,"=",n);if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;"equals"in r&&typeof r.equals=="string"&&(e=e.where(t,"=",r.equals)),"contains"in r&&typeof r.contains=="string"&&(e=e.where(t,"like",`%${r.contains}%`)),"startsWith"in r&&typeof r.startsWith=="string"&&(e=e.where(t,"like",`${r.startsWith}%`)),"endsWith"in r&&typeof r.endsWith=="string"&&(e=e.where(t,"like",`%${r.endsWith}`)),"in"in r&&Array.isArray(r.in)&&(e=e.where(t,"in",r.in))}return e}function gt(e,t,n){if(typeof n=="number")return e.where(t,"=",n);if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;typeof r.equals=="number"&&(e=e.where(t,"=",r.equals)),typeof r.gt=="number"&&(e=e.where(t,">",r.gt)),typeof r.gte=="number"&&(e=e.where(t,">=",r.gte)),typeof r.lt=="number"&&(e=e.where(t,"<",r.lt)),typeof r.lte=="number"&&(e=e.where(t,"<=",r.lte)),Array.isArray(r.in)&&(e=e.where(t,"in",r.in))}return e}function pt(e,t,n){if(typeof n=="boolean")return e.where(t(n));if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;typeof r.equals=="boolean"&&(e=e.where(t(r.equals)))}return e}function mt(e,t,n){if(n instanceof Date)return e.where(t,"=",n);if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;if(r.equals instanceof Date&&(e=e.where(t,"=",r.equals)),r.before instanceof Date&&(e=e.where(t,"<",r.before)),r.after instanceof Date&&(e=e.where(t,">",r.after)),Array.isArray(r.between)&&r.between.length===2){let[i,o]=r.between;i instanceof Date&&(e=e.where(t,">=",i)),o instanceof Date&&(e=e.where(t,"<=",o))}}return e}function wt(e,t,n,r,i){return r==="number"?gt(e,t.number(n),i):r==="boolean"?pt(e,o=>t.booleanEquals(n,o),i):r==="date"?mt(e,t.timestamp(n),i):ft(e,_e(n),i)}function bt(e,t,n){if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let r=n;return"equals"in r&&(e=e.where(t,"=",r.equals)),"contains"in r&&typeof r.contains=="string"&&(e=e.where(t,"like",`%${r.contains}%`)),"startsWith"in r&&typeof r.startsWith=="string"&&(e=e.where(t,"like",`${r.startsWith}%`)),"endsWith"in r&&typeof r.endsWith=="string"&&(e=e.where(t,"like",`%${r.endsWith}`)),"in"in r&&Array.isArray(r.in)&&(e=e.where(t,"in",r.in)),e}return e.where(t,"=",n)}function ht(e){return typeof e=="number"?e:typeof e=="bigint"?Number(e):Number.parseInt(String(e??0),10)}function $e(e,t){return Array.isArray(t)?e("account_id","in",t):e("account_id","=",t)}function R(e,t,n){let r=e.selectFrom("corsair_entities").selectAll().where(i=>$e(i,t)).where("entity_type","=",n);return Array.isArray(t)?r.orderBy("created_at").orderBy("id"):r}function je(e,t,n,r,i,o,a){let d=yt(i),p=new Map,w=async c=>{if(!o?.kek)throw new Error("encryptDataAtRest requires kek");let y=await e.selectFrom("corsair_accounts").select("dek").where("id","=",c).executeTakeFirst();if(!y?.dek)throw new Error(`No DEK found for account "${c}". Initialize the account first.`);let f=p.get(c);if(f&&f.wrapped===y.dek)return f.dek;let g=await F(y.dek,o.kek);return p.set(c,{wrapped:y.dek,dek:g}),g};async function l(c,y){let f=lt(c.data);return o&&(f=ie(f,y??await w(c.account_id))),{...c,data:i.parse(f)}}async function s(){let c=a?await a():[];return c.length<2?{ids:await t()}:{ids:c.map(y=>y.id),labels:new Map(c.map(y=>[y.id,y.label??y.id]))}}async function u(c){let{ids:y,labels:f}=await s(),h=await R(e,y,n).where("entity_id","=",c).execute();return Array.isArray(y)?(h.sort((x,A)=>y.indexOf(x.account_id)-y.indexOf(A.account_id)),{row:h[0],labels:f}):{row:h[0],labels:f}}async function m(c,y){let f=new Map;return o&&await Promise.all([...new Set(c.map(g=>g.account_id))].map(async g=>f.set(g,await w(g)))),Promise.all(c.map(async g=>{let h=await l(g,f.get(g.account_id)),x=y?.get(g.account_id);return x?{...h,account:x}:h}))}async function I(c,y){return o?re(y,await w(c)):y}return{findByEntityId:async c=>{let{row:y,labels:f}=await u(c);return y?(await m([y],f))[0]:null},existsByEntityId:async c=>{let{ids:y}=await s();return await R(e,y,n).select("id").where("entity_id","=",c).executeTakeFirst()!==void 0},findIdByEntityId:async c=>{let{row:y}=await u(c);return y?.id??null},findById:async c=>{let{ids:y,labels:f}=await s(),g=await R(e,y,n).where("id","=",c).executeTakeFirst();return g?(await m([g],f))[0]:null},findManyByEntityIds:async c=>{if(c.length===0)return[];let{ids:y,labels:f}=await s(),g=await R(e,y,n).where("entity_id","in",c).execute();return m(g,f)},list:async c=>{let{ids:y,labels:f}=await s(),g=R(e,y,n);typeof c?.limit=="number"&&(g=g.limit(c.limit)),typeof c?.offset=="number"&&(g=g.offset(c.offset));let h=await g.execute();return m(h,f)},search:async c=>{if(o&&c.data&&typeof c.data=="object"&&Object.keys(c.data).length>0)throw new Error("Entity JSON field search cannot run while encryptDataAtRest is enabled. The stored document is ciphertext.");let{ids:y,labels:f}=await s(),g=R(e,y,n),h=new Set(["data","limit","offset"]);for(let[A,_]of Object.entries(c))h.has(A)||_===void 0||(g=bt(g,A,_));if(c.data&&typeof c.data=="object")for(let[A,_]of Object.entries(c.data)){if(_===void 0)continue;let Q=d[A]??"string";g=wt(g,dt(e),A,Q,_)}typeof c.limit=="number"&&(g=g.limit(c.limit)),typeof c.offset=="number"&&(g=g.offset(c.offset));let x=await g.execute();return m(x,f)},upsertByEntityId:async(c,y)=>{let f=await t(),g=i.parse(y),h=await I(f,g),x=new Date,A=await R(e,f,n).select("id").where("entity_id","=",c).executeTakeFirst();if(A?.id){await e.updateTable("corsair_entities").set({version:r,data:h,updated_at:x}).where("id","=",A.id).execute();let Ue=await e.selectFrom("corsair_entities").selectAll().where("id","=",A.id).executeTakeFirst();return l(Ue)}let _=P();await e.insertInto("corsair_entities").values({id:_,created_at:x,updated_at:x,account_id:f,entity_id:c,entity_type:n,version:r,data:h}).execute();let Q=await e.selectFrom("corsair_entities").selectAll().where("id","=",_).executeTakeFirst();return l(Q)},deleteById:async c=>{let y=await t(),f=await e.deleteFrom("corsair_entities").where("account_id","=",y).where("entity_type","=",n).where("id","=",c).executeTakeFirst();return Number(f.numDeletedRows)>0},deleteByEntityId:async c=>{let y=await t(),f=await e.deleteFrom("corsair_entities").where("account_id","=",y).where("entity_type","=",n).where("entity_id","=",c).executeTakeFirst();return Number(f.numDeletedRows)>0},count:async()=>{let{ids:c}=await s(),y=await e.selectFrom("corsair_entities").select(f=>f.fn.countAll().as("count")).where(f=>$e(f,c)).where("entity_type","=",n).executeTakeFirst();return ht(y?.count)}}}var Ct={corsair_integrations:ae,corsair_accounts:se,corsair_entities:ce,corsair_events:ue};function kt(e){return Ct[e]}function We(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}function b(e){if(!e)throw new Error("Corsair database is not configured. Pass `database` to createCorsair(...) to enable ORM.")}function N(e){if(!e)return[];let t=[];for(let n in e){let r=n,i=e[r];if(i!==void 0)if(typeof i=="object"&&i!==null&&!Array.isArray(i)&&!(i instanceof Date)){let o=i;"in"in o&&Array.isArray(o.in)?t.push({field:r,operator:"in",value:o.in}):"like"in o&&typeof o.like=="string"&&t.push({field:r,operator:"like",value:o.like})}else t.push({field:r,value:i})}return t}function E(e,t){if(!t?.length)return e;let n=e;for(let r of t){let i=r.operator??"=";n=n.where(r.field,i,r.value)}return n}function Tt(e){return typeof e=="number"?e:typeof e=="bigint"?Number(e):Number.parseInt(String(e??0),10)}function J(e,t){let n=kt(t),r=()=>(b(e),e),i=()=>r().db.selectFrom(t),o=()=>r().db.insertInto(t),a=()=>r().db.updateTable(t),d=()=>r().db.deleteFrom(t);function p(l){let s={};for(let[u,m]of Object.entries(l))s[u]=We(m);return n.parse(s)}function w(l){let s={};for(let[u,m]of Object.entries(l))s[u]=We(m);return n.parse(s)}return{findById:async l=>{b(e);let s=i().selectAll();s=E(s,[{field:"id",value:l}]);let u=await s.executeTakeFirst();return u?p(u):null},findOne:async l=>{b(e);let s=i().selectAll();s=E(s,N(l));let u=await s.executeTakeFirst();return u?p(u):null},findMany:async l=>{b(e);let s=i().selectAll();return s=E(s,N(l?.where)),typeof l?.limit=="number"&&(s=s.limit(l.limit)),typeof l?.offset=="number"&&(s=s.offset(l.offset)),(await s.execute()).map(m=>p(m))},create:async l=>{b(e);let s=new Date,u={id:l.id??P(),created_at:s,updated_at:s,...l},m=await o().values(u).returningAll().executeTakeFirst();return m?p(m):w(u)},update:async(l,s)=>{b(e);let u={...s,updated_at:new Date},m=a().set(u).returningAll();m=E(m,[{field:"id",value:l}]);let I=await m.executeTakeFirst();return I?p(I):null},updateMany:async(l,s)=>{b(e);let u={...s,updated_at:new Date},m=i().select("id");m=E(m,N(l));let I=await m.execute();for(let c of I){let y=a().set(u);y=E(y,[{field:"id",value:c.id}]),await y.execute()}return I.length},delete:async l=>{b(e);let s=d();s=E(s,[{field:"id",value:l}]);let u=await s.executeTakeFirst();return Number(u?.numDeletedRows??0)>0},deleteMany:async l=>{b(e);let s=d();s=E(s,N(l));let u=await s.executeTakeFirst();return Number(u?.numDeletedRows??0)},count:async l=>{b(e);let s=i().select(m=>m.fn.countAll().as("count"));s=E(s,N(l));let u=await s.executeTakeFirst();return Tt(u?.count)}}}function At(e){let t=J(e,"corsair_integrations");return{...t,findByName:n=>t.findOne({name:n}),upsertByName:async(n,r)=>{let i=await t.findOne({name:n});return i?await t.update(i.id,r):t.create({...r,name:n})}}}function xt(e){let t=J(e,"corsair_accounts");return{...t,findByTenantAndIntegration:async(n,r)=>{b(e);let i=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",r).executeTakeFirst();if(!i)return null;let o=await B(e.db,{tenantId:n,integrationId:i.id});return o?t.findOne({id:o.id,tenant_id:n,integration_id:i.id}):null},listByTenant:(n,r)=>t.findMany({where:{tenant_id:n},limit:r?.limit,offset:r?.offset}),upsertByTenantAndIntegration:async(n,r,i)=>{b(e);let o=await B(e.db,{tenantId:n,integrationId:r});return o?await t.update(o.id,i):t.create({...i,tenant_id:n,integration_id:r})}}}function It(e){let t=J(e,"corsair_entities");return{...t,findByEntityId:({accountId:n,entityType:r,entityId:i})=>t.findOne({account_id:n,entity_type:r,entity_id:i}),findManyByEntityIds:async({accountId:n,entityType:r,entityIds:i})=>i.length===0?[]:(b(e),await e.db.selectFrom("corsair_entities").selectAll().where("account_id","=",n).where("entity_type","=",r).where("entity_id","in",i).execute()),listByScope:({accountId:n,entityType:r,limit:i,offset:o})=>t.findMany({where:{account_id:n,entity_type:r},limit:i,offset:o}),searchByEntityId:async({accountId:n,entityType:r,query:i,limit:o,offset:a})=>{b(e);let d=e.db.selectFrom("corsair_entities").selectAll().where("account_id","=",n).where("entity_type","=",r).where("entity_id","like",`%${i}%`);return typeof o=="number"&&(d=d.limit(o)),typeof a=="number"&&(d=d.offset(a)),await d.execute()},upsertByEntityId:async({accountId:n,entityType:r,entityId:i,version:o,data:a})=>{let d=await t.findOne({account_id:n,entity_type:r,entity_id:i});return d?await t.update(d.id,{version:o,data:a}):t.create({account_id:n,entity_type:r,entity_id:i,version:o,data:a})},deleteByEntityId:async({accountId:n,entityType:r,entityId:i})=>{b(e);let o=await e.db.deleteFrom("corsair_entities").where("account_id","=",n).where("entity_type","=",r).where("entity_id","=",i).executeTakeFirst();return Number(o.numDeletedRows)>0}}}function Et(e){let t=J(e,"corsair_events");return{...t,listByAccount:(n,r)=>t.findMany({where:{account_id:n},limit:r?.limit,offset:r?.offset}),listByStatus:(n,r)=>{let i={status:n};return r?.accountId&&(i.account_id=r.accountId),t.findMany({where:i,limit:r?.limit,offset:r?.offset})},listPending:n=>{let r={status:"pending"};return n?.accountId&&(r.account_id=n.accountId),t.findMany({where:r,limit:n?.limit??100})},updateStatus:(n,r)=>t.update(n,{status:r})}}function Me(e){return{integrations:At(e),accounts:xt(e),entities:It(e),events:Et(e)}}function _t(e){if(e.encryptDataAtRest===!0)return{encryptDataAtRest:!0,kek:e.kek??""}}function Dt(e,t,n,r,i,o){let a=null;async function d(){if(a!==null)return a;b(e);let p=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",t.integrationName).executeTakeFirst();if(!p)throw new Error(`Integration "${t.integrationName}" not found. Make sure to create the integration first.`);let w=await B(e.db,{tenantId:t.tenantId,integrationId:p.id});if(!w)throw new Error(`Account not found for tenant "${t.tenantId}" and integration "${t.integrationName}". Make sure to create the account first.`);return a=w.id,a}return b(e),je(e.db,d,n,r,i,o)}function Le(e){let{database:t,integrationName:n,schema:r,tenantId:i}=e,o=_t(e),a=Me(t),d={tenantId:i,integrationName:n},p=null;async function w(){if(p!==null)return p;b(t);let s=await t.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!s)throw new Error(`Integration "${n}" not found. Make sure to create the integration first.`);let u=await B(t.db,{tenantId:i,integrationId:s.id});if(!u)throw new Error(`Account not found for tenant "${i}" and integration "${n}". Make sure to create the account first.`);return p=u.id,p}let l={};for(let[s,u]of Object.entries(r.entities))l[s]=Dt(t,d,s,r.version,u,o);return{...l,$orm:a,$integrationName:n,$tenantId:i,$getAccountId:w}}function On(e,t){let n=Me(e);return{$tenantId:t,$orm:n,listAccounts:r=>n.accounts.listByTenant(t,r),findAccountByIntegration:r=>n.accounts.findByTenantAndIntegration(t,r),listEntities:async r=>{b(e);let i=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",t).execute();if(i.length===0)return[];let o=i.map(d=>d.id),a=e.db.selectFrom("corsair_entities").selectAll().where("account_id","in",o);return r?.entityType&&(a=a.where("entity_type","=",r.entityType)),typeof r?.limit=="number"&&(a=a.limit(r.limit)),typeof r?.offset=="number"&&(a=a.offset(r.offset)),await a.execute()},listEvents:async r=>{b(e);let i=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",t).execute();if(i.length===0)return[];let o=i.map(d=>d.id),a=e.db.selectFrom("corsair_events").selectAll().where("account_id","in",o);return r?.status&&(a=a.where("status","=",r.status)),typeof r?.limit=="number"&&(a=a.limit(r.limit)),typeof r?.offset=="number"&&(a=a.offset(r.offset)),await a.execute()},forIntegration:r=>Le({database:e,integrationName:r.integrationName,schema:r.schema,tenantId:t,encryptDataAtRest:r.encryptDataAtRest,kek:r.kek})}}function vn(e,t){return{forTenant:n=>Le({database:e,integrationName:t.integrationName,schema:t.schema,tenantId:n,encryptDataAtRest:t.encryptDataAtRest,kek:t.kek})}}export{K as a,z as b,le as c,Je as d,Qe as e,ze as f,He as g,H as h,Ge as i,Ot as j,qe as k,vt as l,G as m,q as n,Y as o,F as p,X as q,V as r,ee as s,j as t,Lt as u,Ie as v,re as w,ie as x,fn as y,gn as z,P as A,B,rn as C,S as D,L as E,on as F,an as G,sn as H,cn as I,ot as J,at as K,un as L,je as M,Ct as N,Me as O,Le as P,On as Q,vn as R};
@@ -1 +0,0 @@
1
- import{$ as b,_ as a,aa as c}from"./chunk-KSYLMKIZ.js";import"./chunk-6IURNA4L.js";import"./chunk-XCTHEKDP.js";import"./chunk-KOJBIKQZ.js";import"./chunk-XPXWKPFZ.js";import"./chunk-Z2KT4F2U.js";import"./chunk-SOY77BN4.js";export{c as createHubConnectSession,b as createHubConnectSessionForPlugin,a as postHubConnectSession};