corsair 0.1.70 → 0.1.72
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-6KMLS5U6.js +1 -0
- package/dist/chunk-AAWROBCK.js +1 -0
- package/dist/{chunk-275AZA6T.js → chunk-UEIITBYY.js} +1 -1
- package/dist/chunk-W6KENKHM.js +26 -0
- package/dist/core.d.ts +3 -3
- package/dist/core.js +1 -1
- package/dist/db.d.ts +4 -2
- package/dist/db.js +1 -1
- package/dist/{index-Cl9PJjsS.d.ts → index-CN2IlLdT.d.ts} +18 -3
- package/dist/{index-DKq1RoJC.d.ts → index-Cadh5O_D.d.ts} +90 -2
- package/dist/index.d.ts +16 -4
- package/dist/index.js +2 -2
- package/dist/oauth.d.ts +5 -1
- package/dist/oauth.js +1 -1
- package/dist/orm.d.ts +4 -1
- package/dist/orm.js +1 -1
- package/dist/setup.d.ts +1 -1
- package/dist/setup.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-7SONQAHW.js +0 -26
- package/dist/chunk-UBM25HVI.js +0 -1
- package/dist/chunk-ZGVIF3UY.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a}from"./chunk-QAIKSQAD.js";import{Kysely as n,PostgresDialect as b,SqliteDialect as C}from"kysely";import{PostgresJSDialect as D}from"kysely-postgres-js";function w(e){return typeof e.query=="function"&&typeof e.connect=="function"}function d(e){let t=e;return typeof t.prepare=="function"&&typeof t.exec=="function"&&typeof t.close=="function"&&!("query"in e)}function g(e){return typeof e=="function"&&typeof e.begin=="function"&&typeof e.end=="function"}function i(e,t){return typeof e=="function"?e.bind(t):e}function m(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!Buffer.isBuffer(e)&&Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length===0}function S(e){return e instanceof Date?e.toISOString():m(e)?"{}":e}function q(e){return new Proxy(e,{get(t,o,y){return o!=="reserve"?i(Reflect.get(t,o,y),t):async function(){let c=await t.reserve();return new Proxy(c,{get(r,s,f){return s!=="unsafe"?i(Reflect.get(r,s,f),r):function(u,l,p){return r.unsafe(u,l?.map(S),p)}}})}}})}function P(e){return typeof e.selectFrom=="function"}function I(e){if(P(e))return{db:e};if(d(e))return{db:new n({dialect:new C({database:e}),plugins:[new a]})};if(w(e))return{db:new n({dialect:new b({pool:e})})};if(g(e))return{db:new n({dialect:new D({postgres:q(e)})})};throw new Error("Unsupported database input. Expected a pg Pool, postgres.js Sql, better-sqlite3 Database, or a Kysely instance.")}export{I as a};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as b,b as h}from"./chunk-OZHME3EO.js";import{a as E,b as I,c as x,d as D}from"./chunk-3USHGH6P.js";var k={corsair_integrations:E,corsair_accounts:I,corsair_entities:x,corsair_events:D};function F(e){return k[e]}function _(e){if(typeof e=="string")try{return JSON.parse(e)}catch{return e}return e}function S(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.getPrototypeOf(e)===Object.prototype&&Object.keys(e).length===0}function R(e){if(!("config"in e)||!S(e.config))return e;let{config:n,...r}=e;return r}function d(e){if(!e)throw new Error("Corsair database is not configured. Pass `database` to createCorsair(...) to enable ORM.")}function g(e){if(!e)return[];let n=[];for(let r in e){let t=r,i=e[t];if(i!==void 0)if(typeof i=="object"&&i!==null&&!Array.isArray(i)&&!(i instanceof Date)){let s=i;"in"in s&&Array.isArray(s.in)?n.push({field:t,operator:"in",value:s.in}):"like"in s&&typeof s.like=="string"&&n.push({field:t,operator:"like",value:s.like})}else n.push({field:t,value:i})}return n}function p(e,n){if(!n?.length)return e;let r=e;for(let t of n){let i=t.operator??"=";r=r.where(t.field,i,t.value)}return r}function O(e){return typeof e=="number"?e:typeof e=="bigint"?Number(e):Number.parseInt(String(e??0),10)}function T(e,n){let r=F(n),t=()=>(d(e),e),i=()=>t().db.selectFrom(n),s=()=>t().db.insertInto(n),u=()=>t().db.updateTable(n),c=()=>t().db.deleteFrom(n);function m(o){let a={};for(let[l,y]of Object.entries(o))a[l]=_(y);return r.parse(a)}function C(o){let a={};for(let[l,y]of Object.entries(o))a[l]=_(y);return r.parse(a)}return{findById:async o=>{d(e);let a=i().selectAll();a=p(a,[{field:"id",value:o}]);let l=await a.executeTakeFirst();return l?m(l):null},findOne:async o=>{d(e);let a=i().selectAll();a=p(a,g(o));let l=await a.executeTakeFirst();return l?m(l):null},findMany:async o=>{d(e);let a=i().selectAll();return a=p(a,g(o?.where)),typeof o?.limit=="number"&&(a=a.limit(o.limit)),typeof o?.offset=="number"&&(a=a.offset(o.offset)),(await a.execute()).map(y=>m(y))},create:async o=>{d(e);let a=new Date,l=R({id:o.id??b(),created_at:a,updated_at:a,...o}),y=await s().values(l).returningAll().executeTakeFirst();return y?m(y):C(l)},update:async(o,a)=>{d(e);let l={...a,updated_at:new Date},y=u().set(l).returningAll();y=p(y,[{field:"id",value:o}]);let f=await y.executeTakeFirst();return f?m(f):null},updateMany:async(o,a)=>{d(e);let l={...a,updated_at:new Date},y=i().select("id");y=p(y,g(o));let f=await y.execute();for(let B of f){let w=u().set(l);w=p(w,[{field:"id",value:B.id}]),await w.execute()}return f.length},delete:async o=>{d(e);let a=c();a=p(a,[{field:"id",value:o}]);let l=await a.executeTakeFirst();return Number(l?.numDeletedRows??0)>0},deleteMany:async o=>{d(e);let a=c();a=p(a,g(o));let l=await a.executeTakeFirst();return Number(l?.numDeletedRows??0)},count:async o=>{d(e);let a=i().select(y=>y.fn.countAll().as("count"));a=p(a,g(o));let l=await a.executeTakeFirst();return O(l?.count)}}}function N(e){let n=T(e,"corsair_integrations");return{...n,findByName:r=>n.findOne({name:r}),upsertByName:async(r,t)=>{let i=await n.findOne({name:r});return i?await n.update(i.id,t):n.create({...t,name:r})}}}function v(e){let n=T(e,"corsair_accounts");return{...n,findByTenantAndIntegration:async(r,t)=>{d(e);let i=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",t).executeTakeFirst();return i?n.findOne({tenant_id:r,integration_id:i.id}):null},listByTenant:(r,t)=>n.findMany({where:{tenant_id:r},limit:t?.limit,offset:t?.offset}),upsertByTenantAndIntegration:async(r,t,i)=>{let s=await n.findOne({tenant_id:r,integration_id:t});return s?await n.update(s.id,i):n.create({...i,tenant_id:r,integration_id:t})}}}function W(e){let n=T(e,"corsair_entities");return{...n,findByEntityId:({accountId:r,entityType:t,entityId:i})=>n.findOne({account_id:r,entity_type:t,entity_id:i}),findManyByEntityIds:async({accountId:r,entityType:t,entityIds:i})=>i.length===0?[]:(d(e),await e.db.selectFrom("corsair_entities").selectAll().where("account_id","=",r).where("entity_type","=",t).where("entity_id","in",i).execute()),listByScope:({accountId:r,entityType:t,limit:i,offset:s})=>n.findMany({where:{account_id:r,entity_type:t},limit:i,offset:s}),searchByEntityId:async({accountId:r,entityType:t,query:i,limit:s,offset:u})=>{d(e);let c=e.db.selectFrom("corsair_entities").selectAll().where("account_id","=",r).where("entity_type","=",t).where("entity_id","like",`%${i}%`);return typeof s=="number"&&(c=c.limit(s)),typeof u=="number"&&(c=c.offset(u)),await c.execute()},upsertByEntityId:async({accountId:r,entityType:t,entityId:i,version:s,data:u})=>{let c=await n.findOne({account_id:r,entity_type:t,entity_id:i});return c?await n.update(c.id,{version:s,data:u}):n.create({account_id:r,entity_type:t,entity_id:i,version:s,data:u})},deleteByEntityId:async({accountId:r,entityType:t,entityId:i})=>{d(e);let s=await e.db.deleteFrom("corsair_entities").where("account_id","=",r).where("entity_type","=",t).where("entity_id","=",i).executeTakeFirst();return Number(s.numDeletedRows)>0}}}function M(e){let n=T(e,"corsair_events");return{...n,listByAccount:(r,t)=>n.findMany({where:{account_id:r},limit:t?.limit,offset:t?.offset}),listByStatus:(r,t)=>{let i={status:r};return t?.accountId&&(i.account_id=t.accountId),n.findMany({where:i,limit:t?.limit,offset:t?.offset})},listPending:r=>{let t={status:"pending"};return r?.accountId&&(t.account_id=r.accountId),n.findMany({where:t,limit:r?.limit??100})},updateStatus:(r,t)=>n.update(r,{status:t})}}function A(e){return{integrations:N(e),accounts:v(e),entities:W(e),events:M(e)}}function $(e,n,r,t,i){let s=null;async function u(){if(s!==null)return s;d(e);let c=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",n.integrationName).executeTakeFirst();if(!c)throw new Error(`Integration "${n.integrationName}" not found. Make sure to create the integration first.`);let m=await e.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",n.tenantId).where("integration_id","=",c.id).executeTakeFirst();if(!m)throw new Error(`Account not found for tenant "${n.tenantId}" and integration "${n.integrationName}". Make sure to create the account first.`);return s=m.id,s}return d(e),h(e.db,u,r,t,i)}function P(e){let{database:n,integrationName:r,schema:t,tenantId:i}=e,s=A(n),u={tenantId:i,integrationName:r},c=null;async function m(){if(c!==null)return c;d(n);let o=await n.db.selectFrom("corsair_integrations").selectAll().where("name","=",r).executeTakeFirst();if(!o)throw new Error(`Integration "${r}" not found. Make sure to create the integration first.`);let a=await n.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",i).where("integration_id","=",o.id).executeTakeFirst();if(!a)throw new Error(`Account not found for tenant "${i}" and integration "${r}". Make sure to create the account first.`);return c=a.id,c}let C={};for(let[o,a]of Object.entries(t.entities))C[o]=$(n,u,o,t.version,a);return{...C,$orm:s,$integrationName:r,$tenantId:i,$getAccountId:m}}function Z(e,n){let r=A(e);return{$tenantId:n,$orm:r,listAccounts:t=>r.accounts.listByTenant(n,t),findAccountByIntegration:t=>r.accounts.findByTenantAndIntegration(n,t),listEntities:async t=>{d(e);let i=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",n).execute();if(i.length===0)return[];let s=i.map(c=>c.id),u=e.db.selectFrom("corsair_entities").selectAll().where("account_id","in",s);return t?.entityType&&(u=u.where("entity_type","=",t.entityType)),typeof t?.limit=="number"&&(u=u.limit(t.limit)),typeof t?.offset=="number"&&(u=u.offset(t.offset)),await u.execute()},listEvents:async t=>{d(e);let i=await e.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",n).execute();if(i.length===0)return[];let s=i.map(c=>c.id),u=e.db.selectFrom("corsair_events").selectAll().where("account_id","in",s);return t?.status&&(u=u.where("status","=",t.status)),typeof t?.limit=="number"&&(u=u.limit(t.limit)),typeof t?.offset=="number"&&(u=u.offset(t.offset)),await u.execute()},forIntegration:t=>P({database:e,integrationName:t.integrationName,schema:t.schema,tenantId:n})}}function j(e,n){return{forTenant:r=>P({database:e,integrationName:n.integrationName,schema:n.schema,tenantId:r})}}export{k as a,A as b,P as c,Z as d,j as e};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{C as A,D as T,j as w,k as C,l as S}from"./chunk-W6KENKHM.js";import{a as _}from"./chunk-AAWROBCK.js";import{Kysely as I}from"kysely";import{ZodBoolean as M,ZodDate as R,ZodEnum as j,ZodNullable as D,ZodNumber as F,ZodObject as O,ZodOptional as x,ZodRecord as E,ZodString as K,ZodType as B}from"zod";var h={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:{}}},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:{}}}};async function ie(e,t){let a=[],i=s=>{a.push(s),console.log(s)},o=s=>{a.push(s),console.warn(s)},f=t?.caller??"script",d=t?.tenantId;if(!d){if(e?.withTenant)throw new Error("setupCorsair: tenantId must be a non-empty string");d="default"}let n=v(e);if(!n)throw new Error("setupCorsair: invalid corsair instance");if(!n.database)throw new Error("setupCorsair: a database must be configured on the corsair instance");let u={...n,database:n.database},c=u.database.db;await Y(c,o);let p=await H(c,u,d,i),y=await z(p,d,i,f);if(t?.backfill){i("[corsair:setup] Starting backfill...");let s=T({plugins:n.plugins,database:c,kek:n.kek,multiTenancy:!0}).withTenant(d);await Q(s,n.plugins,y,i,o),i("[corsair:setup] Backfill complete.")}return a.join(`
|
|
2
2
|
`)}function b(e){return typeof e=="object"&&e!==null}function Z(e){return!b(e)||!Array.isArray(e.plugins)||typeof e.kek!="string"||typeof e.multiTenancy!="boolean"?!1:e.database===void 0?!0:b(e.database)?e.database.db instanceof I:!1}function v(e){let t=Object.getOwnPropertyDescriptor(e,A);if(t)return Z(t.value)?t.value:void 0}function N(e){return e==="oauth_2"||e==="api_key"||e==="bot_token"}function L(e){let t=e.options?.authType;return N(t)?t:void 0}function m(e,t){if(!b(e))return;let a=e[t];return typeof a=="function"?(...i)=>Reflect.apply(a,e,i):void 0}function $(e,t){return b(e)?t===0?!0:Object.values(e).every(a=>$(a,t-1)):!1}function U(e){return $(e,4)}var W={..._};function k(e){if(e instanceof O){let t={};for(let[a,i]of Object.entries(e.shape))t[a]=i instanceof B?k(i):"unknown";return t}return e instanceof D?`${k(e.unwrap())} | null`:e instanceof x?`${k(e.unwrap())} | undefined`:e instanceof j?e.options.join(" | "):e instanceof K?"string":e instanceof F?"number":e instanceof M?"boolean":e instanceof R?"date":e instanceof E?"jsonb":"unknown"}async function Y(e,t){let a=await e.introspection.getTables(),i=new Set(a.map(o=>o.name));for(let[o,f]of Object.entries(W))i.has(o)||t(`[corsair:setup] Table "${o}" does not exist. Run your database migrations before calling setupCorsair.
|
|
3
3
|
Schema: ${JSON.stringify(k(f),null,2)}`)}async function H(e,t,a,i){let o=new Date,f=new Map;for(let d of t.plugins){let n=d.id,u=L(d),c=await e.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!c){let l=crypto.randomUUID();await e.insertInto("corsair_integrations").values({id:l,name:n,config:{},created_at:o,updated_at:o}).execute(),c=await e.selectFrom("corsair_integrations").selectAll().where("id","=",l).executeTakeFirst(),i(`[corsair:setup] Created integration: ${n}`)}let p=u?d.authConfig?.[u]?.integration??[]:[],y=u?d.authConfig?.[u]?.account??[]:[],s=u&&c?C({authType:u,integrationName:n,kek:t.kek,database:t.database,extraIntegrationFields:p}):void 0;if(c&&!c.dek&&s&&(await s.issue_new_dek(),i(`[corsair:setup] Issued integration DEK: ${n}`)),!c)continue;let r=await e.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",a).where("integration_id","=",c.id).executeTakeFirst();if(!r){let l=crypto.randomUUID();await e.insertInto("corsair_accounts").values({id:l,tenant_id:a,integration_id:c.id,config:{},created_at:o,updated_at:o}).execute(),r=await e.selectFrom("corsair_accounts").selectAll().where("id","=",l).executeTakeFirst(),i(`[corsair:setup] Created account: ${n}`)}let g=u&&r?S({authType:u,integrationName:n,tenantId:a,kek:t.kek,database:t.database,extraAccountFields:y}):void 0;r&&!r.dek&&g&&(await g.issue_new_dek(),i(`[corsair:setup] Issued account DEK: ${n}`)),u&&s&&g&&f.set(n,{pluginId:n,authType:u,integration:s,account:g,integrationFields:[...w[u].integration,...p],accountFields:[...w[u].account,...y]})}return f}var P=new Set(["webhook_signature","expires_at","scope","redirect_url"]);async function J(e,t,a,i,o,f,d,n,u){let c=[],p=[];for(let s of o){if(P.has(s))continue;let r=m(a,`get_${s}`);if(!r)continue;let g=null;try{let l=await r();g=typeof l=="string"?l:null}catch{}g||c.push(s)}for(let s of f){if(P.has(s))continue;let r=m(i,`get_${s}`);if(!r)continue;let g=null;try{let l=await r();g=typeof l=="string"?l:null}catch{}g||p.push(s)}let y=c.length===0&&p.length===0;if(y)n(`[corsair:setup] '${e}' (${t}) is configured \u2713`);else{let s=[...c,...p];if(u==="cli"){let r=s.map(g=>`${g}=VALUE`).join(" ");n(`[corsair:setup] '${e}' (${t}) needs credentials. Run:
|
|
4
4
|
corsair setup --${e} ${r}`)}else{let r=[`[corsair:setup] '${e}' (${t}) needs credentials. Call:`];for(let g of c)r.push(` await corsair.keys.${e}.set_${g}(value)`);for(let g of p){let l=d==="default"?`corsair.${e}`:`corsair.withTenant(${JSON.stringify(d)}).${e}`;r.push(` await ${l}.keys.set_${g}(value)`)}n(r.join(`
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import{a as Pe,b as de}from"./chunk-OZHME3EO.js";import{a as xe}from"./chunk-6KMLS5U6.js";var N=class extends Error{pluginId;constructor(n,r){super(r??`[auth-missing:${n}]`),Object.setPrototypeOf(this,new.target.prototype),this.name="AuthMissingError",this.pluginId=n}};import{createCipheriv as Ee,createDecipheriv as Re,randomBytes as ne,scrypt as on}from"crypto";import{promisify as sn}from"util";var Ie=sn(on),te="aes-256-gcm",De=12,re=16,an=16,V=32;function B(){return ne(V).toString("base64")}async function j(e,n){let r=ne(an),t=await Ie(n,r,V),o=ne(De),i=Ee(te,t,o,{authTagLength:re}),s=Buffer.concat([i.update(e,"utf8"),i.final()]),a=i.getAuthTag();return[r.toString("base64"),o.toString("base64"),a.toString("base64"),s.toString("base64")].join(":")}async function M(e,n){let[r,t,o,i]=e.split(":");if(!r||!t||!o||!i)throw new Error("Invalid encrypted DEK format");let s=Buffer.from(r,"base64"),a=Buffer.from(t,"base64"),d=Buffer.from(o,"base64"),p=Buffer.from(i,"base64"),c=await Ie(n,s,V),l=Re(te,c,a,{authTagLength:re});return l.setAuthTag(d),Buffer.concat([l.update(p),l.final()]).toString("utf8")}function ue(e,n){let r=Buffer.from(n,"base64"),t=ne(De),o=Ee(te,r,t,{authTagLength:re}),i=Buffer.concat([o.update(e,"utf8"),o.final()]),s=o.getAuthTag();return[t.toString("base64"),s.toString("base64"),i.toString("base64")].join(":")}function le(e,n){let[r,t,o]=e.split(":");if(!r||!t||!o)throw new Error("Invalid encrypted data format");let i=Buffer.from(n,"base64"),s=Buffer.from(r,"base64"),a=Buffer.from(t,"base64"),d=Buffer.from(o,"base64"),p=Re(te,i,s,{authTagLength:re});return p.setAuthTag(a),Buffer.concat([p.update(d),p.final()]).toString("utf8")}function H(e,n){let r={};for(let[t,o]of Object.entries(e))r[t]=ue(o,n);return r}function L(e,n){let r={};for(let[t,o]of Object.entries(e))r[t]=le(o,n);return r}function Y(e,n,r){let t=L(e,n);return H(t,r)}function oe(e,n){let r=[];e||r.push("database"),n||r.push("kek");let t={};return new Proxy(t,{get(o,i){let s=r.length>1;throw new Error(`corsair.keys.${String(i)}: Cannot access keys because ${r.join(" and ")} ${s?"are":"is"} not configured. Provide both 'database' and 'kek' in createCorsair() to enable key management.
|
|
2
|
+
|
|
3
|
+
To generate a KEK, run: openssl rand -base64 ${V}`)}})}var Q={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"]}};function ve(e,n,r){let t={};for(let o of r)t[`get_${o}`]=async()=>(await e())[o]??null,t[`set_${o}`]=async i=>{let s=[null,void 0,""].includes(i)?null:i;await n({[o]:s})};return t}var pe=e=>{if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return e};function q(e){let{authType:n,integrationName:r,kek:t,database:o,extraIntegrationFields:i=[]}=e,s=[...Q[n].integration,...i],a=null,d={kek:t,integrationName:r,getIntegration:async()=>{if(a)return a;let u=await o.db.selectFrom("corsair_integrations").selectAll().where("name","=",r).executeTakeFirst();if(!u)throw new Error(`Integration "${r}" not found. Make sure to create the integration first.`);return a={id:u.id,config:pe(u.config),dek:u.dek??null},a},updateIntegration:async u=>{let h=await d.getIntegration();await o.db.updateTable("corsair_integrations").set({...u.config!==void 0?{config:u.config}:{},...u.dek!==void 0?{dek:u.dek}:{},updated_at:new Date}).where("id","=",h.id).execute(),a=null}},p=null,c=async()=>{if(p)return p;let u=await d.getIntegration();if(!u.dek)throw new Error(`No DEK found for integration "${r}". Initialize the integration first.`);return p=await M(u.dek,t),p},l=async()=>{let u=await d.getIntegration(),h=await c(),b=u.config;return!b||Object.keys(b).length===0?{}:L(b,h)};return{get_dek:c,issue_new_dek:async()=>{let u=await d.getIntegration(),h=B(),b={};if(u.dek){let w=await M(u.dek,t),A=u.config;A&&Object.keys(A).length>0&&(b=Y(A,w,h))}let k=await j(h,t);return await d.updateIntegration({config:b,dek:k}),p=h,h},...ve(l,async u=>{let h=await c(),b;try{b=await l()}catch(A){console.error(`[corsair] Failed to decrypt config for integration "${r}", starting fresh:`,A),b={}}let k={...b};for(let[A,y]of Object.entries(u))y===null?delete k[A]:k[A]=y;let w=H(k,h);await d.updateIntegration({config:w})},s)}}function ie(e){let{authType:n,integrationName:r,tenantId:t,kek:o,database:i,extraAccountFields:s=[]}=e,a=[...Q[n].account,...s],d=null,p=null,c=async()=>{if(p)return p;let y=await i.db.selectFrom("corsair_integrations").selectAll().where("name","=",r).executeTakeFirst();if(!y)throw new Error(`Integration "${r}" not found. Make sure to create the integration first.`);return p={id:y.id,config:pe(y.config),dek:y.dek??null},p},l={kek:o,integrationName:r,tenantId:t,getIntegration:c,getAccount:async()=>{if(d)return d;let y=await c(),m=await i.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",t).where("integration_id","=",y.id).executeTakeFirst();if(!m)throw new Error(`Account not found for tenant "${t}" and integration "${r}". Make sure to create the account first.`);return d={id:m.id,config:pe(m.config),dek:m.dek??null},d},updateAccount:async y=>{let m=await l.getAccount();await i.db.updateTable("corsair_accounts").set({...y.config!==void 0?{config:y.config}:{},...y.dek!==void 0?{dek:y.dek}:{},updated_at:new Date}).where("id","=",m.id).execute(),d=null}},f=null,g=null,u=async()=>{if(f)return f;let y=await l.getAccount();if(!y.dek)throw new Error(`No DEK found for account (tenant: "${t}", integration: "${r}"). Initialize the account first.`);return f=await M(y.dek,o),f},h=async()=>{if(g)return g;let y=await l.getIntegration();if(!y.dek)throw new Error(`No DEK found for integration "${r}". Initialize the integration first.`);return g=await M(y.dek,o),g},b=async()=>{let y=await l.getAccount(),m=await u(),T=y.config;return!T||Object.keys(T).length===0?{}:L(T,m)},k=async()=>{let y=await l.getIntegration(),m=await h(),T=y.config;return!T||Object.keys(T).length===0?{}:L(T,m)},A={get_dek:u,issue_new_dek:async()=>{let y=await l.getAccount(),m=B(),T={};if(y.dek){let I=await M(y.dek,o),C=y.config;C&&Object.keys(C).length>0&&(T=Y(C,I,m))}let P=await j(m,o);return await l.updateAccount({config:T,dek:P}),f=m,m},...ve(b,async y=>{let m=await u(),T;try{T=await b()}catch(C){console.error(`[corsair] Failed to decrypt config for account (tenant: "${t}", integration: "${r}"), starting fresh:`,C),T={}}let P={...T};for(let[C,O]of Object.entries(y))O===null?delete P[C]:P[C]=O;let I=H(P,m);await l.updateAccount({config:I})},a)};return n==="oauth_2"&&(A.get_integration_credentials=async()=>{let y=await k();return{client_id:y.client_id||null,client_secret:y.client_secret||null,redirect_url:y.redirect_url??null}}),A}async function _e(e,n,r){let t=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!t)throw new Error(`Integration "${n}" not found.`);let o=B(),i=await j(o,r);return await e.db.updateTable("corsair_integrations").set({dek:i,updated_at:new Date}).where("id","=",t.id).execute(),o}async function Se(e,n,r,t){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","=",r).where("integration_id","=",o.id).executeTakeFirst();if(!i)throw new Error(`Account not found for tenant "${r}" and integration "${n}".`);let s=B(),a=await j(s,t);return await e.db.updateTable("corsair_accounts").set({dek:a,updated_at:new Date}).where("id","=",i.id).execute(),s}import*as X from"crypto";function Oe(e,n){return Buffer.from(JSON.stringify({plugin:e,tenantId:n,iat:Date.now()})).toString("base64url")}function cn(e,{maxAgeMs:n}={}){try{let r=e.includes(".")?e.split(".")[0]:e,t=JSON.parse(Buffer.from(r,"base64url").toString("utf-8"));if(t!==null&&typeof t=="object"&&"plugin"in t&&"tenantId"in t&&typeof t.plugin=="string"&&typeof t.tenantId=="string"){let o=t;return n!==void 0&&typeof o.iat=="number"&&Date.now()-o.iat>n?null:o}return null}catch{return null}}function Fe(e,n){let r=X.createHmac("sha256",n).update(e).digest("base64url");return`${e}.${r}`}var dn=600*1e3;function $e(e,n){let r=e.lastIndexOf(".");if(r===-1)return null;let t=e.slice(0,r),o=e.slice(r+1),i=X.createHmac("sha256",n).update(t).digest("base64url"),s=Buffer.from(o,"base64url"),a=Buffer.from(i,"base64url");return s.length!==a.length||!X.timingSafeEqual(s,a)?null:cn(t,{maxAgeMs:dn})}var un=async(e,n)=>(console.error(`[corsair:${n.pluginId}:${n.operation}]`,{error:e.message,input:n.input}),{maxRetries:0});async function Me(e,n,r,t,o){let i={pluginId:n,operation:r,input:t,originalError:e},s=Object.keys(o).find(p=>o[p]?.match(e,i));return await(o[s||"DEFAULT"]?.handler||un)(e,i)}import{randomBytes as ln}from"crypto";import{v4 as pn}from"uuid";var gn={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 fn(e,n,r){return r!==void 0?r:gn[n][e]}function Ke(e){let n=/(\d+)(d|h|m|s)/g,r=0,t;for(;(t=n.exec(e))!==null;){let o=parseInt(t[1],10);switch(t[2]){case"d":r+=o*864e5;break;case"h":r+=o*36e5;break;case"m":r+=o*6e4;break;case"s":r+=o*1e3;break}}return r>0?r:600*1e3}function Ne(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 Ze(e,n,r){let t=Date.now()+r;for(;Date.now()<t;){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 Be(e){let n=fn(e.riskLevel,e.mode,e.override);if(n==="allow")return{result:"allow"};let r=e.meta?.irreversible?" (irreversible)":"",t=e.meta?.description?`${e.meta.description}${r}`:`${e.pluginId}.${e.endpointPath}${r}`;if(n==="deny"||!e.db)return console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 denied by permission mode '${e.mode}'.`,`
|
|
4
|
+
Action: ${t}`,`
|
|
5
|
+
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 u=e.db,h=a.id;return{result:"allow",onComplete:async()=>{await u.db.updateTable("corsair_permissions").set({status:"completed",updated_at:new Date}).where("id","=",h).execute()}}}return a.status==="executing"?{result:"allow"}:(console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 approval already pending.`,`
|
|
6
|
+
Action: ${t}`,`
|
|
7
|
+
Permission ID: ${a.id}`,`
|
|
8
|
+
Use the token to approve or deny this request.`),(typeof e.approvalMode=="function"?e.approvalMode():e.approvalMode)==="synchronous"?Ze(e.db,a.id,e.timeoutMs??600*1e3):{result:"blocked",reason:"pending",id:a.id,token:a.token})}let d=pn(),p=ln(32).toString("hex"),c=e.timeoutMs??600*1e3,l=new Date(Date.now()+c).toISOString();return await e.db.db.insertInto("corsair_permissions").values({id:d,created_at:new Date,updated_at:new Date,token:p,plugin:e.pluginId,endpoint:e.endpointPath,args:o,tenant_id:s,status:"pending",expires_at:l}).execute(),console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 approval required.`,`
|
|
9
|
+
Action: ${t}`,`
|
|
10
|
+
Permission ID: ${d}`,`
|
|
11
|
+
Permission token: ${p}`,`
|
|
12
|
+
Expires at: ${l}`,`
|
|
13
|
+
Use the token to approve or deny this request.`),(typeof e.approvalMode=="function"?e.approvalMode():e.approvalMode)==="synchronous"?Ze(e.db,d,c):{result:"blocked",reason:"pending",id:d,token:p}}function yn(e){return typeof e=="function"}function je(e,n,r){let t=Fe(Oe(e,n.tenantId??r??"default"),n.kek),o=new URL(n.baseUrl);o.searchParams.set("state",t);let i=o.toString(),s=n.onAuthMissing?n.onAuthMissing({plugin:e,connectUrl:i,state:t}):`[auth-missing:${e}] Authentication required. Direct the user to connect their account: ${i}`;return new Error(s)}function ge({endpoints:e,hooks:n,ctx:r,tree:t,pluginId:o,errorHandlers:i,currentPath:s=[],keyBuilder:a,permissionsConfig:d,endpointMeta:p,database:c,approvalConfig:l,tenantId:f,connectConfig:g}){for(let[u,h]of Object.entries(e)){let b=n?.[u];if(yn(h)){let k=b,w=[...s,u].join("."),A=async(y={})=>{let m;if(d){let E=p?.[w],{result:U,reason:S,onComplete:J,token:F,id:K}=await Be({pluginId:o,endpointPath:w,args:y,mode:d.mode,override:d.overrides?.[w],riskLevel:E?.riskLevel??"write",meta:E,db:c,timeoutMs:l?Ke(l.timeout):void 0,tenantId:f,approvalMode:l?.mode});if(U==="blocked"){let x;throw S==="denied"?x=`Action '${w}' was denied by the user. Await further instructions before proceeding.`:S==="policy"?x=`Action '${w}' is blocked by the permission policy. Update the corsair config to allow it.`:S==="timeout"?x=`Action '${w}' timed out waiting for approval.`:l?.formatAsyncMessage&&F&&K?x=l.formatAsyncMessage({token:F,id:K,plugin:o,endpoint:w,args:y}):x=`Action '${w}' requires user approval before it can run.`,new Error(x)}m=J}let T=async(E,U,S)=>{try{return await h(U,S)}catch(J){if(J instanceof Error){let F=await Me(J,o,w,typeof S=="object"&&S!==null?S:{args:S},i);if(E<(F.maxRetries||0)){let K=E+1;console.log(`Retrying (${K} / ${F.maxRetries})...`);let x;if(F.headersRetryAfterMs)x=F.headersRetryAfterMs;else switch(F.retryStrategy){case"exponential_backoff":x=Math.pow(2,K-1)*1e3;break;case"exponential_backoff_jitter":let ce=Math.pow(2,K-1)*1e3,rn=(Math.random()-.5)*1e3;x=Math.max(0,ce+rn);break;case"linear_1s":x=1e3;break;case"linear_2s":x=2e3;break;case"linear_3s":x=3e3;break;case"linear_4s":x=4e3;break;default:x=1e3;break}await new Promise(ce=>setTimeout(ce,x)),await T(K,U,S),console.log(`[corsair:${o}:${w}] Retry strategy:`,F)}}throw J}},P;try{P=a?await a(r,"endpoint"):void 0}catch(E){throw g?.oauthConfig&&g.kek&&E instanceof N?je(o,g,f):E}if(!P&&a&&g?.oauthConfig&&g.kek)throw je(o,g,f);if(!k?.before&&!k?.after){let E=await T(0,{...r,key:P},y);return await m?.(),E}let I={...r,key:P},C=k.before?await k.before(I,y):{ctx:I,args:y,continue:!0,passToAfter:void 0};if(C.continue===!1)return;let O=await T(0,C.ctx,C.args);return await k.after?.(C.ctx,O,C.passToAfter),await m?.(),O};t[u]=A}else if(h&&typeof h=="object"){let k={};ge({endpoints:h,hooks:b,ctx:r,tree:k,pluginId:o,errorHandlers:i,currentPath:[...s,u],keyBuilder:a,permissionsConfig:d,endpointMeta:p,database:c,approvalConfig:l,tenantId:f,connectConfig:g}),t[u]=k}}}function hn(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function fe({webhooks:e,hooks:n,ctx:r,webhooksTree:t,keyBuilder:o}){for(let[i,s]of Object.entries(e)){let a=n?.[i];if(hn(s)){let d=a,p=async c=>{let l=(g,u)=>s.handler(g,u),f=o?await o(r,"webhook"):void 0;return!d?.before&&!d?.after?l({...r,key:f},c):(async()=>{let g={...r,key:f},u=d.before?await d.before(g,c):{ctx:g,args:c,continue:!0,passToAfter:void 0};if(u.continue===!1)return;let h=await l(u.ctx,u.args);return h?.success===!0&&await d.after?.(u.ctx,h,u.passToAfter),h})()};t[i]={match:s.match,handler:p}}else if(s&&typeof s=="object"){let d={};fe({webhooks:s,hooks:a,ctx:r,webhooksTree:d,keyBuilder:o}),t[i]=d}}}function mn(e,n,r){let t=null;return async()=>{if(t)return t;if(!e)throw new Error("Database not configured");let o=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!o)throw new Error(`Integration "${n}" not found. Make sure to create the integration first.`);let i=await e.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",r).where("integration_id","=",o.id).executeTakeFirst();if(!i)throw new Error(`Account not found for tenant "${r}" and integration "${n}". Make sure to create the account first.`);return t=i.id,t}}function kn(e,n,r,t,o){return e?de(e.db,n,r,t,o):{findByEntityId: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 ye(e,n){let{database:r,tenantId:t,kek:o,rootErrorHandlers:i,approvalConfig:s,connectConfig:a}=n,d={},p={};for(let c of e)d[c.id]={},p[c.id]={};for(let c of e){let l=c.schema,f=t??"default",g=mn(r,c.id,f);if(l?.entities){let C={};for(let[O,E]of Object.entries(l.entities)){let U=r?de(r.db,g,O,l.version,E):kn(void 0,g,O,l.version,E);C[O]=U}p[c.id].db=C,d[c.id].db=C}let u=c.options,h=c.authConfig,b;if(r&&o&&u?.authType){let C=h?.[u.authType]?.account??[];b=ie({authType:u.authType,integrationName:c.id,tenantId:f,kek:o,database:r,extraAccountFields:C}),d[c.id].keys=b}let k={database:r,db:p[c.id]?.db??{},$getAccountId:g,...c.options?{options:c.options}:{},...b?{keys:b,authType:u?.authType}:{},...t?{tenantId:t}:{}},w=c.endpoints??{},A=c.hooks,y={...i,...c.errorHandlers},m={},T=c.options?.permissions;ge({endpoints:w,hooks:A,ctx:k,tree:m,pluginId:c.id,errorHandlers:y,currentPath:[],keyBuilder:c.keyBuilder,permissionsConfig:T,endpointMeta:c.endpointMeta,database:r,approvalConfig:s,tenantId:t,connectConfig:a?{...a,oauthConfig:c.oauthConfig,kek:o,tenantId:f}:void 0}),Object.keys(m).length>0&&(d[c.id].api=m),k.endpoints=m;let P=c.webhooks??{},I=c.webhookHooks;if(Object.keys(P).length>0){let C={};fe({webhooks:P,hooks:I,ctx:k,webhooksTree:C,keyBuilder:c.keyBuilder}),d[c.id].webhooks=C,c.pluginWebhookMatcher&&(d[c.id].pluginWebhookMatcher=c.pluginWebhookMatcher)}}return d}function Le(e,n,r){let t={};for(let o of e){let i=o.options,s=o.authConfig;if(i?.authType){let a=s?.[i.authType]?.integration??[],d=q({authType:i.authType,integrationName:o.id,kek:r,database:n,extraIntegrationFields:a});t[o.id]=d}}return t}async function We(e,n,r,t,o="pending"){if(!e)return null;try{let i=Pe(),s=new Date;return await e.db.insertInto("corsair_events").values({id:i,created_at:s,updated_at:s,account_id:n,event_type:r,payload:t,status:o}).execute(),i}catch(i){return console.warn("Failed to log event:",i),null}}async function bn(e,n,r,t="pending"){try{let o=await e.$getAccountId();return We(e.database,o,n,r,t)}catch(o){return console.warn("Failed to log event:",o),null}}import*as Ue from"https";import*as He from"querystring";function qe(e,n,r,t,o){let i=new URL(t.tokenUrl),s=t.tokenAuthMethod==="basic";return new Promise((a,d)=>{let p={code:e.trim(),redirect_uri:o,grant_type:"authorization_code"};s||(p.client_id=n,p.client_secret=r);let c=He.stringify(p),l={"Content-Type":"application/x-www-form-urlencoded","Content-Length":Buffer.byteLength(c).toString()};s&&(l.Authorization=`Basic ${Buffer.from(`${n}:${r}`).toString("base64")}`);let f=Ue.request({hostname:i.hostname,...i.port?{port:Number(i.port)}:{},path:i.pathname+i.search,method:"POST",headers:l},g=>{let u="";g.on("data",h=>{u+=h}),g.on("end",()=>{if(g.statusCode!==200){d(new Error(`Token exchange failed (${g.statusCode}): ${u}`));return}try{a(JSON.parse(u))}catch{d(new Error(`Token endpoint returned non-JSON response: ${u}`))}})});f.on("error",g=>d(new Error(`Request failed: ${g.message}`))),f.write(c),f.end()})}import*as ze from"querystring";function wn(e){let n=e[ee];if(!n)throw new Error("Invalid corsair instance");return n}function Cn(e,n){let r=e.plugins.find(t=>t.id===n);if(!r)throw new Error(`Plugin '${n}' not found`);return r}function Tn(e){let n=e.oauthConfig;if(!n)throw new Error(`Plugin '${e.id}' has no oauthConfig`);return n}async function An(e,n){let r=wn(e);if(!r.database)throw new Error("No database configured on corsair instance");let t=r.connect?.redirectUri;if(!t)throw new Error("No redirectUri configured. Set connect.redirectUri in createCorsair().");let o=$e(n,r.kek);if(!o)throw new Error("Invalid or tampered state parameter");let{plugin:i,tenantId:s}=o,a=Cn(r,i),d=Tn(a),c=await q({authType:"oauth_2",integrationName:i,kek:r.kek,database:r.database}).get_client_id();if(!c)throw new Error(`client_id not configured for '${i}'`);let l={...d.authParams,client_id:c,redirect_uri:t,response_type:"code",scope:d.scopes.join(" "),state:n},f=`${d.authUrl}?${ze.stringify(l)}`;return{plugin:i,tenantId:s,providerName:d.providerName,oauthUrl:f,state:n}}var Ge=["airtable","amplitude","asana","bitwarden","bluesky","box","cal","calendly","cloudflare","cursor","discord","dodopayments","dropbox","exa","figma","firecrawl","fireflies","github","gitlab","gmail","googlecalendar","googledrive","googlesheets","grafana","hackernews","hubspot","intercom","jira","linear","monday","notion","onedrive","openweathermap","oura","outlook","pagerduty","posthog","razorpay","reddit","resend","sentry","sharepoint","slack","spotify","strava","stripe","tally","tavily","teams","telegram","todoist","trello","twitter","twitterapiio","typeform","vapi","xquik","youtube","zendesk","zoom"];var Je=" ";function v(e){let n=e;return n._def??n.def??{}}function _(e){let n=e.typeName;if(n)return n;let r=e.type;if(r)return`Zod${r.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}`}function D(e){return e.innerType??e.schema??e.out??e.in}function Ye(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 D(e)}}function Qe(e){let n=e.type;return e.element??(typeof n=="string"?void 0:n)}function ae(e,n){let r=n.shape??e.shape;return typeof r=="function"?r():r}function z(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 Xe(e,n){return e.description??n.description}function xn(e){let n=e;for(;n;){let r=v(n),t=Xe(n,r);if(t)return t;let o=_(r);if(we(o)||o==="ZodPipe"||o==="ZodEffects"||o==="ZodTransform"){n=Ye(r,o);continue}break}}function we(e){return e==="ZodOptional"||e==="ZodNullable"||e==="ZodDefault"||e==="ZodCatch"}function R(e){let n=v(e),r=_(n);switch(r){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??z(n)[0]??"unknown");case"ZodEnum":return z(n).map(t=>String(t)).join(" | ");case"ZodOptional":{let t=D(n);return t?R(t):"unknown"}case"ZodNullable":{let t=D(n);return`${t?R(t):"unknown"} | null`}case"ZodDefault":case"ZodCatch":{let t=D(n);return t?R(t):"unknown"}case"ZodArray":{let t=Qe(n);if(!t)return"unknown[]";let o=v(t),i=_(o)==="ZodUnion",s=R(t);return`${i?`(${s})`:s}[]`}case"ZodRecord":return"{}";case"ZodObject":{let t=ae(e,n),o=Object.entries(t);return o.length===0?"{}":`{ ${o.map(([s,a])=>{let d=_(v(a));return`${d==="ZodOptional"||d==="ZodNullable"?s+"?":s}: ${R(a)}`}).join(", ")} }`}case"ZodUnion":return z(n).map(t=>R(t)).join(" | ");case"ZodIntersection":return`${R(n.left)} & ${R(n.right)}`;case"ZodPipe":case"ZodTransform":case"ZodEffects":{let t=Ye(n,r);return t?R(t):"unknown"}default:return(r??"unknown").replace("Zod","").toLowerCase()}}function $(e){let n=v(e),r=_(n),t=Xe(e,n);switch(r){case"ZodString":return{kind:"string",optional:!1,description:t};case"ZodNumber":return{kind:"number",optional:!1,description:t};case"ZodBoolean":return{kind:"boolean",optional:!1,description:t};case"ZodLiteral":{let o=n.value??z(n)[0],i=typeof o=="string"||typeof o=="number"||typeof o=="boolean"?o:String(o??"");return{kind:"literal",optional:!1,description:t,value:i}}case"ZodEnum":{let o=z(n).map(i=>String(i));return{kind:"string",optional:!1,description:t,enum:o}}case"ZodOptional":{let o=D(n),i=o?$(o):{kind:"unknown",optional:!1};return{...i,optional:!0,description:t??i.description}}case"ZodNullable":{let o=D(n),i=o?$(o):{kind:"unknown",optional:!1};return{...i,optional:!0,description:t??i.description}}case"ZodDefault":case"ZodCatch":{let o=D(n);return o?{...$(o),description:t}:{kind:"unknown",optional:!1,description:t}}case"ZodArray":{let o=Qe(n);return{kind:"array",optional:!1,description:t,items:o?$(o):{kind:"unknown",optional:!1}}}case"ZodObject":{let o=ae(e,n),i={};for(let[s,a]of Object.entries(o))i[s]=$(a);return{kind:"object",optional:!1,description:t,fields:i}}case"ZodRecord":return{kind:"unknown",optional:!1,description:t};case"ZodUnion":{let o=z(n);for(let i of o){let s=v(i);if(_(s)==="ZodObject")return{...$(i),description:t}}return{kind:"unknown",optional:!1,description:t}}case"ZodIntersection":case"ZodPipe":case"ZodTransform":case"ZodEffects":{let o=D(n);return o?{...$(o),description:t}:{kind:"unknown",optional:!1,description:t}}default:return{kind:"unknown",optional:!1,description:t}}}function wt(e,n){let r=n.toLowerCase(),t=r.indexOf(".");if(t===-1)return null;let o=r.slice(0,t),i=r.slice(t+1),s=e.find(c=>c.id===o);if(!s)return null;let a=i;a.startsWith("api.")&&(a=a.slice(4));let d=Z(s.endpointMeta,a),p=Z(s.endpointSchemas,a);return!d&&!p?null:{input:p?.input?$(p.input):null,output:p?.output?$(p.output):null,description:d?.description}}var Ce=["equals","contains","startsWith","endsWith","in"],Pn=["equals","gt","gte","lt","lte","in"],En=["equals"],Rn=["equals","before","after","between"];function en(e){let n=v(e);switch(_(n)){case"ZodOptional":case"ZodNullable":case"ZodDefault":case"ZodCatch":{let t=D(n);return t?en(t):null}case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodDate":return"date";default:return null}}function Te(e){let n=v(e),r=_(n);if(we(r)){let i=D(n);return i?Te(i):{}}if(r!=="ZodObject")return{};let t=ae(e,n),o={};for(let[i,s]of Object.entries(t)){let a=en(s);a==="string"?o[i]={type:"string",operators:Ce}:a==="number"?o[i]={type:"number",operators:Pn}:a==="boolean"?o[i]={type:"boolean",operators:En}:a==="date"&&(o[i]={type:"date",operators:Rn})}return o}function nn(e,n){for(let[r,t]of Object.entries(e))if(r.toLowerCase()===n)return[r,t]}function me(e,n,r){for(let[t,o]of Object.entries(e)){let i=[...n,t];typeof o=="function"?r.push(i.join(".")):o!==null&&typeof o=="object"&&me(o,i,r)}}function ke(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function be(e,n,r){for(let[t,o]of Object.entries(e)){let i=[...n,t];ke(o)?r.push(i.join(".")):o!==null&&typeof o=="object"&&be(o,i,r)}}function Ae(e,n){if(n.length===0)return null;let[r,...t]=n,o=Object.entries(e).find(([a])=>a.toLowerCase()===r);if(!o)return null;let[i,s]=o;if(t.length===0)return ke(s)?[i]:null;if(s!==null&&typeof s=="object"&&!ke(s)){let a=Ae(s,t);if(a!==null)return[i,...a]}return null}function tn(e,n){let r=[];r.push(`${e}({`),r.push(" webhookHooks: {");for(let i=0;i<n.length;i++){let s=" ".repeat(i+2);r.push(`${s}${n[i]}: {`)}let t=" ".repeat(n.length+2),o=t+" ";r.push(`${t}before(ctx, args) {`),r.push(`${o}return { ctx, args };`),r.push(`${t}},`),r.push(`${t}after(ctx, response) {`),r.push(`${t}},`);for(let i=n.length-1;i>=0;i--){let s=" ".repeat(i+2);r.push(`${s}},`)}return r.push(" },"),r.push("})"),r.join(`
|
|
14
|
+
`)}var In=new Set(Ge);function W(e,n){let r=n?.type??"api",t=n?.plugin;if(t!==void 0){let i=e.find(a=>a.id===t);if(!i)return In.has(t)?`This plugin (${t}) is not configured. Please add it to the Corsair instance to see its associated methods.`:W(e);if(r==="webhooks"){if(!i.webhooks)return[];let a=[];return be(i.webhooks,[],a),a.map(d=>`${i.id}.webhooks.${d}`)}if(r==="db"){let a=i.schema?.entities;return a?Object.keys(a).map(d=>`${i.id}.db.${d}.search`):[]}if(!i.endpoints)return[];let s=[];return me(i.endpoints,[],s),s.map(a=>`${i.id}.api.${a}`)}let o={};if(r==="webhooks")for(let i of e){if(!i.webhooks)continue;let s=[];be(i.webhooks,[],s),o[i.id]=s.map(a=>`${i.id}.webhooks.${a}`)}else if(r==="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=[];me(i.endpoints,[],s),o[i.id]=s.map(a=>`${i.id}.api.${a}`)}return o}function Z(e,n){if(e){for(let[r,t]of Object.entries(e))if(r.toLowerCase()===n)return t}}function Dn(e,n){let r=e.toLowerCase(),t=n.toLowerCase();if(!r.startsWith(`${t}.`)){let i=r.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 he(e,n){return typeof e=="string"?e:Array.isArray(e)?`${n}:
|
|
15
|
+
${e.join(", ")}`:`${n}:
|
|
16
|
+
`+Object.entries(e).map(([r,t])=>` ${r}: ${t.join(", ")}`).join(`
|
|
17
|
+
`)}function Ct(e,n){let r=n.toLowerCase(),t=r.indexOf(".");if(t!==-1){let o=r.slice(0,t),i=r.slice(t+1),s=e.find(a=>a.id===o);if(s){if(i.startsWith("db.")){let c=i.slice(3),l=c.lastIndexOf(".");if(l!==-1){let f=c.slice(0,l),g=c.slice(l+1),u=s.schema?.entities;if(g==="search"&&u){let h=nn(u,f);if(h){let[b,k]=h,w=Te(k),A=[`Search ${o} ${b} stored in the local database.`,"Pass limit and offset as numbers for pagination.","","filters {",` entity_id: string [${Ce.join(", ")}]`];for(let[y,m]of Object.entries(w))A.push(` ${y}?: ${m.type} [${m.operators.join(", ")}]`);return A.push("}"),A.join(`
|
|
18
|
+
`)}}}return he(W(e,{type:"db"}),"Path not found. Available db operations")}if(i.startsWith("webhooks.")){let c=i.slice(9);if(s.webhooks){let l=Ae(s.webhooks,c.split("."));if(l!==null){let f=l.join("."),g=Z(s.webhookSchemas,f.toLowerCase()),u=g?.response?R(g.response):null,h=[];return g?.description&&h.push(g.description),g?.payload&&h.push(`payload ${se(G(g.payload))}`),u&&h.push(`response: ${u}`),h.push(`usage:
|
|
19
|
+
${tn(o,l)}`),h.join(`
|
|
20
|
+
|
|
21
|
+
`)}}return he(W(e,{type:"webhooks"}),"Path not found. Available webhooks")}let a=i;a.startsWith("api.")&&(a=a.slice(4));let d=Z(s.endpointMeta,a),p=Z(s.endpointSchemas,a);if(d||p){let c=[],l=[d?.riskLevel?`[${d.riskLevel}]`:"",d?.irreversible?"[irreversible]":""].filter(Boolean).join(" "),f=[d?.description,l].filter(Boolean).join(" ");return f&&c.push(f),p?.input&&c.push(`input ${se(G(p.input))}`),p?.output&&c.push(`output ${se(G(p.output))}`),c.join(`
|
|
22
|
+
|
|
23
|
+
`)}}}return he(W(e),"Path not found. Available operations")}function Ve(e){let n=e;for(;;){let r=v(n),t=_(r);if(we(t)){let o=D(r);if(!o)return n;n=o;continue}return n}}function G(e){if(e===void 0)return{kind:"inline",type:"unknown"};let n=Ve(e),r=v(n);if(_(r)==="ZodObject"){let o=ae(n,r),i=[];for(let[s,a]of Object.entries(o)){let d=v(a),p=_(d),c=p==="ZodOptional"||p==="ZodNullable",l=Ve(a),f=xn(a);i.push({key:s,optional:c,type:R(l),...f!==void 0?{description:f}:{}})}return{kind:"object",fields:i}}return{kind:"inline",type:R(n)}}function se(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 r=Je.repeat(n+1),t=Je.repeat(n);return`{
|
|
24
|
+
${e.fields.map(i=>{let s=i.optional?`${i.key}?`:i.key,a=i.description?` // ${i.description}`:"";return`${r}${s}: ${i.type}${a}`}).join(`
|
|
25
|
+
`)}
|
|
26
|
+
${t}}`}return"unknown"}function vn(e,n){let r=W(e,{plugin:n,type:"api"});if(typeof r=="string")return{ok:!1,error:r};if(!Array.isArray(r))return{ok:!1,error:"list_operations did not return a path array \u2014 pass a configured plugin id."};let t=e.find(c=>c.id===n);if(!t)return{ok:!1,error:`Plugin "${n}" is not configured on this instance.`};let o=[];for(let c of r){let{shortPath:l,lookupKey:f}=Dn(c,n),g=Z(t.endpointMeta,f),u=Z(t.endpointSchemas,f);!g&&!u||o.push({path:c,shortPath:l,description:g?.description,riskLevel:g?.riskLevel,irreversible:g?.irreversible,input:G(u?.input),output:G(u?.output)})}o.sort((c,l)=>c.path.localeCompare(l.path));let i=[],s=W(e,{plugin:n,type:"webhooks"});if(Array.isArray(s)&&t.webhooks)for(let c of s){let f=c.toLowerCase().slice(n.length+1),g=f.startsWith(".")?f.slice(1):f;if(!g.startsWith("webhooks."))continue;let u=g.slice(9),h=Ae(t.webhooks,u.split("."));if(h===null)continue;let b=h.join("."),k=Z(t.webhookSchemas,b.toLowerCase()),w=k?.response?R(k.response):void 0;i.push({path:c,description:k?.description,payload:G(k?.payload),responseType:w,usageExample:tn(n,h)})}i.sort((c,l)=>c.path.localeCompare(l.path));let a=[],d=W(e,{plugin:n,type:"db"}),p=t.schema?.entities;if(Array.isArray(d)&&p)for(let c of d){let f=c.toLowerCase().slice(n.length+1),g=f.startsWith(".")?f.slice(1):f;if(!g.startsWith("db."))continue;let u=g.slice(3),h=u.lastIndexOf(".");if(h===-1)continue;let b=u.slice(0,h);if(u.slice(h+1)!=="search")continue;let w=nn(p,b);if(!w)continue;let[A,y]=w,m=Te(y),T=Object.entries(m).map(([P,I])=>({field:P,type:I.type,operators:I.operators}));a.push({path:c,entityName:A,filters:[{field:"entity_id",type:"string",operators:Ce},...T]})}return a.sort((c,l)=>c.path.localeCompare(l.path)),{ok:!0,data:{pluginId:n,api:o,webhooks:i,db:a}}}var ee=Symbol.for("corsair:internal");function Rt(e){let n=e.database?xe(e.database):void 0,r=n&&e.kek?Le(e.plugins,n,e.kek):oe(!!n,!!e.kek),t={plugins:e.plugins,database:n,kek:e.kek,multiTenancy:!!e.multiTenancy,approval:e.approval,connect:e.connect},o=Ne(n);if(e.multiTenancy)return Object.assign({withTenant:s=>{if(!s)throw new Error("corsair.withTenant(tenantId): tenantId must be a non-empty string");let a=ye(e.plugins,{database:n,tenantId:s,kek:e.kek,rootErrorHandlers:e.errorHandlers,approvalConfig:e.approval,connectConfig:e.connect});return Object.assign(a,{[ee]:t})},keys:r,permissions:o},{[ee]:t});let i=ye(e.plugins,{database:n,tenantId:void 0,kek:e.kek,rootErrorHandlers:e.errorHandlers,approvalConfig:e.approval,connectConfig:e.connect});return Object.assign({},i,{keys:r,permissions:o,[ee]:t})}export{N as a,B as b,j as c,M as d,ue as e,le as f,H as g,L as h,Y as i,Q as j,q as k,ie as l,_e as m,Se as n,Oe as o,cn as p,Fe as q,$e as r,We as s,bn as t,qe as u,An as v,Ge as w,wt as x,W as y,Ct as z,se as A,vn as B,ee as C,Rt as D};
|
package/dist/core.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { C as CORSAIR_INTERNAL, a as CorsairInternalConfig, D as DocSchemaFieldRow, b as DocSchemaShape, d as DocsApiEndpoint, e as DocsDbEntity, g as DocsDbFilterField, h as DocsWebhook, E as EndpointSchemaResult, I as IntrospectPluginForDocsResult, L as ListOperationsOptions, P as PluginDocsIntrospection, c as createCorsair, f as formatDocSchemaShape, i as introspectPluginForDocs } from './index-
|
|
1
|
+
export { A as AuthMissingError, C as CORSAIR_INTERNAL, a as CorsairInternalConfig, D as DocSchemaFieldRow, b as DocSchemaShape, d as DocsApiEndpoint, e as DocsDbEntity, g as DocsDbFilterField, h as DocsWebhook, E as EndpointSchemaResult, I as IntrospectPluginForDocsResult, L as ListOperationsOptions, P as PluginDocsIntrospection, R as ResolveConnectLinkResult, c as createCorsair, f as formatDocSchemaShape, i as introspectPluginForDocs, r as resolveConnectLink } from './index-Cadh5O_D.js';
|
|
2
2
|
import { CorsairDatabase } from './db.js';
|
|
3
|
-
import { O as OAuthConfig, A as AuthTypes,
|
|
4
|
-
export {
|
|
3
|
+
import { O as OAuthConfig, A as AuthTypes, f as AccountKeyManagerFor, I as IntegrationKeyManagerFor } from './index-CN2IlLdT.js';
|
|
4
|
+
export { g as AccountFieldNames, m as AllProviders, l as BASE_AUTH_FIELDS, h as BaseAuthFieldConfig, i as BaseKeyManager, e as BaseProviders, H as BeforeHookResult, o as BindEndpoints, a3 as BindWebhooks, a1 as Bivariant, p as BoundEndpointFn, q as BoundEndpointTree, a4 as BoundWebhook, B as BoundWebhookTree, c as CorsairClient, r as CorsairContext, s as CorsairEndpoint, u as CorsairErrorHandler, J as CorsairIntegration, K as CorsairKeyBuilder, L as CorsairKeyBuilderBase, d as CorsairPermissionsNamespace, a as CorsairPlugin, M as CorsairPluginContext, C as CorsairSingleTenantClient, b as CorsairTenantWrapper, a5 as CorsairWebhook, a6 as CorsairWebhookHandler, a7 as CorsairWebhookMatcher, N as EndpointHooks, Q as EndpointMetaEntry, E as EndpointPathsOf, S as EndpointRiskLevel, t as EndpointTree, F as EnforcePermissionOptions, G as EnforcePermissionResult, v as ErrorContext, w as ErrorHandler, x as ErrorHandlerAndMatchFunction, y as ErrorMatcher, j as IntegrationFieldNames, T as KeyBuilderContext, k as OAuth2IntegrationCredentials, U as PermissionMode, V as PermissionPolicy, n as PickAuth, P as PluginAuthConfig, X as PluginEndpointMeta, Y as PluginPermissionsConfig, R as RawWebhookRequest, Z as RequiredPluginEndpointMeta, _ as RequiredPluginEndpointSchemas, $ as RequiredPluginWebhookSchemas, z as RetryStrategies, D as RetryStrategy, a2 as UnionToIntersection, a0 as WebhookHooks, a8 as WebhookPathsOf, a9 as WebhookRequest, W as WebhookResponse, aa as WebhookTree } from './index-CN2IlLdT.js';
|
|
5
5
|
import 'kysely';
|
|
6
6
|
import 'zod';
|
|
7
7
|
import 'pg';
|
package/dist/core.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,
|
|
1
|
+
import{A as s,B as t,C as u,D as v,a,b,c,d,e,f,g,h,i,j,k,l,m,n,s as o,t as p,u as q,v as r}from"./chunk-W6KENKHM.js";import"./chunk-OZHME3EO.js";import"./chunk-6KMLS5U6.js";import"./chunk-QAIKSQAD.js";export{a as AuthMissingError,j as BASE_AUTH_FIELDS,u as CORSAIR_INTERNAL,l as createAccountKeyManager,v as createCorsair,k as createIntegrationKeyManager,h as decryptConfig,d as decryptDEK,f as decryptWithDEK,g as encryptConfig,c as encryptDEK,e as encryptWithDEK,q as exchangeCodeForTokens,s as formatDocSchemaShape,b as generateDEK,n as initializeAccountDEK,m as initializeIntegrationDEK,t as introspectPluginForDocs,o as logEvent,p as logEventFromContext,i as reEncryptConfig,r as resolveConnectLink};
|
package/dist/db.d.ts
CHANGED
|
@@ -97,7 +97,8 @@ type CorsairIntegrationInsert = {
|
|
|
97
97
|
created_at?: Date;
|
|
98
98
|
updated_at?: Date;
|
|
99
99
|
name: string;
|
|
100
|
-
|
|
100
|
+
/** Omit to use the database default (`{}`). */
|
|
101
|
+
config?: Record<string, unknown>;
|
|
101
102
|
dek?: string;
|
|
102
103
|
};
|
|
103
104
|
type CorsairAccountInsert = {
|
|
@@ -106,7 +107,8 @@ type CorsairAccountInsert = {
|
|
|
106
107
|
updated_at?: Date;
|
|
107
108
|
tenant_id: string;
|
|
108
109
|
integration_id: string;
|
|
109
|
-
|
|
110
|
+
/** Omit to use the database default (`{}`). */
|
|
111
|
+
config?: Record<string, unknown>;
|
|
110
112
|
dek?: string;
|
|
111
113
|
};
|
|
112
114
|
type CorsairEntityInsert = {
|
package/dist/db.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as g}from"./chunk-N2XRSSRL.js";import{a as b,b as c,c as d,d as e,e as f}from"./chunk-3USHGH6P.js";import{a}from"./chunk-
|
|
1
|
+
import{a as g}from"./chunk-N2XRSSRL.js";import{a as b,b as c,c as d,d as e,e as f}from"./chunk-3USHGH6P.js";import{a}from"./chunk-6KMLS5U6.js";import"./chunk-QAIKSQAD.js";export{c as CorsairAccountsSchema,d as CorsairEntitiesSchema,e as CorsairEventsSchema,b as CorsairIntegrationsSchema,f as CorsairPermissionsSchema,a as createCorsairDatabase,g as sql};
|
|
@@ -3,8 +3,8 @@ import { CorsairPluginSchema, PluginEntityClients } from './orm.js';
|
|
|
3
3
|
import { CorsairDatabase, CorsairDatabaseInput, CorsairPermission } from './db.js';
|
|
4
4
|
|
|
5
5
|
type AllErrors = 'RATE_LIMIT_ERROR' | 'AUTH_ERROR' | 'PERMISSION_ERROR' | 'NETWORK_ERROR' | 'TIMEOUT_ERROR' | 'SERVER_ERROR' | 'VALIDATION_ERROR' | 'NOT_FOUND_ERROR' | 'BAD_REQUEST_ERROR' | 'PARSING_ERROR' | 'DEFAULT' | (string & {});
|
|
6
|
-
declare const BaseProviders: readonly ["
|
|
7
|
-
type AllProviders = '
|
|
6
|
+
declare const BaseProviders: readonly ["airtable", "amplitude", "asana", "bitwarden", "bluesky", "box", "cal", "calendly", "cloudflare", "cursor", "discord", "dodopayments", "dropbox", "exa", "figma", "firecrawl", "fireflies", "github", "gitlab", "gmail", "googlecalendar", "googledrive", "googlesheets", "grafana", "hackernews", "hubspot", "intercom", "jira", "linear", "monday", "notion", "onedrive", "openweathermap", "oura", "outlook", "pagerduty", "posthog", "razorpay", "reddit", "resend", "sentry", "sharepoint", "slack", "spotify", "strava", "stripe", "tally", "tavily", "teams", "telegram", "todoist", "trello", "twitter", "twitterapiio", "typeform", "vapi", "xquik", "youtube", "zendesk", "zoom"];
|
|
7
|
+
type AllProviders = 'airtable' | 'amplitude' | 'asana' | 'bitwarden' | 'bluesky' | 'box' | 'cal' | 'calendly' | 'cloudflare' | 'cursor' | 'discord' | 'dodopayments' | 'dropbox' | 'exa' | 'figma' | 'firecrawl' | 'fireflies' | 'github' | 'gitlab' | 'gmail' | 'googlecalendar' | 'googledrive' | 'googlesheets' | 'grafana' | 'hackernews' | 'hubspot' | 'intercom' | 'jira' | 'linear' | 'monday' | 'notion' | 'onedrive' | 'openweathermap' | 'oura' | 'outlook' | 'pagerduty' | 'posthog' | 'razorpay' | 'reddit' | 'resend' | 'sentry' | 'sharepoint' | 'slack' | 'spotify' | 'strava' | 'stripe' | 'tally' | 'tavily' | 'teams' | 'telegram' | 'todoist' | 'trello' | 'twitter' | 'twitterapiio' | 'typeform' | 'vapi' | 'xquik' | 'youtube' | 'zendesk' | 'zoom' | (string & {});
|
|
8
8
|
type AuthTypes = 'oauth_2' | 'api_key' | 'bot_token';
|
|
9
9
|
type PickAuth<T extends AuthTypes> = T;
|
|
10
10
|
|
|
@@ -939,6 +939,21 @@ type CorsairIntegration<Plugins extends readonly CorsairPlugin[]> = {
|
|
|
939
939
|
args: unknown;
|
|
940
940
|
}) => string;
|
|
941
941
|
};
|
|
942
|
+
/**
|
|
943
|
+
* Connect link configuration for non-authenticated users.
|
|
944
|
+
* When a plugin endpoint is called but the user hasn't authenticated,
|
|
945
|
+
* Corsair generates a connect link the agent can present to the user.
|
|
946
|
+
* Only applies to plugins with an `oauthConfig`.
|
|
947
|
+
*/
|
|
948
|
+
connect?: {
|
|
949
|
+
baseUrl: string;
|
|
950
|
+
redirectUri: string;
|
|
951
|
+
onAuthMissing?: (opts: {
|
|
952
|
+
plugin: string;
|
|
953
|
+
connectUrl: string;
|
|
954
|
+
state: string;
|
|
955
|
+
}) => string;
|
|
956
|
+
};
|
|
942
957
|
};
|
|
943
958
|
|
|
944
959
|
/**
|
|
@@ -1125,4 +1140,4 @@ type CorsairSingleTenantClient<Plugins extends readonly CorsairPlugin[]> = Corsa
|
|
|
1125
1140
|
permissions: CorsairPermissionsNamespace;
|
|
1126
1141
|
};
|
|
1127
1142
|
|
|
1128
|
-
export { type RequiredPluginWebhookSchemas as $, type AuthTypes as A, type BoundWebhookTree as B, type
|
|
1143
|
+
export { type RequiredPluginWebhookSchemas as $, type AuthTypes as A, type BoundWebhookTree as B, type CorsairSingleTenantClient as C, type RetryStrategy as D, type EndpointPathsOf as E, type EnforcePermissionOptions as F, type EnforcePermissionResult as G, type BeforeHookResult as H, type IntegrationKeyManagerFor as I, type CorsairIntegration as J, type CorsairKeyBuilder as K, type CorsairKeyBuilderBase as L, type CorsairPluginContext as M, type EndpointHooks as N, type OAuthConfig as O, type PluginAuthConfig as P, type EndpointMetaEntry as Q, type RawWebhookRequest as R, type EndpointRiskLevel as S, type KeyBuilderContext as T, type PermissionMode as U, type PermissionPolicy as V, type WebhookResponse as W, type PluginEndpointMeta as X, type PluginPermissionsConfig as Y, type RequiredPluginEndpointMeta as Z, type RequiredPluginEndpointSchemas as _, type CorsairPlugin as a, type WebhookHooks as a0, type Bivariant$2 as a1, type UnionToIntersection$1 as a2, type BindWebhooks as a3, type BoundWebhook as a4, type CorsairWebhook as a5, type CorsairWebhookHandler as a6, type CorsairWebhookMatcher as a7, type WebhookPathsOf as a8, type WebhookRequest as a9, type WebhookTree as aa, type CorsairTenantWrapper as b, type CorsairClient as c, type CorsairPermissionsNamespace as d, BaseProviders as e, type AccountKeyManagerFor as f, type AccountFieldNames as g, type BaseAuthFieldConfig as h, type BaseKeyManager as i, type IntegrationFieldNames as j, type OAuth2IntegrationCredentials as k, BASE_AUTH_FIELDS as l, type AllProviders as m, type PickAuth as n, type BindEndpoints as o, type BoundEndpointFn as p, type BoundEndpointTree as q, type CorsairContext as r, type CorsairEndpoint as s, type EndpointTree as t, type CorsairErrorHandler as u, type ErrorContext as v, type ErrorHandler as w, type ErrorHandlerAndMatchFunction as x, type ErrorMatcher as y, type RetryStrategies as z };
|
|
@@ -1,6 +1,85 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { S as EndpointRiskLevel, a as CorsairPlugin, J as CorsairIntegration, b as CorsairTenantWrapper, C as CorsairSingleTenantClient } from './index-CN2IlLdT.js';
|
|
2
2
|
import { CorsairDatabase } from './db.js';
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* Error thrown when a plugin endpoint is called but the user has not authenticated
|
|
6
|
+
* with the required OAuth provider. Corsair intercepts this error and returns a
|
|
7
|
+
* connect link the agent can present to the user.
|
|
8
|
+
*/
|
|
9
|
+
declare class AuthMissingError extends Error {
|
|
10
|
+
pluginId: string;
|
|
11
|
+
constructor(pluginId: string, message?: string);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
type ResolveConnectLinkResult = {
|
|
15
|
+
/** Plugin ID extracted from the signed state. */
|
|
16
|
+
plugin: string;
|
|
17
|
+
/** Tenant ID extracted from the signed state. */
|
|
18
|
+
tenantId: string;
|
|
19
|
+
/** Human-readable provider name from the plugin's oauthConfig. */
|
|
20
|
+
providerName: string;
|
|
21
|
+
/** The full OAuth authorization URL. Redirect the user here to start the OAuth flow. */
|
|
22
|
+
oauthUrl: string;
|
|
23
|
+
/** The signed state parameter (pass to processOAuthCallback after redirect). */
|
|
24
|
+
state: string;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Resolves a connect link request on the consumer's `/connect` page.
|
|
28
|
+
*
|
|
29
|
+
* Call this when your connect page receives a `state` query parameter.
|
|
30
|
+
* It verifies the HMAC-signed state, looks up the plugin's OAuth config,
|
|
31
|
+
* and returns the full OAuth authorization URL so you just have to render
|
|
32
|
+
* a "Connect" button linking to `result.oauthUrl`.
|
|
33
|
+
*
|
|
34
|
+
* Uses the `redirectUri` from `createCorsair({ connect: { redirectUri } })`.
|
|
35
|
+
*
|
|
36
|
+
* @param corsair - The corsair instance
|
|
37
|
+
* @param state - The `state` query parameter from the connect URL
|
|
38
|
+
* @returns Plugin info and the full OAuth authorization URL
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```ts
|
|
42
|
+
* // On your /connect page handler:
|
|
43
|
+
* const { providerName, oauthUrl } = await resolveConnectLink(corsair, stateQueryParam)
|
|
44
|
+
* // Render a "Connect {providerName}" button linking to oauthUrl
|
|
45
|
+
* // After OAuth redirect, call processOAuthCallback(corsair, { code, state, redirectUri })
|
|
46
|
+
* ```
|
|
47
|
+
*/
|
|
48
|
+
declare function resolveConnectLink(corsair: unknown, state: string): Promise<ResolveConnectLinkResult>;
|
|
49
|
+
|
|
50
|
+
type FormFieldSchema = {
|
|
51
|
+
kind: 'string';
|
|
52
|
+
optional: boolean;
|
|
53
|
+
description?: string;
|
|
54
|
+
enum?: string[];
|
|
55
|
+
} | {
|
|
56
|
+
kind: 'number';
|
|
57
|
+
optional: boolean;
|
|
58
|
+
description?: string;
|
|
59
|
+
} | {
|
|
60
|
+
kind: 'boolean';
|
|
61
|
+
optional: boolean;
|
|
62
|
+
description?: string;
|
|
63
|
+
} | {
|
|
64
|
+
kind: 'literal';
|
|
65
|
+
optional: boolean;
|
|
66
|
+
description?: string;
|
|
67
|
+
value: string | number | boolean;
|
|
68
|
+
} | {
|
|
69
|
+
kind: 'object';
|
|
70
|
+
optional: boolean;
|
|
71
|
+
description?: string;
|
|
72
|
+
fields: Record<string, FormFieldSchema>;
|
|
73
|
+
} | {
|
|
74
|
+
kind: 'array';
|
|
75
|
+
optional: boolean;
|
|
76
|
+
description?: string;
|
|
77
|
+
items: FormFieldSchema;
|
|
78
|
+
} | {
|
|
79
|
+
kind: 'unknown';
|
|
80
|
+
optional: boolean;
|
|
81
|
+
description?: string;
|
|
82
|
+
};
|
|
4
83
|
/** @deprecated get_schema now returns a plain string. This type is kept for backwards compatibility. */
|
|
5
84
|
type EndpointSchemaResult = {
|
|
6
85
|
description?: string;
|
|
@@ -124,6 +203,15 @@ type CorsairInternalConfig = {
|
|
|
124
203
|
args: unknown;
|
|
125
204
|
}) => string;
|
|
126
205
|
};
|
|
206
|
+
connect?: {
|
|
207
|
+
baseUrl: string;
|
|
208
|
+
redirectUri: string;
|
|
209
|
+
onAuthMissing?: (opts: {
|
|
210
|
+
plugin: string;
|
|
211
|
+
connectUrl: string;
|
|
212
|
+
state: string;
|
|
213
|
+
}) => string;
|
|
214
|
+
};
|
|
127
215
|
};
|
|
128
216
|
/**
|
|
129
217
|
* Creates a Corsair integration with multi-tenancy enabled.
|
|
@@ -145,4 +233,4 @@ declare function createCorsair<const Plugins extends readonly CorsairPlugin[]>(c
|
|
|
145
233
|
multiTenancy?: false | undefined;
|
|
146
234
|
}): CorsairSingleTenantClient<Plugins>;
|
|
147
235
|
|
|
148
|
-
export { CORSAIR_INTERNAL as C, type DocSchemaFieldRow as D, type EndpointSchemaResult as E, type IntrospectPluginForDocsResult as I, type ListOperationsOptions as L, type PluginDocsIntrospection as P, type CorsairInternalConfig as a, type DocSchemaShape as b, createCorsair as c, type DocsApiEndpoint as d, type DocsDbEntity as e, formatDocSchemaShape as f, type DocsDbFilterField as g, type DocsWebhook as h, introspectPluginForDocs as i };
|
|
236
|
+
export { AuthMissingError as A, CORSAIR_INTERNAL as C, type DocSchemaFieldRow as D, type EndpointSchemaResult as E, type FormFieldSchema as F, type IntrospectPluginForDocsResult as I, type ListOperationsOptions as L, type PluginDocsIntrospection as P, type ResolveConnectLinkResult as R, type CorsairInternalConfig as a, type DocSchemaShape as b, createCorsair as c, type DocsApiEndpoint as d, type DocsDbEntity as e, formatDocSchemaShape as f, type DocsDbFilterField as g, type DocsWebhook as h, introspectPluginForDocs as i, resolveConnectLink as r };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { L as ListOperationsOptions } from './index-
|
|
2
|
-
export { c as createCorsair, f as formatDocSchemaShape } from './index-
|
|
3
|
-
import {
|
|
1
|
+
import { F as FormFieldSchema, L as ListOperationsOptions } from './index-Cadh5O_D.js';
|
|
2
|
+
export { A as AuthMissingError, R as ResolveConnectLinkResult, c as createCorsair, f as formatDocSchemaShape, r as resolveConnectLink } from './index-Cadh5O_D.js';
|
|
3
|
+
import { C as CorsairSingleTenantClient, a as CorsairPlugin, b as CorsairTenantWrapper, c as CorsairClient, d as CorsairPermissionsNamespace, B as BoundWebhookTree, R as RawWebhookRequest, e as BaseProviders, W as WebhookResponse } from './index-CN2IlLdT.js';
|
|
4
4
|
export { SetupCorsairOptions, setupCorsair } from './setup.js';
|
|
5
5
|
import './db.js';
|
|
6
6
|
import 'kysely';
|
|
@@ -51,6 +51,18 @@ declare function listOperations(corsair: AnyCorsairInstance, options?: ListOpera
|
|
|
51
51
|
* // "Path not found. Available operations:\n slack: slack.api.channels.list, ..."
|
|
52
52
|
*/
|
|
53
53
|
declare function getSchema(corsair: AnyCorsairInstance, path: string): string;
|
|
54
|
+
/**
|
|
55
|
+
* Returns a machine-readable, JSON-serializable form schema for a given operation path.
|
|
56
|
+
* Unlike {@link getSchema} (which returns a TypeScript-style string), this returns
|
|
57
|
+
* structured field definitions suitable for driving dynamic form UIs.
|
|
58
|
+
*
|
|
59
|
+
* Returns `null` if the path does not resolve to a known endpoint.
|
|
60
|
+
*/
|
|
61
|
+
declare function getStructuredSchema(corsair: AnyCorsairInstance, path: string): {
|
|
62
|
+
input: FormFieldSchema | null;
|
|
63
|
+
output: FormFieldSchema | null;
|
|
64
|
+
description?: string;
|
|
65
|
+
} | null;
|
|
54
66
|
|
|
55
67
|
/**
|
|
56
68
|
* The corsair instance type for permission execution.
|
|
@@ -157,4 +169,4 @@ declare function processWebhook(corsair: CorsairInstance, headers: WebhookHeader
|
|
|
157
169
|
[x: string]: string | string[] | undefined;
|
|
158
170
|
}): Promise<WebhookFilterResult>;
|
|
159
171
|
|
|
160
|
-
export { type AnyCorsairInstance, ListOperationsOptions, type PermissionExecuteResult, executePermission, getSchema, listOperations, processWebhook };
|
|
172
|
+
export { type AnyCorsairInstance, FormFieldSchema, ListOperationsOptions, type PermissionExecuteResult, executePermission, getSchema, getStructuredSchema, listOperations, processWebhook };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as A}from"./chunk-UEIITBYY.js";import{A as x,C,D as T,a as I,v as O,w as k,x as y,y as b,z as w}from"./chunk-W6KENKHM.js";import"./chunk-AAWROBCK.js";import"./chunk-OZHME3EO.js";import"./chunk-3USHGH6P.js";import"./chunk-6KMLS5U6.js";import"./chunk-QAIKSQAD.js";function h(n){let r=n[C];if(!r)throw new Error("listOperations / getSchema: invalid corsair instance. Pass the value returned by createCorsair() or corsair.withTenant().");return r.plugins}function B(n,r){let o=b(h(n),r);return typeof o=="string"?o:Array.isArray(o)?o.join(`
|
|
2
2
|
`):Object.values(o).flat().join(`
|
|
3
|
-
`)}function
|
|
3
|
+
`)}function E(n,r){return w(h(n),r)}function F(n,r){return y(h(n),r)}var $=Symbol.for("corsair:internal");function j(n,r){let o=n;for(let e of r){if(!o||typeof o!="object")return null;o=o[e]}return typeof o=="function"?o:null}function S(n){return n[$]?.database}async function _(n,r){let o=new Date().toISOString(),e=await n.permissions.find_by_token(r);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<o){let i=S(n);return i&&await i.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 t=e.tenant_id??"default",g=(n.withTenant?n.withTenant(t):n)[e.plugin];if(!g?.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 c=j(g.api,e.endpoint.split("."));if(!c)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 i=typeof e.args=="string"?JSON.parse(e.args):e.args,u=await c(i);return await n.permissions.set_completed(e.id),{plugin:e.plugin,endpoint:e.endpoint,result:u}}catch(i){let u=i instanceof Error?i.message:String(i),d=S(n);return d&&await d.db.updateTable("corsair_permissions").set({status:"failed",error:u,updated_at:new Date}).where("id","=",e.id).execute(),{plugin:e.plugin,endpoint:e.endpoint,result:null,error:u}}}function v(n){return n!==null&&typeof n=="object"&&"match"in n&&"handler"in n&&typeof n.match=="function"&&typeof n.handler=="function"}function R(n,r,o=[]){for(let[e,t]of Object.entries(n))if(v(t)){if(t.match(r))return{webhook:t,path:[...o,e]}}else if(t&&typeof t=="object"){let s=R(t,r,[...o,e]);if(s)return s}return null}function N(n){let r={};for(let[o,e]of Object.entries(n))r[o.toLowerCase()]=Array.isArray(e)?e[0]:e;return r}function L(n){let r=n["x-goog-resource-uri"],o=n["x-goog-channel-id"];if(!r||!o)return null;let e={resourceId:n["x-goog-resource-id"]||"",resourceState:n["x-goog-resource-state"]||"",resourceUri:r,channelId:o,channelExpiration:n["x-goog-channel-expiration"]||""};return r.includes("/drive/")&&(e.kind="drive#change"),{message:{data:Buffer.from(JSON.stringify(e)).toString("base64"),messageId:n["x-goog-message-number"]||""}}}async function D(n,r,o,e){let t=N(r),s=typeof o=="string"?JSON.parse(o):o;(!s||typeof s=="object"&&Object.keys(s).length===0)&&t["x-goog-resource-uri"]&&(s=L(t)||s);let c={headers:t,body:s},i=e?.tenantId||"default",u=n.withTenant?n.withTenant(i):n,d=k;for(let l of d){let p=u[l];if(!p||!p.webhooks||p.pluginWebhookMatcher&&!p.pluginWebhookMatcher(c))continue;let f=R(p.webhooks,c);if(!f)continue;let m=f.path.join("."),P={payload:s,headers:t,rawBody:typeof o=="string"?o:JSON.stringify(o)};try{let a=await f.webhook.handler(P),W=!!Object.keys(a.returnToSender||{})?.length;return{plugin:l,action:m,body:s,response:W?{...a?.returnToSender,success:!0}:{success:!0},...a.responseHeaders&&{responseHeaders:a.responseHeaders}}}catch(a){return console.error(`Error executing webhook handler for ${l}.${m}:`,a),{plugin:l,action:m,body:s,response:{success:!1,error:a instanceof Error?a.message:"Unknown error"}}}}return{plugin:null,action:null,body:null}}export{I as AuthMissingError,T as createCorsair,_ as executePermission,x as formatDocSchemaShape,E as getSchema,F as getStructuredSchema,B as listOperations,D as processWebhook,O as resolveConnectLink,A as setupCorsair};
|
package/dist/oauth.d.ts
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
type OAuthState = {
|
|
2
2
|
plugin: string;
|
|
3
3
|
tenantId: string;
|
|
4
|
+
iat: number;
|
|
4
5
|
};
|
|
5
6
|
declare function encodeOAuthState(plugin: string, tenantId: string): string;
|
|
6
|
-
declare function decodeOAuthState(state: string
|
|
7
|
+
declare function decodeOAuthState(state: string, { maxAgeMs }?: {
|
|
8
|
+
maxAgeMs?: number;
|
|
9
|
+
}): OAuthState | null;
|
|
10
|
+
|
|
7
11
|
type GenerateOAuthUrlOptions = {
|
|
8
12
|
tenantId: string;
|
|
9
13
|
redirectUri: string;
|
package/dist/oauth.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{C as x,b as C,c as O,k as p,l as m,o as f,p as _,q as A,r as y,u as b}from"./chunk-W6KENKHM.js";import{b as P}from"./chunk-AAWROBCK.js";import"./chunk-OZHME3EO.js";import"./chunk-3USHGH6P.js";import"./chunk-6KMLS5U6.js";import"./chunk-QAIKSQAD.js";import*as E from"querystring";function I(n){let e=n[x];if(!e)throw new Error("Invalid corsair instance");return e}function U(n,e){let o=n.plugins.find(a=>a.id===e);if(!o)throw new Error(`Plugin '${e}' not found`);return o}function N(n){let e=n.oauthConfig;if(!e)throw new Error(`Plugin '${n.id}' has no oauthConfig`);return e}async function R(n,e,o,a){let i=P(n),t=await i.integrations.findByName(e);if(!t)throw new Error(`Integration '${e}' not found. Run setupCorsair first.`);if(await i.accounts.findOne({tenant_id:o,integration_id:t.id}))return;let r=C(),s=await O(r,a);await i.accounts.create({tenant_id:o,integration_id:t.id,dek:s})}async function S(n,e,o){let{tenantId:a,redirectUri:i}=o,t=I(n);if(!t.database)throw new Error("No database configured on corsair instance");let u=U(t,e),r=N(u),d=await p({authType:"oauth_2",integrationName:e,kek:t.kek,database:t.database}).get_client_id();if(!d)throw new Error(`client_id not configured for '${e}'`);let g=A(f(e,a),t.kek),l={...r.authParams,client_id:d,redirect_uri:i,response_type:"code",scope:r.scopes.join(" "),state:g};return{url:`${r.authUrl}?${E.stringify(l)}`,state:g}}async function K(n,e){let{code:o,state:a,redirectUri:i}=e,t=I(n),u=y(a,t.kek);if(!u)throw new Error("Invalid or tampered state parameter");let{plugin:r,tenantId:s}=u;if(!t.database)throw new Error("No database configured on corsair instance");let d=U(t,r),g=N(d),l=p({authType:"oauth_2",integrationName:r,kek:t.kek,database:t.database}),k=await l.get_client_id(),w=await l.get_client_secret();if(!k||!w)throw new Error(`Credentials not configured for '${r}'`);await R(t.database,r,s,t.kek);let c=await b(o,k,w,g,i);if(!c.access_token)throw new Error(`No access_token returned from ${g.providerName}`);let h=m({authType:"oauth_2",integrationName:r,tenantId:s,kek:t.kek,database:t.database});return await h.set_access_token(c.access_token),c.refresh_token&&await h.set_refresh_token(c.refresh_token),c.expires_in&&await h.set_expires_at(String(Math.floor(Date.now()/1e3)+c.expires_in)),{plugin:r,tenantId:s}}export{_ as decodeOAuthState,f as encodeOAuthState,S as generateOAuthUrl,K as processOAuthCallback};
|
package/dist/orm.d.ts
CHANGED
|
@@ -15,8 +15,11 @@ type CorsairOrmTableName = keyof CorsairOrmDatabase;
|
|
|
15
15
|
/**
|
|
16
16
|
* Input type for creating a new row (without auto-generated fields).
|
|
17
17
|
*/
|
|
18
|
-
type CreateInput<T> = Omit<T, 'id' | 'created_at' | 'updated_at'> & {
|
|
18
|
+
type CreateInput<T> = Omit<T, 'id' | 'created_at' | 'updated_at' | 'config'> & {
|
|
19
19
|
id?: string;
|
|
20
|
+
config?: T extends {
|
|
21
|
+
config: infer C;
|
|
22
|
+
} ? C : never;
|
|
20
23
|
};
|
|
21
24
|
/**
|
|
22
25
|
* Input type for updating an existing row.
|
package/dist/orm.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./chunk-N2XRSSRL.js";import{b as o,c as e,d as n,e as s}from"./chunk-
|
|
1
|
+
import"./chunk-N2XRSSRL.js";import{b as o,c as e,d as n,e as s}from"./chunk-AAWROBCK.js";import"./chunk-OZHME3EO.js";import{a as r,b as t,c as i,d as a}from"./chunk-3USHGH6P.js";import"./chunk-6KMLS5U6.js";import"./chunk-QAIKSQAD.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};
|
package/dist/setup.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { a as CorsairPlugin, C as CorsairSingleTenantClient, b as CorsairTenantWrapper } from './index-CN2IlLdT.js';
|
|
2
2
|
import 'zod';
|
|
3
3
|
import './orm.js';
|
|
4
4
|
import './db.js';
|
package/dist/setup.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as o}from"./chunk-
|
|
1
|
+
import{a as o}from"./chunk-UEIITBYY.js";import"./chunk-W6KENKHM.js";import"./chunk-AAWROBCK.js";import"./chunk-OZHME3EO.js";import"./chunk-3USHGH6P.js";import"./chunk-6KMLS5U6.js";import"./chunk-QAIKSQAD.js";export{o as setupCorsair};
|
package/package.json
CHANGED
package/dist/chunk-7SONQAHW.js
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import{a as Te,b as te}from"./chunk-OZHME3EO.js";import{a as we}from"./chunk-ZGVIF3UY.js";import{createCipheriv as Ce,createDecipheriv as Pe,randomBytes as G,scrypt as ze}from"crypto";import{promisify as Ge}from"util";var xe=Ge(ze),J="aes-256-gcm",Ae=12,V=16,Je=16,U=32;function K(){return G(U).toString("base64")}async function M(e,n){let t=G(Je),o=await xe(n,t,U),r=G(Ae),i=Ce(J,o,r,{authTagLength:V}),s=Buffer.concat([i.update(e,"utf8"),i.final()]),a=i.getAuthTag();return[t.toString("base64"),r.toString("base64"),a.toString("base64"),s.toString("base64")].join(":")}async function F(e,n){let[t,o,r,i]=e.split(":");if(!t||!o||!r||!i)throw new Error("Invalid encrypted DEK format");let s=Buffer.from(t,"base64"),a=Buffer.from(o,"base64"),d=Buffer.from(r,"base64"),c=Buffer.from(i,"base64"),l=await xe(n,s,U),p=Pe(J,l,a,{authTagLength:V});return p.setAuthTag(d),Buffer.concat([p.update(c),p.final()]).toString("utf8")}function oe(e,n){let t=Buffer.from(n,"base64"),o=G(Ae),r=Ce(J,t,o,{authTagLength:V}),i=Buffer.concat([r.update(e,"utf8"),r.final()]),s=r.getAuthTag();return[o.toString("base64"),s.toString("base64"),i.toString("base64")].join(":")}function re(e,n){let[t,o,r]=e.split(":");if(!t||!o||!r)throw new Error("Invalid encrypted data format");let i=Buffer.from(n,"base64"),s=Buffer.from(t,"base64"),a=Buffer.from(o,"base64"),d=Buffer.from(r,"base64"),c=Pe(J,i,s,{authTagLength:V});return c.setAuthTag(a),Buffer.concat([c.update(d),c.final()]).toString("utf8")}function j(e,n){let t={};for(let[o,r]of Object.entries(e))t[o]=oe(r,n);return t}function S(e,n){let t={};for(let[o,r]of Object.entries(e))t[o]=re(r,n);return t}function q(e,n,t){let o=S(e,n);return j(o,t)}function Y(e,n){let t=[];e||t.push("database"),n||t.push("kek");let o={};return new Proxy(o,{get(r,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.
|
|
2
|
-
|
|
3
|
-
To generate a KEK, run: openssl rand -base64 ${U}`)}})}var z={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"]}};function Ee(e,n,t){let o={};for(let r of t)o[`get_${r}`]=async()=>(await e())[r]??null,o[`set_${r}`]=async i=>{let s=[null,void 0,""].includes(i)?null:i;await n({[r]:s})};return o}var ie=e=>{if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return e};function Q(e){let{authType:n,integrationName:t,kek:o,database:r,extraIntegrationFields:i=[]}=e,s=[...z[n].integration,...i],a=null,d={kek:o,integrationName:t,getIntegration:async()=>{if(a)return a;let u=await r.db.selectFrom("corsair_integrations").selectAll().where("name","=",t).executeTakeFirst();if(!u)throw new Error(`Integration "${t}" not found. Make sure to create the integration first.`);return a={id:u.id,config:ie(u.config),dek:u.dek??null},a},updateIntegration:async u=>{let y=await d.getIntegration();await r.db.updateTable("corsair_integrations").set({...u.config!==void 0?{config:u.config}:{},...u.dek!==void 0?{dek:u.dek}:{},updated_at:new Date}).where("id","=",y.id).execute(),a=null}},c=null,l=async()=>{if(c)return c;let u=await d.getIntegration();if(!u.dek)throw new Error(`No DEK found for integration "${t}". Initialize the integration first.`);return c=await F(u.dek,o),c},p=async()=>{let u=await d.getIntegration(),y=await l(),m=u.config;return!m||Object.keys(m).length===0?{}:S(m,y)};return{get_dek:l,issue_new_dek:async()=>{let u=await d.getIntegration(),y=K(),m={};if(u.dek){let x=await F(u.dek,o),w=u.config;w&&Object.keys(w).length>0&&(m=q(w,x,y))}let k=await M(y,o);return await d.updateIntegration({config:m,dek:k}),c=y,y},...Ee(p,async u=>{let y=await l(),m;try{m=await p()}catch(w){console.error(`[corsair] Failed to decrypt config for integration "${t}", starting fresh:`,w),m={}}let k={...m};for(let[w,f]of Object.entries(u))f===null?delete k[w]:k[w]=f;let x=j(k,y);await d.updateIntegration({config:x})},s)}}function X(e){let{authType:n,integrationName:t,tenantId:o,kek:r,database:i,extraAccountFields:s=[]}=e,a=[...z[n].account,...s],d=null,c=null,l=async()=>{if(c)return c;let f=await i.db.selectFrom("corsair_integrations").selectAll().where("name","=",t).executeTakeFirst();if(!f)throw new Error(`Integration "${t}" not found. Make sure to create the integration first.`);return c={id:f.id,config:ie(f.config),dek:f.dek??null},c},p={kek:r,integrationName:t,tenantId:o,getIntegration:l,getAccount:async()=>{if(d)return d;let f=await l(),b=await i.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",o).where("integration_id","=",f.id).executeTakeFirst();if(!b)throw new Error(`Account not found for tenant "${o}" and integration "${t}". Make sure to create the account first.`);return d={id:b.id,config:ie(b.config),dek:b.dek??null},d},updateAccount:async f=>{let b=await p.getAccount();await i.db.updateTable("corsair_accounts").set({...f.config!==void 0?{config:f.config}:{},...f.dek!==void 0?{dek:f.dek}:{},updated_at:new Date}).where("id","=",b.id).execute(),d=null}},h=null,g=null,u=async()=>{if(h)return h;let f=await p.getAccount();if(!f.dek)throw new Error(`No DEK found for account (tenant: "${o}", integration: "${t}"). Initialize the account first.`);return h=await F(f.dek,r),h},y=async()=>{if(g)return g;let f=await p.getIntegration();if(!f.dek)throw new Error(`No DEK found for integration "${t}". Initialize the integration first.`);return g=await F(f.dek,r),g},m=async()=>{let f=await p.getAccount(),b=await u(),T=f.config;return!T||Object.keys(T).length===0?{}:S(T,b)},k=async()=>{let f=await p.getIntegration(),b=await y(),T=f.config;return!T||Object.keys(T).length===0?{}:S(T,b)},w={get_dek:u,issue_new_dek:async()=>{let f=await p.getAccount(),b=K(),T={};if(f.dek){let C=await F(f.dek,r),A=f.config;A&&Object.keys(A).length>0&&(T=q(A,C,b))}let D=await M(b,r);return await p.updateAccount({config:T,dek:D}),h=b,b},...Ee(m,async f=>{let b=await u(),T;try{T=await m()}catch(A){console.error(`[corsair] Failed to decrypt config for account (tenant: "${o}", integration: "${t}"), starting fresh:`,A),T={}}let D={...T};for(let[A,E]of Object.entries(f))E===null?delete D[A]:D[A]=E;let C=j(D,b);await p.updateAccount({config:C})},a)};return n==="oauth_2"&&(w.get_integration_credentials=async()=>{let f=await k();return{client_id:f.client_id||null,client_secret:f.client_secret||null,redirect_url:f.redirect_url??null}}),w}async function Re(e,n,t){let o=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!o)throw new Error(`Integration "${n}" not found.`);let r=K(),i=await M(r,t);return await e.db.updateTable("corsair_integrations").set({dek:i,updated_at:new Date}).where("id","=",o.id).execute(),r}async function De(e,n,t,o){let r=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!r)throw new Error(`Integration "${n}" not found.`);let i=await e.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",t).where("integration_id","=",r.id).executeTakeFirst();if(!i)throw new Error(`Account not found for tenant "${t}" and integration "${n}".`);let s=K(),a=await M(s,o);return await e.db.updateTable("corsair_accounts").set({dek:a,updated_at:new Date}).where("id","=",i.id).execute(),s}var Ve=async(e,n)=>(console.error(`[corsair:${n.pluginId}:${n.operation}]`,{error:e.message,input:n.input}),{maxRetries:0});async function Ie(e,n,t,o,r){let i={pluginId:n,operation:t,input:o,originalError:e},s=Object.keys(r).find(c=>r[c]?.match(e,i));return await(r[s||"DEFAULT"]?.handler||Ve)(e,i)}import{randomBytes as Ye}from"crypto";import{v4 as Qe}from"uuid";var Xe={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 en(e,n,t){return t!==void 0?t:Xe[n][e]}function ve(e){let n=/(\d+)(d|h|m|s)/g,t=0,o;for(;(o=n.exec(e))!==null;){let r=parseInt(o[1],10);switch(o[2]){case"d":t+=r*864e5;break;case"h":t+=r*36e5;break;case"m":t+=r*6e4;break;case"s":t+=r*1e3;break}}return t>0?t:600*1e3}function $e(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 _e(e,n,t){let o=Date.now()+t;for(;Date.now()<o;){let r=await e.db.selectFrom("corsair_permissions").select(["id","status"]).where("id","=",n).executeTakeFirst();if(!r)return{result:"blocked",reason:"pending"};if(r.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(r.status==="denied")return{result:"blocked",reason:"denied"};if(r.status==="expired"||r.status==="failed")return{result:"blocked",reason:"timeout"};await new Promise(i=>setTimeout(i,500))}return{result:"blocked",reason:"timeout"}}async function Fe(e){let n=en(e.riskLevel,e.mode,e.override);if(n==="allow")return{result:"allow"};let t=e.meta?.irreversible?" (irreversible)":"",o=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}'.`,`
|
|
4
|
-
Action: ${o}`,`
|
|
5
|
-
To allow this, update the permission mode or add an override in your corsair config.`),{result:"blocked",reason:"policy"};let r=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","=",r).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 u=e.db,y=a.id;return{result:"allow",onComplete:async()=>{await u.db.updateTable("corsair_permissions").set({status:"completed",updated_at:new Date}).where("id","=",y).execute()}}}return a.status==="executing"?{result:"allow"}:(console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 approval already pending.`,`
|
|
6
|
-
Action: ${o}`,`
|
|
7
|
-
Permission ID: ${a.id}`,`
|
|
8
|
-
Use the token to approve or deny this request.`),(typeof e.approvalMode=="function"?e.approvalMode():e.approvalMode)==="synchronous"?_e(e.db,a.id,e.timeoutMs??600*1e3):{result:"blocked",reason:"pending",id:a.id,token:a.token})}let d=Qe(),c=Ye(32).toString("hex"),l=e.timeoutMs??600*1e3,p=new Date(Date.now()+l).toISOString();return await e.db.db.insertInto("corsair_permissions").values({id:d,created_at:new Date,updated_at:new Date,token:c,plugin:e.pluginId,endpoint:e.endpointPath,args:r,tenant_id:s,status:"pending",expires_at:p}).execute(),console.log(`[corsair/${e.pluginId}] '${e.endpointPath}' blocked \u2014 approval required.`,`
|
|
9
|
-
Action: ${o}`,`
|
|
10
|
-
Permission ID: ${d}`,`
|
|
11
|
-
Permission token: ${c}`,`
|
|
12
|
-
Expires at: ${p}`,`
|
|
13
|
-
Use the token to approve or deny this request.`),(typeof e.approvalMode=="function"?e.approvalMode():e.approvalMode)==="synchronous"?_e(e.db,d,l):{result:"blocked",reason:"pending",id:d,token:c}}function nn(e){return typeof e=="function"}function se({endpoints:e,hooks:n,ctx:t,tree:o,pluginId:r,errorHandlers:i,currentPath:s=[],keyBuilder:a,permissionsConfig:d,endpointMeta:c,database:l,approvalConfig:p,tenantId:h}){for(let[g,u]of Object.entries(e)){let y=n?.[g];if(nn(u)){let m=y,k=[...s,g].join("."),x=async(w={})=>{let f;if(d){let E=c?.[k],{result:B,reason:I,onComplete:H,token:_,id:O}=await Fe({pluginId:r,endpointPath:k,args:w,mode:d.mode,override:d.overrides?.[k],riskLevel:E?.riskLevel??"write",meta:E,db:l,timeoutMs:p?ve(p.timeout):void 0,tenantId:h,approvalMode:p?.mode});if(B==="blocked"){let P;throw I==="denied"?P=`Action '${k}' was denied by the user. Await further instructions before proceeding.`:I==="policy"?P=`Action '${k}' is blocked by the permission policy. Update the corsair config to allow it.`:I==="timeout"?P=`Action '${k}' timed out waiting for approval.`:p?.formatAsyncMessage&&_&&O?P=p.formatAsyncMessage({token:_,id:O,plugin:r,endpoint:k,args:w}):P=`Action '${k}' requires user approval before it can run.`,new Error(P)}f=H}let b=async(E,B,I)=>{try{return await u(B,I)}catch(H){if(H instanceof Error){let _=await Ie(H,r,k,typeof I=="object"&&I!==null?I:{args:I},i);if(E<(_.maxRetries||0)){let O=E+1;console.log(`Retrying (${O} / ${_.maxRetries})...`);let P;if(_.headersRetryAfterMs)P=_.headersRetryAfterMs;else switch(_.retryStrategy){case"exponential_backoff":P=Math.pow(2,O-1)*1e3;break;case"exponential_backoff_jitter":let ne=Math.pow(2,O-1)*1e3,qe=(Math.random()-.5)*1e3;P=Math.max(0,ne+qe);break;case"linear_1s":P=1e3;break;case"linear_2s":P=2e3;break;case"linear_3s":P=3e3;break;case"linear_4s":P=4e3;break;default:P=1e3;break}await new Promise(ne=>setTimeout(ne,P)),await b(O,B,I),console.log(`[corsair:${r}:${k}] Retry strategy:`,_)}}throw H}},T=a?await a(t,"endpoint"):void 0;if(!m?.before&&!m?.after){let E=await b(0,{...t,key:T},w);return await f?.(),E}let D={...t,key:T},C=m.before?await m.before(D,w):{ctx:D,args:w,continue:!0,passToAfter:void 0};if(C.continue===!1)return;let A=await b(0,C.ctx,C.args);return await m.after?.(C.ctx,A,C.passToAfter),await f?.(),A};o[g]=x}else if(u&&typeof u=="object"){let m={};se({endpoints:u,hooks:y,ctx:t,tree:m,pluginId:r,errorHandlers:i,currentPath:[...s,g],keyBuilder:a,permissionsConfig:d,endpointMeta:c,database:l,approvalConfig:p,tenantId:h}),o[g]=m}}}function tn(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function ae({webhooks:e,hooks:n,ctx:t,webhooksTree:o,keyBuilder:r}){for(let[i,s]of Object.entries(e)){let a=n?.[i];if(tn(s)){let d=a,c=async l=>{let p=(g,u)=>s.handler(g,u),h=r?await r(t,"webhook"):void 0;return!d?.before&&!d?.after?p({...t,key:h},l):(async()=>{let g={...t,key:h},u=d.before?await d.before(g,l):{ctx:g,args:l,continue:!0,passToAfter:void 0};if(u.continue===!1)return;let y=await p(u.ctx,u.args);return y?.success===!0&&await d.after?.(u.ctx,y,u.passToAfter),y})()};o[i]={match:s.match,handler:c}}else if(s&&typeof s=="object"){let d={};ae({webhooks:s,hooks:a,ctx:t,webhooksTree:d,keyBuilder:r}),o[i]=d}}}function on(e,n,t){let o=null;return async()=>{if(o)return o;if(!e)throw new Error("Database not configured");let r=await e.db.selectFrom("corsair_integrations").selectAll().where("name","=",n).executeTakeFirst();if(!r)throw new Error(`Integration "${n}" not found. Make sure to create the integration first.`);let i=await e.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",t).where("integration_id","=",r.id).executeTakeFirst();if(!i)throw new Error(`Account not found for tenant "${t}" and integration "${n}". Make sure to create the account first.`);return o=i.id,o}}function rn(e,n,t,o,r){return e?te(e.db,n,t,o,r):{findByEntityId: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 ce(e,n){let{database:t,tenantId:o,kek:r,rootErrorHandlers:i,approvalConfig:s}=n,a={},d={};for(let c of e)a[c.id]={},d[c.id]={};for(let c of e){let l=c.schema,p=o??"default",h=on(t,c.id,p);if(l?.entities){let C={};for(let[A,E]of Object.entries(l.entities)){let B=t?te(t.db,h,A,l.version,E):rn(void 0,h,A,l.version,E);C[A]=B}d[c.id].db=C,a[c.id].db=C}let g=c.options,u=c.authConfig,y;if(t&&r&&g?.authType){let C=u?.[g.authType]?.account??[];y=X({authType:g.authType,integrationName:c.id,tenantId:p,kek:r,database:t,extraAccountFields:C}),a[c.id].keys=y}let m={database:t,db:d[c.id]?.db??{},$getAccountId:h,...c.options?{options:c.options}:{},...y?{keys:y,authType:g?.authType}:{},...o?{tenantId:o}:{}},k=c.endpoints??{},x=c.hooks,w={...i,...c.errorHandlers},f={},b=c.options?.permissions;se({endpoints:k,hooks:x,ctx:m,tree:f,pluginId:c.id,errorHandlers:w,currentPath:[],keyBuilder:c.keyBuilder,permissionsConfig:b,endpointMeta:c.endpointMeta,database:t,approvalConfig:s,tenantId:o}),Object.keys(f).length>0&&(a[c.id].api=f),m.endpoints=f;let T=c.webhooks??{},D=c.webhookHooks;if(Object.keys(T).length>0){let C={};ae({webhooks:T,hooks:D,ctx:m,webhooksTree:C,keyBuilder:c.keyBuilder}),a[c.id].webhooks=C,c.pluginWebhookMatcher&&(a[c.id].pluginWebhookMatcher=c.pluginWebhookMatcher)}}return a}function Oe(e,n,t){let o={};for(let r of e){let i=r.options,s=r.authConfig;if(i?.authType){let a=s?.[i.authType]?.integration??[],d=Q({authType:i.authType,integrationName:r.id,kek:t,database:n,extraIntegrationFields:a});o[r.id]=d}}return o}async function Ke(e,n,t,o,r="pending"){if(!e)return null;try{let i=Te(),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:o,status:r}).execute(),i}catch(i){return console.warn("Failed to log event:",i),null}}async function sn(e,n,t,o="pending"){try{let r=await e.$getAccountId();return Ke(e.database,r,n,t,o)}catch(r){return console.warn("Failed to log event:",r),null}}import*as Me from"https";import*as Se from"querystring";function Ze(e,n,t,o,r){let i=new URL(o.tokenUrl),s=o.tokenAuthMethod==="basic";return new Promise((a,d)=>{let c={code:e.trim(),redirect_uri:r,grant_type:"authorization_code"};s||(c.client_id=n,c.client_secret=t);let l=Se.stringify(c),p={"Content-Type":"application/x-www-form-urlencoded","Content-Length":Buffer.byteLength(l).toString()};s&&(p.Authorization=`Basic ${Buffer.from(`${n}:${t}`).toString("base64")}`);let h=Me.request({hostname:i.hostname,...i.port?{port:Number(i.port)}:{},path:i.pathname+i.search,method:"POST",headers:p},g=>{let u="";g.on("data",y=>{u+=y}),g.on("end",()=>{if(g.statusCode!==200){d(new Error(`Token exchange failed (${g.statusCode}): ${u}`));return}try{a(JSON.parse(u))}catch{d(new Error(`Token endpoint returned non-JSON response: ${u}`))}})});h.on("error",g=>d(new Error(`Request failed: ${g.message}`))),h.write(l),h.end()})}var Ne=["ably","airtable","amplitude","asana","bitwarden","box","cal","calendly","cloudflare","cursor","discord","dodopayments","dropbox","exa","figma","firecrawl","fireflies","github","gitlab","gmail","googlecalendar","googledrive","googlesheets","hackernews","hubspot","intercom","jira","linear","monday","notion","onedrive","openweathermap","oura","outlook","pagerduty","posthog","razorpay","reddit","resend","sentry","sharepoint","slack","spotify","strava","stripe","tally","tavily","teams","telegram","todoist","trello","twitter","twitterapiio","typeform","vapi","xquik","youtube","zoom"];var Be=" ";function v(e){let n=e;return n._def??n.def??{}}function $(e){let n=e.typeName;if(n)return n;let t=e.type;if(t)return`Zod${t.split("_").map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join("")}`}function Z(e){return e.innerType??e.schema??e.out??e.in}function Le(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 Z(e)}}function an(e){let n=e.type;return e.element??(typeof n=="string"?void 0:n)}function fe(e,n){let t=n.shape??e.shape;return typeof t=="function"?t():t}function de(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 cn(e,n){return e.description??n.description}function dn(e){let n=e;for(;n;){let t=v(n),o=cn(n,t);if(o)return o;let r=$(t);if(ye(r)||r==="ZodPipe"||r==="ZodEffects"||r==="ZodTransform"){n=Le(t,r);continue}break}}function ye(e){return e==="ZodOptional"||e==="ZodNullable"||e==="ZodDefault"||e==="ZodCatch"}function R(e){let n=v(e),t=$(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??de(n)[0]??"unknown");case"ZodEnum":return de(n).map(o=>String(o)).join(" | ");case"ZodOptional":{let o=Z(n);return o?R(o):"unknown"}case"ZodNullable":{let o=Z(n);return`${o?R(o):"unknown"} | null`}case"ZodDefault":case"ZodCatch":{let o=Z(n);return o?R(o):"unknown"}case"ZodArray":{let o=an(n);if(!o)return"unknown[]";let r=v(o),i=$(r)==="ZodUnion",s=R(o);return`${i?`(${s})`:s}[]`}case"ZodRecord":return"{}";case"ZodObject":{let o=fe(e,n),r=Object.entries(o);return r.length===0?"{}":`{ ${r.map(([s,a])=>{let d=$(v(a));return`${d==="ZodOptional"||d==="ZodNullable"?s+"?":s}: ${R(a)}`}).join(", ")} }`}case"ZodUnion":return de(n).map(o=>R(o)).join(" | ");case"ZodIntersection":return`${R(n.left)} & ${R(n.right)}`;case"ZodPipe":case"ZodTransform":case"ZodEffects":{let o=Le(n,t);return o?R(o):"unknown"}default:return(t??"unknown").replace("Zod","").toLowerCase()}}var he=["equals","contains","startsWith","endsWith","in"],un=["equals","gt","gte","lt","lte","in"],ln=["equals"],pn=["equals","before","after","between"];function We(e){let n=v(e);switch($(n)){case"ZodOptional":case"ZodNullable":case"ZodDefault":case"ZodCatch":{let o=Z(n);return o?We(o):null}case"ZodString":return"string";case"ZodNumber":return"number";case"ZodBoolean":return"boolean";case"ZodDate":return"date";default:return null}}function me(e){let n=v(e),t=$(n);if(ye(t)){let i=Z(n);return i?me(i):{}}if(t!=="ZodObject")return{};let o=fe(e,n),r={};for(let[i,s]of Object.entries(o)){let a=We(s);a==="string"?r[i]={type:"string",operators:he}:a==="number"?r[i]={type:"number",operators:un}:a==="boolean"?r[i]={type:"boolean",operators:ln}:a==="date"&&(r[i]={type:"date",operators:pn})}return r}function He(e,n){for(let[t,o]of Object.entries(e))if(t.toLowerCase()===n)return[t,o]}function le(e,n,t){for(let[o,r]of Object.entries(e)){let i=[...n,o];typeof r=="function"?t.push(i.join(".")):r!==null&&typeof r=="object"&&le(r,i,t)}}function pe(e){return e!==null&&typeof e=="object"&&"match"in e&&"handler"in e&&typeof e.match=="function"&&typeof e.handler=="function"}function ge(e,n,t){for(let[o,r]of Object.entries(e)){let i=[...n,o];pe(r)?t.push(i.join(".")):r!==null&&typeof r=="object"&&ge(r,i,t)}}function ke(e,n){if(n.length===0)return null;let[t,...o]=n,r=Object.entries(e).find(([a])=>a.toLowerCase()===t);if(!r)return null;let[i,s]=r;if(o.length===0)return pe(s)?[i]:null;if(s!==null&&typeof s=="object"&&!pe(s)){let a=ke(s,o);if(a!==null)return[i,...a]}return null}function Ue(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 o=" ".repeat(n.length+2),r=o+" ";t.push(`${o}before(ctx, args) {`),t.push(`${r}return { ctx, args };`),t.push(`${o}},`),t.push(`${o}after(ctx, response) {`),t.push(`${o}},`);for(let i=n.length-1;i>=0;i--){let s=" ".repeat(i+2);t.push(`${s}},`)}return t.push(" },"),t.push("})"),t.join(`
|
|
14
|
-
`)}var gn=new Set(Ne);function N(e,n){let t=n?.type??"api",o=n?.plugin;if(o!==void 0){let i=e.find(a=>a.id===o);if(!i)return gn.has(o)?`This plugin (${o}) is not configured. Please add it to the Corsair instance to see its associated methods.`:N(e);if(t==="webhooks"){if(!i.webhooks)return[];let a=[];return ge(i.webhooks,[],a),a.map(d=>`${i.id}.webhooks.${d}`)}if(t==="db"){let a=i.schema?.entities;return a?Object.keys(a).map(d=>`${i.id}.db.${d}.search`):[]}if(!i.endpoints)return[];let s=[];return le(i.endpoints,[],s),s.map(a=>`${i.id}.api.${a}`)}let r={};if(t==="webhooks")for(let i of e){if(!i.webhooks)continue;let s=[];ge(i.webhooks,[],s),r[i.id]=s.map(a=>`${i.id}.webhooks.${a}`)}else if(t==="db")for(let i of e){let s=i.schema?.entities;s&&(r[i.id]=Object.keys(s).map(a=>`${i.id}.db.${a}.search`))}else for(let i of e){if(!i.endpoints)continue;let s=[];le(i.endpoints,[],s),r[i.id]=s.map(a=>`${i.id}.api.${a}`)}return r}function L(e,n){if(e){for(let[t,o]of Object.entries(e))if(t.toLowerCase()===n)return o}}function fn(e,n){let t=e.toLowerCase(),o=n.toLowerCase();if(!t.startsWith(`${o}.`)){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 r=e.slice(n.length+1);return r.toLowerCase().startsWith("api.")&&(r=r.slice(4)),{shortPath:r,lookupKey:r.toLowerCase()}}function ue(e,n){return typeof e=="string"?e:Array.isArray(e)?`${n}:
|
|
15
|
-
${e.join(", ")}`:`${n}:
|
|
16
|
-
`+Object.entries(e).map(([t,o])=>` ${t}: ${o.join(", ")}`).join(`
|
|
17
|
-
`)}function Yn(e,n){let t=n.toLowerCase(),o=t.indexOf(".");if(o!==-1){let r=t.slice(0,o),i=t.slice(o+1),s=e.find(a=>a.id===r);if(s){if(i.startsWith("db.")){let l=i.slice(3),p=l.lastIndexOf(".");if(p!==-1){let h=l.slice(0,p),g=l.slice(p+1),u=s.schema?.entities;if(g==="search"&&u){let y=He(u,h);if(y){let[m,k]=y,x=me(k),w=[`Search ${r} ${m} stored in the local database.`,"Pass limit and offset as numbers for pagination.","","filters {",` entity_id: string [${he.join(", ")}]`];for(let[f,b]of Object.entries(x))w.push(` ${f}?: ${b.type} [${b.operators.join(", ")}]`);return w.push("}"),w.join(`
|
|
18
|
-
`)}}}return ue(N(e,{type:"db"}),"Path not found. Available db operations")}if(i.startsWith("webhooks.")){let l=i.slice(9);if(s.webhooks){let p=ke(s.webhooks,l.split("."));if(p!==null){let h=p.join("."),g=L(s.webhookSchemas,h.toLowerCase()),u=g?.response?R(g.response):null,y=[];return g?.description&&y.push(g.description),g?.payload&&y.push(`payload ${ee(W(g.payload))}`),u&&y.push(`response: ${u}`),y.push(`usage:
|
|
19
|
-
${Ue(r,p)}`),y.join(`
|
|
20
|
-
|
|
21
|
-
`)}}return ue(N(e,{type:"webhooks"}),"Path not found. Available webhooks")}let a=i;a.startsWith("api.")&&(a=a.slice(4));let d=L(s.endpointMeta,a),c=L(s.endpointSchemas,a);if(d||c){let l=[],p=[d?.riskLevel?`[${d.riskLevel}]`:"",d?.irreversible?"[irreversible]":""].filter(Boolean).join(" "),h=[d?.description,p].filter(Boolean).join(" ");return h&&l.push(h),c?.input&&l.push(`input ${ee(W(c.input))}`),c?.output&&l.push(`output ${ee(W(c.output))}`),l.join(`
|
|
22
|
-
|
|
23
|
-
`)}}}return ue(N(e),"Path not found. Available operations")}function je(e){let n=e;for(;;){let t=v(n),o=$(t);if(ye(o)){let r=Z(t);if(!r)return n;n=r;continue}return n}}function W(e){if(e===void 0)return{kind:"inline",type:"unknown"};let n=je(e),t=v(n);if($(t)==="ZodObject"){let r=fe(n,t),i=[];for(let[s,a]of Object.entries(r)){let d=v(a),c=$(d),l=c==="ZodOptional"||c==="ZodNullable",p=je(a),h=dn(a);i.push({key:s,optional:l,type:R(p),...h!==void 0?{description:h}:{}})}return{kind:"object",fields:i}}return{kind:"inline",type:R(n)}}function ee(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=Be.repeat(n+1),o=Be.repeat(n);return`{
|
|
24
|
-
${e.fields.map(i=>{let s=i.optional?`${i.key}?`:i.key,a=i.description?` // ${i.description}`:"";return`${t}${s}: ${i.type}${a}`}).join(`
|
|
25
|
-
`)}
|
|
26
|
-
${o}}`}return"unknown"}function yn(e,n){let t=N(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 o=e.find(l=>l.id===n);if(!o)return{ok:!1,error:`Plugin "${n}" is not configured on this instance.`};let r=[];for(let l of t){let{shortPath:p,lookupKey:h}=fn(l,n),g=L(o.endpointMeta,h),u=L(o.endpointSchemas,h);!g&&!u||r.push({path:l,shortPath:p,description:g?.description,riskLevel:g?.riskLevel,irreversible:g?.irreversible,input:W(u?.input),output:W(u?.output)})}r.sort((l,p)=>l.path.localeCompare(p.path));let i=[],s=N(e,{plugin:n,type:"webhooks"});if(Array.isArray(s)&&o.webhooks)for(let l of s){let h=l.toLowerCase().slice(n.length+1),g=h.startsWith(".")?h.slice(1):h;if(!g.startsWith("webhooks."))continue;let u=g.slice(9),y=ke(o.webhooks,u.split("."));if(y===null)continue;let m=y.join("."),k=L(o.webhookSchemas,m.toLowerCase()),x=k?.response?R(k.response):void 0;i.push({path:l,description:k?.description,payload:W(k?.payload),responseType:x,usageExample:Ue(n,y)})}i.sort((l,p)=>l.path.localeCompare(p.path));let a=[],d=N(e,{plugin:n,type:"db"}),c=o.schema?.entities;if(Array.isArray(d)&&c)for(let l of d){let h=l.toLowerCase().slice(n.length+1),g=h.startsWith(".")?h.slice(1):h;if(!g.startsWith("db."))continue;let u=g.slice(3),y=u.lastIndexOf(".");if(y===-1)continue;let m=u.slice(0,y);if(u.slice(y+1)!=="search")continue;let x=He(c,m);if(!x)continue;let[w,f]=x,b=me(f),T=Object.entries(b).map(([D,C])=>({field:D,type:C.type,operators:C.operators}));a.push({path:l,entityName:w,filters:[{field:"entity_id",type:"string",operators:he},...T]})}return a.sort((l,p)=>l.path.localeCompare(p.path)),{ok:!0,data:{pluginId:n,api:r,webhooks:i,db:a}}}var be=Symbol.for("corsair:internal");function ot(e){let n=e.database?we(e.database):void 0,t=n&&e.kek?Oe(e.plugins,n,e.kek):Y(!!n,!!e.kek),o={plugins:e.plugins,database:n,kek:e.kek,multiTenancy:!!e.multiTenancy,approval:e.approval},r=$e(n);if(e.multiTenancy)return Object.assign({withTenant:s=>{if(!s)throw new Error("corsair.withTenant(tenantId): tenantId must be a non-empty string");let a=ce(e.plugins,{database:n,tenantId:s,kek:e.kek,rootErrorHandlers:e.errorHandlers,approvalConfig:e.approval});return Object.assign(a,{[be]:o})},keys:t,permissions:r},{[be]:o});let i=ce(e.plugins,{database:n,tenantId:void 0,kek:e.kek,rootErrorHandlers:e.errorHandlers,approvalConfig:e.approval});return Object.assign({},i,{keys:t,permissions:r,[be]:o})}export{K as a,M as b,F as c,oe as d,re as e,j as f,S as g,q as h,z as i,Q as j,X as k,Re as l,De as m,Ke as n,sn as o,Ze as p,Ne as q,N as r,Yn as s,ee as t,yn as u,be as v,ot as w};
|
package/dist/chunk-UBM25HVI.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as h,b}from"./chunk-OZHME3EO.js";import{a as E,b as I,c as x,d as D}from"./chunk-3USHGH6P.js";var k={corsair_integrations:E,corsair_accounts:I,corsair_entities:x,corsair_events:D};function F(t){return k[t]}function _(t){if(typeof t=="string")try{return JSON.parse(t)}catch{return t}return t}function d(t){if(!t)throw new Error("Corsair database is not configured. Pass `database` to createCorsair(...) to enable ORM.")}function g(t){if(!t)return[];let n=[];for(let r in t){let e=r,i=t[e];if(i!==void 0)if(typeof i=="object"&&i!==null&&!Array.isArray(i)&&!(i instanceof Date)){let s=i;"in"in s&&Array.isArray(s.in)?n.push({field:e,operator:"in",value:s.in}):"like"in s&&typeof s.like=="string"&&n.push({field:e,operator:"like",value:s.like})}else n.push({field:e,value:i})}return n}function p(t,n){if(!n?.length)return t;let r=t;for(let e of n){let i=e.operator??"=";r=r.where(e.field,i,e.value)}return r}function S(t){return typeof t=="number"?t:typeof t=="bigint"?Number(t):Number.parseInt(String(t??0),10)}function T(t,n){let r=F(n),e=()=>(d(t),t),i=()=>e().db.selectFrom(n),s=()=>e().db.insertInto(n),u=()=>e().db.updateTable(n),c=()=>e().db.deleteFrom(n);function m(o){let a={};for(let[l,y]of Object.entries(o))a[l]=_(y);return r.parse(a)}function C(o){let a={};for(let[l,y]of Object.entries(o))a[l]=_(y);return r.parse(a)}return{findById:async o=>{d(t);let a=i().selectAll();a=p(a,[{field:"id",value:o}]);let l=await a.executeTakeFirst();return l?m(l):null},findOne:async o=>{d(t);let a=i().selectAll();a=p(a,g(o));let l=await a.executeTakeFirst();return l?m(l):null},findMany:async o=>{d(t);let a=i().selectAll();return a=p(a,g(o?.where)),typeof o?.limit=="number"&&(a=a.limit(o.limit)),typeof o?.offset=="number"&&(a=a.offset(o.offset)),(await a.execute()).map(y=>m(y))},create:async o=>{d(t);let a=new Date,l={id:o.id??h(),created_at:a,updated_at:a,...o},y=await s().values(l).returningAll().executeTakeFirst();return y?m(y):C(l)},update:async(o,a)=>{d(t);let l={...a,updated_at:new Date},y=u().set(l).returningAll();y=p(y,[{field:"id",value:o}]);let f=await y.executeTakeFirst();return f?m(f):null},updateMany:async(o,a)=>{d(t);let l={...a,updated_at:new Date},y=i().select("id");y=p(y,g(o));let f=await y.execute();for(let P of f){let w=u().set(l);w=p(w,[{field:"id",value:P.id}]),await w.execute()}return f.length},delete:async o=>{d(t);let a=c();a=p(a,[{field:"id",value:o}]);let l=await a.executeTakeFirst();return Number(l?.numDeletedRows??0)>0},deleteMany:async o=>{d(t);let a=c();a=p(a,g(o));let l=await a.executeTakeFirst();return Number(l?.numDeletedRows??0)},count:async o=>{d(t);let a=i().select(y=>y.fn.countAll().as("count"));a=p(a,g(o));let l=await a.executeTakeFirst();return S(l?.count)}}}function R(t){let n=T(t,"corsair_integrations");return{...n,findByName:r=>n.findOne({name:r}),upsertByName:async(r,e)=>{let i=await n.findOne({name:r});return i?await n.update(i.id,e):n.create({...e,name:r})}}}function O(t){let n=T(t,"corsair_accounts");return{...n,findByTenantAndIntegration:async(r,e)=>{d(t);let i=await t.db.selectFrom("corsair_integrations").selectAll().where("name","=",e).executeTakeFirst();return i?n.findOne({tenant_id:r,integration_id:i.id}):null},listByTenant:(r,e)=>n.findMany({where:{tenant_id:r},limit:e?.limit,offset:e?.offset}),upsertByTenantAndIntegration:async(r,e,i)=>{let s=await n.findOne({tenant_id:r,integration_id:e});return s?await n.update(s.id,i):n.create({...i,tenant_id:r,integration_id:e})}}}function v(t){let n=T(t,"corsair_entities");return{...n,findByEntityId:({accountId:r,entityType:e,entityId:i})=>n.findOne({account_id:r,entity_type:e,entity_id:i}),findManyByEntityIds:async({accountId:r,entityType:e,entityIds:i})=>i.length===0?[]:(d(t),await t.db.selectFrom("corsair_entities").selectAll().where("account_id","=",r).where("entity_type","=",e).where("entity_id","in",i).execute()),listByScope:({accountId:r,entityType:e,limit:i,offset:s})=>n.findMany({where:{account_id:r,entity_type:e},limit:i,offset:s}),searchByEntityId:async({accountId:r,entityType:e,query:i,limit:s,offset:u})=>{d(t);let c=t.db.selectFrom("corsair_entities").selectAll().where("account_id","=",r).where("entity_type","=",e).where("entity_id","like",`%${i}%`);return typeof s=="number"&&(c=c.limit(s)),typeof u=="number"&&(c=c.offset(u)),await c.execute()},upsertByEntityId:async({accountId:r,entityType:e,entityId:i,version:s,data:u})=>{let c=await n.findOne({account_id:r,entity_type:e,entity_id:i});return c?await n.update(c.id,{version:s,data:u}):n.create({account_id:r,entity_type:e,entity_id:i,version:s,data:u})},deleteByEntityId:async({accountId:r,entityType:e,entityId:i})=>{d(t);let s=await t.db.deleteFrom("corsair_entities").where("account_id","=",r).where("entity_type","=",e).where("entity_id","=",i).executeTakeFirst();return Number(s.numDeletedRows)>0}}}function N(t){let n=T(t,"corsair_events");return{...n,listByAccount:(r,e)=>n.findMany({where:{account_id:r},limit:e?.limit,offset:e?.offset}),listByStatus:(r,e)=>{let i={status:r};return e?.accountId&&(i.account_id=e.accountId),n.findMany({where:i,limit:e?.limit,offset:e?.offset})},listPending:r=>{let e={status:"pending"};return r?.accountId&&(e.account_id=r.accountId),n.findMany({where:e,limit:r?.limit??100})},updateStatus:(r,e)=>n.update(r,{status:e})}}function A(t){return{integrations:R(t),accounts:O(t),entities:v(t),events:N(t)}}function W(t,n,r,e,i){let s=null;async function u(){if(s!==null)return s;d(t);let c=await t.db.selectFrom("corsair_integrations").selectAll().where("name","=",n.integrationName).executeTakeFirst();if(!c)throw new Error(`Integration "${n.integrationName}" not found. Make sure to create the integration first.`);let m=await t.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",n.tenantId).where("integration_id","=",c.id).executeTakeFirst();if(!m)throw new Error(`Account not found for tenant "${n.tenantId}" and integration "${n.integrationName}". Make sure to create the account first.`);return s=m.id,s}return d(t),b(t.db,u,r,e,i)}function B(t){let{database:n,integrationName:r,schema:e,tenantId:i}=t,s=A(n),u={tenantId:i,integrationName:r},c=null;async function m(){if(c!==null)return c;d(n);let o=await n.db.selectFrom("corsair_integrations").selectAll().where("name","=",r).executeTakeFirst();if(!o)throw new Error(`Integration "${r}" not found. Make sure to create the integration first.`);let a=await n.db.selectFrom("corsair_accounts").selectAll().where("tenant_id","=",i).where("integration_id","=",o.id).executeTakeFirst();if(!a)throw new Error(`Account not found for tenant "${i}" and integration "${r}". Make sure to create the account first.`);return c=a.id,c}let C={};for(let[o,a]of Object.entries(e.entities))C[o]=W(n,u,o,e.version,a);return{...C,$orm:s,$integrationName:r,$tenantId:i,$getAccountId:m}}function q(t,n){let r=A(t);return{$tenantId:n,$orm:r,listAccounts:e=>r.accounts.listByTenant(n,e),findAccountByIntegration:e=>r.accounts.findByTenantAndIntegration(n,e),listEntities:async e=>{d(t);let i=await t.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",n).execute();if(i.length===0)return[];let s=i.map(c=>c.id),u=t.db.selectFrom("corsair_entities").selectAll().where("account_id","in",s);return e?.entityType&&(u=u.where("entity_type","=",e.entityType)),typeof e?.limit=="number"&&(u=u.limit(e.limit)),typeof e?.offset=="number"&&(u=u.offset(e.offset)),await u.execute()},listEvents:async e=>{d(t);let i=await t.db.selectFrom("corsair_accounts").select("id").where("tenant_id","=",n).execute();if(i.length===0)return[];let s=i.map(c=>c.id),u=t.db.selectFrom("corsair_events").selectAll().where("account_id","in",s);return e?.status&&(u=u.where("status","=",e.status)),typeof e?.limit=="number"&&(u=u.limit(e.limit)),typeof e?.offset=="number"&&(u=u.offset(e.offset)),await u.execute()},forIntegration:e=>B({database:t,integrationName:e.integrationName,schema:e.schema,tenantId:n})}}function K(t,n){return{forTenant:r=>B({database:t,integrationName:n.integrationName,schema:n.schema,tenantId:r})}}export{k as a,A as b,B as c,q as d,K as e};
|
package/dist/chunk-ZGVIF3UY.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as s}from"./chunk-QAIKSQAD.js";import{Kysely as n,PostgresDialect as b,SqliteDialect as C}from"kysely";import{PostgresJSDialect as D}from"kysely-postgres-js";function w(e){return typeof e.query=="function"&&typeof e.connect=="function"}function d(e){let t=e;return typeof t.prepare=="function"&&typeof t.exec=="function"&&typeof t.close=="function"&&!("query"in e)}function m(e){return typeof e=="function"&&typeof e.begin=="function"&&typeof e.end=="function"}function i(e,t){return typeof e=="function"?e.bind(t):e}function S(e){return e instanceof Date?e.toISOString():e}function g(e){return new Proxy(e,{get(t,a,u){return a!=="reserve"?i(Reflect.get(t,a,u),t):async function(){let c=await t.reserve();return new Proxy(c,{get(r,o,y){return o!=="unsafe"?i(Reflect.get(r,o,y),r):function(l,f,p){return r.unsafe(l,f?.map(S),p)}}})}}})}function q(e){return typeof e.selectFrom=="function"}function x(e){if(q(e))return{db:e};if(d(e))return{db:new n({dialect:new C({database:e}),plugins:[new s]})};if(w(e))return{db:new n({dialect:new b({pool:e})})};if(m(e))return{db:new n({dialect:new D({postgres:g(e)})})};throw new Error("Unsupported database input. Expected a pg Pool, postgres.js Sql, better-sqlite3 Database, or a Kysely instance.")}export{x as a};
|